firewall.py 21 KB

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