dispvm.py 8.9 KB

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