luci-app-firewall: simplify some form actions
[project/luci.git] / applications / luci-app-firewall / htdocs / luci-static / resources / view / firewall / rules.js
1 'use strict';
2 'require view';
3 'require ui';
4 'require rpc';
5 'require uci';
6 'require form';
7 'require firewall as fwmodel';
8 'require tools.firewall as fwtool';
9 'require tools.widgets as widgets';
10
11 function rule_proto_txt(s, ctHelpers) {
12 var f = (uci.get('firewall', s, 'family') || '').toLowerCase().replace(/^(?:any|\*)$/, '');
13
14 var proto = L.toArray(uci.get('firewall', s, 'proto')).filter(function(p) {
15 return (p != '*' && p != 'any' && p != 'all');
16 }).map(function(p) {
17 var pr = fwtool.lookupProto(p);
18 return {
19 num: pr[0],
20 name: pr[1],
21 types: (pr[0] == 1 || pr[0] == 58) ? L.toArray(uci.get('firewall', s, 'icmp_type')) : null
22 };
23 });
24
25 m = String(uci.get('firewall', s, 'helper') || '').match(/^(!\s*)?(\S+)$/);
26 var h = m ? {
27 val: m[0].toUpperCase(),
28 inv: m[1],
29 name: (ctHelpers.filter(function(ctH) { return ctH.name.toLowerCase() == m[2].toLowerCase() })[0] || {}).description
30 } : null;
31
32 m = String(uci.get('firewall', s, 'mark')).match(/^(!\s*)?(0x[0-9a-f]{1,8}|[0-9]{1,10})(?:\/(0x[0-9a-f]{1,8}|[0-9]{1,10}))?$/i);
33 var w = m ? {
34 val: m[0].toUpperCase().replace(/X/g, 'x'),
35 inv: m[1],
36 num: '0x%02X'.format(+m[2]),
37 mask: m[3] ? '0x%02X'.format(+m[3]) : null
38 } : null;
39
40 m = String(uci.get('firewall', s, 'dscp')).match(/^(!\s*)?(?:(CS[0-7]|BE|AF[1234][123]|EF)|(0x[0-9a-f]{1,2}|[0-9]{1,2}))$/);
41 var d = m ? {
42 val: m[0],
43 inv: m[1],
44 name: m[2],
45 num: m[3] ? '0x%02X'.format(+m[3]) : null
46 } : null;
47
48 return fwtool.fmt(_('%{src?%{dest?Forwarded:Incoming}:Outgoing} %{ipv6?%{ipv4?<var>IPv4</var> and <var>IPv6</var>:<var>IPv6</var>}:<var>IPv4</var>}%{proto?, protocol %{proto#%{next?, }%{item.types?<var class="cbi-tooltip-container">%{item.name}<span class="cbi-tooltip">ICMP with types %{item.types#%{next?, }<var>%{item}</var>}</span></var>:<var>%{item.name}</var>}}}%{mark?, mark <var%{mark.inv? data-tooltip="Match fwmarks except %{mark.num}%{mark.mask? with mask %{mark.mask}}.":%{mark.mask? data-tooltip="Mask fwmark value with %{mark.mask} before compare."}}>%{mark.val}</var>}%{dscp?, DSCP %{dscp.inv?<var data-tooltip="Match DSCP classifications except %{dscp.num?:%{dscp.name}}">%{dscp.val}</var>:<var>%{dscp.val}</var>}}%{helper?, helper %{helper.inv?<var data-tooltip="Match any helper except &quot;%{helper.name}&quot;">%{helper.val}</var>:<var data-tooltip="%{helper.name}">%{helper.val}</var>}}'), {
49 ipv4: (!f || f == 'ipv4'),
50 ipv6: (!f || f == 'ipv6'),
51 src: uci.get('firewall', s, 'src'),
52 dest: uci.get('firewall', s, 'dest'),
53 proto: proto,
54 helper: h,
55 mark: w,
56 dscp: d
57 });
58 }
59
60 function rule_src_txt(s, hosts) {
61 var z = uci.get('firewall', s, 'src'),
62 d = (uci.get('firewall', s, 'direction') == 'in') ? uci.get('firewall', s, 'device') : null;
63
64 return fwtool.fmt(_('From %{src}%{src_device?, interface <var>%{src_device}</var>}%{src_ip?, IP %{src_ip#%{next?, }<var%{item.inv? data-tooltip="Match IP addresses except %{item.val}."}>%{item.ival}</var>}}%{src_port?, port %{src_port#%{next?, }<var%{item.inv? data-tooltip="Match ports except %{item.val}."}>%{item.ival}</var>}}%{src_mac?, MAC %{src_mac#%{next?, }<var%{item.inv? data-tooltip="Match MACs except %{item.val}%{item.hint.name? a.k.a. %{item.hint.name}}.":%{item.hint.name? data-tooltip="%{item.hint.name}"}}>%{item.ival}</var>}}'), {
65 src: E('span', { 'class': 'zonebadge', 'style': 'background-color:' + fwmodel.getColorForName((z && z != '*') ? z : null) }, [(z == '*') ? E('em', _('any zone')) : (z || E('em', _('this device')))]),
66 src_ip: fwtool.map_invert(uci.get('firewall', s, 'src_ip'), 'toLowerCase'),
67 src_mac: fwtool.map_invert(uci.get('firewall', s, 'src_mac'), 'toUpperCase').map(function(v) { return Object.assign(v, { hint: hosts[v.val] }) }),
68 src_port: fwtool.map_invert(uci.get('firewall', s, 'src_port')),
69 src_device: d
70 });
71 }
72
73 function rule_dest_txt(s) {
74 var z = uci.get('firewall', s, 'dest'),
75 d = (uci.get('firewall', s, 'direction') == 'out') ? uci.get('firewall', s, 'device') : null;
76
77 return fwtool.fmt(_('To %{dest}%{dest_device?, interface <var>%{dest_device}</var>}%{dest_ip?, IP %{dest_ip#%{next?, }<var%{item.inv? data-tooltip="Match IP addresses except %{item.val}."}>%{item.ival}</var>}}%{dest_port?, port %{dest_port#%{next?, }<var%{item.inv? data-tooltip="Match ports except %{item.val}."}>%{item.ival}</var>}}'), {
78 dest: E('span', { 'class': 'zonebadge', 'style': 'background-color:' + fwmodel.getColorForName((z && z != '*') ? z : null) }, [(z == '*') ? E('em', _('any zone')) : (z || E('em', _('this device')))]),
79 dest_ip: fwtool.map_invert(uci.get('firewall', s, 'dest_ip'), 'toLowerCase'),
80 dest_port: fwtool.map_invert(uci.get('firewall', s, 'dest_port')),
81 dest_device: d
82 });
83 }
84
85 function rule_limit_txt(s) {
86 var m = String(uci.get('firewall', s, 'limit')).match(/^(\d+)\/([smhd])\w*$/i),
87 l = m ? {
88 num: +m[1],
89 unit: ({ s: _('second'), m: _('minute'), h: _('hour'), d: _('day') })[m[2]],
90 burst: uci.get('firewall', s, 'limit_burst')
91 } : null;
92
93 if (!l)
94 return '';
95
96 return fwtool.fmt(_('Limit matching to <var>%{limit.num}</var> packets per <var>%{limit.unit}</var>%{limit.burst? burst <var>%{limit.burst}</var>}'), { limit: l });
97 }
98
99 function rule_target_txt(s, ctHelpers) {
100 var t = uci.get('firewall', s, 'target'),
101 h = (uci.get('firewall', s, 'set_helper') || '').toUpperCase(),
102 s = {
103 target: t,
104 src: uci.get('firewall', s, 'src'),
105 dest: uci.get('firewall', s, 'dest'),
106 set_helper: h,
107 set_mark: uci.get('firewall', s, 'set_mark'),
108 set_xmark: uci.get('firewall', s, 'set_xmark'),
109 set_dscp: uci.get('firewall', s, 'set_dscp'),
110 helper_name: (ctHelpers.filter(function(ctH) { return ctH.name.toUpperCase() == h })[0] || {}).description
111 };
112
113 switch (t) {
114 case 'DROP':
115 return fwtool.fmt(_('<var data-tooltip="DROP">Drop</var> %{src?%{dest?forward:input}:output}'), s);
116
117 case 'ACCEPT':
118 return fwtool.fmt(_('<var data-tooltip="ACCEPT">Accept</var> %{src?%{dest?forward:input}:output}'), s);
119
120 case 'REJECT':
121 return fwtool.fmt(_('<var data-tooltip="REJECT">Reject</var> %{src?%{dest?forward:input}:output}'), s);
122
123 case 'NOTRACK':
124 return fwtool.fmt(_('<var data-tooltip="NOTRACK">Do not track</var> %{src?%{dest?forward:input}:output}'), s);
125
126 case 'HELPER':
127 return fwtool.fmt(_('<var data-tooltip="HELPER">Assign conntrack</var> helper <var%{helper_name? data-tooltip="%{helper_name}"}>%{set_helper}</var>'), s);
128
129 case 'MARK':
130 return fwtool.fmt(_('<var data-tooltip="MARK">%{set_mark?Assign:XOR}</var> firewall mark <var>%{set_mark?:%{set_xmark}}</var>'), s);
131
132 case 'DSCP':
133 return fwtool.fmt(_('<var data-tooltip="DSCP">Assign DSCP</var> classification <var>%{set_dscp}</var>'), s);
134
135 default:
136 return t;
137 }
138 }
139
140 return view.extend({
141 callHostHints: rpc.declare({
142 object: 'luci-rpc',
143 method: 'getHostHints',
144 expect: { '': {} }
145 }),
146
147 callConntrackHelpers: rpc.declare({
148 object: 'luci',
149 method: 'getConntrackHelpers',
150 expect: { result: [] }
151 }),
152
153 load: function() {
154 return Promise.all([
155 this.callHostHints(),
156 this.callConntrackHelpers(),
157 uci.load('firewall')
158 ]);
159 },
160
161 render: function(data) {
162 if (fwtool.checkLegacySNAT())
163 return fwtool.renderMigration();
164 else
165 return this.renderRules(data);
166 },
167
168 renderRules: function(data) {
169 var hosts = data[0],
170 ctHelpers = data[1],
171 m, s, o;
172
173 m = new form.Map('firewall', _('Firewall - Traffic Rules'),
174 _('Traffic rules define policies for packets traveling between different zones, for example to reject traffic between certain hosts or to open WAN ports on the router.'));
175
176 s = m.section(form.GridSection, 'rule', _('Traffic Rules'));
177 s.addremove = true;
178 s.anonymous = true;
179 s.sortable = true;
180
181 s.tab('general', _('General Settings'));
182 s.tab('advanced', _('Advanced Settings'));
183 s.tab('timed', _('Time Restrictions'));
184
185 s.filter = function(section_id) {
186 return (uci.get('firewall', section_id, 'target') != 'SNAT');
187 };
188
189 s.sectiontitle = function(section_id) {
190 return uci.get('firewall', section_id, 'name') || _('Unnamed rule');
191 };
192
193 s.handleAdd = function(ev) {
194 var config_name = this.uciconfig || this.map.config,
195 section_id = uci.add(config_name, this.sectiontype),
196 opt1 = this.getOption('src'),
197 opt2 = this.getOption('dest');
198
199 opt1.default = 'wan';
200 opt2.default = 'lan';
201
202 this.addedSection = section_id;
203 this.renderMoreOptionsModal(section_id);
204
205 delete opt1.default;
206 delete opt2.default;
207 };
208
209 o = s.taboption('general', form.Value, 'name', _('Name'));
210 o.placeholder = _('Unnamed rule');
211 o.modalonly = true;
212
213 o = s.option(form.DummyValue, '_match', _('Match'));
214 o.modalonly = false;
215 o.textvalue = function(s) {
216 return E('small', [
217 rule_proto_txt(s, ctHelpers), E('br'),
218 rule_src_txt(s, hosts), E('br'),
219 rule_dest_txt(s), E('br'),
220 rule_limit_txt(s)
221 ]);
222 };
223
224 o = s.option(form.ListValue, '_target', _('Action'));
225 o.modalonly = false;
226 o.textvalue = function(s) {
227 return rule_target_txt(s, ctHelpers);
228 };
229
230 o = s.option(form.Flag, 'enabled', _('Enable'));
231 o.modalonly = false;
232 o.default = o.enabled;
233 o.editable = true;
234 o.tooltip = function(section_id) {
235 var weekdays = uci.get('firewall', section_id, 'weekdays');
236 var monthdays = uci.get('firewall', section_id, 'monthdays');
237 var start_time = uci.get('firewall', section_id, 'start_time');
238 var stop_time = uci.get('firewall', section_id, 'stop_time');
239 var start_date = uci.get('firewall', section_id, 'start_date');
240 var stop_date = uci.get('firewall', section_id, 'stop_date');
241
242 if (weekdays || monthdays || start_time || stop_time || start_date || stop_date )
243 return _('Time restritions are enabled for this rule');
244
245 return null;
246 };
247
248 o = s.taboption('advanced', form.ListValue, 'direction', _('Match device'));
249 o.modalonly = true;
250 o.value('', _('unspecified'));
251 o.value('in', _('Inbound device'));
252 o.value('out', _('Outbound device'));
253 o.cfgvalue = function(section_id) {
254 var val = uci.get('firewall', section_id, 'direction');
255 switch (val) {
256 case 'in':
257 case 'ingress':
258 return 'in';
259
260 case 'out':
261 case 'egress':
262 return 'out';
263 }
264
265 return null;
266 };
267
268 o = s.taboption('advanced', widgets.DeviceSelect, 'device', _('Device name'),
269 _('Specifies whether to tie this traffic rule to a specific inbound or outbound network device.'));
270 o.modalonly = true;
271 o.noaliases = true;
272 o.rmempty = false;
273 o.depends('direction', 'in');
274 o.depends('direction', 'out');
275
276 o = s.taboption('advanced', form.ListValue, 'family', _('Restrict to address family'));
277 o.modalonly = true;
278 o.rmempty = true;
279 o.value('', _('IPv4 and IPv6'));
280 o.value('ipv4', _('IPv4 only'));
281 o.value('ipv6', _('IPv6 only'));
282 o.validate = function(section_id, value) {
283 fwtool.updateHostHints(this.map, section_id, 'src_ip', value, hosts);
284 fwtool.updateHostHints(this.map, section_id, 'dest_ip', value, hosts);
285 return true;
286 };
287
288 o = s.taboption('general', fwtool.CBIProtocolSelect, 'proto', _('Protocol'));
289 o.modalonly = true;
290 o.default = 'tcp udp';
291
292 o = s.taboption('advanced', form.MultiValue, 'icmp_type', _('Match ICMP type'));
293 o.modalonly = true;
294 o.multiple = true;
295 o.custom = true;
296 o.cast = 'table';
297 o.placeholder = _('any');
298 o.value('', 'any');
299 o.value('address-mask-reply');
300 o.value('address-mask-request');
301 o.value('communication-prohibited');
302 o.value('destination-unreachable');
303 o.value('echo-reply');
304 o.value('echo-request');
305 o.value('fragmentation-needed');
306 o.value('host-precedence-violation');
307 o.value('host-prohibited');
308 o.value('host-redirect');
309 o.value('host-unknown');
310 o.value('host-unreachable');
311 o.value('ip-header-bad');
312 o.value('neighbour-advertisement');
313 o.value('neighbour-solicitation');
314 o.value('network-prohibited');
315 o.value('network-redirect');
316 o.value('network-unknown');
317 o.value('network-unreachable');
318 o.value('packet-too-big');
319 o.value('parameter-problem');
320 o.value('port-unreachable');
321 o.value('precedence-cutoff');
322 o.value('protocol-unreachable');
323 o.value('redirect');
324 o.value('required-option-missing');
325 o.value('router-advertisement');
326 o.value('router-solicitation');
327 o.value('source-quench');
328 o.value('source-route-failed');
329 o.value('time-exceeded');
330 o.value('timestamp-reply');
331 o.value('timestamp-request');
332 o.value('TOS-host-redirect');
333 o.value('TOS-host-unreachable');
334 o.value('TOS-network-redirect');
335 o.value('TOS-network-unreachable');
336 o.value('ttl-zero-during-reassembly');
337 o.value('ttl-zero-during-transit');
338 o.depends({ proto: 'icmp', '!contains': true });
339 o.depends({ proto: 'icmpv6', '!contains': true });
340
341 o = s.taboption('general', widgets.ZoneSelect, 'src', _('Source zone'));
342 o.modalonly = true;
343 o.nocreate = true;
344 o.allowany = true;
345 o.allowlocal = 'src';
346
347 fwtool.addMACOption(s, 'advanced', 'src_mac', _('Source MAC address'), null, hosts);
348 fwtool.addIPOption(s, 'general', 'src_ip', _('Source address'), null, '', hosts, true);
349
350 o = s.taboption('general', form.Value, 'src_port', _('Source port'));
351 o.modalonly = true;
352 o.datatype = 'list(neg(portrange))';
353 o.placeholder = _('any');
354 o.depends({ proto: 'tcp', '!contains': true });
355 o.depends({ proto: 'udp', '!contains': true });
356
357 o = s.taboption('general', widgets.ZoneSelect, 'dest', _('Destination zone'));
358 o.modalonly = true;
359 o.nocreate = true;
360 o.allowany = true;
361 o.allowlocal = true;
362
363 fwtool.addIPOption(s, 'general', 'dest_ip', _('Destination address'), null, '', hosts, true);
364
365 o = s.taboption('general', form.Value, 'dest_port', _('Destination port'));
366 o.modalonly = true;
367 o.datatype = 'list(neg(portrange))';
368 o.placeholder = _('any');
369 o.depends({ proto: 'tcp', '!contains': true });
370 o.depends({ proto: 'udp', '!contains': true });
371
372 o = s.taboption('general', form.ListValue, 'target', _('Action'));
373 o.modalonly = true;
374 o.default = 'ACCEPT';
375 o.value('DROP', _('drop'));
376 o.value('ACCEPT', _('accept'));
377 o.value('REJECT', _('reject'));
378 o.value('NOTRACK', _("don't track"));
379 o.value('HELPER', _('assign conntrack helper'));
380 o.value('MARK_SET', _('apply firewall mark'));
381 o.value('MARK_XOR', _('XOR firewall mark'));
382 o.value('DSCP', _('DSCP classification'));
383 o.cfgvalue = function(section_id) {
384 var t = uci.get('firewall', section_id, 'target'),
385 m = uci.get('firewall', section_id, 'set_mark');
386
387 if (t == 'MARK')
388 return m ? 'MARK_SET' : 'MARK_XOR';
389
390 return t;
391 };
392 o.write = function(section_id, value) {
393 return this.super('write', [section_id, (value == 'MARK_SET' || value == 'MARK_XOR') ? 'MARK' : value]);
394 };
395
396 fwtool.addMarkOption(s, 1);
397 fwtool.addMarkOption(s, 2);
398 fwtool.addDSCPOption(s, true);
399
400 o = s.taboption('general', form.ListValue, 'set_helper', _('Tracking helper'), _('Assign the specified connection tracking helper to matched traffic.'));
401 o.modalonly = true;
402 o.placeholder = _('any');
403 o.depends('target', 'HELPER');
404 for (var i = 0; i < ctHelpers.length; i++)
405 o.value(ctHelpers[i].name, '%s (%s)'.format(ctHelpers[i].description, ctHelpers[i].name.toUpperCase()));
406
407 o = s.taboption('advanced', form.Value, 'helper', _('Match helper'), _('Match traffic using the specified connection tracking helper.'));
408 o.modalonly = true;
409 o.placeholder = _('any');
410 for (var i = 0; i < ctHelpers.length; i++)
411 o.value(ctHelpers[i].name, '%s (%s)'.format(ctHelpers[i].description, ctHelpers[i].name.toUpperCase()));
412 o.validate = function(section_id, value) {
413 if (value == '' || value == null)
414 return true;
415
416 value = value.replace(/^!\s*/, '');
417
418 for (var i = 0; i < ctHelpers.length; i++)
419 if (value == ctHelpers[i].name)
420 return true;
421
422 return _('Unknown or not installed conntrack helper "%s"').format(value);
423 };
424
425 fwtool.addMarkOption(s, false);
426 fwtool.addDSCPOption(s, false);
427 fwtool.addLimitOption(s);
428 fwtool.addLimitBurstOption(s);
429
430 o = s.taboption('advanced', form.Value, 'extra', _('Extra arguments'),
431 _('Passes additional arguments to iptables. Use with care!'));
432 o.modalonly = true;
433
434 o = s.taboption('timed', form.MultiValue, 'weekdays', _('Week Days'));
435 o.modalonly = true;
436 o.multiple = true;
437 o.display = 5;
438 o.placeholder = _('Any day');
439 o.value('Sun', _('Sunday'));
440 o.value('Mon', _('Monday'));
441 o.value('Tue', _('Tuesday'));
442 o.value('Wed', _('Wednesday'));
443 o.value('Thu', _('Thursday'));
444 o.value('Fri', _('Friday'));
445 o.value('Sat', _('Saturday'));
446 o.write = function(section_id, value) {
447 return this.super('write', [ section_id, L.toArray(value).join(' ') ]);
448 };
449
450 o = s.taboption('timed', form.MultiValue, 'monthdays', _('Month Days'));
451 o.modalonly = true;
452 o.multiple = true;
453 o.display_size = 15;
454 o.placeholder = _('Any day');
455 o.write = function(section_id, value) {
456 return this.super('write', [ section_id, L.toArray(value).join(' ') ]);
457 };
458 for (var i = 1; i <= 31; i++)
459 o.value(i);
460
461 o = s.taboption('timed', form.Value, 'start_time', _('Start Time (hh.mm.ss)'));
462 o.modalonly = true;
463 o.datatype = 'timehhmmss';
464
465 o = s.taboption('timed', form.Value, 'stop_time', _('Stop Time (hh.mm.ss)'));
466 o.modalonly = true;
467 o.datatype = 'timehhmmss';
468
469 o = s.taboption('timed', form.Value, 'start_date', _('Start Date (yyyy-mm-dd)'));
470 o.modalonly = true;
471 o.datatype = 'dateyyyymmdd';
472
473 o = s.taboption('timed', form.Value, 'stop_date', _('Stop Date (yyyy-mm-dd)'));
474 o.modalonly = true;
475 o.datatype = 'dateyyyymmdd';
476
477 o = s.taboption('timed', form.Flag, 'utc_time', _('Time in UTC'));
478 o.modalonly = true;
479 o.default = o.disabled;
480
481 return m.render();
482 }
483 });