firewall.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. # -*- encoding: utf8 -*-
  2. # pylint: disable=too-few-public-methods
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2017 Marek Marczykowski-Górecki
  7. # <marmarek@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU Lesser General Public License as published by
  11. # the Free Software Foundation; either version 2.1 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public License along
  20. # with this program; if not, see <http://www.gnu.org/licenses/>.
  21. '''Firewall configuration interface'''
  22. import datetime
  23. import socket
  24. import string
  25. class RuleOption(object):
  26. '''Base class for a single rule element'''
  27. def __init__(self, value):
  28. self._value = str(value)
  29. @property
  30. def rule(self):
  31. '''API representation of this rule element'''
  32. raise NotImplementedError
  33. @property
  34. def pretty_value(self):
  35. '''Human readable representation'''
  36. return str(self)
  37. def __str__(self):
  38. return self._value
  39. def __eq__(self, other):
  40. return str(self) == other
  41. # noinspection PyAbstractClass
  42. class RuleChoice(RuleOption):
  43. '''Base class for multiple-choices rule elements'''
  44. # pylint: disable=abstract-method
  45. def __init__(self, value):
  46. super().__init__(value)
  47. self.allowed_values = \
  48. [v for k, v in self.__class__.__dict__.items()
  49. if not k.startswith('__') and isinstance(v, str) and
  50. not v.startswith('__')]
  51. if value not in self.allowed_values:
  52. raise ValueError(value)
  53. class Action(RuleChoice):
  54. '''Rule action'''
  55. accept = 'accept'
  56. drop = 'drop'
  57. @property
  58. def rule(self):
  59. '''API representation of this rule element'''
  60. return 'action=' + str(self)
  61. class Proto(RuleChoice):
  62. '''Protocol name'''
  63. tcp = 'tcp'
  64. udp = 'udp'
  65. icmp = 'icmp'
  66. @property
  67. def rule(self):
  68. '''API representation of this rule element'''
  69. return 'proto=' + str(self)
  70. class DstHost(RuleOption):
  71. '''Represent host/network address: either IPv4, IPv6, or DNS name'''
  72. def __init__(self, value, prefixlen=None):
  73. # TODO: in python >= 3.3 ipaddress module could be used
  74. if value.count('/') > 1:
  75. raise ValueError('Too many /: ' + value)
  76. if not value.count('/'):
  77. # add prefix length to bare IP addresses
  78. try:
  79. socket.inet_pton(socket.AF_INET6, value)
  80. if prefixlen is not None:
  81. self.prefixlen = prefixlen
  82. else:
  83. self.prefixlen = 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, value)
  92. if value.count('.') != 3:
  93. raise ValueError(
  94. 'Invalid number of dots in IPv4 address')
  95. if prefixlen is not None:
  96. self.prefixlen = prefixlen
  97. else:
  98. self.prefixlen = 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 value):
  109. raise ValueError('Invalid hostname')
  110. else:
  111. host, prefixlen = value.split('/', 1)
  112. prefixlen = int(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, host)
  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, host)
  124. if prefixlen > 32:
  125. raise ValueError('netmask for IPv4 must be <= 32')
  126. self.type = 'dst4'
  127. if host.count('.') != 3:
  128. raise ValueError(
  129. 'Invalid number of dots in IPv4 address')
  130. except socket.error:
  131. raise ValueError('Invalid IP address: ' + host)
  132. super().__init__(value)
  133. @property
  134. def rule(self):
  135. '''API representation of this rule element'''
  136. if self.prefixlen == 0 and self.type != 'dsthost':
  137. # 0.0.0.0/0 or ::/0, doesn't limit to any particular host,
  138. # so skip it
  139. return None
  140. return self.type + '=' + str(self)
  141. class DstPorts(RuleOption):
  142. '''Destination port(s), for TCP/UDP only'''
  143. def __init__(self, value):
  144. if isinstance(value, int):
  145. value = str(value)
  146. if value.count('-') == 1:
  147. self.range = [int(x) for x in value.split('-', 1)]
  148. elif not value.count('-'):
  149. self.range = [int(value), int(value)]
  150. else:
  151. raise ValueError(value)
  152. if any(port < 0 or port > 65536 for port in self.range):
  153. raise ValueError('Ports out of range')
  154. if self.range[0] > self.range[1]:
  155. raise ValueError('Invalid port range')
  156. super().__init__(
  157. str(self.range[0]) if self.range[0] == self.range[1]
  158. else '{!s}-{!s}'.format(*self.range))
  159. @property
  160. def rule(self):
  161. '''API representation of this rule element'''
  162. return 'dstports=' + '{!s}-{!s}'.format(*self.range)
  163. class IcmpType(RuleOption):
  164. '''ICMP packet type'''
  165. def __init__(self, value):
  166. super().__init__(value)
  167. value = int(value)
  168. if value < 0 or value > 255:
  169. raise ValueError('ICMP type out of range')
  170. @property
  171. def rule(self):
  172. '''API representation of this rule element'''
  173. return 'icmptype=' + str(self)
  174. class SpecialTarget(RuleChoice):
  175. '''Special destination'''
  176. dns = 'dns'
  177. @property
  178. def rule(self):
  179. '''API representation of this rule element'''
  180. return 'specialtarget=' + str(self)
  181. class Expire(RuleOption):
  182. '''Rule expire time'''
  183. def __init__(self, value):
  184. super().__init__(value)
  185. self.datetime = datetime.datetime.utcfromtimestamp(int(value))
  186. @property
  187. def rule(self):
  188. '''API representation of this rule element'''
  189. return 'expire=' + str(self)
  190. @property
  191. def expired(self):
  192. '''Has this rule expired already?'''
  193. return self.datetime < datetime.datetime.utcnow()
  194. @property
  195. def pretty_value(self):
  196. '''Human readable representation'''
  197. now = datetime.datetime.utcnow()
  198. duration = (self.datetime - now).total_seconds()
  199. return "{:+.0f}s".format(duration)
  200. class Comment(RuleOption):
  201. '''User comment'''
  202. @property
  203. def rule(self):
  204. '''API representation of this rule element'''
  205. return 'comment=' + str(self)
  206. class Rule(object):
  207. '''A single firewall rule'''
  208. def __init__(self, rule, **kwargs):
  209. '''Single firewall rule
  210. :param xml: XML element describing rule, or None
  211. :param kwargs: rule elements
  212. '''
  213. self._action = None
  214. self._proto = None
  215. self._dsthost = None
  216. self._dstports = None
  217. self._icmptype = None
  218. self._specialtarget = None
  219. self._expire = None
  220. self._comment = None
  221. rule_dict = {}
  222. if rule is not None:
  223. rule_opts, _, comment = rule.partition('comment=')
  224. rule_dict = dict(rule_opt.split('=', 1) for rule_opt in
  225. rule_opts.split(' ') if rule_opt)
  226. if comment:
  227. rule_dict['comment'] = comment
  228. rule_dict.update(kwargs)
  229. rule_elements = ('action', 'proto', 'dsthost', 'dst4', 'dst6',
  230. 'specialtarget', 'dstports', 'icmptype', 'expire', 'comment')
  231. for rule_opt in rule_elements:
  232. value = rule_dict.pop(rule_opt, None)
  233. if value is None:
  234. continue
  235. if rule_opt in ('dst4', 'dst6'):
  236. rule_opt = 'dsthost'
  237. setattr(self, rule_opt, value)
  238. if rule_dict:
  239. raise ValueError('Unknown rule elements: {!r}'.format(
  240. rule_dict))
  241. if self.action is None:
  242. raise ValueError('missing action=')
  243. @property
  244. def action(self):
  245. '''rule action'''
  246. return self._action
  247. @action.setter
  248. def action(self, value):
  249. if not isinstance(value, Action):
  250. value = Action(value)
  251. self._action = value
  252. @property
  253. def proto(self):
  254. '''protocol to match'''
  255. return self._proto
  256. @proto.setter
  257. def proto(self, value):
  258. if value is not None and not isinstance(value, Proto):
  259. value = Proto(value)
  260. if value not in ('tcp', 'udp'):
  261. self.dstports = None
  262. if value not in ('icmp',):
  263. self.icmptype = None
  264. self._proto = value
  265. @property
  266. def dsthost(self):
  267. '''destination host/network'''
  268. return self._dsthost
  269. @dsthost.setter
  270. def dsthost(self, value):
  271. if value is not None and not isinstance(value, DstHost):
  272. value = DstHost(value)
  273. self._dsthost = value
  274. @property
  275. def dstports(self):
  276. ''''Destination port(s) (for \'tcp\' and \'udp\' protocol only)'''
  277. return self._dstports
  278. @dstports.setter
  279. def dstports(self, value):
  280. if value is not None:
  281. if self.proto not in ('tcp', 'udp'):
  282. raise ValueError(
  283. 'dstports valid only for \'tcp\' and \'udp\' protocols')
  284. if not isinstance(value, DstPorts):
  285. value = DstPorts(value)
  286. self._dstports = value
  287. @property
  288. def icmptype(self):
  289. '''ICMP packet type (for \'icmp\' protocol only)'''
  290. return self._icmptype
  291. @icmptype.setter
  292. def icmptype(self, value):
  293. if value is not None:
  294. if self.proto not in ('icmp',):
  295. raise ValueError('icmptype valid only for \'icmp\' protocol')
  296. if not isinstance(value, IcmpType):
  297. value = IcmpType(value)
  298. self._icmptype = value
  299. @property
  300. def specialtarget(self):
  301. '''Special target, for now only \'dns\' supported'''
  302. return self._specialtarget
  303. @specialtarget.setter
  304. def specialtarget(self, value):
  305. if not isinstance(value, SpecialTarget):
  306. value = SpecialTarget(value)
  307. self._specialtarget = value
  308. @property
  309. def expire(self):
  310. '''Timestamp (UNIX epoch) on which this rule expire'''
  311. return self._expire
  312. @expire.setter
  313. def expire(self, value):
  314. if not isinstance(value, Expire):
  315. value = Expire(value)
  316. self._expire = value
  317. @property
  318. def comment(self):
  319. '''User comment'''
  320. return self._comment
  321. @comment.setter
  322. def comment(self, value):
  323. if not isinstance(value, Comment):
  324. value = Comment(value)
  325. self._comment = value
  326. @property
  327. def rule(self):
  328. '''API representation of this rule'''
  329. values = []
  330. # comment must be the last one
  331. for prop in ('action', 'proto', 'dsthost', 'dstports', 'icmptype',
  332. 'specialtarget', 'expire', 'comment'):
  333. value = getattr(self, prop)
  334. if value is None:
  335. continue
  336. if value.rule is None:
  337. continue
  338. values.append(value.rule)
  339. return ' '.join(values)
  340. def __eq__(self, other):
  341. if isinstance(other, Rule):
  342. return self.rule == other.rule
  343. if isinstance(other, str):
  344. return self.rule == str
  345. return NotImplemented
  346. def __repr__(self):
  347. return 'Rule(\'{}\')'.format(self.rule)
  348. class Firewall(object):
  349. '''Firewal manager for a VM'''
  350. def __init__(self, vm):
  351. self.vm = vm
  352. self._rules = []
  353. self._policy = None
  354. self._loaded = False
  355. def load_rules(self):
  356. '''Force (re-)loading firewall rules'''
  357. rules_str = self.vm.qubesd_call(None, 'admin.vm.firewall.Get')
  358. rules = []
  359. for rule_str in rules_str.decode().splitlines():
  360. rules.append(Rule(rule_str))
  361. self._rules = rules
  362. self._loaded = True
  363. @property
  364. def rules(self):
  365. '''Firewall rules
  366. You can either copy them, edit and then assign new rules list to this
  367. property, or edit in-place and call :py:meth:`save_rules`.
  368. Once rules are loaded, they are cached. To reload rules,
  369. call :py:meth:`load_rules`.
  370. '''
  371. if not self._loaded:
  372. self.load_rules()
  373. return self._rules
  374. @rules.setter
  375. def rules(self, value):
  376. self.save_rules(value)
  377. self._rules = value
  378. def save_rules(self, rules=None):
  379. '''Save firewall rules. Needs to be called after in-place editing
  380. :py:attr:`rules`.
  381. '''
  382. if rules is None:
  383. rules = self._rules
  384. self.vm.qubesd_call(None, 'admin.vm.firewall.Set',
  385. payload=(''.join('{}\n'.format(rule.rule)
  386. for rule in rules)).encode('ascii'))
  387. @property
  388. def policy(self):
  389. '''Default action to take if no rule matches'''
  390. return Action('drop')
  391. def reload(self):
  392. '''Force reload the same firewall rules.
  393. Can be used for example to force again names resolution.
  394. '''
  395. self.vm.qubesd_call(None, 'admin.vm.firewall.Reload')