firewall.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. # pylint: disable=too-few-public-methods
  2. #
  3. # The Qubes OS Project, https://www.qubes-os.org/
  4. #
  5. # Copyright (C) 2016
  6. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  7. #
  8. # This library is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU Lesser General Public
  10. # License as published by the Free Software Foundation; either
  11. # version 2.1 of the License, or (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. # Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public
  19. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  20. #
  21. import datetime
  22. import string
  23. import itertools
  24. import os
  25. import socket
  26. import asyncio
  27. import lxml.etree
  28. import qubes
  29. import qubes.utils
  30. import qubes.vm.qubesvm
  31. class RuleOption:
  32. def __init__(self, untrusted_value):
  33. # subset of string.punctuation
  34. safe_set = string.ascii_letters + string.digits + \
  35. ':;,./-_[]'
  36. untrusted_value = str(untrusted_value)
  37. if not all(x in safe_set for x in untrusted_value):
  38. raise ValueError('strange characters in rule')
  39. self._value = untrusted_value
  40. @property
  41. def rule(self):
  42. raise NotImplementedError
  43. @property
  44. def api_rule(self):
  45. return self.rule
  46. def __str__(self):
  47. return self._value
  48. def __eq__(self, other):
  49. return str(self) == other
  50. # noinspection PyAbstractClass
  51. class RuleChoice(RuleOption):
  52. # pylint: disable=abstract-method
  53. def __init__(self, untrusted_value):
  54. # preliminary validation
  55. super().__init__(untrusted_value)
  56. self.allowed_values = \
  57. [v for k, v in self.__class__.__dict__.items()
  58. if not k.startswith('__') and isinstance(v, str) and
  59. not v.startswith('__')]
  60. if untrusted_value not in self.allowed_values:
  61. raise ValueError(untrusted_value)
  62. class Action(RuleChoice):
  63. accept = 'accept'
  64. drop = 'drop'
  65. @property
  66. def rule(self):
  67. return 'action=' + str(self)
  68. class Proto(RuleChoice):
  69. tcp = 'tcp'
  70. udp = 'udp'
  71. icmp = 'icmp'
  72. @property
  73. def rule(self):
  74. return 'proto=' + str(self)
  75. class DstHost(RuleOption):
  76. '''Represent host/network address: either IPv4, IPv6, or DNS name'''
  77. def __init__(self, untrusted_value, prefixlen=None):
  78. if untrusted_value.count('/') > 1:
  79. raise ValueError('Too many /: ' + untrusted_value)
  80. if not untrusted_value.count('/'):
  81. # add prefix length to bare IP addresses
  82. try:
  83. socket.inet_pton(socket.AF_INET6, untrusted_value)
  84. value = untrusted_value
  85. self.prefixlen = prefixlen or 128
  86. if self.prefixlen < 0 or self.prefixlen > 128:
  87. raise ValueError(
  88. 'netmask for IPv6 must be between 0 and 128')
  89. value += '/' + str(self.prefixlen)
  90. self.type = 'dst6'
  91. except socket.error:
  92. try:
  93. socket.inet_pton(socket.AF_INET, untrusted_value)
  94. if untrusted_value.count('.') != 3:
  95. raise ValueError(
  96. 'Invalid number of dots in IPv4 address')
  97. value = untrusted_value
  98. self.prefixlen = prefixlen or 32
  99. if self.prefixlen < 0 or self.prefixlen > 32:
  100. raise ValueError(
  101. 'netmask for IPv4 must be between 0 and 32')
  102. value += '/' + str(self.prefixlen)
  103. self.type = 'dst4'
  104. except socket.error:
  105. self.type = 'dsthost'
  106. self.prefixlen = 0
  107. safe_set = string.ascii_lowercase + string.digits + '-._'
  108. if not all(c in safe_set for c in untrusted_value):
  109. raise ValueError('Invalid hostname')
  110. value = untrusted_value
  111. else:
  112. untrusted_host, untrusted_prefixlen = untrusted_value.split('/', 1)
  113. prefixlen = int(untrusted_prefixlen)
  114. if prefixlen < 0:
  115. raise ValueError('netmask must be non-negative')
  116. self.prefixlen = prefixlen
  117. try:
  118. socket.inet_pton(socket.AF_INET6, untrusted_host)
  119. value = untrusted_value
  120. if prefixlen > 128:
  121. raise ValueError('netmask for IPv6 must be <= 128')
  122. self.type = 'dst6'
  123. except socket.error:
  124. try:
  125. socket.inet_pton(socket.AF_INET, untrusted_host)
  126. if prefixlen > 32:
  127. raise ValueError('netmask for IPv4 must be <= 32')
  128. self.type = 'dst4'
  129. if untrusted_host.count('.') != 3:
  130. raise ValueError(
  131. 'Invalid number of dots in IPv4 address')
  132. value = untrusted_value
  133. except socket.error:
  134. raise ValueError('Invalid IP address: ' + untrusted_host)
  135. super().__init__(value)
  136. @property
  137. def rule(self):
  138. return self.type + '=' + str(self)
  139. class DstPorts(RuleOption):
  140. def __init__(self, untrusted_value):
  141. if isinstance(untrusted_value, int):
  142. untrusted_value = str(untrusted_value)
  143. if untrusted_value.count('-') == 1:
  144. self.range = [int(x) for x in untrusted_value.split('-', 1)]
  145. elif not untrusted_value.count('-'):
  146. self.range = [int(untrusted_value), int(untrusted_value)]
  147. else:
  148. raise ValueError(untrusted_value)
  149. if any(port < 0 or port > 65536 for port in self.range):
  150. raise ValueError('Ports out of range')
  151. if self.range[0] > self.range[1]:
  152. raise ValueError('Invalid port range')
  153. super().__init__(
  154. str(self.range[0]) if self.range[0] == self.range[1]
  155. else '-'.join(map(str, self.range)))
  156. @property
  157. def rule(self):
  158. return 'dstports=' + '{!s}-{!s}'.format(*self.range)
  159. class IcmpType(RuleOption):
  160. def __init__(self, untrusted_value):
  161. untrusted_value = int(untrusted_value)
  162. if untrusted_value < 0 or untrusted_value > 255:
  163. raise ValueError('ICMP type out of range')
  164. super().__init__(untrusted_value)
  165. @property
  166. def rule(self):
  167. return 'icmptype=' + str(self)
  168. class SpecialTarget(RuleChoice):
  169. dns = 'dns'
  170. @property
  171. def rule(self):
  172. return 'specialtarget=' + str(self)
  173. class Expire(RuleOption):
  174. def __init__(self, untrusted_value):
  175. super().__init__(untrusted_value)
  176. self.datetime = datetime.datetime.fromtimestamp(int(untrusted_value))
  177. @property
  178. def rule(self):
  179. pass
  180. @property
  181. def api_rule(self):
  182. return 'expire=' + str(self)
  183. @property
  184. def expired(self):
  185. return self.datetime < datetime.datetime.now()
  186. class Comment(RuleOption):
  187. # noinspection PyMissingConstructor
  188. def __init__(self, untrusted_value):
  189. # pylint: disable=super-init-not-called
  190. # subset of string.punctuation
  191. safe_set = string.ascii_letters + string.digits + \
  192. ':;,./-_[] '
  193. untrusted_value = str(untrusted_value)
  194. if not all(x in safe_set for x in untrusted_value):
  195. raise ValueError('strange characters comment')
  196. self._value = untrusted_value
  197. @property
  198. def rule(self):
  199. pass
  200. @property
  201. def api_rule(self):
  202. return 'comment=' + str(self)
  203. class Rule(qubes.PropertyHolder):
  204. def __init__(self, xml=None, **kwargs):
  205. '''Single firewall rule
  206. :param xml: XML element describing rule, or None
  207. :param kwargs: rule elements
  208. '''
  209. super().__init__(xml, **kwargs)
  210. self.load_properties()
  211. self.events_enabled = True
  212. # validate dependencies
  213. if self.dstports:
  214. self.on_set_dstports('property-set:dstports', 'dstports',
  215. self.dstports, None)
  216. if self.icmptype:
  217. self.on_set_icmptype('property-set:icmptype', 'icmptype',
  218. self.icmptype, None)
  219. self.property_require('action', False, True)
  220. action = qubes.property('action',
  221. type=Action,
  222. order=0,
  223. doc='rule action')
  224. proto = qubes.property('proto',
  225. type=Proto,
  226. default=None,
  227. order=1,
  228. doc='protocol to match')
  229. dsthost = qubes.property('dsthost',
  230. type=DstHost,
  231. default=None,
  232. order=1,
  233. doc='destination host/network')
  234. dstports = qubes.property('dstports',
  235. type=DstPorts,
  236. default=None,
  237. order=2,
  238. doc='Destination port(s) (for \'tcp\' and \'udp\' protocol only)')
  239. icmptype = qubes.property('icmptype',
  240. type=IcmpType,
  241. default=None,
  242. order=2,
  243. doc='ICMP packet type (for \'icmp\' protocol only)')
  244. specialtarget = qubes.property('specialtarget',
  245. type=SpecialTarget,
  246. default=None,
  247. order=1,
  248. doc='Special target, for now only \'dns\' supported')
  249. expire = qubes.property('expire',
  250. type=Expire,
  251. default=None,
  252. doc='Timestamp (UNIX epoch) on which this rule expire')
  253. comment = qubes.property('comment',
  254. type=Comment,
  255. default=None,
  256. doc='User comment')
  257. # noinspection PyUnusedLocal
  258. @qubes.events.handler('property-pre-set:dstports')
  259. def on_set_dstports(self, event, name, newvalue, oldvalue=None):
  260. # pylint: disable=unused-argument
  261. if self.proto not in ('tcp', 'udp'):
  262. raise ValueError(
  263. 'dstports valid only for \'tcp\' and \'udp\' protocols')
  264. # noinspection PyUnusedLocal
  265. @qubes.events.handler('property-pre-set:icmptype')
  266. def on_set_icmptype(self, event, name, newvalue, oldvalue=None):
  267. # pylint: disable=unused-argument
  268. if self.proto not in ('icmp',):
  269. raise ValueError('icmptype valid only for \'icmp\' protocol')
  270. # noinspection PyUnusedLocal
  271. @qubes.events.handler('property-set:proto')
  272. def on_set_proto(self, event, name, newvalue, oldvalue=None):
  273. # pylint: disable=unused-argument
  274. if newvalue not in ('tcp', 'udp'):
  275. self.dstports = qubes.property.DEFAULT
  276. if newvalue not in ('icmp',):
  277. self.icmptype = qubes.property.DEFAULT
  278. @qubes.events.handler('property-reset:proto')
  279. def on_reset_proto(self, event, name, oldvalue):
  280. # pylint: disable=unused-argument
  281. self.dstports = qubes.property.DEFAULT
  282. self.icmptype = qubes.property.DEFAULT
  283. @property
  284. def rule(self):
  285. if self.expire and self.expire.expired:
  286. return None
  287. values = []
  288. for prop in self.property_list():
  289. value = getattr(self, prop.__name__)
  290. if value is None:
  291. continue
  292. if value.rule is None:
  293. continue
  294. values.append(value.rule)
  295. return ' '.join(values)
  296. @property
  297. def api_rule(self):
  298. values = []
  299. if self.expire and self.expire.expired:
  300. return None
  301. # put comment at the end
  302. for prop in sorted(self.property_list(),
  303. key=(lambda p: p.__name__ == 'comment')):
  304. value = getattr(self, prop.__name__)
  305. if value is None:
  306. continue
  307. if value.api_rule is None:
  308. continue
  309. values.append(value.api_rule)
  310. return ' '.join(values)
  311. @classmethod
  312. def from_xml_v1(cls, node, action):
  313. netmask = node.get('netmask')
  314. if netmask is None:
  315. netmask = 32
  316. else:
  317. netmask = int(netmask)
  318. address = node.get('address')
  319. if address:
  320. dsthost = DstHost(address, netmask)
  321. else:
  322. dsthost = None
  323. proto = node.get('proto')
  324. port = node.get('port')
  325. toport = node.get('toport')
  326. if port and toport:
  327. dstports = port + '-' + toport
  328. elif port:
  329. dstports = port
  330. else:
  331. dstports = None
  332. # backward compatibility: protocol defaults to TCP if port is specified
  333. if dstports and not proto:
  334. proto = 'tcp'
  335. if proto == 'any':
  336. proto = None
  337. expire = node.get('expire')
  338. kwargs = {
  339. 'action': action,
  340. }
  341. if dsthost:
  342. kwargs['dsthost'] = dsthost
  343. if dstports:
  344. kwargs['dstports'] = dstports
  345. if proto:
  346. kwargs['proto'] = proto
  347. if expire:
  348. kwargs['expire'] = expire
  349. return cls(**kwargs)
  350. @classmethod
  351. def from_api_string(cls, untrusted_rule):
  352. '''Parse a single line of firewall rule'''
  353. # comment is allowed to have spaces
  354. untrusted_options, _, untrusted_comment = untrusted_rule.partition(
  355. 'comment=')
  356. # appropriate handlers in __init__ of individual options will perform
  357. # option-specific validation
  358. kwargs = {}
  359. if untrusted_comment:
  360. kwargs['comment'] = Comment(untrusted_value=untrusted_comment)
  361. for untrusted_option in untrusted_options.strip().split(' '):
  362. untrusted_key, untrusted_value = untrusted_option.split('=', 1)
  363. if untrusted_key in kwargs:
  364. raise ValueError('Option \'{}\' already set'.format(
  365. untrusted_key))
  366. if untrusted_key in [str(prop) for prop in cls.property_list()]:
  367. kwargs[untrusted_key] = cls.property_get_def(
  368. untrusted_key).type(untrusted_value=untrusted_value)
  369. elif untrusted_key in ('dst4', 'dst6', 'dstname'):
  370. if 'dsthost' in kwargs:
  371. raise ValueError('Option \'{}\' already set'.format(
  372. 'dsthost'))
  373. kwargs['dsthost'] = DstHost(untrusted_value=untrusted_value)
  374. else:
  375. raise ValueError('Unknown firewall option')
  376. return cls(**kwargs)
  377. def __eq__(self, other):
  378. if isinstance(other, Rule):
  379. return self.api_rule == other.api_rule
  380. return self.api_rule == str(other)
  381. def __hash__(self):
  382. return hash(self.api_rule)
  383. class Firewall:
  384. def __init__(self, vm, load=True):
  385. assert hasattr(vm, 'firewall_conf')
  386. self.vm = vm
  387. #: firewall rules
  388. self.rules = []
  389. if load:
  390. self.load()
  391. @property
  392. def policy(self):
  393. ''' Default action - always 'drop' '''
  394. return Action('drop')
  395. def __eq__(self, other):
  396. if isinstance(other, Firewall):
  397. return self.rules == other.rules
  398. return NotImplemented
  399. def load_defaults(self):
  400. '''Load default firewall settings'''
  401. self.rules = [Rule(None, action='accept')]
  402. def clone(self, other):
  403. '''Clone firewall settings from other instance.
  404. This method discards pre-existing firewall settings.
  405. :param other: other :py:class:`Firewall` instance
  406. '''
  407. rules = []
  408. for rule in other.rules:
  409. # Rule constructor require some action, will be overwritten by
  410. # clone_properties below
  411. new_rule = Rule(action='drop')
  412. new_rule.clone_properties(rule)
  413. rules.append(new_rule)
  414. self.rules = rules
  415. def load(self):
  416. '''Load firewall settings from a file'''
  417. firewall_conf = os.path.join(self.vm.dir_path, self.vm.firewall_conf)
  418. if os.path.exists(firewall_conf):
  419. self.rules = []
  420. tree = lxml.etree.parse(firewall_conf)
  421. root = tree.getroot()
  422. version = root.get('version', '1')
  423. if version == '1':
  424. self.load_v1(root)
  425. elif version == '2':
  426. self.load_v2(root)
  427. else:
  428. raise qubes.exc.QubesVMError(self.vm,
  429. 'Unsupported firewall.xml version: {}'.format(version))
  430. else:
  431. self.load_defaults()
  432. def load_v1(self, xml_root):
  433. '''Load old (Qubes < 4.0) firewall XML format'''
  434. policy_v1 = xml_root.get('policy')
  435. assert policy_v1 in ('allow', 'deny')
  436. default_policy_is_accept = (policy_v1 == 'allow')
  437. def _translate_action(key):
  438. if xml_root.get(key, policy_v1) == 'allow':
  439. return Action.accept
  440. return Action.drop
  441. self.rules.append(Rule(None,
  442. action=_translate_action('dns'),
  443. specialtarget=SpecialTarget('dns')))
  444. self.rules.append(Rule(None,
  445. action=_translate_action('icmp'),
  446. proto=Proto.icmp))
  447. if default_policy_is_accept:
  448. rule_action = Action.drop
  449. else:
  450. rule_action = Action.accept
  451. for element in xml_root:
  452. rule = Rule.from_xml_v1(element, rule_action)
  453. self.rules.append(rule)
  454. if default_policy_is_accept:
  455. self.rules.append(Rule(None, action='accept'))
  456. def load_v2(self, xml_root):
  457. '''Load new (Qubes >= 4.0) firewall XML format'''
  458. xml_rules = xml_root.find('rules')
  459. for xml_rule in xml_rules:
  460. rule = Rule(xml_rule)
  461. self.rules.append(rule)
  462. def _expire_rules(self):
  463. '''Function called to reload expired rules'''
  464. self.load()
  465. # this will both save rules skipping those expired and trigger
  466. # QubesDB update; and possibly schedule another timer
  467. self.save()
  468. def save(self):
  469. '''Save firewall rules to a file'''
  470. firewall_conf = os.path.join(self.vm.dir_path, self.vm.firewall_conf)
  471. nearest_expire = None
  472. xml_root = lxml.etree.Element('firewall', version=str(2))
  473. xml_rules = lxml.etree.Element('rules')
  474. for rule in self.rules:
  475. if rule.expire:
  476. if rule.expire and rule.expire.expired:
  477. continue
  478. if nearest_expire is None or rule.expire.datetime < \
  479. nearest_expire:
  480. nearest_expire = rule.expire.datetime
  481. xml_rule = lxml.etree.Element('rule')
  482. xml_rule.append(rule.xml_properties())
  483. xml_rules.append(xml_rule)
  484. xml_root.append(xml_rules)
  485. xml_tree = lxml.etree.ElementTree(xml_root)
  486. try:
  487. with qubes.utils.replace_file(firewall_conf,
  488. permissions=0o664) as tmp_io:
  489. xml_tree.write(tmp_io, encoding='UTF-8', pretty_print=True)
  490. except EnvironmentError as err:
  491. msg='firewall save error: {}'.format(err)
  492. self.vm.log.error(msg)
  493. raise qubes.exc.QubesException(msg)
  494. self.vm.fire_event('firewall-changed')
  495. if nearest_expire and not self.vm.app.vmm.offline_mode:
  496. loop = asyncio.get_event_loop()
  497. # by documentation call_at use loop.time() clock, which not
  498. # necessary must be the same as time module; calculate delay and
  499. # use call_later instead
  500. expire_when = nearest_expire - datetime.datetime.now()
  501. loop.call_later(expire_when.total_seconds(), self._expire_rules)
  502. def qdb_entries(self, addr_family=None):
  503. '''Return firewall settings serialized for QubesDB entries
  504. :param addr_family: include rules only for IPv4 (4) or IPv6 (6); if
  505. None, include both
  506. '''
  507. entries = {
  508. 'policy': str(self.policy)
  509. }
  510. exclude_dsttype = None
  511. if addr_family is not None:
  512. exclude_dsttype = 'dst4' if addr_family == 6 else 'dst6'
  513. for ruleno, rule in zip(itertools.count(), self.rules):
  514. if rule.expire and rule.expire.expired:
  515. continue
  516. # exclude rules for another address family
  517. if rule.dsthost and rule.dsthost.type == exclude_dsttype:
  518. continue
  519. entries['{:04}'.format(ruleno)] = rule.rule
  520. return entries