dispvm.py 9.5 KB

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