internal.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. # -*- encoding: utf-8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This library is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU Lesser General Public
  10. # License as published by the Free Software Foundation; either
  11. # version 2.1 of the License, or (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. # Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public
  19. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  20. ''' Internal interface for dom0 components to communicate with qubesd. '''
  21. import asyncio
  22. import json
  23. import subprocess
  24. import qubes.api
  25. import qubes.api.admin
  26. import qubes.vm.adminvm
  27. import qubes.vm.dispvm
  28. def get_system_info(app):
  29. system_info = {'domains': {
  30. domain.name: {
  31. 'tags': list(domain.tags),
  32. 'type': domain.__class__.__name__,
  33. 'template_for_dispvms':
  34. getattr(domain, 'template_for_dispvms', False),
  35. 'default_dispvm': (domain.default_dispvm.name if
  36. getattr(domain, 'default_dispvm', None) else None),
  37. 'icon': str(domain.label.icon),
  38. 'guivm': (domain.guivm.name if getattr(domain, 'guivm', None)
  39. else None),
  40. } for domain in app.domains
  41. }}
  42. return system_info
  43. class QubesInternalAPI(qubes.api.AbstractQubesAPI):
  44. ''' Communication interface for dom0 components,
  45. by design the input here is trusted.'''
  46. SOCKNAME = '/var/run/qubesd.internal.sock'
  47. @qubes.api.method('internal.GetSystemInfo', no_payload=True)
  48. @asyncio.coroutine
  49. def getsysteminfo(self):
  50. self.enforce(self.dest.name == 'dom0')
  51. self.enforce(not self.arg)
  52. system_info = get_system_info(self.app)
  53. return json.dumps(system_info)
  54. @qubes.api.method('internal.vm.volume.ImportBegin',
  55. scope='local', write=True)
  56. @asyncio.coroutine
  57. def vm_volume_import(self, untrusted_payload):
  58. """Begin importing volume data. Payload is either size of new data
  59. in bytes, or empty. If empty, the current volume's size will be used.
  60. Returns size and path to where data should be written.
  61. Triggered by scripts in /etc/qubes-rpc:
  62. admin.vm.volume.Import, admin.vm.volume.ImportWithSize.
  63. When the script finish importing, it will trigger
  64. internal.vm.volume.ImportEnd (with either b'ok' or b'fail' as a
  65. payload) and response from that call will be actually send to the
  66. caller.
  67. """
  68. self.enforce(self.arg in self.dest.volumes.keys())
  69. if untrusted_payload:
  70. original_method = 'admin.vm.volume.ImportWithSize'
  71. else:
  72. original_method = 'admin.vm.volume.Import'
  73. self.src.fire_event(
  74. 'admin-permission:' + original_method,
  75. pre_event=True, dest=self.dest, arg=self.arg)
  76. if not self.dest.is_halted():
  77. raise qubes.exc.QubesVMNotHaltedError(self.dest)
  78. requested_size = None
  79. if untrusted_payload:
  80. try:
  81. untrusted_value = int(untrusted_payload.decode('ascii'))
  82. except (UnicodeDecodeError, ValueError):
  83. raise qubes.api.ProtocolError('Invalid value')
  84. self.enforce(untrusted_value > 0)
  85. requested_size = untrusted_value
  86. del untrusted_value
  87. del untrusted_payload
  88. path = yield from self.dest.storage.import_data(
  89. self.arg, requested_size)
  90. self.enforce(' ' not in path)
  91. if requested_size is None:
  92. size = self.dest.volumes[self.arg].size
  93. else:
  94. size = requested_size
  95. # when we know the action is allowed, inform extensions that it will
  96. # be performed
  97. self.dest.fire_event(
  98. 'domain-volume-import-begin', volume=self.arg, size=size)
  99. return '{} {}'.format(size, path)
  100. @qubes.api.method('internal.vm.volume.ImportEnd')
  101. @asyncio.coroutine
  102. def vm_volume_import_end(self, untrusted_payload):
  103. '''
  104. This is second half of admin.vm.volume.Import handling. It is called
  105. when actual import is finished. Response from this method is sent do
  106. the client (as a response for admin.vm.volume.Import call).
  107. The payload is either 'ok', or 'fail\n<error message>'.
  108. '''
  109. self.enforce(self.arg in self.dest.volumes.keys())
  110. success = untrusted_payload == b'ok'
  111. try:
  112. yield from self.dest.storage.import_data_end(self.arg,
  113. success=success)
  114. except:
  115. self.dest.fire_event('domain-volume-import-end', volume=self.arg,
  116. success=False)
  117. raise
  118. self.dest.fire_event('domain-volume-import-end', volume=self.arg,
  119. success=success)
  120. if not success:
  121. error = ''
  122. parts = untrusted_payload.decode('ascii').split('\n', 1)
  123. if len(parts) > 1:
  124. error = parts[1]
  125. raise qubes.exc.QubesException(
  126. 'Data import failed: {}'.format(error))
  127. @qubes.api.method('internal.SuspendPre', no_payload=True)
  128. @asyncio.coroutine
  129. def suspend_pre(self):
  130. '''
  131. Method called before host system goes to sleep.
  132. :return:
  133. '''
  134. # first notify all VMs
  135. processes = []
  136. for vm in self.app.domains:
  137. if isinstance(vm, qubes.vm.adminvm.AdminVM):
  138. continue
  139. if not vm.is_running():
  140. continue
  141. if not vm.features.check_with_template('qrexec', False):
  142. continue
  143. try:
  144. proc = yield from vm.run_service(
  145. 'qubes.SuspendPreAll', user='root',
  146. stdin=subprocess.DEVNULL,
  147. stdout=subprocess.DEVNULL,
  148. stderr=subprocess.DEVNULL)
  149. processes.append(proc)
  150. except qubes.exc.QubesException as e:
  151. vm.log.warning('Failed to run qubes.SuspendPreAll: %s', str(e))
  152. # FIXME: some timeout?
  153. if processes:
  154. yield from asyncio.wait([p.wait() for p in processes])
  155. coros = []
  156. # then suspend/pause VMs
  157. for vm in self.app.domains:
  158. if isinstance(vm, qubes.vm.adminvm.AdminVM):
  159. continue
  160. if vm.is_running():
  161. coros.append(vm.suspend())
  162. if coros:
  163. yield from asyncio.wait(coros)
  164. @qubes.api.method('internal.SuspendPost', no_payload=True)
  165. @asyncio.coroutine
  166. def suspend_post(self):
  167. '''
  168. Method called after host system wake up from sleep.
  169. :return:
  170. '''
  171. coros = []
  172. # first resume/unpause VMs
  173. for vm in self.app.domains:
  174. if isinstance(vm, qubes.vm.adminvm.AdminVM):
  175. continue
  176. if vm.get_power_state() in ["Paused", "Suspended"]:
  177. coros.append(vm.resume())
  178. if coros:
  179. yield from asyncio.wait(coros)
  180. # then notify all VMs
  181. processes = []
  182. for vm in self.app.domains:
  183. if isinstance(vm, qubes.vm.adminvm.AdminVM):
  184. continue
  185. if not vm.is_running():
  186. continue
  187. if not vm.features.check_with_template('qrexec', False):
  188. continue
  189. try:
  190. proc = yield from vm.run_service(
  191. 'qubes.SuspendPostAll', user='root',
  192. stdin=subprocess.DEVNULL,
  193. stdout=subprocess.DEVNULL,
  194. stderr=subprocess.DEVNULL)
  195. processes.append(proc)
  196. except qubes.exc.QubesException as e:
  197. vm.log.warning('Failed to run qubes.SuspendPostAll: %s', str(e))
  198. # FIXME: some timeout?
  199. if processes:
  200. yield from asyncio.wait([p.wait() for p in processes])