firewall.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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(':', '-')[-20:]
  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. ['-I', '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. if rule['proto'] == 'icmp' and family == 6:
  202. protos = ['icmpv6']
  203. else:
  204. protos = [rule['proto']]
  205. else:
  206. protos = None
  207. if 'dst4' in rule:
  208. dsthosts = [rule['dst4']]
  209. elif 'dst6' in rule:
  210. dsthosts = [rule['dst6']]
  211. elif 'dsthost' in rule:
  212. addrinfo = socket.getaddrinfo(rule['dsthost'], None,
  213. (socket.AF_INET6 if family == 6 else socket.AF_INET))
  214. dsthosts = set(item[4][0] + fullmask for item in addrinfo)
  215. else:
  216. dsthosts = None
  217. if 'dstports' in rule:
  218. dstports = rule['dstports'].replace('-', ':')
  219. else:
  220. dstports = None
  221. if rule.get('specialtarget', None) == 'dns':
  222. if dstports not in ('53:53', None):
  223. continue
  224. else:
  225. dstports = '53:53'
  226. if not dns:
  227. continue
  228. if protos is not None:
  229. protos = {'tcp', 'udp'}.intersection(protos)
  230. else:
  231. protos = {'tcp', 'udp'}
  232. if dsthosts is not None:
  233. dsthosts = set(dns).intersection(dsthosts)
  234. else:
  235. dsthosts = dns
  236. if 'icmptype' in rule:
  237. icmptype = rule['icmptype']
  238. else:
  239. icmptype = None
  240. # make them iterable
  241. if protos is None:
  242. protos = [None]
  243. if dsthosts is None:
  244. dsthosts = [None]
  245. # sorting here is only to ease writing tests
  246. for proto in sorted(protos):
  247. for dsthost in sorted(dsthosts):
  248. ipt_rule = '-A {}'.format(chain)
  249. if dsthost is not None:
  250. ipt_rule += ' -d {}'.format(dsthost)
  251. if proto is not None:
  252. ipt_rule += ' -p {}'.format(proto)
  253. if dstports is not None:
  254. ipt_rule += ' --dport {}'.format(dstports)
  255. if icmptype is not None:
  256. ipt_rule += ' --icmp-type {}'.format(icmptype)
  257. ipt_rule += ' -j {}\n'.format(
  258. str(rule['action']).upper())
  259. iptables += ipt_rule
  260. iptables += 'COMMIT\n'
  261. return iptables
  262. def apply_rules_family(self, source, rules, family):
  263. '''
  264. Apply rules for given source address.
  265. Handle only rules for given address family (IPv4 or IPv6).
  266. :param source: source address
  267. :param rules: rules list
  268. :param family: address family, either 4 or 6
  269. :return: None
  270. '''
  271. chain = self.chain_for_addr(source)
  272. if chain not in self.chains[family]:
  273. self.create_chain(source, chain, family)
  274. iptables = self.prepare_rules(chain, rules, family)
  275. try:
  276. self.run_ipt(family, ['-F', chain])
  277. p = self.run_ipt_restore(family, ['-n'])
  278. (output, _) = p.communicate(iptables)
  279. if p.returncode != 0:
  280. raise RuleApplyError(
  281. 'iptables-restore failed: {}'.format(output))
  282. except subprocess.CalledProcessError as e:
  283. raise RuleApplyError('\'iptables -F {}\' failed: {}'.format(
  284. chain, e.output))
  285. def apply_rules(self, source, rules):
  286. if self.is_ip6(source):
  287. self.apply_rules_family(source, rules, 6)
  288. else:
  289. self.apply_rules_family(source, rules, 4)
  290. def init(self):
  291. # make sure 'QBS_FORWARD' chain exists - should be created before
  292. # starting qubes-firewall
  293. try:
  294. self.run_ipt(4, ['-F', 'QBS-FORWARD'])
  295. self.run_ipt(4, ['-A', 'QBS-FORWARD', '-j', 'DROP'])
  296. self.run_ipt(6, ['-F', 'QBS-FORWARD'])
  297. self.run_ipt(6, ['-A', 'QBS-FORWARD', '-j', 'DROP'])
  298. except subprocess.CalledProcessError:
  299. self.log_error('\'QBS-FORWARD\' chain not found, create it first')
  300. sys.exit(1)
  301. def cleanup(self):
  302. for family in (4, 6):
  303. self.run_ipt(family, ['-F', 'QBS-FORWARD'])
  304. for chain in self.chains[family]:
  305. self.run_ipt(family, ['-F', chain])
  306. self.run_ipt(family, ['-X', chain])
  307. class NftablesWorker(FirewallWorker):
  308. supported_rule_opts = ['action', 'proto', 'dst4', 'dst6', 'dsthost',
  309. 'dstports', 'specialtarget', 'icmptype']
  310. def __init__(self):
  311. super(NftablesWorker, self).__init__()
  312. self.chains = {
  313. 4: set(),
  314. 6: set(),
  315. }
  316. @staticmethod
  317. def chain_for_addr(addr):
  318. '''Generate iptables chain name for given source address address'''
  319. return 'qbs-' + addr.replace('.', '-').replace(':', '-')
  320. def run_nft(self, nft_input):
  321. # pylint: disable=no-self-use
  322. p = subprocess.Popen(['nft', '-f', '/dev/stdin'],
  323. stdin=subprocess.PIPE,
  324. stdout=subprocess.PIPE,
  325. stderr=subprocess.STDOUT)
  326. stdout, _ = p.communicate(nft_input)
  327. if p.returncode != 0:
  328. raise RuleApplyError('nft failed: {}'.format(stdout))
  329. def create_chain(self, addr, chain, family):
  330. '''
  331. Create iptables chain and hook traffic coming from `addr` to it.
  332. :param addr: source IP from which traffic should be handled by the
  333. chain
  334. :param chain: name of the chain to create
  335. :param family: address family (4 or 6)
  336. :return: None
  337. '''
  338. nft_input = (
  339. 'table {family} {table} {{\n'
  340. ' chain {chain} {{\n'
  341. ' }}\n'
  342. ' chain forward {{\n'
  343. ' {family} saddr {ip} jump {chain}\n'
  344. ' }}\n'
  345. '}}\n'.format(
  346. family=("ip6" if family == 6 else "ip"),
  347. table='qubes-firewall',
  348. chain=chain,
  349. ip=addr,
  350. )
  351. )
  352. self.run_nft(nft_input)
  353. self.chains[family].add(chain)
  354. def prepare_rules(self, chain, rules, family):
  355. '''
  356. Helper function to translate rules list into input for iptables-restore
  357. :param chain: name of the chain to put rules into
  358. :param rules: list of rules
  359. :param family: address family (4 or 6)
  360. :return: input for iptables-restore
  361. :rtype: str
  362. '''
  363. assert family in (4, 6)
  364. nft_rules = []
  365. ip_match = 'ip6' if family == 6 else 'ip'
  366. fullmask = '/128' if family == 6 else '/32'
  367. dns = list(addr + fullmask for addr in self.dns_addresses(family))
  368. for rule in rules:
  369. unsupported_opts = set(rule.keys()).difference(
  370. set(self.supported_rule_opts))
  371. if unsupported_opts:
  372. raise RuleParseError(
  373. 'Unsupported rule option(s): {!s}'.format(unsupported_opts))
  374. if 'dst4' in rule and family == 6:
  375. raise RuleParseError('IPv4 rule found for IPv6 address')
  376. if 'dst6' in rule and family == 4:
  377. raise RuleParseError('dst6 rule found for IPv4 address')
  378. nft_rule = ""
  379. if 'proto' in rule:
  380. if family == 4:
  381. nft_rule += ' ip protocol {}'.format(rule['proto'])
  382. elif family == 6:
  383. proto = 'icmpv6' if rule['proto'] == 'icmp' \
  384. else rule['proto']
  385. nft_rule += ' ip6 nexthdr {}'.format(proto)
  386. if 'dst4' in rule:
  387. nft_rule += ' ip daddr {}'.format(rule['dst4'])
  388. elif 'dst6' in rule:
  389. nft_rule += ' ip6 daddr {}'.format(rule['dst6'])
  390. elif 'dsthost' in rule:
  391. addrinfo = socket.getaddrinfo(rule['dsthost'], None,
  392. (socket.AF_INET6 if family == 6 else socket.AF_INET))
  393. nft_rule += ' {} daddr {{ {} }}'.format(ip_match,
  394. ', '.join(set(item[4][0] + fullmask for item in addrinfo)))
  395. if 'dstports' in rule:
  396. dstports = rule['dstports']
  397. if len(set(dstports.split('-'))) == 1:
  398. dstports = dstports.split('-')[0]
  399. else:
  400. dstports = None
  401. if rule.get('specialtarget', None) == 'dns':
  402. if dstports not in ('53', None):
  403. continue
  404. else:
  405. dstports = '53'
  406. if not dns:
  407. continue
  408. nft_rule += ' {} daddr {{ {} }}'.format(ip_match, ', '.join(
  409. dns))
  410. if 'icmptype' in rule:
  411. if family == 4:
  412. nft_rule += ' icmp type {}'.format(rule['icmptype'])
  413. elif family == 6:
  414. nft_rule += ' icmpv6 type {}'.format(rule['icmptype'])
  415. # now duplicate rules for tcp/udp if needed
  416. # it isn't possible to specify "tcp dport xx || udp dport xx" in
  417. # one rule
  418. if dstports is not None:
  419. if 'proto' not in rule:
  420. nft_rules.append(
  421. nft_rule + ' tcp dport {} {}'.format(
  422. dstports, rule['action']))
  423. nft_rules.append(
  424. nft_rule + ' udp dport {} {}'.format(
  425. dstports, rule['action']))
  426. else:
  427. nft_rules.append(
  428. nft_rule + ' {} dport {} {}'.format(
  429. rule['proto'], dstports, rule['action']))
  430. else:
  431. nft_rules.append(nft_rule + ' ' + rule['action'])
  432. return (
  433. 'flush chain {family} {table} {chain}\n'
  434. 'table {family} {table} {{\n'
  435. ' chain {chain} {{\n'
  436. ' {rules}\n'
  437. ' }}\n'
  438. '}}\n'.format(
  439. family=('ip6' if family == 6 else 'ip'),
  440. table='qubes-firewall',
  441. chain=chain,
  442. rules='\n '.join(nft_rules)
  443. ))
  444. def apply_rules_family(self, source, rules, family):
  445. '''
  446. Apply rules for given source address.
  447. Handle only rules for given address family (IPv4 or IPv6).
  448. :param source: source address
  449. :param rules: rules list
  450. :param family: address family, either 4 or 6
  451. :return: None
  452. '''
  453. chain = self.chain_for_addr(source)
  454. if chain not in self.chains[family]:
  455. self.create_chain(source, chain, family)
  456. self.run_nft(self.prepare_rules(chain, rules, family))
  457. def apply_rules(self, source, rules):
  458. if self.is_ip6(source):
  459. self.apply_rules_family(source, rules, 6)
  460. else:
  461. self.apply_rules_family(source, rules, 4)
  462. def init(self):
  463. # make sure 'QBS_FORWARD' chain exists - should be created before
  464. # starting qubes-firewall
  465. nft_init = (
  466. 'table {family} qubes-firewall {{\n'
  467. ' chain forward {{\n'
  468. ' type filter hook forward priority 0;\n'
  469. ' policy drop;\n'
  470. ' ct state established accept\n'
  471. ' }}\n'
  472. '}}\n'
  473. )
  474. nft_init = ''.join(
  475. nft_init.format(family=family) for family in ('ip', 'ip6'))
  476. self.run_nft(nft_init)
  477. def cleanup(self):
  478. nft_cleanup = (
  479. 'delete table ip qubes-firewall\n'
  480. 'delete table ip6 qubes-firewall\n'
  481. )
  482. self.run_nft(nft_cleanup)
  483. def main():
  484. if spawn.find_executable('nft'):
  485. worker = NftablesWorker()
  486. else:
  487. worker = IptablesWorker()
  488. context = daemon.DaemonContext()
  489. context.stderr = sys.stderr
  490. context.detach_process = False
  491. context.files_preserve = [worker.qdb.watch_fd()]
  492. context.signal_map = {
  493. signal.SIGTERM: lambda _signal, _stack: worker.terminate(),
  494. }
  495. with context:
  496. worker.main()
  497. if __name__ == '__main__':
  498. main()