__init__.py 13 KB

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