firewall.py 20 KB

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