__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2011-2015 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 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 General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. '''Qubes Virtual Machines
  24. '''
  25. import datetime
  26. import os
  27. import subprocess
  28. import sys
  29. import xml.parsers.expat
  30. import lxml.etree
  31. import qubes
  32. import qubes.devices
  33. import qubes.events
  34. import qubes.log
  35. import qubes.tools.qvm_ls
  36. class Features(dict):
  37. '''Manager of the features.
  38. Features can have three distinct values: no value (not present in mapping,
  39. which is closest thing to :py:obj:`None`), empty string (which is
  40. interpreted as :py:obj:`False`) and non-empty string, which is
  41. :py:obj:`True`. Anything assigned to the mapping is coerced to strings,
  42. however if you assign instances of :py:class:`bool`, they are converted as
  43. described above. Be aware that assigning the number `0` (which is considered
  44. false in Python) will result in string `'0'`, which is considered true.
  45. This class inherits from dict, but has most of the methods that manipulate
  46. the item disarmed (they raise NotImplementedError). The ones that are left
  47. fire appropriate events on the qube that owns an instance of this class.
  48. '''
  49. #
  50. # Those are the methods that affect contents. Either disarm them or make
  51. # them report appropriate events. Good approach is to rewrite them carefully
  52. # using official documentation, but use only our (overloaded) methods.
  53. #
  54. def __init__(self, vm, other=None, **kwargs):
  55. super(Features, self).__init__()
  56. self.vm = vm
  57. self.update(other, **kwargs)
  58. def __delitem__(self, key):
  59. super(Features, self).__delitem__(key)
  60. self.vm.fire_event('domain-feature-delete', key)
  61. def __setitem__(self, key, value):
  62. if value is None or isinstance(value, bool):
  63. value = '1' if value else ''
  64. else:
  65. value = str(value)
  66. self.vm.fire_event('domain-feature-set', key, value)
  67. super(Features, self).__setitem__(key, value)
  68. def clear(self):
  69. for key in self:
  70. del self[key]
  71. def pop(self):
  72. '''Not implemented
  73. :raises: NotImplementedError
  74. '''
  75. raise NotImplementedError()
  76. def popitem(self):
  77. '''Not implemented
  78. :raises: NotImplementedError
  79. '''
  80. raise NotImplementedError()
  81. def setdefault(self):
  82. '''Not implemented
  83. :raises: NotImplementedError
  84. '''
  85. raise NotImplementedError()
  86. def update(self, other=None, **kwargs):
  87. if other is not None:
  88. if hasattr(other, 'keys'):
  89. for key in other:
  90. self[key] = other[key]
  91. else:
  92. for key, value in other:
  93. self[key] = value
  94. for key in kwargs:
  95. self[key] = kwargs[key]
  96. #
  97. # end of overriding
  98. #
  99. _NO_DEFAULT = object()
  100. def check_with_template(self, feature, default=_NO_DEFAULT):
  101. ''' Check if the vm's template has the specified feature. '''
  102. if feature in self:
  103. return self[feature]
  104. if hasattr(self.vm, 'template') and self.vm.template is not None:
  105. return self.vm.template.features.check_with_template(feature,
  106. default)
  107. if default is self._NO_DEFAULT:
  108. raise KeyError(feature)
  109. return default
  110. class BaseVMMeta(qubes.events.EmitterMeta):
  111. '''Metaclass for :py:class:`.BaseVM`'''
  112. def __init__(cls, name, bases, dict_):
  113. super(BaseVMMeta, cls).__init__(name, bases, dict_)
  114. qubes.tools.qvm_ls.process_class(cls)
  115. class BaseVM(qubes.PropertyHolder, metaclass=BaseVMMeta):
  116. '''Base class for all VMs
  117. :param app: Qubes application context
  118. :type app: :py:class:`qubes.Qubes`
  119. :param xml: xml node from which to deserialise
  120. :type xml: :py:class:`lxml.etree._Element` or :py:obj:`None`
  121. This class is responsible for serializing and deserialising machines and
  122. provides basic framework. It contains no management logic. For that, see
  123. :py:class:`qubes.vm.qubesvm.QubesVM`.
  124. '''
  125. # pylint: disable=no-member
  126. def __init__(self, app, xml, features=None, devices=None, tags=None,
  127. **kwargs):
  128. # pylint: disable=redefined-outer-name
  129. # self.app must be set before super().__init__, because some property
  130. # setters need working .app attribute
  131. #: mother :py:class:`qubes.Qubes` object
  132. self.app = app
  133. super(BaseVM, self).__init__(xml, **kwargs)
  134. #: dictionary of features of this qube
  135. self.features = Features(self, features)
  136. #: :py:class:`DeviceManager` object keeping devices that are attached to
  137. #: this domain
  138. self.devices = devices or qubes.devices.DeviceManager(self)
  139. #: user-specified tags
  140. self.tags = tags or {}
  141. #: logger instance for logging messages related to this VM
  142. self.log = None
  143. if hasattr(self, 'name'):
  144. self.init_log()
  145. def load_extras(self):
  146. # features
  147. for node in self.xml.xpath('./features/feature'):
  148. self.features[node.get('name')] = node.text
  149. # devices (pci, usb, ...)
  150. for parent in self.xml.xpath('./devices'):
  151. devclass = parent.get('class')
  152. for node in parent.xpath('./device'):
  153. device = self.devices[devclass].devclass(
  154. self.app.domains[node.get('backend-domain')],
  155. node.get('id')
  156. )
  157. self.devices[devclass].attach(device)
  158. # tags
  159. for node in self.xml.xpath('./tags/tag'):
  160. self.tags[node.get('name')] = node.text
  161. # SEE:1815 firewall, policy.
  162. def init_log(self):
  163. '''Initialise logger for this domain.'''
  164. self.log = qubes.log.get_vm_logger(self.name)
  165. def __xml__(self):
  166. element = lxml.etree.Element('domain')
  167. element.set('id', 'domain-' + str(self.qid))
  168. element.set('class', self.__class__.__name__)
  169. element.append(self.xml_properties())
  170. features = lxml.etree.Element('features')
  171. for feature in self.features:
  172. node = lxml.etree.Element('feature', name=feature)
  173. node.text = self.features[feature]
  174. features.append(node)
  175. element.append(features)
  176. for devclass in self.devices:
  177. devices = lxml.etree.Element('devices')
  178. devices.set('class', devclass)
  179. for device in self.devices[devclass].attached(persistent=True):
  180. node = lxml.etree.Element('device')
  181. node.set('backend-domain', device.backend_domain.name)
  182. node.set('id', device.ident)
  183. devices.append(node)
  184. element.append(devices)
  185. tags = lxml.etree.Element('tags')
  186. for tag in self.tags:
  187. node = lxml.etree.Element('tag', name=tag)
  188. node.text = self.tags[tag]
  189. tags.append(node)
  190. element.append(tags)
  191. return element
  192. def __repr__(self):
  193. proprepr = []
  194. for prop in self.property_list():
  195. try:
  196. proprepr.append('{}={!s}'.format(
  197. prop.__name__, getattr(self, prop.__name__)))
  198. except AttributeError:
  199. continue
  200. return '<{} object at {:#x} {}>'.format(
  201. self.__class__.__name__, id(self), ' '.join(proprepr))
  202. #
  203. # xml serialising methods
  204. #
  205. def create_config_file(self, prepare_dvm=False):
  206. '''Create libvirt's XML domain config file
  207. :param bool prepare_dvm: If we are in the process of preparing \
  208. DisposableVM
  209. '''
  210. domain_config = self.app.env.select_template([
  211. 'libvirt/xen/by-name/{}.xml'.format(self.name),
  212. 'libvirt/xen-user.xml',
  213. 'libvirt/xen-dist.xml',
  214. 'libvirt/xen.xml',
  215. ]).render(vm=self, prepare_dvm=prepare_dvm)
  216. return domain_config
  217. class VMProperty(qubes.property):
  218. '''Property that is referring to a VM
  219. :param type vmclass: class that returned VM is supposed to be instance of
  220. and all supported by :py:class:`property` with the exception of ``type`` \
  221. and ``setter``
  222. '''
  223. _none_value = ''
  224. def __init__(self, name, vmclass=BaseVM, allow_none=False,
  225. **kwargs):
  226. if 'type' in kwargs:
  227. raise TypeError(
  228. "'type' keyword parameter is unsupported in {}".format(
  229. self.__class__.__name__))
  230. if 'setter' in kwargs:
  231. raise TypeError(
  232. "'setter' keyword parameter is unsupported in {}".format(
  233. self.__class__.__name__))
  234. if not issubclass(vmclass, BaseVM):
  235. raise TypeError(
  236. "'vmclass' should specify a subclass of qubes.vm.BaseVM")
  237. super(VMProperty, self).__init__(name,
  238. saver=(lambda self_, prop, value:
  239. self._none_value if value is None else value.name),
  240. **kwargs)
  241. self.vmclass = vmclass
  242. self.allow_none = allow_none
  243. def __set__(self, instance, value):
  244. if value is self.__class__.DEFAULT:
  245. self.__delete__(instance)
  246. return
  247. if value == self._none_value:
  248. value = None
  249. if value is None:
  250. if self.allow_none:
  251. super(VMProperty, self).__set__(instance, value)
  252. return
  253. else:
  254. raise ValueError(
  255. 'Property {!r} does not allow setting to {!r}'.format(
  256. self.__name__, value))
  257. app = instance if isinstance(instance, qubes.Qubes) else instance.app
  258. try:
  259. vm = app.domains[value]
  260. except KeyError:
  261. raise qubes.exc.QubesVMNotFoundError(value)
  262. if not isinstance(vm, self.vmclass):
  263. raise TypeError('wrong VM class: domains[{!r}] is of type {!s} '
  264. 'and not {!s}'.format(value,
  265. vm.__class__.__name__,
  266. self.vmclass.__name__))
  267. super(VMProperty, self).__set__(instance, vm)