__init__.py 16 KB

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