firewall.py 21 KB

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