__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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 asyncio
  26. import re
  27. import string
  28. import lxml.etree
  29. import qubes
  30. import qubes.devices
  31. import qubes.events
  32. import qubes.log
  33. VM_ENTRY_POINT = 'qubes.vm'
  34. def validate_name(holder, prop, value):
  35. ''' Check if value is syntactically correct VM name '''
  36. if not isinstance(value, str):
  37. raise TypeError('VM name must be string, {!r} found'.format(
  38. type(value).__name__))
  39. if len(value) > 31:
  40. if holder is not None and prop is not None:
  41. raise qubes.exc.QubesPropertyValueError(holder, prop, value,
  42. '{} value must be shorter than 32 characters'.format(
  43. prop.__name__))
  44. else:
  45. raise qubes.exc.QubesValueError(
  46. 'VM name must be shorter than 32 characters')
  47. # this regexp does not contain '+'; if it had it, we should specifically
  48. # disallow 'lost+found' #1440
  49. if re.match(r"^[a-zA-Z][a-zA-Z0-9_-]*$", value) is None:
  50. if holder is not None and prop is not None:
  51. raise qubes.exc.QubesPropertyValueError(holder, prop, value,
  52. '{} value contains illegal characters'.format(prop.__name__))
  53. else:
  54. raise qubes.exc.QubesValueError(
  55. 'VM name contains illegal characters')
  56. class Features(dict):
  57. '''Manager of the features.
  58. Features can have three distinct values: no value (not present in mapping,
  59. which is closest thing to :py:obj:`None`), empty string (which is
  60. interpreted as :py:obj:`False`) and non-empty string, which is
  61. :py:obj:`True`. Anything assigned to the mapping is coerced to strings,
  62. however if you assign instances of :py:class:`bool`, they are converted as
  63. described above. Be aware that assigning the number `0` (which is considered
  64. false in Python) will result in string `'0'`, which is considered true.
  65. This class inherits from dict, but has most of the methods that manipulate
  66. the item disarmed (they raise NotImplementedError). The ones that are left
  67. fire appropriate events on the qube that owns an instance of this class.
  68. '''
  69. #
  70. # Those are the methods that affect contents. Either disarm them or make
  71. # them report appropriate events. Good approach is to rewrite them carefully
  72. # using official documentation, but use only our (overloaded) methods.
  73. #
  74. def __init__(self, vm, other=None, **kwargs):
  75. super(Features, self).__init__()
  76. self.vm = vm
  77. self.update(other, **kwargs)
  78. def __delitem__(self, key):
  79. super(Features, self).__delitem__(key)
  80. self.vm.fire_event('domain-feature-delete', feature=key)
  81. def __setitem__(self, key, value):
  82. if value is None or isinstance(value, bool):
  83. value = '1' if value else ''
  84. else:
  85. value = str(value)
  86. try:
  87. oldvalue = self[key]
  88. has_oldvalue = True
  89. except KeyError:
  90. has_oldvalue = False
  91. super(Features, self).__setitem__(key, value)
  92. if has_oldvalue:
  93. self.vm.fire_event('domain-feature-set', feature=key, value=value,
  94. oldvalue=oldvalue)
  95. else:
  96. self.vm.fire_event('domain-feature-set', feature=key, value=value)
  97. def clear(self):
  98. for key in tuple(self):
  99. del self[key]
  100. def pop(self, _key, _default=None):
  101. '''Not implemented
  102. :raises: NotImplementedError
  103. '''
  104. raise NotImplementedError()
  105. def popitem(self):
  106. '''Not implemented
  107. :raises: NotImplementedError
  108. '''
  109. raise NotImplementedError()
  110. def setdefault(self, _key, _default=None):
  111. '''Not implemented
  112. :raises: NotImplementedError
  113. '''
  114. raise NotImplementedError()
  115. def update(self, other=None, **kwargs):
  116. if other is not None:
  117. if hasattr(other, 'keys'):
  118. for key in other:
  119. self[key] = other[key]
  120. else:
  121. for key, value in other:
  122. self[key] = value
  123. for key in kwargs:
  124. self[key] = kwargs[key]
  125. #
  126. # end of overriding
  127. #
  128. _NO_DEFAULT = object()
  129. def check_with_template(self, feature, default=_NO_DEFAULT):
  130. ''' Check if the vm's template has the specified feature. '''
  131. if feature in self:
  132. return self[feature]
  133. if hasattr(self.vm, 'template') and self.vm.template is not None:
  134. return self.vm.template.features.check_with_template(feature,
  135. default)
  136. if default is self._NO_DEFAULT:
  137. raise KeyError(feature)
  138. return default
  139. class Tags(set):
  140. '''Manager of the tags.
  141. Tags are simple: tag either can be present on qube or not. Tag is a
  142. simple string consisting of ASCII alphanumeric characters, plus `_` and
  143. `-`.
  144. This class inherits from set, but has most of the methods that manipulate
  145. the item disarmed (they raise NotImplementedError). The ones that are left
  146. fire appropriate events on the qube that owns an instance of this class.
  147. '''
  148. #
  149. # Those are the methods that affect contents. Either disarm them or make
  150. # them report appropriate events. Good approach is to rewrite them carefully
  151. # using official documentation, but use only our (overloaded) methods.
  152. #
  153. def __init__(self, vm, seq=()):
  154. super(Tags, self).__init__()
  155. self.vm = vm
  156. self.update(seq)
  157. def clear(self):
  158. '''Remove all tags'''
  159. for item in tuple(self):
  160. self.remove(item)
  161. def symmetric_difference_update(self, *args, **kwargs):
  162. '''Not implemented
  163. :raises: NotImplementedError
  164. '''
  165. raise NotImplementedError()
  166. def intersection_update(self, *args, **kwargs):
  167. '''Not implemented
  168. :raises: NotImplementedError
  169. '''
  170. raise NotImplementedError()
  171. def pop(self):
  172. '''Not implemented
  173. :raises: NotImplementedError
  174. '''
  175. raise NotImplementedError()
  176. def discard(self, elem):
  177. '''Remove a tag if present'''
  178. if elem in self:
  179. self.remove(elem)
  180. def update(self, *others):
  181. '''Add tags from iterable(s)'''
  182. for other in others:
  183. for elem in other:
  184. self.add(elem)
  185. def add(self, elem):
  186. '''Add a tag'''
  187. allowed_chars = string.ascii_letters + string.digits + '_-'
  188. if any(i not in allowed_chars for i in elem):
  189. raise ValueError('Invalid character in tag')
  190. if elem in self:
  191. return
  192. super(Tags, self).add(elem)
  193. self.vm.fire_event('domain-tag-add', tag=elem)
  194. def remove(self, elem):
  195. '''Remove a tag'''
  196. super(Tags, self).remove(elem)
  197. self.vm.fire_event('domain-tag-delete', tag=elem)
  198. #
  199. # end of overriding
  200. #
  201. @staticmethod
  202. def validate_tag(tag):
  203. safe_set = string.ascii_letters + string.digits + '-_'
  204. assert all((x in safe_set) for x in tag)
  205. class BaseVM(qubes.PropertyHolder):
  206. '''Base class for all VMs
  207. :param app: Qubes application context
  208. :type app: :py:class:`qubes.Qubes`
  209. :param xml: xml node from which to deserialise
  210. :type xml: :py:class:`lxml.etree._Element` or :py:obj:`None`
  211. This class is responsible for serializing and deserialising machines and
  212. provides basic framework. It contains no management logic. For that, see
  213. :py:class:`qubes.vm.qubesvm.QubesVM`.
  214. '''
  215. # pylint: disable=no-member
  216. def __init__(self, app, xml, features=None, devices=None, tags=None,
  217. **kwargs):
  218. # pylint: disable=redefined-outer-name
  219. # self.app must be set before super().__init__, because some property
  220. # setters need working .app attribute
  221. #: mother :py:class:`qubes.Qubes` object
  222. self._qdb_watch_paths = set()
  223. self._qdb_connection_watch = None
  224. self.app = app
  225. super(BaseVM, self).__init__(xml, **kwargs)
  226. #: dictionary of features of this qube
  227. self.features = Features(self, features)
  228. #: :py:class:`DeviceManager` object keeping devices that are attached to
  229. #: this domain
  230. self.devices = devices or qubes.devices.DeviceManager(self)
  231. #: user-specified tags
  232. self.tags = Tags(self, tags or ())
  233. #: logger instance for logging messages related to this VM
  234. self.log = None
  235. #: storage volumes
  236. self.volumes = {}
  237. #: storage manager
  238. self.storage = None
  239. if hasattr(self, 'name'):
  240. self.init_log()
  241. def load_extras(self):
  242. # features
  243. for node in self.xml.xpath('./features/feature'):
  244. self.features[node.get('name')] = node.text
  245. # devices (pci, usb, ...)
  246. for parent in self.xml.xpath('./devices'):
  247. devclass = parent.get('class')
  248. for node in parent.xpath('./device'):
  249. options = {}
  250. for option in node.xpath('./option'):
  251. options[option.get('name')] = option.text
  252. device_assignment = qubes.devices.DeviceAssignment(
  253. self.app.domains[node.get('backend-domain')],
  254. node.get('id'),
  255. options,
  256. persistent=True
  257. )
  258. self.devices[devclass].load_persistent(device_assignment)
  259. # tags
  260. for node in self.xml.xpath('./tags/tag'):
  261. self.tags.add(node.get('name'))
  262. # SEE:1815 firewall, policy.
  263. def init_log(self):
  264. '''Initialise logger for this domain.'''
  265. self.log = qubes.log.get_vm_logger(self.name)
  266. def __xml__(self):
  267. element = lxml.etree.Element('domain')
  268. element.set('id', 'domain-' + str(self.qid))
  269. element.set('class', self.__class__.__name__)
  270. element.append(self.xml_properties())
  271. features = lxml.etree.Element('features')
  272. for feature in self.features:
  273. node = lxml.etree.Element('feature', name=feature)
  274. node.text = self.features[feature]
  275. features.append(node)
  276. element.append(features)
  277. for devclass in self.devices:
  278. devices = lxml.etree.Element('devices')
  279. devices.set('class', devclass)
  280. for device in self.devices[devclass].assignments(persistent=True):
  281. node = lxml.etree.Element('device')
  282. node.set('backend-domain', device.backend_domain.name)
  283. node.set('id', device.ident)
  284. for key, val in device.options.items():
  285. option_node = lxml.etree.Element('option')
  286. option_node.set('name', key)
  287. option_node.text = val
  288. node.append(option_node)
  289. devices.append(node)
  290. element.append(devices)
  291. tags = lxml.etree.Element('tags')
  292. for tag in self.tags:
  293. node = lxml.etree.Element('tag', name=tag)
  294. tags.append(node)
  295. element.append(tags)
  296. return element
  297. def __repr__(self):
  298. proprepr = []
  299. for prop in self.property_list():
  300. try:
  301. proprepr.append('{}={!s}'.format(
  302. prop.__name__, getattr(self, prop.__name__)))
  303. except AttributeError:
  304. continue
  305. return '<{} object at {:#x} {}>'.format(
  306. self.__class__.__name__, id(self), ' '.join(proprepr))
  307. #
  308. # xml serialising methods
  309. #
  310. def create_config_file(self):
  311. '''Create libvirt's XML domain config file
  312. '''
  313. domain_config = self.app.env.select_template([
  314. 'libvirt/xen/by-name/{}.xml'.format(self.name),
  315. 'libvirt/xen-user.xml',
  316. 'libvirt/xen-dist.xml',
  317. 'libvirt/xen.xml',
  318. ]).render(vm=self)
  319. return domain_config
  320. def watch_qdb_path(self, path):
  321. '''Add a QubesDB path to be watched.
  322. Each change to the path will cause `domain-qdb-change:path` event to be
  323. fired.
  324. You can call this method for example in response to
  325. `domain-init` and `domain-load` events.
  326. '''
  327. if path not in self._qdb_watch_paths:
  328. self._qdb_watch_paths.add(path)
  329. if self._qdb_connection_watch:
  330. self._qdb_connection_watch.watch(path)
  331. def _qdb_watch_reader(self, loop):
  332. '''Callback when self._qdb_connection_watch.watch_fd() FD is
  333. readable.
  334. Read reported event (watched path change) and fire appropriate event.
  335. '''
  336. import qubesdb # pylint: disable=import-error
  337. try:
  338. path = self._qdb_connection_watch.read_watch()
  339. for watched_path in self._qdb_watch_paths:
  340. if watched_path == path or (
  341. watched_path.endswith('/') and
  342. path.startswith(watched_path)):
  343. self.fire_event('domain-qdb-change:' + watched_path,
  344. path=path)
  345. except qubesdb.DisconnectedError:
  346. loop.remove_reader(self._qdb_connection_watch.watch_fd())
  347. self._qdb_connection_watch.close()
  348. self._qdb_connection_watch = None
  349. def start_qdb_watch(self, name, loop=None):
  350. '''Start watching QubesDB
  351. Calling this method in appropriate time is responsibility of child
  352. class.
  353. '''
  354. import qubesdb # pylint: disable=import-error
  355. self._qdb_connection_watch = qubesdb.QubesDB(name)
  356. if loop is None:
  357. loop = asyncio.get_event_loop()
  358. loop.add_reader(self._qdb_connection_watch.watch_fd(),
  359. self._qdb_watch_reader, loop)
  360. for path in self._qdb_watch_paths:
  361. self._qdb_connection_watch.watch(path)
  362. class VMProperty(qubes.property):
  363. '''Property that is referring to a VM
  364. :param type vmclass: class that returned VM is supposed to be instance of
  365. and all supported by :py:class:`property` with the exception of ``type`` \
  366. and ``setter``
  367. '''
  368. _none_value = ''
  369. def __init__(self, name, vmclass=BaseVM, allow_none=False,
  370. **kwargs):
  371. if 'type' in kwargs:
  372. raise TypeError(
  373. "'type' keyword parameter is unsupported in {}".format(
  374. self.__class__.__name__))
  375. if not issubclass(vmclass, BaseVM):
  376. raise TypeError(
  377. "'vmclass' should specify a subclass of qubes.vm.BaseVM")
  378. super(VMProperty, self).__init__(name,
  379. saver=(lambda self_, prop, value:
  380. self._none_value if value is None else value.name),
  381. **kwargs)
  382. self.vmclass = vmclass
  383. self.allow_none = allow_none
  384. def __set__(self, instance, value):
  385. if value is self.__class__.DEFAULT:
  386. self.__delete__(instance)
  387. return
  388. if value == self._none_value:
  389. value = None
  390. if value is None:
  391. if self.allow_none:
  392. super(VMProperty, self).__set__(instance, value)
  393. return
  394. else:
  395. raise ValueError(
  396. 'Property {!r} does not allow setting to {!r}'.format(
  397. self.__name__, value))
  398. app = instance if isinstance(instance, qubes.Qubes) else instance.app
  399. try:
  400. vm = app.domains[value]
  401. except KeyError:
  402. raise qubes.exc.QubesVMNotFoundError(value)
  403. if not isinstance(vm, self.vmclass):
  404. raise TypeError('wrong VM class: domains[{!r}] is of type {!s} '
  405. 'and not {!s}'.format(value,
  406. vm.__class__.__name__,
  407. self.vmclass.__name__))
  408. super(VMProperty, self).__set__(instance, vm)
  409. def sanitize(self, *, untrusted_newvalue):
  410. try:
  411. untrusted_vmname = untrusted_newvalue.decode('ascii')
  412. except UnicodeDecodeError:
  413. raise qubes.exc.QubesValueError
  414. if untrusted_vmname == '':
  415. # allow empty VM name for setting VMProperty value, because it's
  416. # string representation of None (see self._none_value)
  417. return untrusted_vmname
  418. validate_name(None, self, untrusted_vmname)
  419. return untrusted_vmname
  420. def setter_label(self, prop, value):
  421. ''' Helper for setting the domain label '''
  422. # pylint: disable=unused-argument
  423. if isinstance(value, qubes.Label):
  424. return value
  425. if isinstance(value, str) and value.startswith('label-'):
  426. return self.app.labels[int(value.split('-', 1)[1])]
  427. return self.app.get_label(value)