__init__.py 19 KB

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