firewall.py 20 KB

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