firewall.py 21 KB

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