dispvm.py 8.3 KB

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