firewall.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. forward = 'forward'
  58. @property
  59. def rule(self):
  60. '''API representation of this rule element'''
  61. return 'action=' + str(self)
  62. class Proto(RuleChoice):
  63. '''Protocol name'''
  64. tcp = 'tcp'
  65. udp = 'udp'
  66. icmp = 'icmp'
  67. @property
  68. def rule(self):
  69. '''API representation of this rule element'''
  70. return 'proto=' + str(self)
  71. class DstHost(RuleOption):
  72. '''Represent host/network address: either IPv4, IPv6, or DNS name'''
  73. def __init__(self, value, prefixlen=None):
  74. # TODO: in python >= 3.3 ipaddress module could be used
  75. if value.count('/') > 1:
  76. raise ValueError('Too many /: ' + value)
  77. if not value.count('/'):
  78. # add prefix length to bare IP addresses
  79. try:
  80. socket.inet_pton(socket.AF_INET6, value)
  81. if prefixlen is not None:
  82. self.prefixlen = prefixlen
  83. else:
  84. self.prefixlen = 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, value)
  93. if value.count('.') != 3:
  94. raise ValueError(
  95. 'Invalid number of dots in IPv4 address')
  96. if prefixlen is not None:
  97. self.prefixlen = prefixlen
  98. else:
  99. self.prefixlen = 32
  100. if self.prefixlen < 0 or self.prefixlen > 32:
  101. raise ValueError(
  102. 'netmask for IPv4 must be between 0 and 32')
  103. value += '/' + str(self.prefixlen)
  104. self.type = 'dst4'
  105. except socket.error:
  106. self.type = 'dsthost'
  107. self.prefixlen = 0
  108. safe_set = string.ascii_lowercase + string.digits + '-._'
  109. if not all(c in safe_set for c in value):
  110. raise ValueError('Invalid hostname')
  111. else:
  112. host, prefixlen = value.split('/', 1)
  113. prefixlen = int(prefixlen)
  114. if prefixlen < 0:
  115. raise ValueError('netmask must be non-negative')
  116. self.prefixlen = prefixlen
  117. try:
  118. socket.inet_pton(socket.AF_INET6, host)
  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, host)
  125. if prefixlen > 32:
  126. raise ValueError('netmask for IPv4 must be <= 32')
  127. self.type = 'dst4'
  128. if host.count('.') != 3:
  129. raise ValueError(
  130. 'Invalid number of dots in IPv4 address')
  131. except socket.error:
  132. raise ValueError('Invalid IP address: ' + host)
  133. super().__init__(value)
  134. @property
  135. def rule(self):
  136. '''API representation of this rule element'''
  137. if self.prefixlen == 0 and self.type != 'dsthost':
  138. # 0.0.0.0/0 or ::/0, doesn't limit to any particular host,
  139. # so skip it
  140. return None
  141. return self.type + '=' + str(self)
  142. class DstPorts(RuleOption):
  143. '''Destination port(s), for TCP/UDP only'''
  144. def __init__(self, value):
  145. if isinstance(value, int):
  146. value = str(value)
  147. if value.count('-') == 1:
  148. self.range = [int(x) for x in value.split('-', 1)]
  149. elif not value.count('-'):
  150. self.range = [int(value), int(value)]
  151. else:
  152. raise ValueError(value)
  153. if any(port < 0 or port > 65536 for port in self.range):
  154. raise ValueError('Ports out of range')
  155. if self.range[0] > self.range[1]:
  156. raise ValueError('Invalid port range')
  157. super().__init__(
  158. str(self.range[0]) if self.range[0] == self.range[1]
  159. else '{!s}-{!s}'.format(*self.range))
  160. @property
  161. def rule(self):
  162. '''API representation of this rule element'''
  163. return 'dstports=' + '{!s}-{!s}'.format(*self.range)
  164. class IcmpType(RuleOption):
  165. '''ICMP packet type'''
  166. def __init__(self, value):
  167. super().__init__(value)
  168. value = int(value)
  169. if value < 0 or value > 255:
  170. raise ValueError('ICMP type out of range')
  171. @property
  172. def rule(self):
  173. '''API representation of this rule element'''
  174. return 'icmptype=' + str(self)
  175. class SpecialTarget(RuleChoice):
  176. '''Special destination'''
  177. dns = 'dns'
  178. @property
  179. def rule(self):
  180. '''API representation of this rule element'''
  181. return 'specialtarget=' + str(self)
  182. class Expire(RuleOption):
  183. '''Rule expire time'''
  184. def __init__(self, value):
  185. super().__init__(value)
  186. self.datetime = datetime.datetime.utcfromtimestamp(int(value))
  187. @property
  188. def rule(self):
  189. '''API representation of this rule element'''
  190. return 'expire=' + str(self)
  191. @property
  192. def expired(self):
  193. '''Has this rule expired already?'''
  194. return self.datetime < datetime.datetime.utcnow()
  195. @property
  196. def pretty_value(self):
  197. '''Human readable representation'''
  198. now = datetime.datetime.utcnow()
  199. duration = (self.datetime - now).total_seconds()
  200. return "{:+.0f}s".format(duration)
  201. class Comment(RuleOption):
  202. '''User comment'''
  203. @property
  204. def rule(self):
  205. '''API representation of this rule element'''
  206. return 'comment=' + str(self)
  207. class Rule(object):
  208. '''A single firewall rule'''
  209. def __init__(self, rule, **kwargs):
  210. '''Single firewall rule
  211. :param xml: XML element describing rule, or None
  212. :param kwargs: rule elements
  213. '''
  214. self._action = None
  215. self._proto = None
  216. self._dsthost = None
  217. self._dstports = None
  218. self._icmptype = None
  219. self._specialtarget = None
  220. self._expire = None
  221. self._comment = None
  222. rule_dict = {}
  223. if rule is not None:
  224. rule_opts, _, comment = rule.partition('comment=')
  225. rule_dict = dict(rule_opt.split('=', 1) for rule_opt in
  226. rule_opts.split(' ') if rule_opt)
  227. if comment:
  228. rule_dict['comment'] = comment
  229. rule_dict.update(kwargs)
  230. rule_elements = ('action', 'proto', 'dsthost', 'dst4', 'dst6',
  231. 'specialtarget', 'dstports', 'icmptype', 'expire', 'comment')
  232. for rule_opt in rule_elements:
  233. value = rule_dict.pop(rule_opt, None)
  234. if value is None:
  235. continue
  236. if rule_opt in ('dst4', 'dst6'):
  237. rule_opt = 'dsthost'
  238. setattr(self, rule_opt, value)
  239. if rule_dict:
  240. raise ValueError('Unknown rule elements: {!r}'.format(
  241. rule_dict))
  242. if self.action is None:
  243. raise ValueError('missing action=')
  244. @property
  245. def action(self):
  246. '''rule action'''
  247. return self._action
  248. @action.setter
  249. def action(self, value):
  250. if not isinstance(value, Action):
  251. value = Action(value)
  252. self._action = value
  253. @property
  254. def proto(self):
  255. '''protocol to match'''
  256. return self._proto
  257. @proto.setter
  258. def proto(self, value):
  259. if value is not None and not isinstance(value, Proto):
  260. value = Proto(value)
  261. if value not in ('tcp', 'udp'):
  262. self.dstports = None
  263. if value not in ('icmp',):
  264. self.icmptype = None
  265. self._proto = value
  266. @property
  267. def dsthost(self):
  268. '''destination host/network'''
  269. return self._dsthost
  270. @dsthost.setter
  271. def dsthost(self, value):
  272. if value is not None and not isinstance(value, DstHost):
  273. value = DstHost(value)
  274. self._dsthost = value
  275. @property
  276. def dstports(self):
  277. ''''Destination port(s) (for \'tcp\' and \'udp\' protocol only)'''
  278. return self._dstports
  279. @dstports.setter
  280. def dstports(self, value):
  281. if value is not None:
  282. if self.proto not in ('tcp', 'udp'):
  283. raise ValueError(
  284. 'dstports valid only for \'tcp\' and \'udp\' protocols')
  285. if not isinstance(value, DstPorts):
  286. value = DstPorts(value)
  287. self._dstports = value
  288. @property
  289. def icmptype(self):
  290. '''ICMP packet type (for \'icmp\' protocol only)'''
  291. return self._icmptype
  292. @icmptype.setter
  293. def icmptype(self, value):
  294. if value is not None:
  295. if self.proto not in ('icmp',):
  296. raise ValueError('icmptype valid only for \'icmp\' protocol')
  297. if not isinstance(value, IcmpType):
  298. value = IcmpType(value)
  299. self._icmptype = value
  300. @property
  301. def specialtarget(self):
  302. '''Special target, for now only \'dns\' supported'''
  303. return self._specialtarget
  304. @specialtarget.setter
  305. def specialtarget(self, value):
  306. if not isinstance(value, SpecialTarget):
  307. value = SpecialTarget(value)
  308. self._specialtarget = value
  309. @property
  310. def expire(self):
  311. '''Timestamp (UNIX epoch) on which this rule expire'''
  312. return self._expire
  313. @expire.setter
  314. def expire(self, value):
  315. if not isinstance(value, Expire):
  316. value = Expire(value)
  317. self._expire = value
  318. @property
  319. def comment(self):
  320. '''User comment'''
  321. return self._comment
  322. @comment.setter
  323. def comment(self, value):
  324. if not isinstance(value, Comment):
  325. value = Comment(value)
  326. self._comment = value
  327. @property
  328. def rule(self):
  329. '''API representation of this rule'''
  330. values = []
  331. # comment must be the last one
  332. for prop in ('action', 'proto', 'dsthost', 'dstports', 'icmptype',
  333. 'specialtarget', 'expire', 'comment'):
  334. value = getattr(self, prop)
  335. if value is None:
  336. continue
  337. if value.rule is None:
  338. continue
  339. values.append(value.rule)
  340. return ' '.join(values)
  341. def __eq__(self, other):
  342. if isinstance(other, Rule):
  343. return self.rule == other.rule
  344. if isinstance(other, str):
  345. return self.rule == str
  346. return NotImplemented
  347. def __repr__(self):
  348. return 'Rule(\'{}\')'.format(self.rule)
  349. class Firewall(object):
  350. '''Firewal manager for a VM'''
  351. def __init__(self, vm):
  352. self.vm = vm
  353. self._rules = []
  354. self._policy = None
  355. self._loaded = False
  356. def load_rules(self):
  357. '''Force (re-)loading firewall rules'''
  358. rules_str = self.vm.qubesd_call(None, 'admin.vm.firewall.Get')
  359. rules = []
  360. for rule_str in rules_str.decode().splitlines():
  361. rules.append(Rule(rule_str))
  362. self._rules = rules
  363. self._loaded = True
  364. @property
  365. def rules(self):
  366. '''Firewall rules
  367. You can either copy them, edit and then assign new rules list to this
  368. property, or edit in-place and call :py:meth:`save_rules`.
  369. Once rules are loaded, they are cached. To reload rules,
  370. call :py:meth:`load_rules`.
  371. '''
  372. if not self._loaded:
  373. self.load_rules()
  374. return self._rules
  375. @rules.setter
  376. def rules(self, value):
  377. self.save_rules(value)
  378. self._rules = value
  379. def save_rules(self, rules=None):
  380. '''Save firewall rules. Needs to be called after in-place editing
  381. :py:attr:`rules`.
  382. '''
  383. if rules is None:
  384. rules = self._rules
  385. self.vm.qubesd_call(None, 'admin.vm.firewall.Set',
  386. payload=(''.join('{}\n'.format(rule.rule)
  387. for rule in rules)).encode('ascii'))
  388. @property
  389. def policy(self):
  390. '''Default action to take if no rule matches'''
  391. return Action('drop')
  392. def reload(self):
  393. '''Force reload the same firewall rules.
  394. Can be used for example to force again names resolution.
  395. '''
  396. self.vm.qubesd_call(None, 'admin.vm.firewall.Reload')