dispvm.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. self_props = [prop.__name__ for prop in self.property_list()]
  103. self.clone_properties(template, set(proplist).intersection(
  104. self_props))
  105. self.firewall.clone(template.firewall)
  106. self.features.update(template.features)
  107. self.tags.update(template.tags)
  108. @qubes.events.handler('domain-load')
  109. def on_domain_loaded(self, event):
  110. ''' When domain is loaded assert that this vm has a template.
  111. ''' # pylint: disable=unused-argument
  112. assert self.template
  113. @qubes.events.handler('property-pre-set:template',
  114. 'property-pre-del:template')
  115. def on_property_pre_set_template(self, event, name, newvalue=None,
  116. oldvalue=None):
  117. ''' Disposable VM cannot have template changed '''
  118. # pylint: disable=unused-argument
  119. raise qubes.exc.QubesValueError(self,
  120. 'Cannot change template of Disposable VM')
  121. @qubes.events.handler('domain-shutdown')
  122. @asyncio.coroutine
  123. def on_domain_shutdown(self, _event, **_kwargs):
  124. yield from self._auto_cleanup()
  125. @asyncio.coroutine
  126. def _auto_cleanup(self):
  127. '''Do auto cleanup if enabled'''
  128. if self.auto_cleanup and self in self.app.domains:
  129. del self.app.domains[self]
  130. yield from self.remove_from_disk()
  131. self.app.save()
  132. @classmethod
  133. @asyncio.coroutine
  134. def from_appvm(cls, appvm, **kwargs):
  135. '''Create a new instance from given AppVM
  136. :param qubes.vm.appvm.AppVM appvm: template from which the VM should \
  137. be created
  138. :returns: new disposable vm
  139. *kwargs* are passed to the newly created VM
  140. >>> import qubes.vm.dispvm.DispVM
  141. >>> dispvm = qubes.vm.dispvm.DispVM.from_appvm(appvm).start()
  142. >>> dispvm.run_service('qubes.VMShell', input='firefox')
  143. >>> dispvm.cleanup()
  144. This method modifies :file:`qubes.xml` file.
  145. The qube returned is not started.
  146. '''
  147. if not appvm.template_for_dispvms:
  148. raise qubes.exc.QubesException(
  149. 'Refusing to create DispVM out of this AppVM, because '
  150. 'template_for_dispvms=False')
  151. app = appvm.app
  152. dispvm = app.add_new_vm(
  153. cls,
  154. template=appvm,
  155. auto_cleanup=True,
  156. **kwargs)
  157. yield from dispvm.create_on_disk()
  158. app.save()
  159. return dispvm
  160. @asyncio.coroutine
  161. def cleanup(self):
  162. '''Clean up after the DispVM
  163. This stops the disposable qube and removes it from the store.
  164. This method modifies :file:`qubes.xml` file.
  165. '''
  166. try:
  167. # pylint: disable=not-an-iterable
  168. yield from self.kill()
  169. except qubes.exc.QubesVMNotStartedError:
  170. pass
  171. # if auto_cleanup is set, this will be done automatically
  172. if not self.auto_cleanup:
  173. del self.app.domains[self]
  174. yield from self.remove_from_disk()
  175. self.app.save()
  176. @asyncio.coroutine
  177. def start(self, **kwargs):
  178. # pylint: disable=arguments-differ
  179. try:
  180. # sanity check, if template_for_dispvm got changed in the meantime
  181. if not self.template.template_for_dispvms:
  182. raise qubes.exc.QubesException(
  183. 'template for DispVM ({}) needs to have '
  184. 'template_for_dispvms=True'.format(self.template.name))
  185. yield from super(DispVM, self).start(**kwargs)
  186. except:
  187. # Cleanup also on failed startup
  188. yield from self._auto_cleanup()
  189. raise
  190. def create_qdb_entries(self):
  191. super().create_qdb_entries()
  192. self.untrusted_qdb.write('/qubes-vm-persistence', 'none')