firewall.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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 update_dns_info(self, source, dns):
  112. """
  113. Write resolved DNS addresses back to QubesDB. This can be useful
  114. for the user or DNS applications to pin these DNS addresses to the
  115. IPs resolved during firewall setup.
  116. :param source: VM IP
  117. :param dns: dict: hostname -> set of IP addresses
  118. :return: None
  119. """
  120. #clear old info
  121. self.qdb.rm('/dns/{}/'.format(source))
  122. for host, hostaddrs in dns.items():
  123. self.qdb.write('/dns/{}/{}'.format(source, host), str(hostaddrs))
  124. def update_handled(self, addr):
  125. """
  126. Update the QubesDB count of how often the given address was handled.
  127. User applications may watch these paths for count increases to remain
  128. up to date with QubesDB changes.
  129. """
  130. cnt = self.qdb.read('/qubes-firewall_handled/{}'.format(addr))
  131. try:
  132. cnt = int(cnt)
  133. except (TypeError, ValueError):
  134. cnt = 0
  135. self.qdb.write('/qubes-firewall_handled/{}'.format(addr), str(cnt+1))
  136. def list_targets(self):
  137. return set(t.split('/')[2] for t in self.qdb.list('/qubes-firewall/'))
  138. @staticmethod
  139. def is_ip6(addr):
  140. return addr.count(':') > 0
  141. def log_error(self, msg):
  142. self.log.error(msg)
  143. subprocess.call(
  144. ['notify-send', '-t', '3000', msg],
  145. env=os.environ.copy().update({'DISPLAY': ':0'})
  146. )
  147. def handle_addr(self, addr):
  148. try:
  149. rules = self.read_rules(addr)
  150. self.apply_rules(addr, rules)
  151. except RuleParseError as e:
  152. self.log_error(
  153. 'Failed to parse rules for {} ({}), blocking traffic'.format(
  154. addr, str(e)
  155. ))
  156. self.apply_rules(addr, [{'action': 'drop'}])
  157. except RuleApplyError as e:
  158. self.log_error(
  159. 'Failed to apply rules for {} ({}), blocking traffic'.format(
  160. addr, str(e))
  161. )
  162. # retry with fallback rules
  163. try:
  164. self.apply_rules(addr, [{'action': 'drop'}])
  165. except RuleApplyError:
  166. self.log_error(
  167. 'Failed to block traffic for {}'.format(addr))
  168. self.update_handled(addr)
  169. @staticmethod
  170. def dns_addresses(family=None):
  171. with open('/etc/resolv.conf') as resolv:
  172. for line in resolv.readlines():
  173. line = line.strip()
  174. if line.startswith('nameserver'):
  175. if line.count('.') == 3 and (family or 4) == 4:
  176. yield line.split(' ')[1]
  177. elif line.count(':') and (family or 6) == 6:
  178. yield line.split(' ')[1]
  179. def main(self):
  180. self.terminate_requested = False
  181. self.init()
  182. self.run_firewall_dir()
  183. self.run_user_script()
  184. self.sd_notify('READY=1')
  185. self.qdb.watch('/qubes-firewall/')
  186. self.qdb.watch('/connected-ips')
  187. self.qdb.watch('/connected-ips6')
  188. # initial load
  189. for source_addr in self.list_targets():
  190. self.handle_addr(source_addr)
  191. self.update_connected_ips(4)
  192. self.update_connected_ips(6)
  193. try:
  194. for watch_path in iter(self.qdb.read_watch, None):
  195. if watch_path == '/connected-ips':
  196. self.update_connected_ips(4)
  197. if watch_path == '/connected-ips6':
  198. self.update_connected_ips(6)
  199. # ignore writing rules itself - wait for final write at
  200. # source_addr level empty write (/qubes-firewall/SOURCE_ADDR)
  201. if watch_path.startswith('/qubes-firewall/') and watch_path.count('/') == 2:
  202. source_addr = watch_path.split('/')[2]
  203. self.handle_addr(source_addr)
  204. except OSError: # EINTR
  205. # signal received, don't continue the loop
  206. pass
  207. self.cleanup()
  208. def terminate(self):
  209. self.terminate_requested = True
  210. class IptablesWorker(FirewallWorker):
  211. supported_rule_opts = ['action', 'proto', 'dst4', 'dst6', 'dsthost',
  212. 'dstports', 'specialtarget', 'icmptype']
  213. def __init__(self):
  214. super(IptablesWorker, self).__init__()
  215. self.chains = {
  216. 4: set(),
  217. 6: set(),
  218. }
  219. @staticmethod
  220. def chain_for_addr(addr):
  221. """Generate iptables chain name for given source address address"""
  222. return 'qbs-' + addr.replace('.', '-').replace(':', '-')[-20:]
  223. def run_ipt(self, family, args, **kwargs):
  224. # pylint: disable=no-self-use
  225. if family == 6:
  226. subprocess.check_call(['ip6tables'] + args, **kwargs)
  227. else:
  228. subprocess.check_call(['iptables'] + args, **kwargs)
  229. def run_ipt_restore(self, family, args):
  230. # pylint: disable=no-self-use
  231. if family == 6:
  232. return subprocess.Popen(['ip6tables-restore'] + args,
  233. stdin=subprocess.PIPE,
  234. stdout=subprocess.PIPE,
  235. stderr=subprocess.STDOUT)
  236. else:
  237. return subprocess.Popen(['iptables-restore'] + args,
  238. stdin=subprocess.PIPE,
  239. stdout=subprocess.PIPE,
  240. stderr=subprocess.STDOUT)
  241. def create_chain(self, addr, chain, family):
  242. """
  243. Create iptables chain and hook traffic coming from `addr` to it.
  244. :param addr: source IP from which traffic should be handled by the
  245. chain
  246. :param chain: name of the chain to create
  247. :param family: address family (4 or 6)
  248. :return: None
  249. """
  250. self.run_ipt(family, ['-N', chain])
  251. self.run_ipt(family,
  252. ['-I', 'QBS-FORWARD', '-s', addr, '-j', chain])
  253. self.chains[family].add(chain)
  254. def prepare_rules(self, chain, rules, family):
  255. """
  256. Helper function to translate rules list into input for iptables-restore
  257. :param chain: name of the chain to put rules into
  258. :param rules: list of rules
  259. :param family: address family (4 or 6)
  260. :return: tuple: (input for iptables-restore, dict of DNS records resolved
  261. during execution)
  262. :rtype: (str, dict)
  263. """
  264. iptables = "*filter\n"
  265. fullmask = '/128' if family == 6 else '/32'
  266. dns = list(addr + fullmask for addr in self.dns_addresses(family))
  267. ret_dns = {}
  268. for rule in rules:
  269. unsupported_opts = set(rule.keys()).difference(
  270. set(self.supported_rule_opts))
  271. if unsupported_opts:
  272. raise RuleParseError(
  273. 'Unsupported rule option(s): {!s}'.format(unsupported_opts))
  274. if 'dst4' in rule and family == 6:
  275. raise RuleParseError('IPv4 rule found for IPv6 address')
  276. if 'dst6' in rule and family == 4:
  277. raise RuleParseError('dst6 rule found for IPv4 address')
  278. if 'proto' in rule:
  279. if rule['proto'] == 'icmp' and family == 6:
  280. protos = ['icmpv6']
  281. else:
  282. protos = [rule['proto']]
  283. else:
  284. protos = None
  285. if 'dst4' in rule:
  286. dsthosts = [rule['dst4']]
  287. elif 'dst6' in rule:
  288. dsthosts = [rule['dst6']]
  289. elif 'dsthost' in rule:
  290. try:
  291. addrinfo = socket.getaddrinfo(rule['dsthost'], None,
  292. (socket.AF_INET6 if family == 6 else socket.AF_INET))
  293. except socket.gaierror as e:
  294. raise RuleParseError('Failed to resolve {}: {}'.format(
  295. rule['dsthost'], str(e)))
  296. dsthosts = set(item[4][0] + fullmask for item in addrinfo)
  297. ret_dns[rule['dsthost']] = dsthosts
  298. else:
  299. dsthosts = None
  300. if 'dstports' in rule:
  301. dstports = rule['dstports'].replace('-', ':')
  302. else:
  303. dstports = None
  304. if rule.get('specialtarget', None) == 'dns':
  305. if dstports not in ('53:53', None):
  306. continue
  307. else:
  308. dstports = '53:53'
  309. if not dns:
  310. continue
  311. if protos is not None:
  312. protos = {'tcp', 'udp'}.intersection(protos)
  313. else:
  314. protos = {'tcp', 'udp'}
  315. if dsthosts is not None:
  316. dsthosts = set(dns).intersection(dsthosts)
  317. else:
  318. dsthosts = dns
  319. if 'icmptype' in rule:
  320. icmptype = rule['icmptype']
  321. else:
  322. icmptype = None
  323. # make them iterable
  324. if protos is None:
  325. protos = [None]
  326. if dsthosts is None:
  327. dsthosts = [None]
  328. if rule['action'] == 'accept':
  329. action = 'ACCEPT'
  330. elif rule['action'] == 'drop':
  331. action = 'REJECT --reject-with {}'.format(
  332. 'icmp6-adm-prohibited' if family == 6 else
  333. 'icmp-admin-prohibited')
  334. else:
  335. raise RuleParseError(
  336. 'Invalid rule action {}'.format(rule['action']))
  337. # sorting here is only to ease writing tests
  338. for proto in sorted(protos):
  339. for dsthost in sorted(dsthosts):
  340. ipt_rule = '-A {}'.format(chain)
  341. if dsthost is not None:
  342. ipt_rule += ' -d {}'.format(dsthost)
  343. if proto is not None:
  344. ipt_rule += ' -p {}'.format(proto)
  345. if dstports is not None:
  346. ipt_rule += ' --dport {}'.format(dstports)
  347. if icmptype is not None:
  348. ipt_rule += ' --icmp-type {}'.format(icmptype)
  349. ipt_rule += ' -j {}\n'.format(action)
  350. iptables += ipt_rule
  351. iptables += 'COMMIT\n'
  352. return (iptables, ret_dns)
  353. def apply_rules_family(self, source, rules, family):
  354. """
  355. Apply rules for given source address.
  356. Handle only rules for given address family (IPv4 or IPv6).
  357. :param source: source address
  358. :param rules: rules list
  359. :param family: address family, either 4 or 6
  360. :return: None
  361. """
  362. chain = self.chain_for_addr(source)
  363. if chain not in self.chains[family]:
  364. self.create_chain(source, chain, family)
  365. (iptables, dns) = self.prepare_rules(chain, rules, family)
  366. try:
  367. self.run_ipt(family, ['-F', chain])
  368. p = self.run_ipt_restore(family, ['-n'])
  369. (output, _) = p.communicate(iptables.encode())
  370. if p.returncode != 0:
  371. raise RuleApplyError(
  372. 'iptables-restore failed: {}'.format(output))
  373. self.update_dns_info(source, dns)
  374. except subprocess.CalledProcessError as e:
  375. raise RuleApplyError('\'iptables -F {}\' failed: {}'.format(
  376. chain, e.output))
  377. def apply_rules(self, source, rules):
  378. if self.is_ip6(source):
  379. self.apply_rules_family(source, rules, 6)
  380. else:
  381. self.apply_rules_family(source, rules, 4)
  382. def update_connected_ips(self, family):
  383. ips = self.get_connected_ips(family)
  384. if not ips:
  385. # Just flush.
  386. self.run_ipt(family, ['-t', 'raw', '-F', 'QBS-PREROUTING'])
  387. self.run_ipt(family, ['-t', 'mangle', '-F', 'QBS-POSTROUTING'])
  388. return
  389. # Temporarily set policy to DROP while updating the rules.
  390. self.run_ipt(family, ['-t', 'raw', '-P', 'PREROUTING', 'DROP'])
  391. self.run_ipt(family, ['-t', 'mangle', '-P', 'POSTROUTING', 'DROP'])
  392. self.run_ipt(family, ['-t', 'raw', '-F', 'QBS-PREROUTING'])
  393. self.run_ipt(family, ['-t', 'mangle', '-F', 'QBS-POSTROUTING'])
  394. for ip in ips:
  395. self.run_ipt(family, [
  396. '-t', 'raw', '-A', 'QBS-PREROUTING',
  397. '!', '-i', 'vif+', '-s', ip, '-j', 'DROP'])
  398. self.run_ipt(family, [
  399. '-t', 'mangle', '-A', 'QBS-POSTROUTING',
  400. '!', '-o', 'vif+', '-d', ip, '-j', 'DROP'])
  401. self.run_ipt(family, ['-t', 'raw', '-P', 'PREROUTING', 'ACCEPT'])
  402. self.run_ipt(family, ['-t', 'mangle', '-P', 'POSTROUTING', 'ACCEPT'])
  403. def init(self):
  404. # Chains QBS-FORWARD, QBS-PREROUTING, QBS-POSTROUTING
  405. # need to be created before running this.
  406. try:
  407. self.run_ipt(4, ['-F', 'QBS-FORWARD'])
  408. self.run_ipt(4,
  409. ['-A', 'QBS-FORWARD', '!', '-i', 'vif+', '-j', 'RETURN'])
  410. self.run_ipt(4, ['-A', 'QBS-FORWARD', '-j', 'DROP'])
  411. self.run_ipt(4, ['-t', 'raw', '-F', 'QBS-PREROUTING'])
  412. self.run_ipt(4, ['-t', 'mangle', '-F', 'QBS-POSTROUTING'])
  413. self.run_ipt(6, ['-F', 'QBS-FORWARD'])
  414. self.run_ipt(6,
  415. ['-A', 'QBS-FORWARD', '!', '-i', 'vif+', '-j', 'RETURN'])
  416. self.run_ipt(6, ['-A', 'QBS-FORWARD', '-j', 'DROP'])
  417. self.run_ipt(6, ['-t', 'raw', '-F', 'QBS-PREROUTING'])
  418. self.run_ipt(6, ['-t', 'mangle', '-F', 'QBS-POSTROUTING'])
  419. except subprocess.CalledProcessError:
  420. self.log_error(
  421. 'Error initializing iptables. '
  422. 'You probably need to create QBS-FORWARD, QBS-PREROUTING and '
  423. 'QBS-POSTROUTING chains first.'
  424. )
  425. sys.exit(1)
  426. def cleanup(self):
  427. for family in (4, 6):
  428. self.run_ipt(family, ['-F', 'QBS-FORWARD'])
  429. self.run_ipt(family, ['-t', 'raw', '-F', 'QBS-PREROUTING'])
  430. self.run_ipt(family, ['-t', 'mangle', '-F', 'QBS-POSTROUTING'])
  431. for chain in self.chains[family]:
  432. self.run_ipt(family, ['-F', chain])
  433. self.run_ipt(family, ['-X', chain])
  434. class NftablesWorker(FirewallWorker):
  435. supported_rule_opts = ['action', 'proto', 'dst4', 'dst6', 'dsthost',
  436. 'dstports', 'specialtarget', 'icmptype']
  437. def __init__(self):
  438. super(NftablesWorker, self).__init__()
  439. self.chains = {
  440. 4: set(),
  441. 6: set(),
  442. }
  443. @staticmethod
  444. def chain_for_addr(addr):
  445. """Generate iptables chain name for given source address address"""
  446. return 'qbs-' + addr.replace('.', '-').replace(':', '-')
  447. def run_nft(self, nft_input):
  448. # pylint: disable=no-self-use
  449. p = subprocess.Popen(['nft', '-f', '/dev/stdin'],
  450. stdin=subprocess.PIPE,
  451. stdout=subprocess.PIPE,
  452. stderr=subprocess.STDOUT)
  453. stdout, _ = p.communicate(nft_input.encode())
  454. if p.returncode != 0:
  455. raise RuleApplyError('nft failed: {}'.format(stdout))
  456. def create_chain(self, addr, chain, family):
  457. """
  458. Create iptables chain and hook traffic coming from `addr` to it.
  459. :param addr: source IP from which traffic should be handled by the
  460. chain
  461. :param chain: name of the chain to create
  462. :param family: address family (4 or 6)
  463. :return: None
  464. """
  465. nft_input = (
  466. 'table {family} {table} {{\n'
  467. ' chain {chain} {{\n'
  468. ' }}\n'
  469. ' chain forward {{\n'
  470. ' {family} saddr {ip} jump {chain}\n'
  471. ' }}\n'
  472. '}}\n'.format(
  473. family=("ip6" if family == 6 else "ip"),
  474. table='qubes-firewall',
  475. chain=chain,
  476. ip=addr,
  477. )
  478. )
  479. self.run_nft(nft_input)
  480. self.chains[family].add(chain)
  481. def update_connected_ips(self, family):
  482. family_name = ('ip6' if family == 6 else 'ip')
  483. table = 'qubes-firewall'
  484. nft_input = (
  485. 'flush chain {family_name} {table} prerouting\n'
  486. 'flush chain {family_name} {table} postrouting\n'
  487. ).format(family_name=family_name, table=table)
  488. ips = self.get_connected_ips(family)
  489. if ips:
  490. addr = '{' + ', '.join(ips) + '}'
  491. irule = 'iifname != "vif*" {family_name} saddr {addr} drop\n'.format(
  492. family_name=family_name, addr=addr)
  493. orule = 'oifname != "vif*" {family_name} daddr {addr} drop\n'.format(
  494. family_name=family_name, addr=addr)
  495. nft_input += (
  496. 'table {family_name} {table} {{\n'
  497. ' chain prerouting {{\n'
  498. ' {irule}'
  499. ' }}\n'
  500. ' chain postrouting {{\n'
  501. ' {orule}'
  502. ' }}\n'
  503. '}}\n'
  504. ).format(
  505. family_name=family_name,
  506. table=table,
  507. irule=irule,
  508. orule=orule,
  509. )
  510. self.run_nft(nft_input)
  511. def prepare_rules(self, chain, rules, family):
  512. """
  513. Helper function to translate rules list into input for nft
  514. :param chain: name of the chain to put rules into
  515. :param rules: list of rules
  516. :param family: address family (4 or 6)
  517. :return: tuple: (input for nft, dict of DNS records resolved
  518. during execution)
  519. :rtype: (str, dict)
  520. """
  521. assert family in (4, 6)
  522. nft_rules = []
  523. ip_match = 'ip6' if family == 6 else 'ip'
  524. fullmask = '/128' if family == 6 else '/32'
  525. dns = list(addr + fullmask for addr in self.dns_addresses(family))
  526. ret_dns = {}
  527. for rule in rules:
  528. unsupported_opts = set(rule.keys()).difference(
  529. set(self.supported_rule_opts))
  530. if unsupported_opts:
  531. raise RuleParseError(
  532. 'Unsupported rule option(s): {!s}'.format(unsupported_opts))
  533. if 'dst4' in rule and family == 6:
  534. raise RuleParseError('IPv4 rule found for IPv6 address')
  535. if 'dst6' in rule and family == 4:
  536. raise RuleParseError('dst6 rule found for IPv4 address')
  537. nft_rule = ""
  538. if rule['action'] == 'accept':
  539. action = 'accept'
  540. elif rule['action'] == 'drop':
  541. action = 'reject with icmp{} type admin-prohibited'.format(
  542. 'v6' if family == 6 else '')
  543. else:
  544. raise RuleParseError(
  545. 'Invalid rule action {}'.format(rule['action']))
  546. if 'proto' in rule:
  547. if family == 4:
  548. nft_rule += ' ip protocol {}'.format(rule['proto'])
  549. elif family == 6:
  550. proto = 'icmpv6' if rule['proto'] == 'icmp' \
  551. else rule['proto']
  552. nft_rule += ' ip6 nexthdr {}'.format(proto)
  553. if 'dst4' in rule:
  554. nft_rule += ' ip daddr {}'.format(rule['dst4'])
  555. elif 'dst6' in rule:
  556. nft_rule += ' ip6 daddr {}'.format(rule['dst6'])
  557. elif 'dsthost' in rule:
  558. try:
  559. addrinfo = socket.getaddrinfo(rule['dsthost'], None,
  560. (socket.AF_INET6 if family == 6 else socket.AF_INET))
  561. except socket.gaierror as e:
  562. raise RuleParseError('Failed to resolve {}: {}'.format(
  563. rule['dsthost'], str(e)))
  564. except UnicodeError as e:
  565. raise RuleParseError('Invalid destination {}: {}'.format(
  566. rule['dsthost'], str(e)))
  567. dsthosts = set(item[4][0] + fullmask for item in addrinfo)
  568. nft_rule += ' {} daddr {{ {} }}'.format(ip_match,
  569. ', '.join(dsthosts))
  570. ret_dns[rule['dsthost']] = dsthosts
  571. if 'dstports' in rule:
  572. dstports = rule['dstports']
  573. if len(set(dstports.split('-'))) == 1:
  574. dstports = dstports.split('-')[0]
  575. else:
  576. dstports = None
  577. if rule.get('specialtarget', None) == 'dns':
  578. if dstports not in ('53', None):
  579. continue
  580. else:
  581. dstports = '53'
  582. if not dns:
  583. continue
  584. nft_rule += ' {} daddr {{ {} }}'.format(ip_match, ', '.join(
  585. dns))
  586. if 'icmptype' in rule:
  587. if family == 4:
  588. nft_rule += ' icmp type {}'.format(rule['icmptype'])
  589. elif family == 6:
  590. nft_rule += ' icmpv6 type {}'.format(rule['icmptype'])
  591. # now duplicate rules for tcp/udp if needed
  592. # it isn't possible to specify "tcp dport xx || udp dport xx" in
  593. # one rule
  594. if dstports is not None:
  595. if 'proto' not in rule:
  596. nft_rules.append(
  597. nft_rule + ' tcp dport {} {}'.format(
  598. dstports, action))
  599. nft_rules.append(
  600. nft_rule + ' udp dport {} {}'.format(
  601. dstports, action))
  602. else:
  603. nft_rules.append(
  604. nft_rule + ' {} dport {} {}'.format(
  605. rule['proto'], dstports, action))
  606. else:
  607. nft_rules.append(nft_rule + ' ' + action)
  608. return (
  609. 'flush chain {family} {table} {chain}\n'
  610. 'table {family} {table} {{\n'
  611. ' chain {chain} {{\n'
  612. ' {rules}\n'
  613. ' }}\n'
  614. '}}\n'.format(
  615. family=('ip6' if family == 6 else 'ip'),
  616. table='qubes-firewall',
  617. chain=chain,
  618. rules='\n '.join(nft_rules)
  619. ), ret_dns)
  620. def apply_rules_family(self, source, rules, family):
  621. """
  622. Apply rules for given source address.
  623. Handle only rules for given address family (IPv4 or IPv6).
  624. :param source: source address
  625. :param rules: rules list
  626. :param family: address family, either 4 or 6
  627. :return: None
  628. """
  629. chain = self.chain_for_addr(source)
  630. if chain not in self.chains[family]:
  631. self.create_chain(source, chain, family)
  632. (nft, dns) = self.prepare_rules(chain, rules, family)
  633. self.run_nft(nft)
  634. self.update_dns_info(source, dns)
  635. def apply_rules(self, source, rules):
  636. if self.is_ip6(source):
  637. self.apply_rules_family(source, rules, 6)
  638. else:
  639. self.apply_rules_family(source, rules, 4)
  640. def init(self):
  641. nft_init = (
  642. 'table {family} qubes-firewall {{\n'
  643. ' chain forward {{\n'
  644. ' type filter hook forward priority 0;\n'
  645. ' policy drop;\n'
  646. ' ct state established,related accept\n'
  647. ' meta iifname != "vif*" accept\n'
  648. ' }}\n'
  649. ' chain prerouting {{\n'
  650. ' type filter hook prerouting priority -300;\n'
  651. ' policy accept;\n'
  652. ' }}\n'
  653. ' chain postrouting {{\n'
  654. ' type filter hook postrouting priority -300;\n'
  655. ' policy accept;\n'
  656. ' }}\n'
  657. '}}\n'
  658. )
  659. nft_init = ''.join(
  660. nft_init.format(family=family) for family in ('ip', 'ip6'))
  661. self.run_nft(nft_init)
  662. def cleanup(self):
  663. nft_cleanup = (
  664. 'delete table ip qubes-firewall\n'
  665. 'delete table ip6 qubes-firewall\n'
  666. )
  667. self.run_nft(nft_cleanup)
  668. def main():
  669. if shutil.which('nft'):
  670. worker = NftablesWorker()
  671. else:
  672. worker = IptablesWorker()
  673. context = daemon.DaemonContext()
  674. context.stderr = sys.stderr
  675. context.detach_process = False
  676. context.files_preserve = [worker.qdb.watch_fd()]
  677. context.signal_map = {
  678. signal.SIGTERM: lambda _signal, _stack: worker.terminate(),
  679. }
  680. with context:
  681. worker.main()
  682. if __name__ == '__main__':
  683. main()