firewall.py 14 KB

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