15 class ASTAction(Enum):
23 def __init__(self, action, left, right=None):
25 if action == ASTAction.FALSE or action == ASTAction.TRUE:
26 assert left is None and right is None
30 assert action == ASTAction.EXPR or action == ASTAction.NOT
34 def write(self, expr_param, expr_param2=None):
35 if self.action == ASTAction.OR:
36 return "(" + self.left.write(expr_param, expr_param2) + ") || (" + self.right.write(expr_param, expr_param2) + ")"
37 if self.action == ASTAction.AND:
38 return "(" + self.left.write(expr_param, expr_param2) + ") && (" + self.right.write(expr_param, expr_param2) + ")"
39 if self.action == ASTAction.NOT:
40 return "!(" + self.left.write(expr_param, expr_param2) + ")"
41 if self.action == ASTAction.FALSE:
43 if self.action == ASTAction.TRUE:
45 if self.action == ASTAction.EXPR:
46 return self.left.write(expr_param, expr_param2)
48 def parse_ast(expr, parse_expr, comma_is_or):
51 comma_split = expr.split(",", 1)
52 or_split = expr.split("||", 1)
53 if len(comma_split) > 1 and not "||" in comma_split[0]:
54 # Confusingly, BIRD uses `,` as either || or &&, depending on the type
55 # of expression being parsed. Specifically, a `numbers-match` uses `,`
56 # as OR, whereas a `bitmask-match` uses `,` as AND.
58 return ASTNode(ASTAction.OR, parse_ast(comma_split[0], parse_expr, comma_is_or), parse_ast(comma_split[1], parse_expr, comma_is_or))
60 return ASTNode(ASTAction.AND, parse_ast(comma_split[0], parse_expr, comma_is_or), parse_ast(comma_split[1], parse_expr, comma_is_or))
62 assert not "," in or_split[0]
63 return ASTNode(ASTAction.OR, parse_ast(or_split[0], parse_expr, comma_is_or), parse_ast(or_split[1], parse_expr, comma_is_or))
65 and_split = expr.split("&&", 1)
66 if len(and_split) > 1:
67 return ASTNode(ASTAction.AND, parse_ast(and_split[0], parse_expr, comma_is_or), parse_ast(and_split[1], parse_expr, comma_is_or))
69 if expr.strip() == "true":
70 return ASTNode(ASTAction.TRUE, None)
71 if expr.strip() == "false":
72 return ASTNode(ASTAction.FALSE, None)
74 if expr.startswith("!"):
75 return ASTNode(ASTAction.NOT, parse_ast(expr[1:], parse_expr, comma_is_or))
77 return parse_expr(expr)
80 class NumbersAction(Enum):
87 def __init__(self, action, val):
91 def write(self, param, param2):
92 if param2 is not None:
93 return "(" + param + self.action.value + self.val + ") || (" + param2 + self.action.value + self.val + ")"
94 return param + self.action.value + self.val
96 def parse_numbers_expr(expr):
97 space_split = expr.split(" ")
98 if expr.startswith(">="):
99 assert len(space_split) == 2
100 return ASTNode(ASTAction.EXPR, NumbersExpr(NumbersAction.GTOE, space_split[1]))
101 if expr.startswith(">"):
102 assert len(space_split) == 2
103 return ASTNode(ASTAction.EXPR, NumbersExpr(NumbersAction.GT, space_split[1]))
104 if expr.startswith("<="):
105 assert len(space_split) == 2
106 return ASTNode(ASTAction.EXPR, NumbersExpr(NumbersAction.LTOE, space_split[1]))
107 if expr.startswith("<"):
108 assert len(space_split) == 2
109 return ASTNode(ASTAction.EXPR, NumbersExpr(NumbersAction.LT, space_split[1]))
111 rangesplit = expr.split("..")
112 assert len(rangesplit) == 2
113 #XXX: Are ranges really inclusive,inclusive?
114 left = ASTNode(ASTAction.EXPR, NumbersExpr(NumbersAction.GTOE, rangesplit[0]))
115 right = ASTNode(ASTAction.EXPR, NumbersExpr(NumbersAction.LTOE, rangesplit[1]))
116 return ASTNode(ASTAction.AND, left, right)
118 if expr.startswith("= "):
120 return ASTNode(ASTAction.EXPR, NumbersExpr(NumbersAction.EQ, expr))
122 class FragExpr(Enum):
128 def write(self, ipproto, _param2):
130 if self == FragExpr.IF:
131 return "(ip->frag_off & BE16(IP_MF|IP_OFFSET)) != 0"
132 elif self == FragExpr.FF:
133 return "((ip->frag_off & BE16(IP_MF)) != 0 && (ip->frag_off & BE16(IP_OFFSET)) == 0)"
134 elif self == FragExpr.DF:
135 return "(ip->frag_off & BE16(IP_DF)) != 0"
136 elif self == FragExpr.LF:
137 return "((ip->frag_off & BE16(IP_MF)) == 0 && (ip->frag_off & BE16(IP_OFFSET)) != 0)"
141 if self == FragExpr.IF:
142 return "frag6 != NULL"
143 elif self == FragExpr.FF:
144 return "(frag6 != NULL && (frag6->frag_off & BE16(IP6_MF)) != 0 && (frag6->frag_off & BE16(IP6_FRAGOFF)) == 0)"
145 elif self == FragExpr.DF:
146 assert False # No such thing in v6
147 elif self == FragExpr.LF:
148 return "(frag6 != NULL && (frag6->frag_off & BE16(IP6_MF)) == 0 && (frag6->frag_off & BE16(IP6_FRAGOFF)) != 0)"
152 def parse_frag_expr(expr):
153 if expr == "is_fragment":
154 return ASTNode(ASTAction.EXPR, FragExpr.IF)
155 elif expr == "first_fragment":
156 return ASTNode(ASTAction.EXPR, FragExpr.FF)
157 elif expr == "dont_fragment":
158 return ASTNode(ASTAction.EXPR, FragExpr.DF)
159 elif expr == "last_fragment":
160 return ASTNode(ASTAction.EXPR, FragExpr.LF)
165 def __init__(self, val):
171 def write(self, param, _param2):
172 return f"({param} & {self.mask}) == {self.match}"
174 def parse_bit_expr(expr):
175 return ASTNode(ASTAction.EXPR, BitExpr(expr))
178 def ip_to_rule(proto, inip, ty, offset):
180 assert offset is None
181 net = ipaddress.IPv4Network(inip.strip())
182 if net.prefixlen == 0:
184 return f"""if ((ip->{ty} & MASK4({net.prefixlen})) != BIGEND32({int(net.network_address)}ULL))
187 net = ipaddress.IPv6Network(inip.strip())
188 if net.prefixlen == 0:
190 u32s = [(int(net.network_address) >> (3*32)) & 0xffffffff,
191 (int(net.network_address) >> (2*32)) & 0xffffffff,
192 (int(net.network_address) >> (1*32)) & 0xffffffff,
193 (int(net.network_address) >> (0*32)) & 0xffffffff]
195 mask = f"MASK6({net.prefixlen})"
197 mask = f"MASK6_OFFS({offset}, {net.prefixlen})"
198 return f"""if ((ip6->{ty} & {mask}) != (BIGEND128({u32s[0]}ULL, {u32s[1]}ULL, {u32s[2]}ULL, {u32s[3]}ULL) & {mask}))
201 def fragment_to_rule(ipproto, rules):
202 ast = parse_ast(rules, parse_frag_expr, False)
203 return "if (!( " + ast.write(ipproto) + " )) break;"
205 def len_to_rule(rules):
206 ast = parse_ast(rules, parse_numbers_expr, True)
207 return "if (!( " + ast.write("(data_end - pktdata)") + " )) break;"
209 def proto_to_rule(ipproto, proto):
210 ast = parse_ast(proto, parse_numbers_expr, True)
213 return "if (!( " + ast.write("ip->protocol") + " )) break;"
215 return "if (!( " + ast.write("ip6->nexthdr") + " )) break;"
217 def icmp_type_to_rule(proto, ty):
218 ast = parse_ast(ty, parse_numbers_expr, True)
220 return "if (icmp == NULL) break;\nif (!( " + ast.write("icmp->type") + " )) break;"
222 return "if (icmpv6 == NULL) break;\nif (!( " + ast.write("icmpv6->icmp6_type") + " )) break;"
224 def icmp_code_to_rule(proto, code):
225 ast = parse_ast(code, parse_numbers_expr, True)
227 return "if (icmp == NULL) break;\nif (!( " + ast.write("icmp->code") + " )) break;"
229 return "if (icmpv6 == NULL) break;\nif (!( " + ast.write("icmpv6->icmp6_code") + " )) break;"
231 def dscp_to_rule(proto, rules):
232 ast = parse_ast(rules, parse_numbers_expr, True)
235 return "if (!( " + ast.write("((ip->tos & 0xfc) >> 2)") + " )) break;"
237 return "if (!( " + ast.write("((ip6->priority << 2) | ((ip6->flow_lbl[0] & 0xc0) >> 6))") + " )) break;"
239 def port_to_rule(ty, rules):
241 ast = parse_ast(rules, parse_numbers_expr, True)
242 return "if (sport == -1 || dport == -1) break;\nif (!( " + ast.write("sport", "dport") + " )) break;"
244 ast = parse_ast(rules, parse_numbers_expr, True)
245 return "if (" + ty + " == -1) break;\nif (!( " + ast.write(ty) + " )) break;"
247 def tcp_flags_to_rule(rules):
248 ast = parse_ast(rules, parse_bit_expr, False)
250 return f"""if (tcp == NULL) break;
251 if (!( {ast.write("(ntohs(tcp->flags) & 0xfff)")} )) break;"""
253 def flow_label_to_rule(rules):
254 ast = parse_ast(rules, parse_bit_expr, False)
256 return f"""if (ip6 == NULL) break;
257 if (!( {ast.write("((((uint32_t)(ip6->flow_lbl[0] & 0xf)) << 2*8) | (((uint32_t)ip6->flow_lbl[1]) << 1*8) | (uint32_t)ip6->flow_lbl[0])")} )) break;"""
260 with open("rules.h", "w") as out:
261 parse = argparse.ArgumentParser()
262 parse.add_argument("--ihl", dest="ihl", required=True, choices=["drop-options","accept-options","parse-options"])
263 parse.add_argument("--v6frag", dest="v6frag", required=True, choices=["drop-frags","ignore","parse-frags","ignore-parse-if-rule"])
264 parse.add_argument("--8021q", dest="vlan", required=True, choices=["drop-vlan","accept-vlan","parse-vlan"])
265 parse.add_argument("--require-8021q", dest="vlan_tag")
266 args = parse.parse_args(sys.argv[1:])
268 if args.ihl == "drop-options":
269 out.write("#define PARSE_IHL XDP_DROP\n")
270 elif args.ihl == "accept-options":
271 out.write("#define PARSE_IHL XDP_PASS\n")
272 elif args.ihl == "parse-options":
273 out.write("#define PARSE_IHL PARSE\n")
275 if args.v6frag == "drop-frags":
276 out.write("#define PARSE_V6_FRAG XDP_DROP\n")
277 elif args.v6frag == "ignore":
279 elif args.v6frag == "parse-frags":
280 out.write("#define PARSE_V6_FRAG PARSE\n")
282 if args.vlan == "drop-vlan":
283 out.write("#define PARSE_8021Q XDP_DROP\n")
284 elif args.vlan == "accept-vlan":
285 out.write("#define PARSE_8021Q XDP_PASS\n")
286 elif args.vlan == "parse-vlan":
287 out.write("#define PARSE_8021Q PARSE\n")
289 if args.vlan_tag is not None:
290 if args.vlan != "parse-vlan":
292 out.write("#define REQ_8021Q " + args.vlan_tag + "\n")
299 v4persrcratelimits = []
300 v5persrcratelimits = []
301 v6persrcratelimits = []
304 for line in sys.stdin.readlines():
306 if lastrule is not None:
307 print("Skipped rule due to lack of understood community tag: " + lastrule)
310 if "BGP.ext_community: " in line:
311 assert lastrule is not None
313 t = lastrule.split("{")
314 if t[0].strip() == "flow4":
316 rules4 += "\tdo {\\\n"
317 elif t[0].strip() == "flow6":
319 rules6 += "\tdo {\\\n"
323 # LLVM can be pretty bad at optimizing out common subexpressions. Ideally we'd optimize
324 # by pulling common subexpressions in back-to-back rules out into a single check, but
325 # that's a bunch of work that LLVM really should do for us. Instead, we blindly guess
326 # that source-address is the least likely to be a common subexpression and rely on LLVM
327 # managing to pull out common subexpressions as long as they're the first check(s). By
328 # placing source-address checks last, LLVM should do at least some work for us.
329 # See https://bugs.llvm.org/show_bug.cgi?id=52455
331 def write_rule(r, place_at_end=False):
332 global rules4, rules6, last_checks
334 last_checks += "\t\t" + r.replace("\n", " \\\n\t\t") + " \\\n"
336 rules6 += "\t\t" + r.replace("\n", " \\\n\t\t") + " \\\n"
338 rules4 += "\t\t" + r.replace("\n", " \\\n\t\t") + " \\\n"
340 rule = t[1].split("}")[0].strip()
341 for step in rule.split(";"):
342 if step.strip().startswith("src") or step.strip().startswith("dst"):
343 nets = step.strip()[3:].strip().split(" ")
345 assert nets[1] == "offset"
349 if step.strip().startswith("src"):
350 write_rule(ip_to_rule(proto, nets[0], "saddr", offset), True)
352 write_rule(ip_to_rule(proto, nets[0], "daddr", offset))
353 elif step.strip().startswith("proto") and proto == 4:
354 write_rule(proto_to_rule(4, step.strip()[6:]))
355 elif step.strip().startswith("next header") and proto == 6:
356 write_rule(proto_to_rule(6, step.strip()[12:]))
357 elif step.strip().startswith("icmp type"):
358 write_rule(icmp_type_to_rule(proto, step.strip()[10:]))
359 elif step.strip().startswith("icmp code"):
360 write_rule(icmp_code_to_rule(proto, step.strip()[10:]))
361 elif step.strip().startswith("sport") or step.strip().startswith("dport") or step.strip().startswith("port"):
362 write_rule(port_to_rule(step.strip().split(" ")[0], step.strip().split(" ", 1)[1]))
363 elif step.strip().startswith("length"):
364 write_rule(len_to_rule(step.strip()[7:]))
365 elif step.strip().startswith("dscp"):
366 write_rule(dscp_to_rule(proto, step.strip()[5:]))
367 elif step.strip().startswith("tcp flags"):
368 write_rule(tcp_flags_to_rule(step.strip()[10:]))
369 elif step.strip().startswith("label"):
370 write_rule(flow_label_to_rule(step.strip()[6:]))
371 elif step.strip().startswith("fragment"):
374 write_rule(fragment_to_rule(proto, step.strip()[9:]))
375 elif step.strip() == "":
381 rules6 += last_checks
383 rules4 += last_checks
385 # Now write the match handling!
389 for community in line.split("("):
390 if not community.startswith("generic, "):
392 blocks = community.split(",")
393 assert len(blocks) == 3
394 if len(blocks[1].strip()) != 10: # Should be 0x12345678
396 ty = blocks[1].strip()[:6]
397 high_byte = int(blocks[1].strip()[6:8], 16)
398 mid_byte = int(blocks[1].strip()[8:], 16)
399 low_bytes = int(blocks[2].strip(") \n"), 16)
400 if ty == "0x8006" or ty == "0x800c" or ty == "0x8306" or ty == "0x830c":
401 if first_action is not None:
402 # Two ratelimit actions, just drop the old one. RFC 8955 says we can.
404 exp = (low_bytes & (0xff << 23)) >> 23
406 first_action = "{stats_replace}\nreturn XDP_DROP;"
407 elif low_bytes & (1 << 31) != 0:
408 # Negative limit, just drop
409 first_action = "{stats_replace}\nreturn XDP_DROP;"
411 # NaN/INF. Just treat as INF and accept
413 elif exp < 127: # < 1
414 first_action = "{stats_replace}\nreturn XDP_DROP;"
415 elif exp >= 127 + 29: # We can't handle the precision required with ns this high
418 mantissa = low_bytes & ((1 << 23) - 1)
419 value = 1.0 + mantissa / (2**23)
420 value *= 2**(exp-127)
422 first_action = "int64_t time_masked = bpf_ktime_get_ns() & RATE_TIME_MASK;\n"
423 first_action += f"int64_t per_pkt_ns = (1000000000LL << RATE_BUCKET_INTEGER_BITS) / {math.floor(value)};\n"
424 if ty == "0x8006" or ty == "0x8306":
425 first_action += "uint64_t amt = data_end - pktdata;\n"
427 first_action += "uint64_t amt = 1;\n"
428 if ty == "0x8006" or ty == "0x800c":
429 first_action += f"const uint32_t ratelimitidx = {ratelimitcnt};\n"
430 first_action += "struct ratelimit *rate = bpf_map_lookup_elem(&rate_map, &ratelimitidx);\n"
432 first_action += "int matched = 0;\n"
433 first_action += "DO_RATE_LIMIT(bpf_spin_lock(&rate->lock), rate, time_masked, amt, per_pkt_ns, matched);\n"
434 first_action += "if (rate) { bpf_spin_unlock(&rate->lock); }\n"
439 first_action += f"const uint32_t srcip = ip->saddr & MASK4({mid_byte});\n"
440 first_action += f"void *rate_map = &v4_src_rate_{len(v4persrcratelimits)};\n"
441 first_action += f"int matched = check_v4_persrc_ratelimit(srcip, rate_map, {(high_byte + 1) * 4096}, time_masked, amt, per_pkt_ns);\n"
442 v4persrcratelimits.append((high_byte + 1) * 4096)
444 first_action += f"const uint64_t srcip = BE128BEHIGH64(ip6->saddr & MASK6({mid_byte}));\n"
445 first_action += f"void *rate_map = &v5_src_rate_{len(v5persrcratelimits)};\n"
446 first_action += f"int matched = check_v5_persrc_ratelimit(srcip, rate_map, {(high_byte + 1) * 4096}, time_masked, amt, per_pkt_ns);\n"
447 v5persrcratelimits.append((high_byte + 1) * 4096)
451 first_action += f"const uint128_t srcip = ip6->saddr & MASK6({mid_byte});\n"
452 first_action += f"void *rate_map = &v6_src_rate_{len(v6persrcratelimits)};\n"
453 first_action += f"int matched = check_v6_persrc_ratelimit(srcip, rate_map, {(high_byte + 1) * 4096}, time_masked, amt, per_pkt_ns);\n"
454 v6persrcratelimits.append((high_byte + 1) * 4096)
455 first_action += "if (matched) {\n"
456 first_action += "\t{stats_replace}\n"
457 first_action += "\treturn XDP_DROP;\n"
458 first_action += "}\n"
460 if low_bytes & 1 == 0:
461 last_action = "return XDP_PASS;"
462 if low_bytes & 2 == 2:
463 stats_action = f"const uint32_t ruleidx = STATIC_RULE_CNT + {stats_rulecnt};\n"
464 stats_action += "INCREMENT_MATCH(ruleidx);"
466 assert False # We do not implement the redirect action
468 if low_bytes & ~0b111111 != 0:
469 assert False # Invalid DSCP value
471 write_rule("int32_t chk = ~BE16(ip->check) & 0xffff;")
472 write_rule("uint8_t orig_tos = ip->tos;")
473 write_rule("ip->tos = (ip->tos & 3) | " + str(low_bytes << 2) + ";")
474 write_rule("chk = (chk - orig_tos + ip->tos);")
475 write_rule("if (unlikely(chk > 0xffff)) { chk -= 65535; }")
476 write_rule("else if (unlikely(chk < 0)) { chk += 65535; }")
477 write_rule("ip->check = ~BE16(chk);")
479 write_rule("ip6->priority = " + str(low_bytes >> 2) + ";")
480 write_rule("ip6->flow_lbl[0] = (ip6->flow_lbl[0] & 0x3f) | " + str((low_bytes & 3) << 6) + ";")
481 if first_action is not None:
482 write_rule(first_action.replace("{stats_replace}", stats_action))
483 if stats_action != "" and (first_action is None or "{stats_replace}" not in first_action):
484 write_rule(stats_action)
485 if last_action is not None:
486 write_rule(last_action)
488 rules6 += "\t} while(0);\\\n"
490 rules4 += "\t} while(0);\\\n"
491 if stats_action != "":
497 out.write(f"#define STATS_RULECNT {stats_rulecnt}\n")
498 if ratelimitcnt != 0:
499 out.write(f"#define RATE_CNT {ratelimitcnt}\n")
501 out.write("#define NEED_V4_PARSE\n")
502 out.write("#define RULES4 {\\\n" + rules4 + "}\n")
504 out.write("#define NEED_V6_PARSE\n")
505 out.write("#define RULES6 {\\\n" + rules6 + "}\n")
506 if args.v6frag == "ignore-parse-if-rule":
508 out.write("#define PARSE_V6_FRAG PARSE\n")
509 with open("maps.h", "w") as out:
510 for idx, limit in enumerate(v4persrcratelimits):
511 out.write(f"SRC_RATE_DEFINE(4, {idx}, {limit})\n")
512 for idx, limit in enumerate(v5persrcratelimits):
513 out.write(f"SRC_RATE_DEFINE(5, {idx}, {limit})\n")
514 for idx, limit in enumerate(v6persrcratelimits):
515 out.write(f"SRC_RATE_DEFINE(6, {idx}, {limit})\n")