firewall.py 28 KB

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