-
Notifications
You must be signed in to change notification settings - Fork 39
/
parse.lua
1209 lines (1097 loc) · 39.9 KB
/
parse.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
module(...,package.seeall)
allow_address_of = true
local utils = require('pf.utils')
local constants = require('pf.constants')
local ipv4_to_int, ipv6_as_4x32 = utils.ipv4_to_int, utils.ipv6_as_4x32
local uint32 = utils.uint32
local function skip_whitespace(str, pos)
while pos <= #str and str:match('^%s', pos) do
pos = pos + 1
end
return pos
end
local function set(...)
local ret = {}
for k, v in pairs({...}) do ret[v] = true end
return ret
end
local punctuation = set(
'(', ')', '[', ']', ':', '!', '!=', '<', '<=', '>', '>=', '=', '==',
'+', '-', '*', '/', '&', '|', '^', '&&', '||', '<<', '>>', '\\'
)
local number_terminators = " \t\r\n)]:!<>=+-*/%&|^"
local function lex_number(str, pos, base)
local res = 0
local i = pos
while i <= #str do
local chr = str:sub(i,i)
local n = tonumber(chr, base)
if n then
res = res * base + n
i = i + 1
elseif not number_terminators:find(chr, 1, true) then
return nil
else
break
end
end
if i == pos then
-- No digits parsed, can happen when lexing "0x" or "09".
return nil
end
return res, i -- EOS or end of number.
end
local function maybe_lex_number(str, pos)
if str:match("^0x", pos) then
return "hexadecimal", lex_number(str, pos+2, 16)
elseif str:match("^0%d", pos) then
return "octal", lex_number(str, pos+1, 8)
elseif str:match("^%d", pos) then
return "decimal", lex_number(str, pos, 10)
end
end
local function lex_host_or_keyword(str, pos)
local name, next_pos = str:match("^([%w.-]+)()", pos)
assert(name, "failed to parse hostname or keyword at "..pos)
assert(name:match("^%w", 1, 1), "bad hostname or keyword "..name)
assert(name:match("^%w", #name, #name), "bad hostname or keyword "..name)
local kind, number, number_next_pos = maybe_lex_number(str, pos)
-- Only interpret name as a number as a whole.
if number and number_next_pos == next_pos then
assert(number <= 0xffffffff, 'integer too large: '..name)
return number, next_pos
else
return name, next_pos
end
end
local function lex_ipv4(str, pos)
local function lex_byte(str)
local byte = tonumber(str, 10)
if byte >= 256 then return nil end
return byte
end
local digits, dot = str:match("^(%d%d?%d?)()", pos)
if not digits then return nil end
local addr = { 'ipv4' }
local byte = lex_byte(digits)
if not byte then return nil end
table.insert(addr, byte)
pos = dot
for i=1,3 do
local digits, dot = str:match("^%.(%d%d?%d?)()", pos)
if not digits then break end
local byte = lex_byte(digits)
if not byte then return nil end
table.insert(addr, byte)
pos = dot
end
local last_char = str:sub(pos, pos)
-- IPv4 address is actually a hostname
if last_char:match("[%w.-]") then return nil end
local terminators = " \t\r\n)/"
assert(pos > #str or terminators:find(last_char, 1, true),
"unexpected terminator for ipv4 address")
return addr, pos
end
local function lex_ipv6(str, pos)
local addr = { 'ipv6' }
local hole_index
if str:sub(pos, pos + 1) == "::" then
hole_index = 2
pos = pos + 2
end
local after_sep = false
local digits_pattern = "^(%x%x?%x?%x?)()"
local expected_sep = ":"
local ipv4_fields = 0
while true do
local digits, next_pos = str:match(digits_pattern, pos)
if not digits then
if after_sep then
error("wrong IPv6 address")
else
break
end
end
local sep = str:sub(next_pos, next_pos)
if sep == "." and expected_sep == ":" then
expected_sep = "."
digits_pattern = "^(%d%d?%d?)()"
-- Continue loop without advancing pos.
-- Will parse field as decimal in the next iteration.
else
pos = next_pos
if expected_sep == ":" then
table.insert(addr, tonumber(digits, 16))
else
local ipv4_field = tonumber(digits, 10)
assert(ipv4_field < 255, "wrong IPv6 address")
ipv4_fields = ipv4_fields + 1
if ipv4_fields % 2 == 0 then
addr[#addr] = addr[#addr] * 256 + ipv4_field
else
table.insert(addr, ipv4_field)
end
end
if sep ~= expected_sep then break end
pos = pos + 1
if sep == ":" and not hole_index and str:sub(pos, pos) == ":" then
pos = pos + 1
hole_index = #addr + 1
after_sep = false
else
after_sep = true
end
end
end
assert(ipv4_fields == 0 or ipv4_fields == 4, "wrong IPv6 address")
if hole_index then
local zeros = 9 - #addr
assert(zeros >= 1, "wrong IPv6 address")
for i=1,zeros do
table.insert(addr, hole_index, 0)
end
end
assert(#addr == 9, "wrong IPv6 address")
local terminators = " \t\r\n)/"
assert(pos > #str or terminators:find(str:sub(pos, pos), 1, true),
"unexpected terminator for ipv6 address")
return addr, pos
end
local function lex_ehost(str, pos)
local start = pos
local addr = { 'ehost' }
local digits, dot = str:match("^(%x%x?)()%:", pos)
assert(digits, "failed to parse ethernet host address at "..pos)
table.insert(addr, tonumber(digits, 16))
pos = dot
for i=1,5 do
local digits, dot = str:match("^%:(%x%x?)()", pos)
assert(digits, "failed to parse ethernet host address at "..pos)
table.insert(addr, tonumber(digits, 16))
pos = dot
end
local terminators = " \t\r\n)/"
local last_char = str:sub(pos, pos)
-- MAC address is actually an IPv6 address
if last_char == ':' or last_char == '.' then return nil, start end
assert(pos > #str or terminators:find(last_char, 1, true),
"unexpected terminator for ethernet host address")
return addr, pos
end
local function lex_addr_or_host(str, pos)
if str:match('^%x%x?:%x%x?:%x%x?:%x%x?:%x%x?:%x%x?', pos) then
local result, pos = lex_ehost(str, pos)
if result then return result, pos end
return lex_ipv6(str, pos)
elseif str:match("^%x?%x?%x?%x?%:", pos) then
return lex_ipv6(str, pos)
elseif str:match("^%d%d?%d?", pos) then
local result, pos = lex_ipv4(str, pos)
if result then return result, pos end -- Fall through.
end
return lex_host_or_keyword(str, pos)
end
local function lex(str, pos, opts)
-- EOF.
if pos > #str then return nil, pos end
if opts.address then
-- Net addresses.
return lex_addr_or_host(str, pos)
end
-- Non-alphanumeric tokens.
local two = str:sub(pos,pos+1)
if punctuation[two] then return two, pos+2 end
local one = str:sub(pos,pos)
if punctuation[one] then return one, pos+1 end
-- Numeric literals.
if opts.maybe_arithmetic then
local kind, number, next_pos = maybe_lex_number(str, pos)
if kind then
assert(number, "unexpected end of "..kind.." literal at "..pos)
assert(number <= 0xffffffff, 'integer too large: '..str:sub(pos, next_pos-1))
return number, next_pos
end
end
-- "len" is the only bare name that can appear in an arithmetic
-- expression. "len-1" lexes as { 'len', '-', 1 } in arithmetic
-- contexts, but { "len-1" } otherwise.
if opts.maybe_arithmetic and str:match("^len", pos) then
if pos + 3 > #str or not str:match("^[%w.]", pos+3) then
return 'len', pos+3
end
end
return lex_host_or_keyword(str, pos)
end
local function tokens(str)
local pos, next_pos = 1, nil
local peeked = nil
local peeked_address = nil
local peeked_maybe_arithmetic = nil
local last_pos = 0
local primitive_error = error
local function peek(opts)
opts = opts or {}
if not next_pos or opts.address ~= peeked_address or
opts.maybe_arithmetic ~= peeked_maybe_arithmetic then
pos = skip_whitespace(str, pos)
peeked, next_pos = lex(str, pos, opts or {})
peeked_address = opts.address
peeked_maybe_arithmetic = opts.maybe_arithmetic
assert(next_pos, "next pos is nil")
end
return peeked
end
local function next(opts)
local tok = assert(peek(opts), "unexpected end of filter string")
pos, next_pos = next_pos, nil
last_pos = pos
return tok
end
local function consume(expected, opts)
local tok = next(opts)
assert(tok == expected, "expected "..expected..", got: "..tok)
end
local function check(expected, opts)
if peek(opts) ~= expected then return false end
next()
return true
end
local function error_str(message, ...)
local location_error_message = "Pflua parse error: In expression \"%s\""
local start = #location_error_message - 4
local cursor_pos = start + last_pos
local result = "\n"
result = result..location_error_message:format(str).."\n"
result = result..string.rep(" ", cursor_pos).."^".."\n"
result = result..message:format(...).."\n"
return result
end
local function error(message, ...)
primitive_error(error_str(message, ...))
end
return { peek = peek, next = next, consume = consume, check = check, error = error }
end
local addressables = set(
'arp', 'rarp', 'wlan', 'ether', 'fddi', 'tr', 'ppp',
'slip', 'link', 'radio', 'ip', 'ip6', 'tcp', 'udp', 'icmp',
'igmp', 'pim', 'igrp', 'vrrp', 'sctp'
)
local function nullary()
return function(lexer, tok)
return { tok }
end
end
local function unary(parse_arg)
return function(lexer, tok)
return { tok, parse_arg(lexer) }
end
end
function parse_host_arg(lexer)
local arg = lexer.next({address=true})
if type(arg) == 'string' or arg[1] == 'ipv4' or arg[1] == 'ipv6' then
return arg
end
lexer.error('ethernet address used in non-ether expression')
end
function parse_int_arg(lexer, max_len)
local ret = lexer.next({maybe_arithmetic=true})
assert(type(ret) == 'number', 'expected a number', ret)
if max_len then assert(ret <= max_len, 'out of range '..ret) end
return ret
end
function parse_uint16_arg(lexer) return parse_int_arg(lexer, 0xffff) end
function parse_net_arg(lexer)
local function check_non_network_bits_in_ipv4(addr, mask_bits, mask_str)
local ipv4 = uint32(addr[2], addr[3], addr[4], addr[5])
if (bit.band(ipv4, mask_bits) ~= bit.tobit(ipv4)) then
lexer.error("Non-network bits set in %s/%s",
table.concat(addr, ".", 2), mask_str)
end
end
local function check_non_network_bits_in_ipv6(addr, mask_len)
local function format_ipv6(addr, mask_len)
return string.format("%x:%x:%x:%x:%x:%x:%x:%x/%d, ",
addr[2], addr[3], addr[4], addr[5], addr[5], addr[6], addr[7],
addr[8], mask_len)
end
local ipv6 = ipv6_as_4x32(addr)
for i, fragment in ipairs(ipv6) do
local mask_len_fragment = mask_len > 32 and 32 or mask_len
local mask_bits = 2^32 - 2^(32 - mask_len_fragment)
if (bit.band(fragment, mask_bits) ~= bit.tobit(fragment)) then
lexer.error("Non-network bits set in %s", format_ipv6(addr, mask_len))
end
mask_len = mask_len - mask_len_fragment
end
end
local arg = lexer.next({address=true})
if type(arg) ~= 'table' then
lexer.error('named nets currently unsupported')
elseif arg[1] == 'ehost' then
lexer.error('ethernet address used in non-ether expression')
end
-- IPv4 dotted triple, dotted pair or bare net addresses
if arg[1] == 'ipv4' and #arg < 5 then
local mask_len = 32
for i=#arg+1,5 do
arg[i] = 0
mask_len = mask_len - 8
end
return { 'ipv4/len', arg, mask_len }
end
if arg[1] == 'ipv4' or arg[1] == 'ipv6' then
if lexer.check('/') then
local mask_len = parse_int_arg(lexer, arg[1] == 'ipv4' and 32 or 128)
if (arg[1] == 'ipv4') then
local mask_bits = 2^32 - 2^(32 - mask_len)
check_non_network_bits_in_ipv4(arg, mask_bits, tostring(mask_len))
end
if (arg[1] == 'ipv6') then
check_non_network_bits_in_ipv6(arg, mask_len)
end
return { arg[1]..'/len', arg, mask_len }
elseif lexer.check('mask') then
if (arg[1] == 'ipv6') then
lexer.error("Not valid syntax for IPv6")
end
local mask = lexer.next({address=true})
if type(mask) ~= 'table' or mask[1] ~= 'ipv4' then
lexer.error("Invalid IPv4 mask")
end
check_non_network_bits_in_ipv4(arg, ipv4_to_int(mask),
table.concat(mask, '.', 2))
return { arg[1]..'/mask', arg, mask }
else
return arg
end
end
end
local function to_port_number(tok)
local port = tok
if type(tok) == 'string' then
local next_pos
port, next_pos = lex_number(tok, 1, 10)
if not port or next_pos ~= #tok+1 then
-- Token is not a valid decimal literal, fallback to services.
return constants.services[tok]
end
end
assert(port <= 65535, 'port '..port..' out of range')
return port
end
local function parse_port_arg(lexer)
local tok = lexer.next()
local result = to_port_number(tok)
if not result then
lexer.error('unsupported port %s', tok)
end
return result
end
local function parse_portrange_arg(lexer)
local tok = lexer.next()
-- Try to split portrange from start to first hyphen, or from start to
-- second hyphen, and so on.
local pos = 1
while true do
pos = tok:match("^%w+%-()", pos)
if not pos then
lexer.error('error parsing portrange %s', tok)
end
local from, to = to_port_number(tok:sub(1, pos - 2)), to_port_number(tok:sub(pos))
if from and to then
-- For libpcap compatibility, if to < from, swap them
if from > to then from, to = to, from end
return { from, to }
end
end
end
local function parse_ehost_arg(lexer)
local arg = lexer.next({address=true})
if type(arg) == 'string' or arg[1] == 'ehost' then
return arg
end
lexer.error('invalid ethernet host %s', arg)
end
local function table_parser(table, default)
return function (lexer, tok)
local subtok = lexer.peek()
if table[subtok] then
lexer.consume(subtok)
return table[subtok](lexer, tok..'_'..subtok)
end
if default then return default(lexer, tok) end
lexer.error('unknown %s type %s ', tok, subtok)
end
end
local ip_protos = set(
'icmp', 'icmp6', 'igmp', 'igrp', 'pim', 'ah', 'esp', 'vrrp', 'udp', 'tcp', 'sctp'
)
local function parse_proto_arg(lexer, proto_type, protos)
lexer.check('\\')
local arg = lexer.next()
if not proto_type then proto_type = 'ip' end
if not protos then protos = ip_protos end
if type(arg) == 'number' then return arg end
if type(arg) == 'string' then
local proto = arg:match("^(%w+)")
if protos[proto] then return proto end
end
lexer.error('invalid %s proto %s', proto_type, arg)
end
local ether_protos = set(
'ip', 'ip6', 'arp', 'rarp', 'atalk', 'aarp', 'decnet', 'sca', 'lat',
'mopdl', 'moprc', 'iso', 'stp', 'ipx', 'netbeui'
)
local function parse_ether_proto_arg(lexer)
return parse_proto_arg(lexer, 'ethernet', ether_protos)
end
local function parse_ip_proto_arg(lexer)
return parse_proto_arg(lexer, 'ip', ip_protos)
end
local iso_protos = set('clnp', 'esis', 'isis')
local function parse_iso_proto_arg(lexer)
return parse_proto_arg(lexer, 'iso', iso_protos)
end
local function simple_typed_arg_parser(expected)
return function(lexer)
local arg = lexer.next()
if type(arg) == expected then return arg end
lexer.error('expected a %s string, got %s', expected, type(arg))
end
end
local parse_string_arg = simple_typed_arg_parser('string')
local function parse_decnet_host_arg(lexer)
local arg = lexer.next({address=true})
if type(arg) == 'string' then return arg end
if arg[1] == 'ipv4' then
arg[1] = 'decnet'
assert(#arg == 3, "bad decnet address", arg)
return arg
end
lexer.error('invalid decnet host %s', arg)
end
local llc_types = set(
'i', 's', 'u', 'rr', 'rnr', 'rej', 'ui', 'ua',
'disc', 'sabme', 'test', 'xis', 'frmr'
)
local function parse_llc(lexer, tok)
if llc_types[lexer.peek()] then return { tok, lexer.next() } end
return { tok }
end
local pf_reasons = set(
'match', 'bad-offset', 'fragment', 'short', 'normalize', 'memory'
)
local pf_actions = set(
'pass', 'block', 'nat', 'rdr', 'binat', 'scrub'
)
local wlan_frame_types = set('mgt', 'ctl', 'data')
local wlan_frame_mgt_subtypes = set(
'assoc-req', 'assoc-resp', 'reassoc-req', 'reassoc-resp',
'probe-req', 'probe-resp', 'beacon', 'atim', 'disassoc', 'auth', 'deauth'
)
local wlan_frame_ctl_subtypes = set(
'ps-poll', 'rts', 'cts', 'ack', 'cf-end', 'cf-end-ack'
)
local wlan_frame_data_subtypes = set(
'data', 'data-cf-ack', 'data-cf-poll', 'data-cf-ack-poll', 'null',
'cf-ack', 'cf-poll', 'cf-ack-poll', 'qos-data', 'qos-data-cf-ack',
'qos-data-cf-poll', 'qos-data-cf-ack-poll', 'qos', 'qos-cf-poll',
'quos-cf-ack-poll'
)
local wlan_directions = set('nods', 'tods', 'fromds', 'dstods')
local function parse_enum_arg(lexer, set)
local arg = lexer.next()
assert(set[arg], 'invalid argument: '..arg)
return arg
end
local function enum_arg_parser(set)
return function(lexer) return parse_enum_arg(lexer, set) end
end
local function parse_wlan_type(lexer, tok)
local type = enum_arg_parser(wlan_frame_types)(lexer)
if lexer.check('subtype') then
local set
if type == 'mgt' then set = wlan_frame_mgt_subtypes
elseif type == 'mgt' then set = wlan_frame_ctl_subtypes
else set = wlan_frame_data_subtypes end
return { 'type', type, enum_arg_parser(set)(lexer) }
end
return { tok, type }
end
local function parse_wlan_subtype(lexer, tok)
local subtype = lexer.next()
assert(wlan_frame_mgt_subtypes[subtype]
or wlan_frame_ctl_subtypes[subtype]
or wlan_frame_data_subtypes[subtype],
'bad wlan subtype '..subtype)
return { tok, subtype }
end
local function parse_wlan_dir(lexer, tok)
if (type(lexer.peek()) == 'number') then
return { tok, lexer.next() }
end
return { tok, parse_enum_arg(lexer, wlan_directions) }
end
local function parse_optional_int(lexer, tok)
if (type(lexer.peek()) == 'number') then
return { tok, lexer.next() }
end
return { tok }
end
local src_or_dst_types = {
host = unary(parse_host_arg),
net = unary(parse_net_arg),
port = unary(parse_port_arg),
portrange = unary(parse_portrange_arg)
}
local ether_host_type = {
host = unary(parse_ehost_arg)
}
local ether_types = {
dst = table_parser(ether_host_type, unary(parse_ehost_arg)),
src = table_parser(ether_host_type, unary(parse_ehost_arg)),
host = unary(parse_ehost_arg),
broadcast = nullary(),
multicast = nullary(),
proto = unary(parse_ether_proto_arg),
}
local ip_types = {
dst = table_parser(src_or_dst_types, unary(parse_host_arg)),
src = table_parser(src_or_dst_types, unary(parse_host_arg)),
host = unary(parse_host_arg),
proto = unary(parse_ip_proto_arg),
protochain = unary(parse_ip_proto_arg),
broadcast = nullary(),
multicast = nullary(),
}
local ip6_types = {
proto = unary(parse_ip_proto_arg),
protochain = unary(parse_ip_proto_arg),
broadcast = nullary(),
multicast = nullary(),
}
local decnet_host_type = {
host = unary(parse_decnet_host_arg),
}
local decnet_types = {
src = table_parser(decnet_host_type, unary(parse_decnet_host_arg)),
dst = table_parser(decnet_host_type, unary(parse_decnet_host_arg)),
host = unary(parse_decnet_host_arg),
}
local wlan_types = {
ra = unary(parse_ehost_arg),
ta = unary(parse_ehost_arg),
addr1 = unary(parse_ehost_arg),
addr2 = unary(parse_ehost_arg),
addr3 = unary(parse_ehost_arg),
addr4 = unary(parse_ehost_arg),
-- As an alias of 'ether'
dst = table_parser(ether_host_type, unary(parse_ehost_arg)),
src = table_parser(ether_host_type, unary(parse_ehost_arg)),
host = unary(parse_ehost_arg),
broadcast = nullary(),
multicast = nullary(),
proto = unary(parse_ether_proto_arg),
}
local iso_types = {
proto = unary(parse_iso_proto_arg),
ta = unary(parse_ehost_arg),
addr1 = unary(parse_ehost_arg),
addr2 = unary(parse_ehost_arg),
addr3 = unary(parse_ehost_arg),
addr4 = unary(parse_ehost_arg),
}
local tcp_or_udp_types = {
port = unary(parse_port_arg),
portrange = unary(parse_portrange_arg),
dst = table_parser(src_or_dst_types),
src = table_parser(src_or_dst_types),
}
local arp_types = {
dst = table_parser(src_or_dst_types, unary(parse_host_arg)),
src = table_parser(src_or_dst_types, unary(parse_host_arg)),
host = unary(parse_host_arg),
}
local rarp_types = {
dst = table_parser(src_or_dst_types, unary(parse_host_arg)),
src = table_parser(src_or_dst_types, unary(parse_host_arg)),
host = unary(parse_host_arg),
}
local parse_arithmetic
local function parse_addressable(lexer, tok)
if not tok then
tok = lexer.next({maybe_arithmetic=true})
if not addressables[tok] then
lexer.error('bad token while parsing addressable: %s', tok)
end
end
lexer.consume('[')
local pos = parse_arithmetic(lexer)
local size = 1
if lexer.check(':') then
if lexer.check(1) then size = 1
elseif lexer.check(2) then size = 2
else lexer.consume(4); size = 4 end
end
lexer.consume(']')
return { '['..tok..']', pos, size}
end
local function parse_primary_arithmetic(lexer, tok)
tok = tok or lexer.next({maybe_arithmetic=true})
if tok == '(' then
local expr = parse_arithmetic(lexer)
lexer.consume(')')
return expr
elseif tok == 'len' or type(tok) == 'number' then
return tok
elseif allow_address_of and tok == '&' then
return { 'addr', parse_addressable(lexer) }
elseif addressables[tok] then
return parse_addressable(lexer, tok)
else
-- 'tok' may be a constant
local val = constants.protocol_header_field_offsets[tok] or
constants.icmp_type_fields[tok] or
constants.tcp_flag_fields[tok]
if val ~= nil then return val end
lexer.error('bad token while parsing arithmetic expression %s', tok)
end
end
local arithmetic_precedence = {
['*'] = 1, ['/'] = 1,
['+'] = 2, ['-'] = 2,
['<<'] = 3, ['>>'] = 3,
['&'] = 4,
['^'] = 5,
['|'] = 6
}
function parse_arithmetic(lexer, tok, max_precedence, parsed_exp)
local exp = parsed_exp or parse_primary_arithmetic(lexer, tok)
max_precedence = max_precedence or math.huge
while true do
local op = lexer.peek()
local prec = arithmetic_precedence[op]
if not prec or prec > max_precedence then return exp end
lexer.consume(op)
local rhs = parse_arithmetic(lexer, nil, prec - 1)
exp = { op, exp, rhs }
end
end
local primitives = {
dst = table_parser(src_or_dst_types, unary(parse_host_arg)),
src = table_parser(src_or_dst_types, unary(parse_host_arg)),
host = unary(parse_host_arg),
ether = table_parser(ether_types),
fddi = table_parser(ether_types),
tr = table_parser(ether_types),
wlan = table_parser(wlan_types),
broadcast = nullary(),
multicast = nullary(),
gateway = unary(parse_string_arg),
net = unary(parse_net_arg),
port = unary(parse_port_arg),
portrange = unary(parse_portrange_arg),
less = unary(parse_arithmetic),
greater = unary(parse_arithmetic),
ip = table_parser(ip_types, nullary()),
ip6 = table_parser(ip6_types, nullary()),
proto = unary(parse_proto_arg),
tcp = table_parser(tcp_or_udp_types, nullary()),
udp = table_parser(tcp_or_udp_types, nullary()),
icmp = nullary(),
icmp6 = nullary(),
igmp = nullary(),
igrp = nullary(),
pim = nullary(),
ah = nullary(),
esp = nullary(),
vrrp = nullary(),
sctp = nullary(),
protochain = unary(parse_proto_arg),
arp = table_parser(arp_types, nullary()),
rarp = table_parser(rarp_types, nullary()),
atalk = nullary(),
aarp = nullary(),
decnet = table_parser(decnet_types, nullary()),
iso = nullary(),
stp = nullary(),
ipx = nullary(),
netbeui = nullary(),
sca = nullary(),
lat = nullary(),
moprc = nullary(),
mopdl = nullary(),
llc = parse_llc,
ifname = unary(parse_string_arg),
on = unary(parse_string_arg),
rnr = unary(parse_int_arg),
rulenum = unary(parse_int_arg),
reason = unary(enum_arg_parser(pf_reasons)),
rset = unary(parse_string_arg),
ruleset = unary(parse_string_arg),
srnr = unary(parse_int_arg),
subrulenum = unary(parse_int_arg),
action = unary(enum_arg_parser(pf_actions)),
type = parse_wlan_type,
subtype = parse_wlan_subtype,
dir = unary(enum_arg_parser(wlan_directions)),
vlan = parse_optional_int,
mpls = parse_optional_int,
pppoed = nullary(),
pppoes = parse_optional_int,
iso = table_parser(iso_types, nullary()),
clnp = nullary(),
esis = nullary(),
isis = nullary(),
l1 = nullary(),
l2 = nullary(),
iih = nullary(),
lsp = nullary(),
snp = nullary(),
csnp = nullary(),
psnp = nullary(),
vpi = unary(parse_int_arg),
vci = unary(parse_int_arg),
lane = nullary(),
oamf4s = nullary(),
oamf4e = nullary(),
oamf4 = nullary(),
oam = nullary(),
metac = nullary(),
bcc = nullary(),
sc = nullary(),
ilmic = nullary(),
connectmsg = nullary(),
metaconnect = nullary()
}
local function parse_primitive_or_arithmetic(lexer)
local tok = lexer.next({maybe_arithmetic=true})
if (type(tok) == 'number' or tok == 'len' or
addressables[tok] and lexer.peek() == '[') then
return parse_arithmetic(lexer, tok)
end
local parser = primitives[tok]
if parser then return parser(lexer, tok) end
-- At this point the official pcap grammar is squirrely. It says:
-- "If an identifier is given without a keyword, the most recent
-- keyword is assumed. For example, `not host vs and ace' is
-- short for `not host vs and host ace` and which should not be
-- confused with `not (host vs or ace)`." For now we punt on this
-- part of the grammar.
local msg =
[[%s is not a recognized keyword. Likely causes:
a) %s is a typo, invalid keyword, or similar error.
b) You're trying to implicitly repeat the previous clause's keyword.
Instead of libpcap-style elision, explicitly use keywords in each clause:
ie, "host a and host b", not "host a and b".]]
local err = string.format(msg, tok, tok)
lexer.error(err)
end
local logical_ops = set('&&', 'and', '||', 'or')
local function is_arithmetic(exp)
return (exp == 'len' or type(exp) == 'number' or
exp[1]:match("^%[") or arithmetic_precedence[exp[1]])
end
local parse_logical
local function parse_logical_or_arithmetic(lexer, pick_first)
local exp
if lexer.peek() == 'not' or lexer.peek() == '!' then
exp = { lexer.next(), parse_logical(lexer, true) }
elseif lexer.check('(') then
exp = parse_logical_or_arithmetic(lexer)
lexer.consume(')')
else
exp = parse_primitive_or_arithmetic(lexer)
end
if is_arithmetic(exp) then
if arithmetic_precedence[lexer.peek()] then
exp = parse_arithmetic(lexer, nil, nil, exp)
end
if lexer.peek() == ')' then return exp end
local op = lexer.next()
assert(set('>', '<', '>=', '<=', '=', '!=', '==')[op],
"expected a comparison operator, got "..op)
-- Normalize == to =, because libpcap treats them identically
if op == '==' then op = '=' end
exp = { op, exp, parse_arithmetic(lexer) }
end
if pick_first then return exp end
while true do
local op = lexer.peek()
if not op or op == ')' then return exp end
local is_logical = logical_ops[op]
if is_logical then
lexer.consume(op)
else
-- The grammar is such that "tcp port 80" should actually
-- parse as "tcp and port 80".
op = 'and'
end
local rhs = parse_logical(lexer, true)
exp = { op, exp, rhs }
end
end
function parse_logical(lexer, pick_first)
local expr = parse_logical_or_arithmetic(lexer, pick_first)
assert(not is_arithmetic(expr), "expected a logical expression")
return expr
end
function parse(str, opts)
opts = opts or {}
local lexer = tokens(str)
local expr
if opts.arithmetic then
expr = parse_arithmetic(lexer)
else
if not lexer.peek({maybe_arithmetic=true}) then return { 'true' } end
expr = parse_logical(lexer)
end
if lexer.peek() then error("unexpected token "..lexer.peek()) end
return expr
end
function selftest ()
print("selftest: pf.parse")
local function check(expected, actual)
assert(type(expected) == type(actual),
"expected type "..type(expected).." but got "..type(actual))
if type(expected) == 'table' then
for k, v in pairs(expected) do check(v, actual[k]) end
else
assert(expected == actual, "expected "..expected.." but got "..actual)
end
end
local function lex_test(str, elts, opts)
local lexer = tokens(str)
for i, val in ipairs(elts) do
check(val, lexer.next(opts))
end
assert(not lexer.peek(opts), "more tokens, yo")
end
lex_test("ip", {"ip"}, {maybe_arithmetic=true})
lex_test("len", {"len"}, {maybe_arithmetic=true})
lex_test("len", {"len"}, {})
lex_test("len-1", {"len-1"}, {})
lex_test("len-1", {"len", "-", 1}, {maybe_arithmetic=true})
lex_test("1-len", {1, "-", "len"}, {maybe_arithmetic=true})
lex_test("1-len", {"1-len"}, {})
lex_test("tcp port 80", {"tcp", "port", 80}, {})
lex_test("tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)",
{ 'tcp', 'port', 80, 'and',
'(', '(',
'(',
'ip', '[', 2, ':', 2, ']', '-',
'(', '(', 'ip', '[', 0, ']', '&', 15, ')', '<<', 2, ')',
')',
'-',
'(', '(', 'tcp', '[', 12, ']', '&', 240, ')', '>>', 2, ')',
')', '!=', 0, ')'
}, {maybe_arithmetic=true})
lex_test("127.0.0.1", { { 'ipv4', 127, 0, 0, 1 } }, {address=true})
lex_test("::", { { 'ipv6', 0, 0, 0, 0, 0, 0, 0, 0 } }, {address=true})