firewall.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. # vim: fileencoding=utf-8
  2. #
  3. # The Qubes OS Project, https://www.qubes-os.org/
  4. #
  5. # Copyright (C) 2016
  6. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. #
  22. import logging
  23. import os
  24. import socket
  25. import subprocess
  26. import shutil
  27. import daemon
  28. import qubesdb
  29. import sys
  30. import signal
  31. class RuleParseError(Exception):
  32. pass
  33. class RuleApplyError(Exception):
  34. pass
  35. class FirewallWorker(object):
  36. def __init__(self):
  37. self.terminate_requested = False
  38. self.qdb = qubesdb.QubesDB()
  39. self.log = logging.getLogger('qubes.firewall')
  40. self.log.addHandler(logging.StreamHandler(sys.stderr))
  41. def init(self):
  42. """Create appropriate chains/tables"""
  43. raise NotImplementedError
  44. def sd_notify(self, state):
  45. """Send notification to systemd, if available"""
  46. # based on sdnotify python module
  47. if 'NOTIFY_SOCKET' not in os.environ:
  48. return
  49. addr = os.environ['NOTIFY_SOCKET']
  50. if addr[0] == '@':
  51. addr = '\0' + addr[1:]
  52. try:
  53. sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
  54. sock.connect(addr)
  55. sock.sendall(state.encode())
  56. except:
  57. # generally ignore error on systemd notification
  58. pass
  59. def cleanup(self):
  60. """Remove tables/chains - reverse work done by init"""
  61. raise NotImplementedError
  62. def apply_rules(self, source_addr, rules):
  63. """Apply rules in given source address"""
  64. raise NotImplementedError
  65. def update_connected_ips(self, family):
  66. raise NotImplementedError
  67. def get_connected_ips(self, family):
  68. ips = self.qdb.read('/connected-ips6' if family == 6 else '/connected-ips')
  69. if ips is None:
  70. return []
  71. return ips.decode().split()
  72. def run_firewall_dir(self):
  73. """Run scripts dir contents, before user script"""
  74. script_dir_paths = ['/etc/qubes/qubes-firewall.d',
  75. '/rw/config/qubes-firewall.d']
  76. for script_dir_path in script_dir_paths:
  77. if not os.path.isdir(script_dir_path):
  78. continue
  79. for d_script in sorted(os.listdir(script_dir_path)):
  80. d_script_path = os.path.join(script_dir_path, d_script)
  81. if os.path.isfile(d_script_path) and \
  82. os.access(d_script_path, os.X_OK):
  83. subprocess.call([d_script_path])
  84. def run_user_script(self):
  85. """Run user script in /rw/config"""
  86. user_script_path = '/rw/config/qubes-firewall-user-script'
  87. if os.path.isfile(user_script_path) and \
  88. os.access(user_script_path, os.X_OK):
  89. subprocess.call([user_script_path])
  90. def read_rules(self, target):
  91. """Read rules from QubesDB and return them as a list of dicts"""
  92. entries = self.qdb.multiread('/qubes-firewall/{}/'.format(target))
  93. assert isinstance(entries, dict)
  94. # drop full path
  95. entries = dict(((k.split('/')[3], v.decode())
  96. for k, v in entries.items()))
  97. if 'policy' not in entries:
  98. raise RuleParseError('No \'policy\' defined')
  99. policy = entries.pop('policy')
  100. rules = []
  101. for ruleno, rule in sorted(entries.items()):
  102. if len(ruleno) != 4 or not ruleno.isdigit():
  103. raise RuleParseError(
  104. 'Unexpected non-rule found: {}={}'.format(ruleno, rule))
  105. rule_dict = dict(elem.split('=') for elem in rule.split(' '))
  106. if 'action' not in rule_dict:
  107. raise RuleParseError('Rule \'{}\' lack action'.format(rule))
  108. rules.append(rule_dict)
  109. rules.append({'action': policy})
  110. return rules
  111. def resolve_dns(self, fqdn, family):
  112. """
  113. Resolve the given FQDN via DNS.
  114. :param fqdn: FQDN
  115. :param family: 4 or 6 for IPv4 or IPv6
  116. :return: see socket.getaddrinfo()
  117. :raises: RuleParseError
  118. """
  119. try:
  120. addrinfo = socket.getaddrinfo(fqdn, None,
  121. (socket.AF_INET6 if family == 6 else socket.AF_INET))
  122. except socket.gaierror as e:
  123. raise RuleParseError('Failed to resolve {}: {}'.format(
  124. fqdn, str(e)))
  125. except UnicodeError as e:
  126. raise RuleParseError('Invalid destination {}: {}'.format(
  127. fqdn, str(e)))
  128. return addrinfo
  129. def update_dns_info(self, source, dns):
  130. """
  131. Write resolved DNS addresses back to QubesDB. This can be useful
  132. for the user or DNS applications to pin these DNS addresses to the
  133. IPs resolved during firewall setup.
  134. :param source: VM IP
  135. :param dns: dict: hostname -> set of IP addresses
  136. :return: None
  137. """
  138. #clear old info
  139. self.qdb.rm('/dns/{}/'.format(source))
  140. for host, hostaddrs in dns.items():
  141. self.qdb.write('/dns/{}/{}'.format(source, host), str(hostaddrs))
  142. def update_handled(self, addr):
  143. """
  144. Update the QubesDB count of how often the given address was handled.
  145. User applications may watch these paths for count increases to remain
  146. up to date with QubesDB changes.
  147. """
  148. cnt = self.qdb.read('/qubes-firewall-handled/{}'.format(addr))
  149. try:
  150. cnt = int(cnt)
  151. except (TypeError, ValueError):
  152. cnt = 0
  153. self.qdb.write('/qubes-firewall-handled/{}'.format(addr), str(cnt+1))
  154. def list_targets(self):
  155. return set(t.split('/')[2] for t in self.qdb.list('/qubes-firewall/'))
  156. @staticmethod
  157. def is_ip6(addr):
  158. return addr.count(':') > 0
  159. def log_error(self, msg):
  160. self.log.error(msg)
  161. subprocess.call(
  162. ['notify-send', '-t', '3000', msg],
  163. env=os.environ.copy().update({'DISPLAY': ':0'})
  164. )
  165. def handle_addr(self, addr):
  166. try:
  167. rules = self.read_rules(addr)
  168. self.apply_rules(addr, rules)
  169. except RuleParseError as e:
  170. self.log_error(
  171. 'Failed to parse rules for {} ({}), blocking traffic'.format(
  172. addr, str(e)
  173. ))
  174. self.apply_rules(addr, [{'action': 'drop'}])
  175. except RuleApplyError as e:
  176. self.log_error(
  177. 'Failed to apply rules for {} ({}), blocking traffic'.format(
  178. addr, str(e))
  179. )
  180. # retry with fallback rules
  181. try:
  182. self.apply_rules(addr, [{'action': 'drop'}])
  183. except RuleApplyError:
  184. self.log_error(
  185. 'Failed to block traffic for {}'.format(addr))
  186. self.update_handled(addr)
  187. @staticmethod
  188. def dns_addresses(family=None):
  189. with open('/etc/resolv.conf') as resolv:
  190. for line in resolv.readlines():
  191. line = line.strip()
  192. if line.startswith('nameserver'):
  193. if line.count('.') == 3 and (family or 4) == 4:
  194. yield line.split(' ')[1]
  195. elif line.count(':') and (family or 6) == 6:
  196. yield line.split(' ')[1]
  197. def main(self):
  198. self.terminate_requested = False
  199. self.init()
  200. self.run_firewall_dir()
  201. self.run_user_script()
  202. self.sd_notify('READY=1')
  203. self.qdb.watch('/qubes-firewall/')
  204. self.qdb.watch('/connected-ips')
  205. self.qdb.watch('/connected-ips6')
  206. # initial load
  207. for source_addr in self.list_targets():
  208. self.handle_addr(source_addr)
  209. self.update_connected_ips(4)
  210. self.update_connected_ips(6)
  211. try:
  212. for watch_path in iter(self.qdb.read_watch, None):
  213. if watch_path == '/connected-ips':
  214. self.update_connected_ips(4)
  215. if watch_path == '/connected-ips6':
  216. self.update_connected_ips(6)
  217. # ignore writing rules itself - wait for final write at
  218. # source_addr level empty write (/qubes-firewall/SOURCE_ADDR)
  219. if watch_path.startswith('/qubes-firewall/') and watch_path.count('/') == 2:
  220. source_addr = watch_path.split('/')[2]
  221. self.handle_addr(source_addr)
  222. except OSError: # EINTR
  223. # signal received, don't continue the loop
  224. pass
  225. self.cleanup()
  226. def terminate(self):
  227. self.terminate_requested = True
  228. class IptablesWorker(FirewallWorker):
  229. supported_rule_opts = ['action', 'proto', 'dst4', 'dst6', 'dsthost',
  230. 'dstports', 'specialtarget', 'icmptype']
  231. def __init__(self):
  232. super(IptablesWorker, self).__init__()
  233. self.chains = {
  234. 4: set(),
  235. 6: set(),
  236. }
  237. @staticmethod
  238. def chain_for_addr(addr):
  239. """Generate iptables chain name for given source address address"""
  240. return 'qbs-' + addr.replace('.', '-').replace(':', '-')[-20:]
  241. def run_ipt(self, family, args, **kwargs):
  242. # pylint: disable=no-self-use
  243. if family == 6:
  244. subprocess.check_call(['ip6tables'] + args, **kwargs)
  245. else:
  246. subprocess.check_call(['iptables'] + args, **kwargs)
  247. def run_ipt_restore(self, family, args):
  248. # pylint: disable=no-self-use
  249. if family == 6:
  250. return subprocess.Popen(['ip6tables-restore'] + args,
  251. stdin=subprocess.PIPE,
  252. stdout=subprocess.PIPE,
  253. stderr=subprocess.STDOUT)
  254. else:
  255. return subprocess.Popen(['iptables-restore'] + args,
  256. stdin=subprocess.PIPE,
  257. stdout=subprocess.PIPE,
  258. stderr=subprocess.STDOUT)
  259. def create_chain(self, addr, chain, family):
  260. """
  261. Create iptables chain and hook traffic coming from `addr` to it.
  262. :param addr: source IP from which traffic should be handled by the
  263. chain
  264. :param chain: name of the chain to create
  265. :param family: address family (4 or 6)
  266. :return: None
  267. """
  268. self.run_ipt(family, ['-N', chain])
  269. self.run_ipt(family,
  270. ['-I', 'QBS-FORWARD', '-s', addr, '-j', chain])
  271. self.chains[family].add(chain)
  272. def prepare_rules(self, chain, rules, family):
  273. """
  274. Helper function to translate rules list into input for iptables-restore
  275. :param chain: name of the chain to put rules into
  276. :param rules: list of rules
  277. :param family: address family (4 or 6)
  278. :return: tuple: (input for iptables-restore, dict of DNS records resolved
  279. during execution)
  280. :rtype: (str, dict)
  281. """
  282. iptables = "*filter\n"
  283. fullmask = '/128' if family == 6 else '/32'
  284. dns = list(addr + fullmask for addr in self.dns_addresses(family))
  285. ret_dns = {}
  286. for rule in rules:
  287. unsupported_opts = set(rule.keys()).difference(
  288. set(self.supported_rule_opts))
  289. if unsupported_opts:
  290. raise RuleParseError(
  291. 'Unsupported rule option(s): {!s}'.format(unsupported_opts))
  292. if 'dst4' in rule and family == 6:
  293. raise RuleParseError('IPv4 rule found for IPv6 address')
  294. if 'dst6' in rule and family == 4:
  295. raise RuleParseError('dst6 rule found for IPv4 address')
  296. if 'proto' in rule:
  297. if rule['proto'] == 'icmp' and family == 6:
  298. protos = ['icmpv6']
  299. else:
  300. protos = [rule['proto']]
  301. else:
  302. protos = None
  303. if 'dst4' in rule:
  304. dsthosts = [rule['dst4']]
  305. elif 'dst6' in rule:
  306. dsthosts = [rule['dst6']]
  307. elif 'dsthost' in rule:
  308. addrinfo = self.resolve_dns(rule['dsthost'], family)
  309. dsthosts = set(item[4][0] + fullmask for item in addrinfo)
  310. ret_dns[rule['dsthost']] = dsthosts
  311. else:
  312. dsthosts = None
  313. if 'dstports' in rule:
  314. dstports = rule['dstports'].replace('-', ':')
  315. else:
  316. dstports = None
  317. if rule.get('specialtarget', None) == 'dns':
  318. if dstports not in ('53:53', None):
  319. continue
  320. else:
  321. dstports = '53:53'
  322. if not dns:
  323. continue
  324. if protos is not None:
  325. protos = {'tcp', 'udp'}.intersection(protos)
  326. else:
  327. protos = {'tcp', 'udp'}
  328. if dsthosts is not None:
  329. dsthosts = set(dns).intersection(dsthosts)
  330. else:
  331. dsthosts = dns
  332. if 'icmptype' in rule:
  333. icmptype = rule['icmptype']
  334. else:
  335. icmptype = None
  336. # make them iterable
  337. if protos is None:
  338. protos = [None]
  339. if dsthosts is None:
  340. dsthosts = [None]
  341. if rule['action'] == 'accept':
  342. action = 'ACCEPT'
  343. elif rule['action'] == 'drop':
  344. action = 'REJECT --reject-with {}'.format(
  345. 'icmp6-adm-prohibited' if family == 6 else
  346. 'icmp-admin-prohibited')
  347. else:
  348. raise RuleParseError(
  349. 'Invalid rule action {}'.format(rule['action']))
  350. # sorting here is only to ease writing tests
  351. for proto in sorted(protos):
  352. for dsthost in sorted(dsthosts):
  353. ipt_rule = '-A {}'.format(chain)
  354. if dsthost is not None:
  355. ipt_rule += ' -d {}'.format(dsthost)
  356. if proto is not None:
  357. ipt_rule += ' -p {}'.format(proto)
  358. if dstports is not None:
  359. ipt_rule += ' --dport {}'.format(dstports)
  360. if icmptype is not None:
  361. ipt_rule += ' --icmp-type {}'.format(icmptype)
  362. ipt_rule += ' -j {}\n'.format(action)
  363. iptables += ipt_rule
  364. iptables += 'COMMIT\n'
  365. return (iptables, ret_dns)
  366. def apply_rules_family(self, source, rules, family):
  367. """
  368. Apply rules for given source address.
  369. Handle only rules for given address family (IPv4 or IPv6).
  370. :param source: source address
  371. :param rules: rules list
  372. :param family: address family, either 4 or 6
  373. :return: None
  374. """
  375. chain = self.chain_for_addr(source)
  376. if chain not in self.chains[family]:
  377. self.create_chain(source, chain, family)
  378. (iptables, dns) = self.prepare_rules(chain, rules, family)
  379. try:
  380. self.run_ipt(family, ['-F', chain])
  381. p = self.run_ipt_restore(family, ['-n'])
  382. (output, _) = p.communicate(iptables.encode())
  383. if p.returncode != 0:
  384. raise RuleApplyError(
  385. 'iptables-restore failed: {}'.format(output))
  386. self.update_dns_info(source, dns)
  387. except subprocess.CalledProcessError as e:
  388. raise RuleApplyError('\'iptables -F {}\' failed: {}'.format(
  389. chain, e.output))
  390. def apply_rules(self, source, rules):
  391. if self.is_ip6(source):
  392. self.apply_rules_family(source, rules, 6)
  393. else:
  394. self.apply_rules_family(source, rules, 4)
  395. def update_connected_ips(self, family):
  396. ips = self.get_connected_ips(family)
  397. if not ips:
  398. # Just flush.
  399. self.run_ipt(family, ['-t', 'raw', '-F', 'QBS-PREROUTING'])
  400. self.run_ipt(family, ['-t', 'mangle', '-F', 'QBS-POSTROUTING'])
  401. return
  402. # Temporarily set policy to DROP while updating the rules.
  403. self.run_ipt(family, ['-t', 'raw', '-P', 'PREROUTING', 'DROP'])
  404. self.run_ipt(family, ['-t', 'mangle', '-P', 'POSTROUTING', 'DROP'])
  405. self.run_ipt(family, ['-t', 'raw', '-F', 'QBS-PREROUTING'])
  406. self.run_ipt(family, ['-t', 'mangle', '-F', 'QBS-POSTROUTING'])
  407. for ip in ips:
  408. self.run_ipt(family, [
  409. '-t', 'raw', '-A', 'QBS-PREROUTING',
  410. '!', '-i', 'vif+', '-s', ip, '-j', 'DROP'])
  411. self.run_ipt(family, [
  412. '-t', 'mangle', '-A', 'QBS-POSTROUTING',
  413. '!', '-o', 'vif+', '-d', ip, '-j', 'DROP'])
  414. self.run_ipt(family, ['-t', 'raw', '-P', 'PREROUTING', 'ACCEPT'])
  415. self.run_ipt(family, ['-t', 'mangle', '-P', 'POSTROUTING', 'ACCEPT'])
  416. def init(self):
  417. # Chains QBS-FORWARD, QBS-PREROUTING, QBS-POSTROUTING
  418. # need to be created before running this.
  419. try:
  420. self.run_ipt(4, ['-F', 'QBS-FORWARD'])
  421. self.run_ipt(4,
  422. ['-A', 'QBS-FORWARD', '!', '-i', 'vif+', '-j', 'RETURN'])
  423. self.run_ipt(4, ['-A', 'QBS-FORWARD', '-j', 'DROP'])
  424. self.run_ipt(4, ['-t', 'raw', '-F', 'QBS-PREROUTING'])
  425. self.run_ipt(4, ['-t', 'mangle', '-F', 'QBS-POSTROUTING'])
  426. self.run_ipt(6, ['-F', 'QBS-FORWARD'])
  427. self.run_ipt(6,
  428. ['-A', 'QBS-FORWARD', '!', '-i', 'vif+', '-j', 'RETURN'])
  429. self.run_ipt(6, ['-A', 'QBS-FORWARD', '-j', 'DROP'])
  430. self.run_ipt(6, ['-t', 'raw', '-F', 'QBS-PREROUTING'])
  431. self.run_ipt(6, ['-t', 'mangle', '-F', 'QBS-POSTROUTING'])
  432. except subprocess.CalledProcessError:
  433. self.log_error(
  434. 'Error initializing iptables. '
  435. 'You probably need to create QBS-FORWARD, QBS-PREROUTING and '
  436. 'QBS-POSTROUTING chains first.'
  437. )
  438. sys.exit(1)
  439. def cleanup(self):
  440. for family in (4, 6):
  441. self.run_ipt(family, ['-F', 'QBS-FORWARD'])
  442. self.run_ipt(family, ['-t', 'raw', '-F', 'QBS-PREROUTING'])
  443. self.run_ipt(family, ['-t', 'mangle', '-F', 'QBS-POSTROUTING'])
  444. for chain in self.chains[family]:
  445. self.run_ipt(family, ['-F', chain])
  446. self.run_ipt(family, ['-X', chain])
  447. class NftablesWorker(FirewallWorker):
  448. supported_rule_opts = ['action', 'proto', 'dst4', 'dst6', 'dsthost',
  449. 'dstports', 'specialtarget', 'icmptype']
  450. def __init__(self):
  451. super(NftablesWorker, self).__init__()
  452. self.chains = {
  453. 4: set(),
  454. 6: set(),
  455. }
  456. @staticmethod
  457. def chain_for_addr(addr):
  458. """Generate iptables chain name for given source address address"""
  459. return 'qbs-' + addr.replace('.', '-').replace(':', '-')
  460. def run_nft(self, nft_input):
  461. # pylint: disable=no-self-use
  462. p = subprocess.Popen(['nft', '-f', '/dev/stdin'],
  463. stdin=subprocess.PIPE,
  464. stdout=subprocess.PIPE,
  465. stderr=subprocess.STDOUT)
  466. stdout, _ = p.communicate(nft_input.encode())
  467. if p.returncode != 0:
  468. raise RuleApplyError('nft failed: {}'.format(stdout))
  469. def create_chain(self, addr, chain, family):
  470. """
  471. Create iptables chain and hook traffic coming from `addr` to it.
  472. :param addr: source IP from which traffic should be handled by the
  473. chain
  474. :param chain: name of the chain to create
  475. :param family: address family (4 or 6)
  476. :return: None
  477. """
  478. nft_input = (
  479. 'table {family} {table} {{\n'
  480. ' chain {chain} {{\n'
  481. ' }}\n'
  482. ' chain forward {{\n'
  483. ' {family} saddr {ip} jump {chain}\n'
  484. ' }}\n'
  485. '}}\n'.format(
  486. family=("ip6" if family == 6 else "ip"),
  487. table='qubes-firewall',
  488. chain=chain,
  489. ip=addr,
  490. )
  491. )
  492. self.run_nft(nft_input)
  493. self.chains[family].add(chain)
  494. def update_connected_ips(self, family):
  495. family_name = ('ip6' if family == 6 else 'ip')
  496. table = 'qubes-firewall'
  497. nft_input = (
  498. 'flush chain {family_name} {table} prerouting\n'
  499. 'flush chain {family_name} {table} postrouting\n'
  500. ).format(family_name=family_name, table=table)
  501. ips = self.get_connected_ips(family)
  502. if ips:
  503. addr = '{' + ', '.join(ips) + '}'
  504. irule = 'iifname != "vif*" {family_name} saddr {addr} drop\n'.format(
  505. family_name=family_name, addr=addr)
  506. orule = 'oifname != "vif*" {family_name} daddr {addr} drop\n'.format(
  507. family_name=family_name, addr=addr)
  508. nft_input += (
  509. 'table {family_name} {table} {{\n'
  510. ' chain prerouting {{\n'
  511. ' {irule}'
  512. ' }}\n'
  513. ' chain postrouting {{\n'
  514. ' {orule}'
  515. ' }}\n'
  516. '}}\n'
  517. ).format(
  518. family_name=family_name,
  519. table=table,
  520. irule=irule,
  521. orule=orule,
  522. )
  523. self.run_nft(nft_input)
  524. def prepare_rules(self, chain, rules, family):
  525. """
  526. Helper function to translate rules list into input for nft
  527. :param chain: name of the chain to put rules into
  528. :param rules: list of rules
  529. :param family: address family (4 or 6)
  530. :return: tuple: (input for nft, dict of DNS records resolved
  531. during execution)
  532. :rtype: (str, dict)
  533. """
  534. assert family in (4, 6)
  535. nft_rules = []
  536. ip_match = 'ip6' if family == 6 else 'ip'
  537. fullmask = '/128' if family == 6 else '/32'
  538. dns = list(addr + fullmask for addr in self.dns_addresses(family))
  539. ret_dns = {}
  540. for rule in rules:
  541. unsupported_opts = set(rule.keys()).difference(
  542. set(self.supported_rule_opts))
  543. if unsupported_opts:
  544. raise RuleParseError(
  545. 'Unsupported rule option(s): {!s}'.format(unsupported_opts))
  546. if 'dst4' in rule and family == 6:
  547. raise RuleParseError('IPv4 rule found for IPv6 address')
  548. if 'dst6' in rule and family == 4:
  549. raise RuleParseError('dst6 rule found for IPv4 address')
  550. nft_rule = ""
  551. if rule['action'] == 'accept':
  552. action = 'accept'
  553. elif rule['action'] == 'drop':
  554. action = 'reject with icmp{} type admin-prohibited'.format(
  555. 'v6' if family == 6 else '')
  556. else:
  557. raise RuleParseError(
  558. 'Invalid rule action {}'.format(rule['action']))
  559. if 'proto' in rule:
  560. if family == 4:
  561. nft_rule += ' ip protocol {}'.format(rule['proto'])
  562. elif family == 6:
  563. proto = 'icmpv6' if rule['proto'] == 'icmp' \
  564. else rule['proto']
  565. nft_rule += ' ip6 nexthdr {}'.format(proto)
  566. if 'dst4' in rule:
  567. nft_rule += ' ip daddr {}'.format(rule['dst4'])
  568. elif 'dst6' in rule:
  569. nft_rule += ' ip6 daddr {}'.format(rule['dst6'])
  570. elif 'dsthost' in rule:
  571. addrinfo = self.resolve_dns(rule['dsthost'], family)
  572. dsthosts = set(item[4][0] + fullmask for item in addrinfo)
  573. nft_rule += ' {} daddr {{ {} }}'.format(ip_match,
  574. ', '.join(dsthosts))
  575. ret_dns[rule['dsthost']] = dsthosts
  576. if 'dstports' in rule:
  577. dstports = rule['dstports']
  578. if len(set(dstports.split('-'))) == 1:
  579. dstports = dstports.split('-')[0]
  580. else:
  581. dstports = None
  582. if rule.get('specialtarget', None) == 'dns':
  583. if dstports not in ('53', None):
  584. continue
  585. else:
  586. dstports = '53'
  587. if not dns:
  588. continue
  589. nft_rule += ' {} daddr {{ {} }}'.format(ip_match, ', '.join(
  590. dns))
  591. if 'icmptype' in rule:
  592. if family == 4:
  593. nft_rule += ' icmp type {}'.format(rule['icmptype'])
  594. elif family == 6:
  595. nft_rule += ' icmpv6 type {}'.format(rule['icmptype'])
  596. # now duplicate rules for tcp/udp if needed
  597. # it isn't possible to specify "tcp dport xx || udp dport xx" in
  598. # one rule
  599. if dstports is not None:
  600. if 'proto' not in rule:
  601. nft_rules.append(
  602. nft_rule + ' tcp dport {} {}'.format(
  603. dstports, action))
  604. nft_rules.append(
  605. nft_rule + ' udp dport {} {}'.format(
  606. dstports, action))
  607. else:
  608. nft_rules.append(
  609. nft_rule + ' {} dport {} {}'.format(
  610. rule['proto'], dstports, action))
  611. else:
  612. nft_rules.append(nft_rule + ' ' + action)
  613. return (
  614. 'flush chain {family} {table} {chain}\n'
  615. 'table {family} {table} {{\n'
  616. ' chain {chain} {{\n'
  617. ' {rules}\n'
  618. ' }}\n'
  619. '}}\n'.format(
  620. family=('ip6' if family == 6 else 'ip'),
  621. table='qubes-firewall',
  622. chain=chain,
  623. rules='\n '.join(nft_rules)
  624. ), ret_dns)
  625. def apply_rules_family(self, source, rules, family):
  626. """
  627. Apply rules for given source address.
  628. Handle only rules for given address family (IPv4 or IPv6).
  629. :param source: source address
  630. :param rules: rules list
  631. :param family: address family, either 4 or 6
  632. :return: None
  633. """
  634. chain = self.chain_for_addr(source)
  635. if chain not in self.chains[family]:
  636. self.create_chain(source, chain, family)
  637. (nft, dns) = self.prepare_rules(chain, rules, family)
  638. self.run_nft(nft)
  639. self.update_dns_info(source, dns)
  640. def apply_rules(self, source, rules):
  641. if self.is_ip6(source):
  642. self.apply_rules_family(source, rules, 6)
  643. else:
  644. self.apply_rules_family(source, rules, 4)
  645. def init(self):
  646. nft_init = (
  647. 'table {family} qubes-firewall {{\n'
  648. ' chain forward {{\n'
  649. ' type filter hook forward priority 0;\n'
  650. ' policy drop;\n'
  651. ' ct state established,related accept\n'
  652. ' meta iifname != "vif*" accept\n'
  653. ' }}\n'
  654. ' chain prerouting {{\n'
  655. ' type filter hook prerouting priority -300;\n'
  656. ' policy accept;\n'
  657. ' }}\n'
  658. ' chain postrouting {{\n'
  659. ' type filter hook postrouting priority -300;\n'
  660. ' policy accept;\n'
  661. ' }}\n'
  662. '}}\n'
  663. )
  664. nft_init = ''.join(
  665. nft_init.format(family=family) for family in ('ip', 'ip6'))
  666. self.run_nft(nft_init)
  667. def cleanup(self):
  668. nft_cleanup = (
  669. 'delete table ip qubes-firewall\n'
  670. 'delete table ip6 qubes-firewall\n'
  671. )
  672. self.run_nft(nft_cleanup)
  673. def main():
  674. if shutil.which('nft'):
  675. worker = NftablesWorker()
  676. else:
  677. worker = IptablesWorker()
  678. context = daemon.DaemonContext()
  679. context.stderr = sys.stderr
  680. context.detach_process = False
  681. context.files_preserve = [worker.qdb.watch_fd()]
  682. context.signal_map = {
  683. signal.SIGTERM: lambda _signal, _stack: worker.terminate(),
  684. }
  685. with context:
  686. worker.main()
  687. if __name__ == '__main__':
  688. main()