firewall.py 19 KB

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