dispvm.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. #
  2. # The Qubes OS Project, http://www.qubes-os.org
  3. #
  4. # Copyright (C) 2014-2016 Wojtek Porczyk <woju@invisiblethingslab.com>
  5. # Copyright (C) 2016 Marek Marczykowski <marmarek@invisiblethingslab.com>)
  6. #
  7. # This library is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU Lesser General Public
  9. # License as published by the Free Software Foundation; either
  10. # version 2.1 of the License, or (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. # Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public
  18. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  19. #
  20. ''' A disposable vm implementation '''
  21. import asyncio
  22. import copy
  23. import qubes.vm.qubesvm
  24. import qubes.vm.appvm
  25. import qubes.config
  26. def _setter_template(self, prop, value):
  27. if not getattr(value, 'template_for_dispvms', False):
  28. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  29. 'template for DispVM must have template_for_dispvms=True')
  30. return value
  31. class DispVM(qubes.vm.qubesvm.QubesVM):
  32. '''Disposable VM'''
  33. template = qubes.VMProperty('template',
  34. load_stage=4,
  35. setter=_setter_template,
  36. doc='AppVM, on which this DispVM is based.')
  37. dispid = qubes.property('dispid', type=int, write_once=True,
  38. clone=False,
  39. doc='''Internal, persistent identifier of particular DispVM.''')
  40. auto_cleanup = qubes.property('auto_cleanup', type=bool, default=False,
  41. doc='automatically remove this VM upon shutdown')
  42. include_in_backups = qubes.property('include_in_backups', type=bool,
  43. default=(lambda self: not self.auto_cleanup),
  44. doc='If this domain is to be included in default backup.')
  45. default_dispvm = qubes.VMProperty('default_dispvm',
  46. load_stage=4,
  47. allow_none=True,
  48. default=(lambda self: self.template),
  49. doc='Default VM to be used as Disposable VM for service calls.')
  50. default_volume_config = {
  51. 'root': {
  52. 'name': 'root',
  53. 'snap_on_start': True,
  54. 'save_on_stop': False,
  55. 'rw': True,
  56. 'source': None,
  57. },
  58. 'private': {
  59. 'name': 'private',
  60. 'snap_on_start': True,
  61. 'save_on_stop': False,
  62. 'rw': True,
  63. 'source': None,
  64. },
  65. 'volatile': {
  66. 'name': 'volatile',
  67. 'snap_on_start': False,
  68. 'save_on_stop': False,
  69. 'rw': True,
  70. 'size': qubes.config.defaults['root_img_size'] +
  71. qubes.config.defaults['private_img_size'],
  72. },
  73. 'kernel': {
  74. 'name': 'kernel',
  75. 'snap_on_start': False,
  76. 'save_on_stop': False,
  77. 'rw': False,
  78. },
  79. }
  80. def __init__(self, app, xml, *args, **kwargs):
  81. self.volume_config = copy.deepcopy(self.default_volume_config)
  82. template = kwargs.get('template', None)
  83. if xml is None:
  84. assert template is not None
  85. if not getattr(template, 'template_for_dispvms', False):
  86. raise qubes.exc.QubesValueError(
  87. 'template for DispVM ({}) needs to be an AppVM with '
  88. 'template_for_dispvms=True'.format(template.name))
  89. if 'dispid' not in kwargs:
  90. kwargs['dispid'] = app.domains.get_new_unused_dispid()
  91. if 'name' not in kwargs:
  92. kwargs['name'] = 'disp' + str(kwargs['dispid'])
  93. if template is not None:
  94. # template is only passed if the AppVM is created, in other cases we
  95. # don't need to patch the volume_config because the config is
  96. # coming from XML, already as we need it
  97. for name, config in template.volume_config.items():
  98. # in case the template vm has more volumes add them to own
  99. # config
  100. if name not in self.volume_config:
  101. self.volume_config[name] = config.copy()
  102. if 'vid' in self.volume_config[name]:
  103. del self.volume_config[name]['vid']
  104. # copy pool setting from base AppVM; root and private would be
  105. # in the same pool anyway (because of snap_on_start),
  106. # but not volatile, which could be surprising
  107. elif 'pool' not in self.volume_config[name] \
  108. and 'pool' in config:
  109. self.volume_config[name]['pool'] = config['pool']
  110. super().__init__(app, xml, *args, **kwargs)
  111. if xml is None:
  112. # by default inherit properties from the DispVM template
  113. proplist = [prop.__name__ for prop in template.property_list()
  114. if prop.clone and prop.__name__ not in ['template']]
  115. # Do not overwrite properties that have already been set to a
  116. # non-default value.
  117. self_props = [prop.__name__ for prop in self.property_list()
  118. if self.property_is_default(prop)]
  119. self.clone_properties(template, set(proplist).intersection(
  120. self_props))
  121. self.firewall.clone(template.firewall)
  122. self.features.update(template.features)
  123. self.tags.update(template.tags)
  124. @qubes.events.handler('domain-load')
  125. def on_domain_loaded(self, event):
  126. ''' When domain is loaded assert that this vm has a template.
  127. ''' # pylint: disable=unused-argument
  128. assert self.template
  129. @qubes.events.handler('property-pre-reset:template')
  130. def on_property_pre_reset_template(self, event, name, oldvalue=None):
  131. '''Forbid deleting template of VM
  132. ''' # pylint: disable=unused-argument,no-self-use
  133. raise qubes.exc.QubesValueError('Cannot unset template')
  134. @qubes.events.handler('property-pre-set:template')
  135. def on_property_pre_set_template(self, event, name, newvalue,
  136. oldvalue=None):
  137. '''Forbid changing template of running VM
  138. ''' # pylint: disable=unused-argument
  139. if not self.is_halted():
  140. raise qubes.exc.QubesVMNotHaltedError(self,
  141. 'Cannot change template while qube is running')
  142. @qubes.events.handler('property-set:template')
  143. def on_property_set_template(self, event, name, newvalue, oldvalue=None):
  144. ''' Adjust root (and possibly other snap_on_start=True) volume
  145. on template change.
  146. ''' # pylint: disable=unused-argument
  147. qubes.vm.appvm.template_changed_update_storage(self)
  148. @qubes.events.handler('domain-shutdown')
  149. @asyncio.coroutine
  150. def on_domain_shutdown(self, _event, **_kwargs):
  151. yield from self._auto_cleanup()
  152. @asyncio.coroutine
  153. def _auto_cleanup(self):
  154. '''Do auto cleanup if enabled'''
  155. if self.auto_cleanup and self in self.app.domains:
  156. del self.app.domains[self]
  157. yield from self.remove_from_disk()
  158. self.app.save()
  159. @classmethod
  160. @asyncio.coroutine
  161. def from_appvm(cls, appvm, **kwargs):
  162. '''Create a new instance from given AppVM
  163. :param qubes.vm.appvm.AppVM appvm: template from which the VM should \
  164. be created
  165. :returns: new disposable vm
  166. *kwargs* are passed to the newly created VM
  167. >>> import qubes.vm.dispvm.DispVM
  168. >>> dispvm = qubes.vm.dispvm.DispVM.from_appvm(appvm).start()
  169. >>> dispvm.run_service('qubes.VMShell', input='firefox')
  170. >>> dispvm.cleanup()
  171. This method modifies :file:`qubes.xml` file.
  172. The qube returned is not started.
  173. '''
  174. if not appvm.template_for_dispvms:
  175. raise qubes.exc.QubesException(
  176. 'Refusing to create DispVM out of this AppVM, because '
  177. 'template_for_dispvms=False')
  178. app = appvm.app
  179. dispvm = app.add_new_vm(
  180. cls,
  181. template=appvm,
  182. auto_cleanup=True,
  183. **kwargs)
  184. yield from dispvm.create_on_disk()
  185. app.save()
  186. return dispvm
  187. @asyncio.coroutine
  188. def cleanup(self):
  189. '''Clean up after the DispVM
  190. This stops the disposable qube and removes it from the store.
  191. This method modifies :file:`qubes.xml` file.
  192. '''
  193. try:
  194. # pylint: disable=not-an-iterable
  195. yield from self.kill()
  196. except qubes.exc.QubesVMNotStartedError:
  197. pass
  198. # if auto_cleanup is set, this will be done automatically
  199. if not self.auto_cleanup:
  200. del self.app.domains[self]
  201. yield from self.remove_from_disk()
  202. self.app.save()
  203. @asyncio.coroutine
  204. def start(self, **kwargs):
  205. # pylint: disable=arguments-differ
  206. try:
  207. # sanity check, if template_for_dispvm got changed in the meantime
  208. if not self.template.template_for_dispvms:
  209. raise qubes.exc.QubesException(
  210. 'template for DispVM ({}) needs to have '
  211. 'template_for_dispvms=True'.format(self.template.name))
  212. yield from super().start(**kwargs)
  213. except:
  214. # Cleanup also on failed startup
  215. yield from self._auto_cleanup()
  216. raise
  217. def create_qdb_entries(self):
  218. super().create_qdb_entries()
  219. self.untrusted_qdb.write('/qubes-vm-persistence', 'none')