__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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 re
  28. import subprocess
  29. import sys
  30. import xml.parsers.expat
  31. import lxml.etree
  32. import qubes
  33. import qubes.devices
  34. import qubes.events
  35. import qubes.log
  36. VM_ENTRY_POINT = 'qubes.vm'
  37. def validate_name(holder, prop, value):
  38. ''' Check if value is syntactically correct VM name '''
  39. if not isinstance(value, str):
  40. raise TypeError('VM name must be string, {!r} found'.format(
  41. type(value).__name__))
  42. if len(value) > 31:
  43. if holder is not None and prop is not None:
  44. raise qubes.exc.QubesPropertyValueError(holder, prop, value,
  45. '{} value must be shorter than 32 characters'.format(
  46. prop.__name__))
  47. else:
  48. raise qubes.exc.QubesValueError(
  49. 'VM name must be shorter than 32 characters')
  50. # this regexp does not contain '+'; if it had it, we should specifically
  51. # disallow 'lost+found' #1440
  52. if re.match(r"^[a-zA-Z][a-zA-Z0-9_-]*$", value) is None:
  53. if holder is not None and prop is not None:
  54. raise qubes.exc.QubesPropertyValueError(holder, prop, value,
  55. '{} value contains illegal characters'.format(prop.__name__))
  56. else:
  57. raise qubes.exc.QubesValueError(
  58. 'VM name contains illegal characters')
  59. class Features(dict):
  60. '''Manager of the features.
  61. Features can have three distinct values: no value (not present in mapping,
  62. which is closest thing to :py:obj:`None`), empty string (which is
  63. interpreted as :py:obj:`False`) and non-empty string, which is
  64. :py:obj:`True`. Anything assigned to the mapping is coerced to strings,
  65. however if you assign instances of :py:class:`bool`, they are converted as
  66. described above. Be aware that assigning the number `0` (which is considered
  67. false in Python) will result in string `'0'`, which is considered true.
  68. This class inherits from dict, but has most of the methods that manipulate
  69. the item disarmed (they raise NotImplementedError). The ones that are left
  70. fire appropriate events on the qube that owns an instance of this class.
  71. '''
  72. #
  73. # Those are the methods that affect contents. Either disarm them or make
  74. # them report appropriate events. Good approach is to rewrite them carefully
  75. # using official documentation, but use only our (overloaded) methods.
  76. #
  77. def __init__(self, vm, other=None, **kwargs):
  78. super(Features, self).__init__()
  79. self.vm = vm
  80. self.update(other, **kwargs)
  81. def __delitem__(self, key):
  82. super(Features, self).__delitem__(key)
  83. self.vm.fire_event('domain-feature-delete', key=key)
  84. def __setitem__(self, key, value):
  85. if value is None or isinstance(value, bool):
  86. value = '1' if value else ''
  87. else:
  88. value = str(value)
  89. self.vm.fire_event('domain-feature-set', key=key, value=value)
  90. super(Features, self).__setitem__(key, value)
  91. def clear(self):
  92. for key in self:
  93. del self[key]
  94. def pop(self):
  95. '''Not implemented
  96. :raises: NotImplementedError
  97. '''
  98. raise NotImplementedError()
  99. def popitem(self):
  100. '''Not implemented
  101. :raises: NotImplementedError
  102. '''
  103. raise NotImplementedError()
  104. def setdefault(self):
  105. '''Not implemented
  106. :raises: NotImplementedError
  107. '''
  108. raise NotImplementedError()
  109. def update(self, other=None, **kwargs):
  110. if other is not None:
  111. if hasattr(other, 'keys'):
  112. for key in other:
  113. self[key] = other[key]
  114. else:
  115. for key, value in other:
  116. self[key] = value
  117. for key in kwargs:
  118. self[key] = kwargs[key]
  119. #
  120. # end of overriding
  121. #
  122. _NO_DEFAULT = object()
  123. def check_with_template(self, feature, default=_NO_DEFAULT):
  124. ''' Check if the vm's template has the specified feature. '''
  125. if feature in self:
  126. return self[feature]
  127. if hasattr(self.vm, 'template') and self.vm.template is not None:
  128. return self.vm.template.features.check_with_template(feature,
  129. default)
  130. if default is self._NO_DEFAULT:
  131. raise KeyError(feature)
  132. return default
  133. class BaseVMMeta(qubes.events.EmitterMeta):
  134. '''Metaclass for :py:class:`.BaseVM`'''
  135. def __init__(cls, name, bases, dict_):
  136. super(BaseVMMeta, cls).__init__(name, bases, dict_)
  137. class BaseVM(qubes.PropertyHolder, metaclass=BaseVMMeta):
  138. '''Base class for all VMs
  139. :param app: Qubes application context
  140. :type app: :py:class:`qubes.Qubes`
  141. :param xml: xml node from which to deserialise
  142. :type xml: :py:class:`lxml.etree._Element` or :py:obj:`None`
  143. This class is responsible for serializing and deserialising machines and
  144. provides basic framework. It contains no management logic. For that, see
  145. :py:class:`qubes.vm.qubesvm.QubesVM`.
  146. '''
  147. # pylint: disable=no-member
  148. def __init__(self, app, xml, features=None, devices=None, tags=None,
  149. **kwargs):
  150. # pylint: disable=redefined-outer-name
  151. # self.app must be set before super().__init__, because some property
  152. # setters need working .app attribute
  153. #: mother :py:class:`qubes.Qubes` object
  154. self.app = app
  155. super(BaseVM, self).__init__(xml, **kwargs)
  156. #: dictionary of features of this qube
  157. self.features = Features(self, features)
  158. #: :py:class:`DeviceManager` object keeping devices that are attached to
  159. #: this domain
  160. self.devices = devices or qubes.devices.DeviceManager(self)
  161. #: user-specified tags
  162. self.tags = tags or {}
  163. #: logger instance for logging messages related to this VM
  164. self.log = None
  165. if hasattr(self, 'name'):
  166. self.init_log()
  167. def load_extras(self):
  168. # features
  169. for node in self.xml.xpath('./features/feature'):
  170. self.features[node.get('name')] = node.text
  171. # devices (pci, usb, ...)
  172. for parent in self.xml.xpath('./devices'):
  173. devclass = parent.get('class')
  174. for node in parent.xpath('./device'):
  175. options = {}
  176. if node.get('options'):
  177. options = node.get('options').attribs(),
  178. device_assignment = qubes.devices.DeviceAssignment(
  179. self.app.domains[node.get('backend-domain')],
  180. node.get('id'),
  181. options,
  182. persistent=True
  183. )
  184. self.devices[devclass].attach(device_assignment)
  185. # tags
  186. for node in self.xml.xpath('./tags/tag'):
  187. self.tags[node.get('name')] = node.text
  188. # SEE:1815 firewall, policy.
  189. def init_log(self):
  190. '''Initialise logger for this domain.'''
  191. self.log = qubes.log.get_vm_logger(self.name)
  192. def __xml__(self):
  193. element = lxml.etree.Element('domain')
  194. element.set('id', 'domain-' + str(self.qid))
  195. element.set('class', self.__class__.__name__)
  196. element.append(self.xml_properties())
  197. features = lxml.etree.Element('features')
  198. for feature in self.features:
  199. node = lxml.etree.Element('feature', name=feature)
  200. node.text = self.features[feature]
  201. features.append(node)
  202. element.append(features)
  203. for devclass in self.devices:
  204. devices = lxml.etree.Element('devices')
  205. devices.set('class', devclass)
  206. for device in self.devices[devclass].assignments(persistent=True):
  207. node = lxml.etree.Element('device')
  208. node.set('backend-domain', device.backend_domain.name)
  209. node.set('id', device.ident)
  210. options_node = lxml.etree.Element('options')
  211. for key, val in device.options:
  212. options_node.set(key, val)
  213. node.append(options_node)
  214. devices.append(node)
  215. element.append(devices)
  216. tags = lxml.etree.Element('tags')
  217. for tag in self.tags:
  218. node = lxml.etree.Element('tag', name=tag)
  219. node.text = self.tags[tag]
  220. tags.append(node)
  221. element.append(tags)
  222. return element
  223. def __repr__(self):
  224. proprepr = []
  225. for prop in self.property_list():
  226. try:
  227. proprepr.append('{}={!s}'.format(
  228. prop.__name__, getattr(self, prop.__name__)))
  229. except AttributeError:
  230. continue
  231. return '<{} object at {:#x} {}>'.format(
  232. self.__class__.__name__, id(self), ' '.join(proprepr))
  233. #
  234. # xml serialising methods
  235. #
  236. def create_config_file(self, prepare_dvm=False):
  237. '''Create libvirt's XML domain config file
  238. :param bool prepare_dvm: If we are in the process of preparing \
  239. DisposableVM
  240. '''
  241. domain_config = self.app.env.select_template([
  242. 'libvirt/xen/by-name/{}.xml'.format(self.name),
  243. 'libvirt/xen-user.xml',
  244. 'libvirt/xen-dist.xml',
  245. 'libvirt/xen.xml',
  246. ]).render(vm=self, prepare_dvm=prepare_dvm)
  247. return domain_config
  248. class VMProperty(qubes.property):
  249. '''Property that is referring to a VM
  250. :param type vmclass: class that returned VM is supposed to be instance of
  251. and all supported by :py:class:`property` with the exception of ``type`` \
  252. and ``setter``
  253. '''
  254. _none_value = ''
  255. def __init__(self, name, vmclass=BaseVM, allow_none=False,
  256. **kwargs):
  257. if 'type' in kwargs:
  258. raise TypeError(
  259. "'type' keyword parameter is unsupported in {}".format(
  260. self.__class__.__name__))
  261. if 'setter' in kwargs:
  262. raise TypeError(
  263. "'setter' keyword parameter is unsupported in {}".format(
  264. self.__class__.__name__))
  265. if not issubclass(vmclass, BaseVM):
  266. raise TypeError(
  267. "'vmclass' should specify a subclass of qubes.vm.BaseVM")
  268. super(VMProperty, self).__init__(name,
  269. saver=(lambda self_, prop, value:
  270. self._none_value if value is None else value.name),
  271. **kwargs)
  272. self.vmclass = vmclass
  273. self.allow_none = allow_none
  274. def __set__(self, instance, value):
  275. if value is self.__class__.DEFAULT:
  276. self.__delete__(instance)
  277. return
  278. if value == self._none_value:
  279. value = None
  280. if value is None:
  281. if self.allow_none:
  282. super(VMProperty, self).__set__(instance, value)
  283. return
  284. else:
  285. raise ValueError(
  286. 'Property {!r} does not allow setting to {!r}'.format(
  287. self.__name__, value))
  288. app = instance if isinstance(instance, qubes.Qubes) else instance.app
  289. try:
  290. vm = app.domains[value]
  291. except KeyError:
  292. raise qubes.exc.QubesVMNotFoundError(value)
  293. if not isinstance(vm, self.vmclass):
  294. raise TypeError('wrong VM class: domains[{!r}] is of type {!s} '
  295. 'and not {!s}'.format(value,
  296. vm.__class__.__name__,
  297. self.vmclass.__name__))
  298. super(VMProperty, self).__set__(instance, vm)
  299. def sanitize(self, *, untrusted_newvalue):
  300. try:
  301. untrusted_vmname = untrusted_newvalue.decode('ascii')
  302. except UnicodeDecodeError:
  303. raise qubes.exc.QubesValueError
  304. validate_name(None, self, untrusted_vmname)
  305. return untrusted_vmname