firewall.py 14 KB

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