firewall.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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 list_targets(self):
  125. return set(t.split('/')[2] for t in self.qdb.list('/qubes-firewall/'))
  126. @staticmethod
  127. def is_ip6(addr):
  128. return addr.count(':') > 0
  129. def log_error(self, msg):
  130. self.log.error(msg)
  131. subprocess.call(
  132. ['notify-send', '-t', '3000', msg],
  133. env=os.environ.copy().update({'DISPLAY': ':0'})
  134. )
  135. def handle_addr(self, addr):
  136. try:
  137. rules = self.read_rules(addr)
  138. self.apply_rules(addr, rules)
  139. except RuleParseError as e:
  140. self.log_error(
  141. 'Failed to parse rules for {} ({}), blocking traffic'.format(
  142. addr, str(e)
  143. ))
  144. self.apply_rules(addr, [{'action': 'drop'}])
  145. except RuleApplyError as e:
  146. self.log_error(
  147. 'Failed to apply rules for {} ({}), blocking traffic'.format(
  148. addr, str(e))
  149. )
  150. # retry with fallback rules
  151. try:
  152. self.apply_rules(addr, [{'action': 'drop'}])
  153. except RuleApplyError:
  154. self.log_error(
  155. 'Failed to block traffic for {}'.format(addr))
  156. @staticmethod
  157. def dns_addresses(family=None):
  158. with open('/etc/resolv.conf') as resolv:
  159. for line in resolv.readlines():
  160. line = line.strip()
  161. if line.startswith('nameserver'):
  162. if line.count('.') == 3 and (family or 4) == 4:
  163. yield line.split(' ')[1]
  164. elif line.count(':') and (family or 6) == 6:
  165. yield line.split(' ')[1]
  166. def main(self):
  167. self.terminate_requested = False
  168. self.init()
  169. self.run_firewall_dir()
  170. self.run_user_script()
  171. self.sd_notify('READY=1')
  172. # initial load
  173. for source_addr in self.list_targets():
  174. self.handle_addr(source_addr)
  175. self.update_connected_ips(4)
  176. self.update_connected_ips(6)
  177. self.qdb.watch('/qubes-firewall/')
  178. self.qdb.watch('/connected-ips')
  179. self.qdb.watch('/connected-ips6')
  180. try:
  181. for watch_path in iter(self.qdb.read_watch, None):
  182. if watch_path == '/connected-ips':
  183. self.update_connected_ips(4)
  184. if watch_path == '/connected-ips6':
  185. self.update_connected_ips(6)
  186. # ignore writing rules itself - wait for final write at
  187. # source_addr level empty write (/qubes-firewall/SOURCE_ADDR)
  188. if watch_path.startswith('/qubes-firewall/') and watch_path.count('/') == 2:
  189. source_addr = watch_path.split('/')[2]
  190. self.handle_addr(source_addr)
  191. except OSError: # EINTR
  192. # signal received, don't continue the loop
  193. pass
  194. self.cleanup()
  195. def terminate(self):
  196. self.terminate_requested = True
  197. class IptablesWorker(FirewallWorker):
  198. supported_rule_opts = ['action', 'proto', 'dst4', 'dst6', 'dsthost',
  199. 'dstports', 'specialtarget', 'icmptype']
  200. def __init__(self):
  201. super(IptablesWorker, self).__init__()
  202. self.chains = {
  203. 4: set(),
  204. 6: set(),
  205. }
  206. @staticmethod
  207. def chain_for_addr(addr):
  208. """Generate iptables chain name for given source address address"""
  209. return 'qbs-' + addr.replace('.', '-').replace(':', '-')[-20:]
  210. def run_ipt(self, family, args, **kwargs):
  211. # pylint: disable=no-self-use
  212. if family == 6:
  213. subprocess.check_call(['ip6tables'] + args, **kwargs)
  214. else:
  215. subprocess.check_call(['iptables'] + args, **kwargs)
  216. def run_ipt_restore(self, family, args):
  217. # pylint: disable=no-self-use
  218. if family == 6:
  219. return subprocess.Popen(['ip6tables-restore'] + args,
  220. stdin=subprocess.PIPE,
  221. stdout=subprocess.PIPE,
  222. stderr=subprocess.STDOUT)
  223. else:
  224. return subprocess.Popen(['iptables-restore'] + args,
  225. stdin=subprocess.PIPE,
  226. stdout=subprocess.PIPE,
  227. stderr=subprocess.STDOUT)
  228. def create_chain(self, addr, chain, family):
  229. """
  230. Create iptables chain and hook traffic coming from `addr` to it.
  231. :param addr: source IP from which traffic should be handled by the
  232. chain
  233. :param chain: name of the chain to create
  234. :param family: address family (4 or 6)
  235. :return: None
  236. """
  237. self.run_ipt(family, ['-N', chain])
  238. self.run_ipt(family,
  239. ['-I', 'QBS-FORWARD', '-s', addr, '-j', chain])
  240. self.chains[family].add(chain)
  241. def prepare_rules(self, chain, rules, family):
  242. """
  243. Helper function to translate rules list into input for iptables-restore
  244. :param chain: name of the chain to put rules into
  245. :param rules: list of rules
  246. :param family: address family (4 or 6)
  247. :return: tuple: (input for iptables-restore, dict of DNS records resolved
  248. during execution)
  249. :rtype: (str, dict)
  250. """
  251. iptables = "*filter\n"
  252. fullmask = '/128' if family == 6 else '/32'
  253. dns = list(addr + fullmask for addr in self.dns_addresses(family))
  254. ret_dns = {}
  255. for rule in rules:
  256. unsupported_opts = set(rule.keys()).difference(
  257. set(self.supported_rule_opts))
  258. if unsupported_opts:
  259. raise RuleParseError(
  260. 'Unsupported rule option(s): {!s}'.format(unsupported_opts))
  261. if 'dst4' in rule and family == 6:
  262. raise RuleParseError('IPv4 rule found for IPv6 address')
  263. if 'dst6' in rule and family == 4:
  264. raise RuleParseError('dst6 rule found for IPv4 address')
  265. if 'proto' in rule:
  266. if rule['proto'] == 'icmp' and family == 6:
  267. protos = ['icmpv6']
  268. else:
  269. protos = [rule['proto']]
  270. else:
  271. protos = None
  272. if 'dst4' in rule:
  273. dsthosts = [rule['dst4']]
  274. elif 'dst6' in rule:
  275. dsthosts = [rule['dst6']]
  276. elif 'dsthost' in rule:
  277. try:
  278. addrinfo = socket.getaddrinfo(rule['dsthost'], None,
  279. (socket.AF_INET6 if family == 6 else socket.AF_INET))
  280. except socket.gaierror as e:
  281. raise RuleParseError('Failed to resolve {}: {}'.format(
  282. rule['dsthost'], str(e)))
  283. dsthosts = set(item[4][0] + fullmask for item in addrinfo)
  284. ret_dns[rule['dsthost']] = dsthosts
  285. else:
  286. dsthosts = None
  287. if 'dstports' in rule:
  288. dstports = rule['dstports'].replace('-', ':')
  289. else:
  290. dstports = None
  291. if rule.get('specialtarget', None) == 'dns':
  292. if dstports not in ('53:53', None):
  293. continue
  294. else:
  295. dstports = '53:53'
  296. if not dns:
  297. continue
  298. if protos is not None:
  299. protos = {'tcp', 'udp'}.intersection(protos)
  300. else:
  301. protos = {'tcp', 'udp'}
  302. if dsthosts is not None:
  303. dsthosts = set(dns).intersection(dsthosts)
  304. else:
  305. dsthosts = dns
  306. if 'icmptype' in rule:
  307. icmptype = rule['icmptype']
  308. else:
  309. icmptype = None
  310. # make them iterable
  311. if protos is None:
  312. protos = [None]
  313. if dsthosts is None:
  314. dsthosts = [None]
  315. if rule['action'] == 'accept':
  316. action = 'ACCEPT'
  317. elif rule['action'] == 'drop':
  318. action = 'REJECT --reject-with {}'.format(
  319. 'icmp6-adm-prohibited' if family == 6 else
  320. 'icmp-admin-prohibited')
  321. else:
  322. raise RuleParseError(
  323. 'Invalid rule action {}'.format(rule['action']))
  324. # sorting here is only to ease writing tests
  325. for proto in sorted(protos):
  326. for dsthost in sorted(dsthosts):
  327. ipt_rule = '-A {}'.format(chain)
  328. if dsthost is not None:
  329. ipt_rule += ' -d {}'.format(dsthost)
  330. if proto is not None:
  331. ipt_rule += ' -p {}'.format(proto)
  332. if dstports is not None:
  333. ipt_rule += ' --dport {}'.format(dstports)
  334. if icmptype is not None:
  335. ipt_rule += ' --icmp-type {}'.format(icmptype)
  336. ipt_rule += ' -j {}\n'.format(action)
  337. iptables += ipt_rule
  338. iptables += 'COMMIT\n'
  339. return (iptables, ret_dns)
  340. def apply_rules_family(self, source, rules, family):
  341. """
  342. Apply rules for given source address.
  343. Handle only rules for given address family (IPv4 or IPv6).
  344. :param source: source address
  345. :param rules: rules list
  346. :param family: address family, either 4 or 6
  347. :return: None
  348. """
  349. chain = self.chain_for_addr(source)
  350. if chain not in self.chains[family]:
  351. self.create_chain(source, chain, family)
  352. (iptables, dns) = self.prepare_rules(chain, rules, family)
  353. try:
  354. self.run_ipt(family, ['-F', chain])
  355. p = self.run_ipt_restore(family, ['-n'])
  356. (output, _) = p.communicate(iptables.encode())
  357. if p.returncode != 0:
  358. raise RuleApplyError(
  359. 'iptables-restore failed: {}'.format(output))
  360. self.update_dns_info(source, dns)
  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):
  499. """
  500. Helper function to translate rules list into input for nft
  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. :return: tuple: (input for nft, dict of DNS records resolved
  505. during execution)
  506. :rtype: (str, dict)
  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. ret_dns = {}
  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. ret_dns[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. ), ret_dns)
  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. (nft, dns) = self.prepare_rules(chain, rules, family)
  620. self.run_nft(nft)
  621. self.update_dns_info(source, dns)
  622. def apply_rules(self, source, rules):
  623. if self.is_ip6(source):
  624. self.apply_rules_family(source, rules, 6)
  625. else:
  626. self.apply_rules_family(source, rules, 4)
  627. def init(self):
  628. nft_init = (
  629. 'table {family} qubes-firewall {{\n'
  630. ' chain forward {{\n'
  631. ' type filter hook forward priority 0;\n'
  632. ' policy drop;\n'
  633. ' ct state established,related accept\n'
  634. ' meta iifname != "vif*" accept\n'
  635. ' }}\n'
  636. ' chain prerouting {{\n'
  637. ' type filter hook prerouting priority -300;\n'
  638. ' policy accept;\n'
  639. ' }}\n'
  640. ' chain postrouting {{\n'
  641. ' type filter hook postrouting priority -300;\n'
  642. ' policy accept;\n'
  643. ' }}\n'
  644. '}}\n'
  645. )
  646. nft_init = ''.join(
  647. nft_init.format(family=family) for family in ('ip', 'ip6'))
  648. self.run_nft(nft_init)
  649. def cleanup(self):
  650. nft_cleanup = (
  651. 'delete table ip qubes-firewall\n'
  652. 'delete table ip6 qubes-firewall\n'
  653. )
  654. self.run_nft(nft_cleanup)
  655. def main():
  656. if shutil.which('nft'):
  657. worker = NftablesWorker()
  658. else:
  659. worker = IptablesWorker()
  660. context = daemon.DaemonContext()
  661. context.stderr = sys.stderr
  662. context.detach_process = False
  663. context.files_preserve = [worker.qdb.watch_fd()]
  664. context.signal_map = {
  665. signal.SIGTERM: lambda _signal, _stack: worker.terminate(),
  666. }
  667. with context:
  668. worker.main()
  669. if __name__ == '__main__':
  670. main()