ffho_netfilter.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. #
  2. # FFHO netfilter helper functions
  3. #
  4. import ipaddress
  5. import re
  6. import ffho_net
  7. # Prepare regex to match VLAN intefaces / extract IDs
  8. vlan_re = re.compile (r'^vlan(\d+)$')
  9. ################################################################################
  10. # Internal helper functions #
  11. ################################################################################
  12. #
  13. # Check if at least one of the node roles are supposed to run DHCP
  14. def _allow_dhcp (fw_policy, roles):
  15. for dhcp_role in fw_policy.get ('dhcp_roles', []):
  16. if dhcp_role in roles:
  17. return True
  18. return False
  19. # Generate services rules for the given AF
  20. def _generate_service_rules (services, acls, af):
  21. rules = []
  22. for srv in services:
  23. rule = ""
  24. comment = srv['descr']
  25. acl_comment = ""
  26. src_prefixes = []
  27. # If there are no DST IPs set at all or DST IPs for this AF set, we have a rule to build,
  28. # if this is NOT the case, there is no rule for this AF to generate, carry on.
  29. if not ((not srv['ips']['4'] and not srv['ips']['6']) or srv['ips'][str(af)]):
  30. continue
  31. # Is/are IP(s) set for this service?
  32. if srv['ips'][str(af)]:
  33. rule += "ip" if af == 4 else "ip6"
  34. dst_ips = srv['ips'][str(af)]
  35. if len (dst_ips) == 1:
  36. rule += " daddr %s " % dst_ips[0]
  37. else:
  38. rule += " daddr { %s } " % ", ".join (dst_ips)
  39. # ACLs defined for this service?
  40. if srv['acl']:
  41. srv_acl = sorted (srv['acl'])
  42. for ace in srv_acl:
  43. ace_pfx = (acls[ace][af])
  44. # Many entries
  45. if type (ace_pfx) == list:
  46. src_prefixes.extend (ace_pfx)
  47. else:
  48. src_prefixes.append (ace_pfx)
  49. acl_comment = "acl: %s" % ", ".join (srv_acl)
  50. # Additional prefixes defined for this service?
  51. if srv['additional_prefixes']:
  52. add_pfx = []
  53. # Additional prefixes are given as a space separated list
  54. for entry in srv['additional_prefixes'].split ():
  55. # Strip commas and spaces, just in case
  56. pfx_str = entry.strip (" ,")
  57. pfx_obj = ipaddress.ip_network (pfx_str)
  58. # We only care for additional pfx for this AF
  59. if pfx_obj.version != af:
  60. continue
  61. add_pfx.append (pfx_str)
  62. if add_pfx:
  63. src_prefixes.extend (add_pfx)
  64. if acl_comment:
  65. acl_comment += ", "
  66. acl_comment += "additional pfx"
  67. # Combine ACL + additional prefixes (if any)
  68. if src_prefixes:
  69. rule += "ip" if af == 4 else "ip6"
  70. if len (src_prefixes) > 1:
  71. rule += " saddr { %s } " % ", ".join (src_prefixes)
  72. else:
  73. rule += " saddr %s " % src_prefixes[0]
  74. if acl_comment:
  75. comment += " (%s)" % acl_comment
  76. # Multiple ports?
  77. if len (srv['ports']) > 1:
  78. ports = "{ %s }" % ", ".join (map (str, srv['ports']))
  79. else:
  80. ports = srv['ports'][0]
  81. rule += "%s dport %s counter accept comment \"%s\"" % (srv['proto'], ports, comment)
  82. rules.append (rule)
  83. return rules
  84. ################################################################################
  85. # Public functions #
  86. ################################################################################
  87. #
  88. # Generate rules to allow access to services running on this node.
  89. # Services can either be allow programmatically here or explicitly
  90. # as Services applied to the device/VM in Netbox
  91. def generate_service_rules (fw_config, node_config):
  92. acls = fw_config.get ('acls', {})
  93. fw_policy = fw_config.get ('policy', {})
  94. services = node_config.get ('services', [])
  95. roles = node_config.get ('roles', [])
  96. rules = {
  97. 4 : [],
  98. 6 : [],
  99. }
  100. # Does this node run a DHCP server?
  101. if _allow_dhcp (fw_policy, roles):
  102. rules[4].append ('udp dport 67 counter accept comment "DHCP"')
  103. # Allow respondd queries on gateways
  104. if 'batman_gw' in roles:
  105. rules[6].append ('ip6 saddr fe80::/64 ip6 daddr ff05::2:1001 udp dport 1001 counter accept comment "responnd"')
  106. # Generate rules for services from Netbox
  107. for af in [ 4, 6 ]:
  108. rules[af].extend (_generate_service_rules (services, acls, af))
  109. return rules
  110. def generate_forward_policy (fw_config, node_config):
  111. policy = fw_config.get ('policy', {})
  112. roles = node_config.get ('roles', [])
  113. nf_cc = node_config.get ('nftables', {})
  114. fp = {
  115. # Get default policy for packets to be forwarded
  116. 'policy' : 'drop',
  117. 'policy_reason' : 'default',
  118. 'rules': {
  119. 4 : [],
  120. 6 : [],
  121. },
  122. }
  123. if 'forward_default_policy' in policy:
  124. fp['policy'] = policy['forward_default_policy']
  125. fp['policy_reason'] = 'forward_default_policy'
  126. # Does any local role warrants for forwarding packets?
  127. accept_roles = [role for role in policy.get ('forward_accept_roles', []) if role in roles]
  128. if accept_roles:
  129. fp['policy'] = 'accept'
  130. fp['policy_reason'] = "roles: " + ",".join (accept_roles)
  131. try:
  132. cust_rules = nf_cc['filter']['forward']
  133. for af in [ 4, 6 ]:
  134. if af not in cust_rules:
  135. continue
  136. if type (cust_rules[af]) != list:
  137. raise ValueError ("nftables:filter:forward:%d in config context expected to be a list!" % af)
  138. fp['rules'][af] = cust_rules[af]
  139. except KeyError:
  140. pass
  141. return fp
  142. def generate_nat_policy (node_config):
  143. roles = node_config.get ('roles', [])
  144. nf_cc = node_config.get ('nftables', {})
  145. np = {
  146. 4 : {},
  147. 6 : {},
  148. }
  149. # Any custom rules?
  150. cc_nat = nf_cc.get ('nat')
  151. if cc_nat:
  152. for chain in ['output', 'prerouting', 'postrouting']:
  153. if chain not in cc_nat:
  154. continue
  155. for af in [ 4, 6 ]:
  156. if str (af) in cc_nat[chain]:
  157. np[af][chain] = cc_nat[chain][str (af)]
  158. return np
  159. def _active_urpf (iface, iface_config):
  160. # Ignore loopbacks
  161. if iface == 'lo' or iface_config.get ('link-type', '') == 'dummy':
  162. return False
  163. # Forcefully enable uRPF via tags on Netbox interface?
  164. if 'urpf_enable' in iface_config.get ('tags', []):
  165. return True
  166. # No uRPF on infra VPNs
  167. for vpn_prefix in ["gre_", "ovpn-", "wg-"]:
  168. if iface.startswith (vpn_prefix):
  169. return False
  170. # No address, no uRPF
  171. if not iface_config.get ('prefixes'):
  172. return False
  173. # Interface in vrf_external connect to the Internet
  174. if iface_config.get ('vrf') in ['vrf_external']:
  175. return False
  176. # Ignore interfaces by VLAN
  177. match = vlan_re.search (iface)
  178. if match:
  179. vid = int (match.group (1))
  180. # Magic
  181. if 900 <= vid <= 999:
  182. return False
  183. # Wired infrastructure stuff
  184. if 1000 <= vid <= 1499:
  185. return False
  186. # Wireless infrastructure stuff
  187. if 2000 <= vid <= 2299:
  188. return False
  189. return True
  190. def generate_urpf_policy (interfaces):
  191. urpf = {}
  192. for iface in sorted (interfaces.keys ()):
  193. iface_config = interfaces[iface]
  194. if not _active_urpf (iface, iface_config):
  195. continue
  196. # Ok this seems to be and edge interface
  197. urpf[iface] = {
  198. 'iface' : iface,
  199. 'desc' : iface_config.get ('desc', ''),
  200. 4 : [],
  201. 6 : [],
  202. }
  203. # Gather configure prefixes
  204. for address in iface_config.get ('prefixes'):
  205. pfx = ipaddress.ip_network (address, strict = False)
  206. urpf[iface][pfx.version].append ("%s/%s" % (pfx.network_address, pfx.prefixlen))
  207. sorted_urpf = []
  208. for iface in ffho_net.get_interface_list (urpf):
  209. sorted_urpf.append (urpf[iface])
  210. return sorted_urpf
  211. #
  212. # Get a list of interfaces to allow VXLAN encapsulated traffic on
  213. def get_vxlan_interfaces (interfaces):
  214. vxlan_ifaces = []
  215. for iface in interfaces:
  216. if interfaces[iface].get ('batman_connect_sites'):
  217. vxlan_ifaces.append (iface)
  218. return vxlan_ifaces