firewall.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2016
  7. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. import logging
  24. import os
  25. import socket
  26. import subprocess
  27. from distutils import spawn
  28. import daemon
  29. import qubesdb
  30. import sys
  31. import signal
  32. class RuleParseError(Exception):
  33. pass
  34. class RuleApplyError(Exception):
  35. pass
  36. class FirewallWorker(object):
  37. def __init__(self):
  38. self.terminate_requested = False
  39. self.qdb = qubesdb.QubesDB()
  40. self.log = logging.getLogger('qubes.firewall')
  41. self.log.addHandler(logging.StreamHandler(sys.stderr))
  42. def init(self):
  43. '''Create appropriate chains/tables'''
  44. raise NotImplementedError
  45. def cleanup(self):
  46. '''Remove tables/chains - reverse work done by init'''
  47. raise NotImplementedError
  48. def apply_rules(self, source_addr, rules):
  49. '''Apply rules in given source address'''
  50. raise NotImplementedError
  51. def read_rules(self, target):
  52. '''Read rules from QubesDB and return them as a list of dicts'''
  53. entries = self.qdb.multiread('/qubes-firewall/{}/'.format(target))
  54. assert isinstance(entries, dict)
  55. # drop full path
  56. entries = dict(((k.split('/')[3], v) for k, v in entries.items()))
  57. if 'policy' not in entries:
  58. raise RuleParseError('No \'policy\' defined')
  59. policy = entries.pop('policy')
  60. rules = []
  61. for ruleno, rule in sorted(entries.items()):
  62. if len(ruleno) != 4 or not ruleno.isdigit():
  63. raise RuleParseError(
  64. 'Unexpected non-rule found: {}={}'.format(ruleno, rule))
  65. rule_dict = dict(elem.split('=') for elem in rule.split(' '))
  66. if 'action' not in rule_dict:
  67. raise RuleParseError('Rule \'{}\' lack action'.format(rule))
  68. rules.append(rule_dict)
  69. rules.append({'action': policy})
  70. return rules
  71. def list_targets(self):
  72. return set(t.split('/')[2] for t in self.qdb.list('/qubes-firewall/'))
  73. @staticmethod
  74. def is_ip6(addr):
  75. return addr.count(':') > 0
  76. def log_error(self, msg):
  77. self.log.error(msg)
  78. subprocess.call(
  79. ['notify-send', '-t', '3000', msg],
  80. env=os.environ.copy().update({'DISPLAY': ':0'})
  81. )
  82. def handle_addr(self, addr):
  83. try:
  84. rules = self.read_rules(addr)
  85. self.apply_rules(addr, rules)
  86. except RuleParseError as e:
  87. self.log_error(
  88. 'Failed to parse rules for {} ({}), blocking traffic'.format(
  89. addr, str(e)
  90. ))
  91. self.apply_rules(addr, [{'action': 'drop'}])
  92. except RuleApplyError as e:
  93. self.log_error(
  94. 'Failed to apply rules for {} ({}), blocking traffic'.format(
  95. addr, str(e))
  96. )
  97. # retry with fallback rules
  98. try:
  99. self.apply_rules(addr, [{'action': 'drop'}])
  100. except RuleApplyError:
  101. self.log_error(
  102. 'Failed to block traffic for {}'.format(addr))
  103. @staticmethod
  104. def dns_addresses(family=None):
  105. with open('/etc/resolv.conf') as resolv:
  106. for line in resolv.readlines():
  107. line = line.strip()
  108. if line.startswith('nameserver'):
  109. if line.count('.') == 3 and (family or 4) == 4:
  110. yield line.split(' ')[1]
  111. elif line.count(':') and (family or 6) == 6:
  112. yield line.split(' ')[1]
  113. def main(self):
  114. self.terminate_requested = False
  115. self.init()
  116. # initial load
  117. for source_addr in self.list_targets():
  118. self.handle_addr(source_addr)
  119. self.qdb.watch('/qubes-firewall/')
  120. try:
  121. for watch_path in iter(self.qdb.read_watch, None):
  122. # ignore writing rules itself - wait for final write at
  123. # source_addr level empty write (/qubes-firewall/SOURCE_ADDR)
  124. if watch_path.count('/') > 2:
  125. continue
  126. source_addr = watch_path.split('/')[2]
  127. self.handle_addr(source_addr)
  128. except OSError: # EINTR
  129. # signal received, don't continue the loop
  130. pass
  131. self.cleanup()
  132. def terminate(self):
  133. self.terminate_requested = True
  134. class IptablesWorker(FirewallWorker):
  135. supported_rule_opts = ['action', 'proto', 'dst4', 'dst6', 'dsthost',
  136. 'dstports', 'specialtarget', 'icmptype']
  137. def __init__(self):
  138. super(IptablesWorker, self).__init__()
  139. self.chains = {
  140. 4: set(),
  141. 6: set(),
  142. }
  143. @staticmethod
  144. def chain_for_addr(addr):
  145. '''Generate iptables chain name for given source address address'''
  146. return 'qbs-' + addr.replace('.', '-').replace(':', '-')
  147. def run_ipt(self, family, args, **kwargs):
  148. # pylint: disable=no-self-use
  149. if family == 6:
  150. subprocess.check_call(['ip6tables'] + args, **kwargs)
  151. else:
  152. subprocess.check_call(['iptables'] + args, **kwargs)
  153. def run_ipt_restore(self, family, args):
  154. # pylint: disable=no-self-use
  155. if family == 6:
  156. return subprocess.Popen(['ip6tables-restore'] + args,
  157. stdin=subprocess.PIPE,
  158. stdout=subprocess.PIPE,
  159. stderr=subprocess.STDOUT)
  160. else:
  161. return subprocess.Popen(['iptables-restore'] + args,
  162. stdin=subprocess.PIPE,
  163. stdout=subprocess.PIPE,
  164. stderr=subprocess.STDOUT)
  165. def create_chain(self, addr, chain, family):
  166. '''
  167. Create iptables chain and hook traffic coming from `addr` to it.
  168. :param addr: source IP from which traffic should be handled by the
  169. chain
  170. :param chain: name of the chain to create
  171. :param family: address family (4 or 6)
  172. :return: None
  173. '''
  174. self.run_ipt(family, ['-N', chain])
  175. self.run_ipt(family,
  176. ['-A', 'QBS-FORWARD', '-s', addr, '-j', chain])
  177. self.chains[family].add(chain)
  178. def prepare_rules(self, chain, rules, family):
  179. '''
  180. Helper function to translate rules list into input for iptables-restore
  181. :param chain: name of the chain to put rules into
  182. :param rules: list of rules
  183. :param family: address family (4 or 6)
  184. :return: input for iptables-restore
  185. :rtype: str
  186. '''
  187. iptables = "*filter\n"
  188. fullmask = '/128' if family == 6 else '/32'
  189. dns = list(addr + fullmask for addr in self.dns_addresses(family))
  190. for rule in rules:
  191. unsupported_opts = set(rule.keys()).difference(
  192. set(self.supported_rule_opts))
  193. if unsupported_opts:
  194. raise RuleParseError(
  195. 'Unsupported rule option(s): {!s}'.format(unsupported_opts))
  196. if 'dst4' in rule and family == 6:
  197. raise RuleParseError('IPv4 rule found for IPv6 address')
  198. if 'dst6' in rule and family == 4:
  199. raise RuleParseError('dst6 rule found for IPv4 address')
  200. if 'proto' in rule:
  201. protos = [rule['proto']]
  202. else:
  203. protos = None
  204. if 'dst4' in rule:
  205. dsthosts = [rule['dst4']]
  206. elif 'dst6' in rule:
  207. dsthosts = [rule['dst6']]
  208. elif 'dsthost' in rule:
  209. addrinfo = socket.getaddrinfo(rule['dsthost'], None,
  210. (socket.AF_INET6 if family == 6 else socket.AF_INET))
  211. dsthosts = set(item[4][0] + fullmask for item in addrinfo)
  212. else:
  213. dsthosts = None
  214. if 'dstports' in rule:
  215. dstports = rule['dstports'].replace('-', ':')
  216. else:
  217. dstports = None
  218. if rule.get('specialtarget', None) == 'dns':
  219. if dstports not in ('53:53', None):
  220. continue
  221. else:
  222. dstports = '53:53'
  223. if not dns:
  224. continue
  225. if protos is not None:
  226. protos = {'tcp', 'udp'}.intersection(protos)
  227. else:
  228. protos = {'tcp', 'udp'}
  229. if dsthosts is not None:
  230. dsthosts = set(dns).intersection(dsthosts)
  231. else:
  232. dsthosts = dns
  233. if 'icmptype' in rule:
  234. icmptype = rule['icmptype']
  235. else:
  236. icmptype = None
  237. # make them iterable
  238. if protos is None:
  239. protos = [None]
  240. if dsthosts is None:
  241. dsthosts = [None]
  242. # sorting here is only to ease writing tests
  243. for proto in sorted(protos):
  244. for dsthost in sorted(dsthosts):
  245. ipt_rule = '-A {}'.format(chain)
  246. if dsthost is not None:
  247. ipt_rule += ' -d {}'.format(dsthost)
  248. if proto is not None:
  249. ipt_rule += ' -p {}'.format(proto)
  250. if dstports is not None:
  251. ipt_rule += ' --dport {}'.format(dstports)
  252. if icmptype is not None:
  253. ipt_rule += ' --icmp-type {}'.format(icmptype)
  254. ipt_rule += ' -j {}\n'.format(
  255. str(rule['action']).upper())
  256. iptables += ipt_rule
  257. iptables += 'COMMIT\n'
  258. return iptables
  259. def apply_rules_family(self, source, rules, family):
  260. '''
  261. Apply rules for given source address.
  262. Handle only rules for given address family (IPv4 or IPv6).
  263. :param source: source address
  264. :param rules: rules list
  265. :param family: address family, either 4 or 6
  266. :return: None
  267. '''
  268. chain = self.chain_for_addr(source)
  269. if chain not in self.chains[family]:
  270. self.create_chain(source, chain, family)
  271. iptables = self.prepare_rules(chain, rules, family)
  272. try:
  273. self.run_ipt(family, ['-F', chain])
  274. p = self.run_ipt_restore(family, ['-n'])
  275. (output, _) = p.communicate(iptables)
  276. if p.returncode != 0:
  277. raise RuleApplyError(
  278. 'iptables-restore failed: {}'.format(output))
  279. except subprocess.CalledProcessError as e:
  280. raise RuleApplyError('\'iptables -F {}\' failed: {}'.format(
  281. chain, e.output))
  282. def apply_rules(self, source, rules):
  283. if self.is_ip6(source):
  284. self.apply_rules_family(source, rules, 6)
  285. else:
  286. self.apply_rules_family(source, rules, 4)
  287. def init(self):
  288. # make sure 'QBS_FORWARD' chain exists - should be created before
  289. # starting qubes-firewall
  290. try:
  291. self.run_ipt(4, ['-nL', 'QBS-FORWARD'])
  292. self.run_ipt(6, ['-nL', 'QBS-FORWARD'])
  293. except subprocess.CalledProcessError:
  294. self.log_error('\'QBS-FORWARD\' chain not found, create it first')
  295. sys.exit(1)
  296. def cleanup(self):
  297. for family in (4, 6):
  298. self.run_ipt(family, ['-F', 'QBS-FORWARD'])
  299. for chain in self.chains[family]:
  300. self.run_ipt(family, ['-F', chain])
  301. self.run_ipt(family, ['-X', chain])
  302. class NftablesWorker(FirewallWorker):
  303. supported_rule_opts = ['action', 'proto', 'dst4', 'dst6', 'dsthost',
  304. 'dstports', 'specialtarget', 'icmptype']
  305. def __init__(self):
  306. super(NftablesWorker, self).__init__()
  307. self.chains = {
  308. 4: set(),
  309. 6: set(),
  310. }
  311. @staticmethod
  312. def chain_for_addr(addr):
  313. '''Generate iptables chain name for given source address address'''
  314. return 'qbs-' + addr.replace('.', '-').replace(':', '-')
  315. def run_nft(self, nft_input):
  316. # pylint: disable=no-self-use
  317. p = subprocess.Popen(['nft', '-f', '/dev/stdin'],
  318. stdin=subprocess.PIPE,
  319. stdout=subprocess.PIPE,
  320. stderr=subprocess.STDOUT)
  321. stdout, _ = p.communicate(nft_input)
  322. if p.returncode != 0:
  323. raise RuleApplyError('nft failed: {}'.format(stdout))
  324. def create_chain(self, addr, chain, family):
  325. '''
  326. Create iptables chain and hook traffic coming from `addr` to it.
  327. :param addr: source IP from which traffic should be handled by the
  328. chain
  329. :param chain: name of the chain to create
  330. :param family: address family (4 or 6)
  331. :return: None
  332. '''
  333. nft_input = (
  334. 'table {family} {table} {{\n'
  335. ' chain {chain} {{\n'
  336. ' }}\n'
  337. ' chain forward {{\n'
  338. ' {family} saddr {ip} jump {chain}\n'
  339. ' }}\n'
  340. '}}\n'.format(
  341. family=("ip6" if family == 6 else "ip"),
  342. table='qubes-firewall',
  343. chain=chain,
  344. ip=addr,
  345. )
  346. )
  347. self.run_nft(nft_input)
  348. self.chains[family].add(chain)
  349. def prepare_rules(self, chain, rules, family):
  350. '''
  351. Helper function to translate rules list into input for iptables-restore
  352. :param chain: name of the chain to put rules into
  353. :param rules: list of rules
  354. :param family: address family (4 or 6)
  355. :return: input for iptables-restore
  356. :rtype: str
  357. '''
  358. assert family in (4, 6)
  359. nft_rules = []
  360. ip_match = 'ip6' if family == 6 else 'ip'
  361. fullmask = '/128' if family == 6 else '/32'
  362. dns = list(addr + fullmask for addr in self.dns_addresses(family))
  363. for rule in rules:
  364. unsupported_opts = set(rule.keys()).difference(
  365. set(self.supported_rule_opts))
  366. if unsupported_opts:
  367. raise RuleParseError(
  368. 'Unsupported rule option(s): {!s}'.format(unsupported_opts))
  369. if 'dst4' in rule and family == 6:
  370. raise RuleParseError('IPv4 rule found for IPv6 address')
  371. if 'dst6' in rule and family == 4:
  372. raise RuleParseError('dst6 rule found for IPv4 address')
  373. nft_rule = ""
  374. if 'proto' in rule:
  375. if family == 4:
  376. nft_rule += ' ip protocol {}'.format(rule['proto'])
  377. elif family == 6:
  378. proto = 'icmpv6' if rule['proto'] == 'icmp' \
  379. else rule['proto']
  380. nft_rule += ' ip6 nexthdr {}'.format(proto)
  381. if 'dst4' in rule:
  382. nft_rule += ' ip daddr {}'.format(rule['dst4'])
  383. elif 'dst6' in rule:
  384. nft_rule += ' ip6 daddr {}'.format(rule['dst6'])
  385. elif 'dsthost' in rule:
  386. addrinfo = socket.getaddrinfo(rule['dsthost'], None,
  387. (socket.AF_INET6 if family == 6 else socket.AF_INET))
  388. nft_rule += ' {} daddr {{ {} }}'.format(ip_match,
  389. ', '.join(set(item[4][0] + fullmask for item in addrinfo)))
  390. if 'dstports' in rule:
  391. dstports = rule['dstports']
  392. if len(set(dstports.split('-'))) == 1:
  393. dstports = dstports.split('-')[0]
  394. else:
  395. dstports = None
  396. if rule.get('specialtarget', None) == 'dns':
  397. if dstports not in ('53', None):
  398. continue
  399. else:
  400. dstports = '53'
  401. if not dns:
  402. continue
  403. nft_rule += ' {} daddr {{ {} }}'.format(ip_match, ', '.join(
  404. dns))
  405. if 'icmptype' in rule:
  406. if family == 4:
  407. nft_rule += ' icmp type {}'.format(rule['icmptype'])
  408. elif family == 6:
  409. nft_rule += ' icmpv6 type {}'.format(rule['icmptype'])
  410. # now duplicate rules for tcp/udp if needed
  411. # it isn't possible to specify "tcp dport xx || udp dport xx" in
  412. # one rule
  413. if dstports is not None:
  414. if 'proto' not in rule:
  415. nft_rules.append(
  416. nft_rule + ' tcp dport {} {}'.format(
  417. dstports, rule['action']))
  418. nft_rules.append(
  419. nft_rule + ' udp dport {} {}'.format(
  420. dstports, rule['action']))
  421. else:
  422. nft_rules.append(
  423. nft_rule + ' {} dport {} {}'.format(
  424. rule['proto'], dstports, rule['action']))
  425. else:
  426. nft_rules.append(nft_rule + ' ' + rule['action'])
  427. return (
  428. 'flush chain {family} {table} {chain}\n'
  429. 'table {family} {table} {{\n'
  430. ' chain {chain} {{\n'
  431. ' {rules}\n'
  432. ' }}\n'
  433. '}}\n'.format(
  434. family=('ip6' if family == 6 else 'ip'),
  435. table='qubes-firewall',
  436. chain=chain,
  437. rules='\n '.join(nft_rules)
  438. ))
  439. def apply_rules_family(self, source, rules, family):
  440. '''
  441. Apply rules for given source address.
  442. Handle only rules for given address family (IPv4 or IPv6).
  443. :param source: source address
  444. :param rules: rules list
  445. :param family: address family, either 4 or 6
  446. :return: None
  447. '''
  448. chain = self.chain_for_addr(source)
  449. if chain not in self.chains[family]:
  450. self.create_chain(source, chain, family)
  451. self.run_nft(self.prepare_rules(chain, rules, family))
  452. def apply_rules(self, source, rules):
  453. if self.is_ip6(source):
  454. self.apply_rules_family(source, rules, 6)
  455. else:
  456. self.apply_rules_family(source, rules, 4)
  457. def init(self):
  458. # make sure 'QBS_FORWARD' chain exists - should be created before
  459. # starting qubes-firewall
  460. nft_init = (
  461. 'table {family} qubes-firewall {{\n'
  462. ' chain forward {{\n'
  463. ' type filter hook forward priority 0;\n'
  464. ' }}\n'
  465. '}}\n'
  466. )
  467. nft_init = ''.join(
  468. nft_init.format(family=family) for family in ('ip', 'ip6'))
  469. self.run_nft(nft_init)
  470. def cleanup(self):
  471. nft_cleanup = (
  472. 'delete table ip qubes-firewall\n'
  473. 'delete table ip6 qubes-firewall\n'
  474. )
  475. self.run_nft(nft_cleanup)
  476. def main():
  477. if spawn.find_executable('nft'):
  478. worker = NftablesWorker()
  479. else:
  480. worker = IptablesWorker()
  481. context = daemon.DaemonContext()
  482. context.stderr = sys.stderr
  483. context.detach_process = False
  484. context.files_preserve = [worker.qdb.watch_fd()]
  485. context.signal_map = {
  486. signal.SIGTERM: lambda _signal, _stack: worker.terminate(),
  487. }
  488. with context:
  489. worker.main()
  490. if __name__ == '__main__':
  491. main()