firewall.py 20 KB

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