firewall.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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. # put comment at the end
  297. for prop in sorted(self.property_list(),
  298. key=(lambda p: p.__name__ == 'comment')):
  299. value = getattr(self, prop.__name__)
  300. if value is None:
  301. continue
  302. if value.api_rule is None:
  303. continue
  304. values.append(value.api_rule)
  305. return ' '.join(values)
  306. @classmethod
  307. def from_xml_v1(cls, node, action):
  308. netmask = node.get('netmask')
  309. if netmask is None:
  310. netmask = 32
  311. else:
  312. netmask = int(netmask)
  313. address = node.get('address')
  314. if address:
  315. dsthost = DstHost(address, netmask)
  316. else:
  317. dsthost = None
  318. proto = node.get('proto')
  319. port = node.get('port')
  320. toport = node.get('toport')
  321. if port and toport:
  322. dstports = port + '-' + toport
  323. elif port:
  324. dstports = port
  325. else:
  326. dstports = None
  327. # backward compatibility: protocol defaults to TCP if port is specified
  328. if dstports and not proto:
  329. proto = 'tcp'
  330. if proto == 'any':
  331. proto = None
  332. expire = node.get('expire')
  333. kwargs = {
  334. 'action': action,
  335. }
  336. if dsthost:
  337. kwargs['dsthost'] = dsthost
  338. if dstports:
  339. kwargs['dstports'] = dstports
  340. if proto:
  341. kwargs['proto'] = proto
  342. if expire:
  343. kwargs['expire'] = expire
  344. return cls(**kwargs)
  345. @classmethod
  346. def from_api_string(cls, untrusted_rule):
  347. '''Parse a single line of firewall rule'''
  348. # comment is allowed to have spaces
  349. untrusted_options, _, untrusted_comment = untrusted_rule.partition(
  350. 'comment=')
  351. # appropriate handlers in __init__ of individual options will perform
  352. # option-specific validation
  353. kwargs = {}
  354. if untrusted_comment:
  355. kwargs['comment'] = Comment(untrusted_value=untrusted_comment)
  356. for untrusted_option in untrusted_options.strip().split(' '):
  357. untrusted_key, untrusted_value = untrusted_option.split('=', 1)
  358. if untrusted_key in kwargs:
  359. raise ValueError('Option \'{}\' already set'.format(
  360. untrusted_key))
  361. if untrusted_key in [str(prop) for prop in cls.property_list()]:
  362. kwargs[untrusted_key] = cls.property_get_def(
  363. untrusted_key).type(untrusted_value=untrusted_value)
  364. elif untrusted_key in ('dst4', 'dst6', 'dstname'):
  365. if 'dsthost' in kwargs:
  366. raise ValueError('Option \'{}\' already set'.format(
  367. 'dsthost'))
  368. kwargs['dsthost'] = DstHost(untrusted_value=untrusted_value)
  369. else:
  370. raise ValueError('Unknown firewall option')
  371. return cls(**kwargs)
  372. def __eq__(self, other):
  373. if isinstance(other, Rule):
  374. return self.api_rule == other.api_rule
  375. return self.api_rule == str(other)
  376. def __hash__(self):
  377. return hash(self.api_rule)
  378. class Firewall(object):
  379. def __init__(self, vm, load=True):
  380. assert hasattr(vm, 'firewall_conf')
  381. self.vm = vm
  382. #: firewall rules
  383. self.rules = []
  384. if load:
  385. self.load()
  386. @property
  387. def policy(self):
  388. ''' Default action - always 'drop' '''
  389. return Action('drop')
  390. def __eq__(self, other):
  391. if isinstance(other, Firewall):
  392. return self.rules == other.rules
  393. return NotImplemented
  394. def load_defaults(self):
  395. '''Load default firewall settings'''
  396. self.rules = [Rule(None, action='accept')]
  397. def clone(self, other):
  398. '''Clone firewall settings from other instance.
  399. This method discards pre-existing firewall settings.
  400. :param other: other :py:class:`Firewall` instance
  401. '''
  402. rules = []
  403. for rule in other.rules:
  404. # Rule constructor require some action, will be overwritten by
  405. # clone_properties below
  406. new_rule = Rule(action='drop')
  407. new_rule.clone_properties(rule)
  408. rules.append(new_rule)
  409. self.rules = rules
  410. def load(self):
  411. '''Load firewall settings from a file'''
  412. firewall_conf = os.path.join(self.vm.dir_path, self.vm.firewall_conf)
  413. if os.path.exists(firewall_conf):
  414. self.rules = []
  415. tree = lxml.etree.parse(firewall_conf)
  416. root = tree.getroot()
  417. version = root.get('version', '1')
  418. if version == '1':
  419. self.load_v1(root)
  420. elif version == '2':
  421. self.load_v2(root)
  422. else:
  423. raise qubes.exc.QubesVMError(self.vm,
  424. 'Unsupported firewall.xml version: {}'.format(version))
  425. else:
  426. self.load_defaults()
  427. def load_v1(self, xml_root):
  428. '''Load old (Qubes < 4.0) firewall XML format'''
  429. policy_v1 = xml_root.get('policy')
  430. assert policy_v1 in ('allow', 'deny')
  431. default_policy_is_accept = (policy_v1 == 'allow')
  432. def _translate_action(key):
  433. if xml_root.get(key, policy_v1) == 'allow':
  434. return Action.accept
  435. return Action.drop
  436. self.rules.append(Rule(None,
  437. action=_translate_action('dns'),
  438. specialtarget=SpecialTarget('dns')))
  439. self.rules.append(Rule(None,
  440. action=_translate_action('icmp'),
  441. proto=Proto.icmp))
  442. if default_policy_is_accept:
  443. rule_action = Action.drop
  444. else:
  445. rule_action = Action.accept
  446. for element in xml_root:
  447. rule = Rule.from_xml_v1(element, rule_action)
  448. self.rules.append(rule)
  449. if default_policy_is_accept:
  450. self.rules.append(Rule(None, action='accept'))
  451. def load_v2(self, xml_root):
  452. '''Load new (Qubes >= 4.0) firewall XML format'''
  453. xml_rules = xml_root.find('rules')
  454. for xml_rule in xml_rules:
  455. rule = Rule(xml_rule)
  456. self.rules.append(rule)
  457. def save(self):
  458. '''Save firewall rules to a file'''
  459. firewall_conf = os.path.join(self.vm.dir_path, self.vm.firewall_conf)
  460. expiring_rules_present = False
  461. xml_root = lxml.etree.Element('firewall', version=str(2))
  462. xml_rules = lxml.etree.Element('rules')
  463. for rule in self.rules:
  464. if rule.expire:
  465. if rule.expire and rule.expire.expired:
  466. continue
  467. else:
  468. expiring_rules_present = True
  469. xml_rule = lxml.etree.Element('rule')
  470. xml_rule.append(rule.xml_properties())
  471. xml_rules.append(xml_rule)
  472. xml_root.append(xml_rules)
  473. xml_tree = lxml.etree.ElementTree(xml_root)
  474. try:
  475. old_umask = os.umask(0o002)
  476. with open(firewall_conf, 'wb') as firewall_xml:
  477. xml_tree.write(firewall_xml, encoding="UTF-8",
  478. pretty_print=True)
  479. os.umask(old_umask)
  480. except EnvironmentError as err:
  481. self.vm.log.error("save error: {}".format(err))
  482. raise qubes.exc.QubesException('save error: {}'.format(err))
  483. self.vm.fire_event('firewall-changed')
  484. if expiring_rules_present and not self.vm.app.vmm.offline_mode:
  485. subprocess.call(["sudo", "systemctl", "start",
  486. "qubes-reload-firewall@%s.timer" % self.vm.name])
  487. def qdb_entries(self, addr_family=None):
  488. '''Return firewall settings serialized for QubesDB entries
  489. :param addr_family: include rules only for IPv4 (4) or IPv6 (6); if
  490. None, include both
  491. '''
  492. entries = {
  493. 'policy': str(self.policy)
  494. }
  495. exclude_dsttype = None
  496. if addr_family is not None:
  497. exclude_dsttype = 'dst4' if addr_family == 6 else 'dst6'
  498. for ruleno, rule in zip(itertools.count(), self.rules):
  499. # exclude rules for another address family
  500. if rule.dsthost and rule.dsthost.type == exclude_dsttype:
  501. continue
  502. entries['{:04}'.format(ruleno)] = rule.rule
  503. return entries