__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2011-2015 Marek Marczykowski-Górecki
  8. # <marmarek@invisiblethingslab.com>
  9. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License along
  22. # with this program; if not, write to the Free Software Foundation, Inc.,
  23. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. #
  25. '''Qubes Virtual Machines
  26. '''
  27. import datetime
  28. import os
  29. import subprocess
  30. import sys
  31. import xml.parsers.expat
  32. import lxml.etree
  33. import qubes
  34. import qubes.devices
  35. import qubes.events
  36. import qubes.log
  37. import qubes.tools.qvm_ls
  38. class Features(dict):
  39. '''Manager of the features.
  40. Features can have three distinct values: no value (not present in mapping,
  41. which is closest thing to :py:obj:`None`), empty string (which is
  42. interpreted as :py:obj:`False`) and non-empty string, which is
  43. :py:obj:`True`. Anything assigned to the mapping is coerced to strings,
  44. however if you assign instances of :py:class:`bool`, they are converted as
  45. described above. Be aware that assigning the number `0` (which is considered
  46. false in Python) will result in string `'0'`, which is considered true.
  47. This class inherits from dict, but has most of the methods that manipulate
  48. the item disarmed (they raise NotImplementedError). The ones that are left
  49. fire appropriate events on the qube that owns an instance of this class.
  50. '''
  51. #
  52. # Those are the methods that affect contents. Either disarm them or make
  53. # them report appropriate events. Good approach is to rewrite them carefully
  54. # using official documentation, but use only our (overloaded) methods.
  55. #
  56. def __init__(self, vm, other=None, **kwargs):
  57. super(Features, self).__init__()
  58. self.vm = vm
  59. self.update(other, **kwargs)
  60. def __delitem__(self, key):
  61. super(Features, self).__delitem__(key)
  62. self.vm.fire_event('domain-feature-delete', key)
  63. def __setitem__(self, key, value):
  64. if value is None or isinstance(value, bool):
  65. value = '1' if value else ''
  66. else:
  67. value = str(value)
  68. self.vm.fire_event('domain-feature-set', key, value)
  69. super(Features, self).__setitem__(key, value)
  70. def clear(self):
  71. for key in self:
  72. del self[key]
  73. def pop(self):
  74. '''Not implemented
  75. :raises: NotImplementedError
  76. '''
  77. raise NotImplementedError()
  78. def popitem(self):
  79. '''Not implemented
  80. :raises: NotImplementedError
  81. '''
  82. raise NotImplementedError()
  83. def setdefault(self):
  84. '''Not implemented
  85. :raises: NotImplementedError
  86. '''
  87. raise NotImplementedError()
  88. def update(self, other=None, **kwargs):
  89. if other is not None:
  90. if hasattr(other, 'keys'):
  91. for key in other:
  92. self[key] = other[key]
  93. else:
  94. for key, value in other:
  95. self[key] = value
  96. for key in kwargs:
  97. self[key] = kwargs[key]
  98. #
  99. # end of overriding
  100. #
  101. _NO_DEFAULT = object()
  102. def check_with_template(self, feature, default=_NO_DEFAULT):
  103. ''' Check if the vm's template has the specified feature. '''
  104. if feature in self:
  105. return self[feature]
  106. if hasattr(self.vm, 'template') and self.vm.template is not None:
  107. try:
  108. return self.vm.template.features[feature]
  109. except KeyError:
  110. # handle default just below
  111. pass
  112. if default is self._NO_DEFAULT:
  113. raise KeyError(feature)
  114. return default
  115. class BaseVMMeta(qubes.events.EmitterMeta):
  116. '''Metaclass for :py:class:`.BaseVM`'''
  117. def __init__(cls, name, bases, dict_):
  118. super(BaseVMMeta, cls).__init__(name, bases, dict_)
  119. qubes.tools.qvm_ls.process_class(cls)
  120. class BaseVM(qubes.PropertyHolder):
  121. '''Base class for all VMs
  122. :param app: Qubes application context
  123. :type app: :py:class:`qubes.Qubes`
  124. :param xml: xml node from which to deserialise
  125. :type xml: :py:class:`lxml.etree._Element` or :py:obj:`None`
  126. This class is responsible for serializing and deserialising machines and
  127. provides basic framework. It contains no management logic. For that, see
  128. :py:class:`qubes.vm.qubesvm.QubesVM`.
  129. '''
  130. # pylint: disable=no-member
  131. __metaclass__ = BaseVMMeta
  132. def __init__(self, app, xml, features=None, devices=None, tags=None,
  133. **kwargs):
  134. # pylint: disable=redefined-outer-name
  135. # self.app must be set before super().__init__, because some property
  136. # setters need working .app attribute
  137. #: mother :py:class:`qubes.Qubes` object
  138. self.app = app
  139. super(BaseVM, self).__init__(xml, **kwargs)
  140. #: dictionary of features of this qube
  141. self.features = Features(self, features)
  142. #: :py:class:`DeviceManager` object keeping devices that are attached to
  143. #: this domain
  144. self.devices = devices or qubes.devices.DeviceManager(self)
  145. #: user-specified tags
  146. self.tags = tags or {}
  147. #: logger instance for logging messages related to this VM
  148. self.log = None
  149. if hasattr(self, 'name'):
  150. self.init_log()
  151. def load_extras(self):
  152. # features
  153. for node in self.xml.xpath('./features/feature'):
  154. self.features[node.get('name')] = node.text
  155. # devices (pci, usb, ...)
  156. for parent in self.xml.xpath('./devices'):
  157. devclass = parent.get('class')
  158. for node in parent.xpath('./device'):
  159. device = self.devices[devclass].devclass(
  160. self.app.domains[node.get('backend-domain')],
  161. node.get('id')
  162. )
  163. self.devices[devclass].attach(device)
  164. # tags
  165. for node in self.xml.xpath('./tags/tag'):
  166. self.tags[node.get('name')] = node.text
  167. # SEE:1815 firewall, policy.
  168. def init_log(self):
  169. '''Initialise logger for this domain.'''
  170. self.log = qubes.log.get_vm_logger(self.name)
  171. def __xml__(self):
  172. element = lxml.etree.Element('domain')
  173. element.set('id', 'domain-' + str(self.qid))
  174. element.set('class', self.__class__.__name__)
  175. element.append(self.xml_properties())
  176. features = lxml.etree.Element('features')
  177. for feature in self.features:
  178. node = lxml.etree.Element('feature', name=feature)
  179. node.text = self.features[feature]
  180. features.append(node)
  181. element.append(features)
  182. for devclass in self.devices:
  183. devices = lxml.etree.Element('devices')
  184. devices.set('class', devclass)
  185. for device in self.devices[devclass].attached(persistent=True):
  186. node = lxml.etree.Element('device')
  187. node.set('backend-domain', device.backend_domain.name)
  188. node.set('id', device.ident)
  189. devices.append(node)
  190. element.append(devices)
  191. tags = lxml.etree.Element('tags')
  192. for tag in self.tags:
  193. node = lxml.etree.Element('tag', name=tag)
  194. node.text = self.tags[tag]
  195. tags.append(node)
  196. element.append(tags)
  197. return element
  198. def __repr__(self):
  199. proprepr = []
  200. for prop in self.property_list():
  201. try:
  202. proprepr.append('{}={!s}'.format(
  203. prop.__name__, getattr(self, prop.__name__)))
  204. except AttributeError:
  205. continue
  206. return '<{} object at {:#x} {}>'.format(
  207. self.__class__.__name__, id(self), ' '.join(proprepr))
  208. #
  209. # xml serialising methods
  210. #
  211. def create_config_file(self, prepare_dvm=False):
  212. '''Create libvirt's XML domain config file
  213. :param bool prepare_dvm: If we are in the process of preparing \
  214. DisposableVM
  215. '''
  216. domain_config = self.app.env.get_template('libvirt/xen.xml').render(
  217. vm=self, prepare_dvm=prepare_dvm)
  218. return domain_config
  219. #
  220. # firewall
  221. # SEE:1815 rewrite it, have <firewall/> node under <domain/>
  222. # and possibly integrate with generic policy framework.
  223. #
  224. def write_firewall_conf(self, conf):
  225. '''Write firewall config file.
  226. '''
  227. defaults = self.get_firewall_conf()
  228. expiring_rules_present = False
  229. for item in defaults.keys():
  230. if item not in conf:
  231. conf[item] = defaults[item]
  232. root = lxml.etree.Element(
  233. "QubesFirewallRules",
  234. policy=("allow" if conf["allow"] else "deny"),
  235. dns=("allow" if conf["allowDns"] else "deny"),
  236. icmp=("allow" if conf["allowIcmp"] else "deny"),
  237. yumProxy=("allow" if conf["allowYumProxy"] else "deny"))
  238. for rule in conf["rules"]:
  239. # For backward compatibility
  240. if "proto" not in rule:
  241. if rule["portBegin"] is not None and rule["portBegin"] > 0:
  242. rule["proto"] = "tcp"
  243. else:
  244. rule["proto"] = "any"
  245. element = lxml.etree.Element(
  246. "rule",
  247. address=rule["address"],
  248. proto=str(rule["proto"]),
  249. )
  250. if rule["netmask"] is not None and rule["netmask"] != 32:
  251. element.set("netmask", str(rule["netmask"]))
  252. if rule.get("portBegin", None) is not None and \
  253. rule["portBegin"] > 0:
  254. element.set("port", str(rule["portBegin"]))
  255. if rule.get("portEnd", None) is not None and rule["portEnd"] > 0:
  256. element.set("toport", str(rule["portEnd"]))
  257. if "expire" in rule:
  258. element.set("expire", str(rule["expire"]))
  259. expiring_rules_present = True
  260. root.append(element)
  261. tree = lxml.etree.ElementTree(root)
  262. try:
  263. old_umask = os.umask(0o002)
  264. with open(os.path.join(self.dir_path,
  265. self.firewall_conf), 'w') as fd:
  266. tree.write(fd, encoding="UTF-8", pretty_print=True)
  267. fd.close()
  268. os.umask(old_umask)
  269. except EnvironmentError as err: # pylint: disable=broad-except
  270. print >> sys.stderr, "{0}: save error: {1}".format(
  271. os.path.basename(sys.argv[0]), err)
  272. return False
  273. # Automatically enable/disable 'updates-proxy-setup' service based on
  274. # allowYumProxy
  275. if conf['allowYumProxy']:
  276. self.features['updates-proxy-setup'] = '1'
  277. else:
  278. try:
  279. del self.features['updates-proxy-setup']
  280. except KeyError:
  281. pass
  282. if expiring_rules_present:
  283. subprocess.call(["sudo", "systemctl", "start",
  284. "qubes-reload-firewall@%s.timer" % self.name])
  285. # SEE:1815 any better idea? some arguments?
  286. self.fire_event('firewall-changed')
  287. return True
  288. def has_firewall(self):
  289. ''' Return `True` if there are some vm specific firewall rules set '''
  290. return os.path.exists(os.path.join(self.dir_path, self.firewall_conf))
  291. @staticmethod
  292. def get_firewall_defaults():
  293. ''' Returns the default firewall rules '''
  294. return {
  295. 'rules': list(),
  296. 'allow': True,
  297. 'allowDns': True,
  298. 'allowIcmp': True,
  299. 'allowYumProxy': False}
  300. def get_firewall_conf(self):
  301. ''' Returns the firewall config dictionary '''
  302. conf = self.get_firewall_defaults()
  303. try:
  304. tree = lxml.etree.parse(os.path.join(self.dir_path,
  305. self.firewall_conf))
  306. root = tree.getroot()
  307. conf["allow"] = (root.get("policy") == "allow")
  308. conf["allowDns"] = (root.get("dns") == "allow")
  309. conf["allowIcmp"] = (root.get("icmp") == "allow")
  310. conf["allowYumProxy"] = (root.get("yumProxy") == "allow")
  311. for element in root:
  312. rule = {}
  313. attr_list = ("address", "netmask", "proto", "port", "toport",
  314. "expire")
  315. for attribute in attr_list:
  316. rule[attribute] = element.get(attribute)
  317. if rule["netmask"] is not None:
  318. rule["netmask"] = int(rule["netmask"])
  319. else:
  320. rule["netmask"] = 32
  321. if rule["port"] is not None:
  322. rule["portBegin"] = int(rule["port"])
  323. else:
  324. # backward compatibility
  325. rule["portBegin"] = 0
  326. # For backward compatibility
  327. if rule["proto"] is None:
  328. if rule["portBegin"] > 0:
  329. rule["proto"] = "tcp"
  330. else:
  331. rule["proto"] = "any"
  332. if rule["toport"] is not None:
  333. rule["portEnd"] = int(rule["toport"])
  334. else:
  335. rule["portEnd"] = None
  336. if rule["expire"] is not None:
  337. rule["expire"] = int(rule["expire"])
  338. if rule["expire"] <= int(datetime.datetime.now().strftime(
  339. "%s")):
  340. continue
  341. else:
  342. del rule["expire"]
  343. del rule["port"]
  344. del rule["toport"]
  345. conf["rules"].append(rule)
  346. except EnvironmentError as err: # pylint: disable=broad-except
  347. # problem accessing file, like ENOTFOUND, EPERM or sth
  348. # return default config
  349. return conf
  350. except (xml.parsers.expat.ExpatError,
  351. ValueError, LookupError) as err:
  352. # config is invalid
  353. print("{0}: load error: {1}".format(
  354. os.path.basename(sys.argv[0]), err))
  355. return None
  356. return conf
  357. class VMProperty(qubes.property):
  358. '''Property that is referring to a VM
  359. :param type vmclass: class that returned VM is supposed to be instance of
  360. and all supported by :py:class:`property` with the exception of ``type`` \
  361. and ``setter``
  362. '''
  363. _none_value = ''
  364. def __init__(self, name, vmclass=BaseVM, allow_none=False,
  365. **kwargs):
  366. if 'type' in kwargs:
  367. raise TypeError(
  368. "'type' keyword parameter is unsupported in {}".format(
  369. self.__class__.__name__))
  370. if 'setter' in kwargs:
  371. raise TypeError(
  372. "'setter' keyword parameter is unsupported in {}".format(
  373. self.__class__.__name__))
  374. if not issubclass(vmclass, BaseVM):
  375. raise TypeError(
  376. "'vmclass' should specify a subclass of qubes.vm.BaseVM")
  377. super(VMProperty, self).__init__(name,
  378. saver=(lambda self_, prop, value:
  379. self._none_value if value is None else value.name),
  380. **kwargs)
  381. self.vmclass = vmclass
  382. self.allow_none = allow_none
  383. def __set__(self, instance, value):
  384. if value is self.__class__.DEFAULT:
  385. self.__delete__(instance)
  386. return
  387. if value == self._none_value:
  388. value = None
  389. if value is None:
  390. if self.allow_none:
  391. super(VMProperty, self).__set__(instance, value)
  392. return
  393. else:
  394. raise ValueError(
  395. 'Property {!r} does not allow setting to {!r}'.format(
  396. self.__name__, value))
  397. app = instance if isinstance(instance, qubes.Qubes) else instance.app
  398. try:
  399. vm = app.domains[value]
  400. except KeyError:
  401. raise qubes.exc.QubesVMNotFoundError(value)
  402. if not isinstance(vm, self.vmclass):
  403. raise TypeError('wrong VM class: domains[{!r}] is of type {!s} '
  404. 'and not {!s}'.format(value,
  405. vm.__class__.__name__,
  406. self.vmclass.__name__))
  407. super(VMProperty, self).__set__(instance, vm)