adminvm.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2013-2015 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2.1 of the License, or (at your option) any later version.
  13. #
  14. # This library is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. # Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  21. #
  22. ''' This module contains the AdminVM implementation '''
  23. import asyncio
  24. import subprocess
  25. import libvirt
  26. import qubes
  27. import qubes.exc
  28. import qubes.vm
  29. class AdminVM(qubes.vm.BaseVM):
  30. '''Dom0'''
  31. dir_path = None
  32. name = qubes.property('name',
  33. default='dom0', setter=qubes.property.forbidden)
  34. qid = qubes.property('qid',
  35. default=0, type=int, setter=qubes.property.forbidden)
  36. uuid = qubes.property('uuid',
  37. default='00000000-0000-0000-0000-000000000000',
  38. setter=qubes.property.forbidden)
  39. default_dispvm = qubes.VMProperty('default_dispvm',
  40. load_stage=4,
  41. allow_none=True,
  42. default=(lambda self: self.app.default_dispvm),
  43. doc='Default VM to be used as Disposable VM for service calls.')
  44. include_in_backups = qubes.property('include_in_backups',
  45. default=True, type=bool,
  46. doc='If this domain is to be included in default backup.')
  47. updateable = qubes.property('updateable',
  48. default=True,
  49. type=bool,
  50. setter=qubes.property.forbidden,
  51. doc='True if this machine may be updated on its own.')
  52. def __init__(self, *args, **kwargs):
  53. super().__init__(*args, **kwargs)
  54. self._qdb_connection = None
  55. self._libvirt_domain = None
  56. if not self.app.vmm.offline_mode:
  57. self.start_qdb_watch()
  58. def __str__(self):
  59. return self.name
  60. def __lt__(self, other):
  61. # order dom0 before anything
  62. return self.name != other.name
  63. @property
  64. def attached_volumes(self):
  65. return []
  66. @property
  67. def xid(self):
  68. '''Always ``0``.
  69. .. seealso:
  70. :py:attr:`qubes.vm.qubesvm.QubesVM.xid`
  71. '''
  72. return 0
  73. @property
  74. def libvirt_domain(self):
  75. '''Libvirt object for dom0.
  76. .. seealso:
  77. :py:attr:`qubes.vm.qubesvm.QubesVM.libvirt_domain`
  78. '''
  79. if self._libvirt_domain is None:
  80. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByID(0)
  81. return self._libvirt_domain
  82. @staticmethod
  83. def is_running():
  84. '''Always :py:obj:`True`.
  85. .. seealso:
  86. :py:meth:`qubes.vm.qubesvm.QubesVM.is_running`
  87. '''
  88. return True
  89. @staticmethod
  90. def is_halted():
  91. '''Always :py:obj:`False`.
  92. .. seealso:
  93. :py:meth:`qubes.vm.qubesvm.QubesVM.is_halted`
  94. '''
  95. return False
  96. @staticmethod
  97. def get_power_state():
  98. '''Always ``'Running'``.
  99. .. seealso:
  100. :py:meth:`qubes.vm.qubesvm.QubesVM.get_power_state`
  101. '''
  102. return 'Running'
  103. @staticmethod
  104. def get_mem():
  105. '''Get current memory usage of Dom0.
  106. Unit is KiB.
  107. .. seealso:
  108. :py:meth:`qubes.vm.qubesvm.QubesVM.get_mem`
  109. '''
  110. # return psutil.virtual_memory().total/1024
  111. with open('/proc/meminfo') as file:
  112. for line in file:
  113. if line.startswith('MemTotal:'):
  114. return int(line.split(':')[1].strip().split()[0])
  115. raise NotImplementedError()
  116. def get_mem_static_max(self):
  117. '''Get maximum memory available to Dom0.
  118. .. seealso:
  119. :py:meth:`qubes.vm.qubesvm.QubesVM.get_mem_static_max`
  120. '''
  121. if self.app.vmm.offline_mode:
  122. # default value passed on xen cmdline
  123. return 4096
  124. try:
  125. return self.app.vmm.libvirt_conn.getInfo()[1]
  126. except libvirt.libvirtError as e:
  127. self.log.warning('Failed to get memory limit for dom0: %s', e)
  128. return 4096
  129. def get_cputime(self):
  130. '''Get total CPU time burned by Dom0 since start.
  131. .. seealso:
  132. :py:meth:`qubes.vm.qubesvm.QubesVM.get_cputime`
  133. '''
  134. try:
  135. return self.libvirt_domain.info()[4]
  136. except libvirt.libvirtError as e:
  137. self.log.warning('Failed to get CPU time for dom0: %s', e)
  138. return 0
  139. def verify_files(self):
  140. '''Always :py:obj:`True`
  141. .. seealso:
  142. :py:meth:`qubes.vm.qubesvm.QubesVM.verify_files`
  143. ''' # pylint: disable=no-self-use
  144. return True
  145. def start(self, start_guid=True, notify_function=None,
  146. mem_required=None):
  147. '''Always raises an exception.
  148. .. seealso:
  149. :py:meth:`qubes.vm.qubesvm.QubesVM.start`
  150. ''' # pylint: disable=unused-argument,arguments-differ
  151. raise qubes.exc.QubesVMError(self, 'Cannot start Dom0 fake domain!')
  152. def suspend(self):
  153. '''Does nothing.
  154. .. seealso:
  155. :py:meth:`qubes.vm.qubesvm.QubesVM.suspend`
  156. '''
  157. raise qubes.exc.QubesVMError(self, 'Cannot suspend Dom0 fake domain!')
  158. def shutdown(self):
  159. '''Does nothing.
  160. .. seealso:
  161. :py:meth:`qubes.vm.qubesvm.QubesVM.shutdown`
  162. '''
  163. raise qubes.exc.QubesVMError(self, 'Cannot shutdown Dom0 fake domain!')
  164. def kill(self):
  165. '''Does nothing.
  166. .. seealso:
  167. :py:meth:`qubes.vm.qubesvm.QubesVM.kill`
  168. '''
  169. raise qubes.exc.QubesVMError(self, 'Cannot kill Dom0 fake domain!')
  170. @property
  171. def icon_path(self):
  172. pass
  173. @property
  174. def untrusted_qdb(self):
  175. '''QubesDB handle for this domain.'''
  176. if self._qdb_connection is None:
  177. import qubesdb # pylint: disable=import-error
  178. self._qdb_connection = qubesdb.QubesDB(self.name)
  179. return self._qdb_connection
  180. @asyncio.coroutine
  181. def run_service(self, service, source=None, user=None,
  182. filter_esc=False, autostart=False, gui=False, **kwargs):
  183. '''Run service on this VM
  184. :param str service: service name
  185. :param qubes.vm.qubesvm.QubesVM source: source domain as presented to
  186. this VM
  187. :param str user: username to run service as
  188. :param bool filter_esc: filter escape sequences to protect terminal \
  189. emulator
  190. :param bool autostart: if :py:obj:`True`, machine will be started if \
  191. it is not running
  192. :param bool gui: when autostarting, also start gui daemon
  193. :rtype: asyncio.subprocess.Process
  194. .. note::
  195. User ``root`` is redefined to ``SYSTEM`` in the Windows agent code
  196. '''
  197. # pylint: disable=unused-argument
  198. source = 'dom0' if source is None else self.app.domains[source].name
  199. if filter_esc:
  200. raise NotImplementedError(
  201. 'filter_esc=True not supported on calls to dom0')
  202. if user is None:
  203. user = 'root'
  204. yield from self.fire_event_async('domain-cmd-pre-run', pre_event=True,
  205. start_guid=gui)
  206. if user != 'root':
  207. cmd = ['runuser', '-u', user, '--']
  208. else:
  209. cmd = []
  210. cmd.extend([
  211. qubes.config.system_path['qrexec_rpc_multiplexer'],
  212. service,
  213. source,
  214. 'name',
  215. self.name,
  216. ])
  217. return (yield from asyncio.create_subprocess_exec(
  218. *cmd,
  219. **kwargs))
  220. @asyncio.coroutine
  221. def run_service_for_stdio(self, *args, input=None, **kwargs):
  222. '''Run a service, pass an optional input and return (stdout, stderr).
  223. Raises an exception if return code != 0.
  224. *args* and *kwargs* are passed verbatim to :py:meth:`run_service`.
  225. .. warning::
  226. There are some combinations if stdio-related *kwargs*, which are
  227. not filtered for problems originating between the keyboard and the
  228. chair.
  229. ''' # pylint: disable=redefined-builtin
  230. kwargs.setdefault('stdin', subprocess.PIPE)
  231. kwargs.setdefault('stdout', subprocess.PIPE)
  232. kwargs.setdefault('stderr', subprocess.PIPE)
  233. p = yield from self.run_service(*args, **kwargs)
  234. # this one is actually a tuple, but there is no need to unpack it
  235. stdouterr = yield from p.communicate(input=input)
  236. if p.returncode:
  237. raise subprocess.CalledProcessError(p.returncode,
  238. args[0], *stdouterr)
  239. return stdouterr