__init__.py 20 KB

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