__init__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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 string
  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. 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. # TODO: perhaps this shouldn't be fired on unchanged value? or at
  91. # least oldvalue should be provided?
  92. self.vm.fire_event('domain-feature-set', key=key, value=value)
  93. super(Features, self).__setitem__(key, value)
  94. def clear(self):
  95. for key in tuple(self):
  96. del self[key]
  97. def pop(self, _key, _default=None):
  98. '''Not implemented
  99. :raises: NotImplementedError
  100. '''
  101. raise NotImplementedError()
  102. def popitem(self):
  103. '''Not implemented
  104. :raises: NotImplementedError
  105. '''
  106. raise NotImplementedError()
  107. def setdefault(self, _key, _default=None):
  108. '''Not implemented
  109. :raises: NotImplementedError
  110. '''
  111. raise NotImplementedError()
  112. def update(self, other=None, **kwargs):
  113. if other is not None:
  114. if hasattr(other, 'keys'):
  115. for key in other:
  116. self[key] = other[key]
  117. else:
  118. for key, value in other:
  119. self[key] = value
  120. for key in kwargs:
  121. self[key] = kwargs[key]
  122. #
  123. # end of overriding
  124. #
  125. _NO_DEFAULT = object()
  126. def check_with_template(self, feature, default=_NO_DEFAULT):
  127. ''' Check if the vm's template has the specified feature. '''
  128. if feature in self:
  129. return self[feature]
  130. if hasattr(self.vm, 'template') and self.vm.template is not None:
  131. return self.vm.template.features.check_with_template(feature,
  132. default)
  133. if default is self._NO_DEFAULT:
  134. raise KeyError(feature)
  135. return default
  136. class Tags(set):
  137. '''Manager of the tags.
  138. Tags are simple: tag either can be present on qube or not. Tag is a
  139. simple string consisting of ASCII alphanumeric characters, plus `_` and
  140. `-`.
  141. This class inherits from set, but has most of the methods that manipulate
  142. the item disarmed (they raise NotImplementedError). The ones that are left
  143. fire appropriate events on the qube that owns an instance of this class.
  144. '''
  145. #
  146. # Those are the methods that affect contents. Either disarm them or make
  147. # them report appropriate events. Good approach is to rewrite them carefully
  148. # using official documentation, but use only our (overloaded) methods.
  149. #
  150. def __init__(self, vm, seq=()):
  151. super(Tags, self).__init__()
  152. self.vm = vm
  153. self.update(seq)
  154. def clear(self):
  155. '''Remove all tags'''
  156. for item in tuple(self):
  157. self.remove(item)
  158. def symmetric_difference_update(self, *args, **kwargs):
  159. '''Not implemented
  160. :raises: NotImplementedError
  161. '''
  162. raise NotImplementedError()
  163. def intersection_update(self, *args, **kwargs):
  164. '''Not implemented
  165. :raises: NotImplementedError
  166. '''
  167. raise NotImplementedError()
  168. def pop(self):
  169. '''Not implemented
  170. :raises: NotImplementedError
  171. '''
  172. raise NotImplementedError()
  173. def discard(self, elem):
  174. '''Remove a tag if present'''
  175. if elem in self:
  176. self.remove(elem)
  177. def update(self, *others):
  178. '''Add tags from iterable(s)'''
  179. for other in others:
  180. for elem in other:
  181. self.add(elem)
  182. def add(self, elem):
  183. '''Add a tag'''
  184. allowed_chars = string.ascii_letters + string.digits + '_-'
  185. if any(i not in allowed_chars for i in elem):
  186. raise ValueError('Invalid character in tag')
  187. if elem in self:
  188. return
  189. self.vm.fire_event('domain-tag-add', tag=elem)
  190. super(Tags, self).add(elem)
  191. def remove(self, elem):
  192. '''Remove a tag'''
  193. super(Tags, self).remove(elem)
  194. self.vm.fire_event('domain-tag-delete', tag=elem)
  195. #
  196. # end of overriding
  197. #
  198. class BaseVM(qubes.PropertyHolder):
  199. '''Base class for all VMs
  200. :param app: Qubes application context
  201. :type app: :py:class:`qubes.Qubes`
  202. :param xml: xml node from which to deserialise
  203. :type xml: :py:class:`lxml.etree._Element` or :py:obj:`None`
  204. This class is responsible for serializing and deserialising machines and
  205. provides basic framework. It contains no management logic. For that, see
  206. :py:class:`qubes.vm.qubesvm.QubesVM`.
  207. '''
  208. # pylint: disable=no-member
  209. def __init__(self, app, xml, features=None, devices=None, tags=None,
  210. **kwargs):
  211. # pylint: disable=redefined-outer-name
  212. # self.app must be set before super().__init__, because some property
  213. # setters need working .app attribute
  214. #: mother :py:class:`qubes.Qubes` object
  215. self.app = app
  216. super(BaseVM, self).__init__(xml, **kwargs)
  217. #: dictionary of features of this qube
  218. self.features = Features(self, features)
  219. #: :py:class:`DeviceManager` object keeping devices that are attached to
  220. #: this domain
  221. self.devices = devices or qubes.devices.DeviceManager(self)
  222. #: user-specified tags
  223. self.tags = Tags(self, tags or ())
  224. #: logger instance for logging messages related to this VM
  225. self.log = None
  226. if hasattr(self, 'name'):
  227. self.init_log()
  228. def load_extras(self):
  229. # features
  230. for node in self.xml.xpath('./features/feature'):
  231. self.features[node.get('name')] = node.text
  232. # devices (pci, usb, ...)
  233. for parent in self.xml.xpath('./devices'):
  234. devclass = parent.get('class')
  235. for node in parent.xpath('./device'):
  236. options = {}
  237. if node.get('options'):
  238. options = node.get('options').attribs(),
  239. device_assignment = qubes.devices.DeviceAssignment(
  240. self.app.domains[node.get('backend-domain')],
  241. node.get('id'),
  242. options,
  243. persistent=True
  244. )
  245. self.devices[devclass].attach(device_assignment)
  246. # tags
  247. for node in self.xml.xpath('./tags/tag'):
  248. self.tags.add(node.get('name'))
  249. # SEE:1815 firewall, policy.
  250. def init_log(self):
  251. '''Initialise logger for this domain.'''
  252. self.log = qubes.log.get_vm_logger(self.name)
  253. def __xml__(self):
  254. element = lxml.etree.Element('domain')
  255. element.set('id', 'domain-' + str(self.qid))
  256. element.set('class', self.__class__.__name__)
  257. element.append(self.xml_properties())
  258. features = lxml.etree.Element('features')
  259. for feature in self.features:
  260. node = lxml.etree.Element('feature', name=feature)
  261. node.text = self.features[feature]
  262. features.append(node)
  263. element.append(features)
  264. for devclass in self.devices:
  265. devices = lxml.etree.Element('devices')
  266. devices.set('class', devclass)
  267. for device in self.devices[devclass].assignments(persistent=True):
  268. node = lxml.etree.Element('device')
  269. node.set('backend-domain', device.backend_domain.name)
  270. node.set('id', device.ident)
  271. options_node = lxml.etree.Element('options')
  272. for key, val in device.options:
  273. options_node.set(key, val)
  274. node.append(options_node)
  275. devices.append(node)
  276. element.append(devices)
  277. tags = lxml.etree.Element('tags')
  278. for tag in self.tags:
  279. node = lxml.etree.Element('tag', name=tag)
  280. tags.append(node)
  281. element.append(tags)
  282. return element
  283. def __repr__(self):
  284. proprepr = []
  285. for prop in self.property_list():
  286. try:
  287. proprepr.append('{}={!s}'.format(
  288. prop.__name__, getattr(self, prop.__name__)))
  289. except AttributeError:
  290. continue
  291. return '<{} object at {:#x} {}>'.format(
  292. self.__class__.__name__, id(self), ' '.join(proprepr))
  293. #
  294. # xml serialising methods
  295. #
  296. def create_config_file(self, prepare_dvm=False):
  297. '''Create libvirt's XML domain config file
  298. :param bool prepare_dvm: If we are in the process of preparing \
  299. DisposableVM
  300. '''
  301. domain_config = self.app.env.select_template([
  302. 'libvirt/xen/by-name/{}.xml'.format(self.name),
  303. 'libvirt/xen-user.xml',
  304. 'libvirt/xen-dist.xml',
  305. 'libvirt/xen.xml',
  306. ]).render(vm=self, prepare_dvm=prepare_dvm)
  307. return domain_config
  308. class VMProperty(qubes.property):
  309. '''Property that is referring to a VM
  310. :param type vmclass: class that returned VM is supposed to be instance of
  311. and all supported by :py:class:`property` with the exception of ``type`` \
  312. and ``setter``
  313. '''
  314. _none_value = ''
  315. def __init__(self, name, vmclass=BaseVM, allow_none=False,
  316. **kwargs):
  317. if 'type' in kwargs:
  318. raise TypeError(
  319. "'type' keyword parameter is unsupported in {}".format(
  320. self.__class__.__name__))
  321. if not issubclass(vmclass, BaseVM):
  322. raise TypeError(
  323. "'vmclass' should specify a subclass of qubes.vm.BaseVM")
  324. super(VMProperty, self).__init__(name,
  325. saver=(lambda self_, prop, value:
  326. self._none_value if value is None else value.name),
  327. **kwargs)
  328. self.vmclass = vmclass
  329. self.allow_none = allow_none
  330. def __set__(self, instance, value):
  331. if value is self.__class__.DEFAULT:
  332. self.__delete__(instance)
  333. return
  334. if value == self._none_value:
  335. value = None
  336. if value is None:
  337. if self.allow_none:
  338. super(VMProperty, self).__set__(instance, value)
  339. return
  340. else:
  341. raise ValueError(
  342. 'Property {!r} does not allow setting to {!r}'.format(
  343. self.__name__, value))
  344. app = instance if isinstance(instance, qubes.Qubes) else instance.app
  345. try:
  346. vm = app.domains[value]
  347. except KeyError:
  348. raise qubes.exc.QubesVMNotFoundError(value)
  349. if not isinstance(vm, self.vmclass):
  350. raise TypeError('wrong VM class: domains[{!r}] is of type {!s} '
  351. 'and not {!s}'.format(value,
  352. vm.__class__.__name__,
  353. self.vmclass.__name__))
  354. super(VMProperty, self).__set__(instance, vm)
  355. def sanitize(self, *, untrusted_newvalue):
  356. try:
  357. untrusted_vmname = untrusted_newvalue.decode('ascii')
  358. except UnicodeDecodeError:
  359. raise qubes.exc.QubesValueError
  360. validate_name(None, self, untrusted_vmname)
  361. return untrusted_vmname