__init__.py 15 KB

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