dispvm.py 8.7 KB

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