adminvm.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. from qubes.vm.qubesvm import _setter_kbd_layout
  30. class AdminVM(qubes.vm.BaseVM):
  31. '''Dom0'''
  32. dir_path = None
  33. name = qubes.property('name',
  34. default='dom0', setter=qubes.property.forbidden)
  35. qid = qubes.property('qid',
  36. default=0, type=int, setter=qubes.property.forbidden)
  37. uuid = qubes.property('uuid',
  38. default='00000000-0000-0000-0000-000000000000',
  39. setter=qubes.property.forbidden)
  40. default_dispvm = qubes.VMProperty('default_dispvm',
  41. load_stage=4,
  42. allow_none=True,
  43. default=(lambda self: self.app.default_dispvm),
  44. doc='Default VM to be used as Disposable VM for service calls.')
  45. include_in_backups = qubes.property('include_in_backups',
  46. default=True, type=bool,
  47. doc='If this domain is to be included in default backup.')
  48. updateable = qubes.property('updateable',
  49. default=True,
  50. type=bool,
  51. setter=qubes.property.forbidden,
  52. doc='True if this machine may be updated on its own.')
  53. # for changes in keyboard_layout, see also the same property in QubesVM
  54. keyboard_layout = qubes.property(
  55. 'keyboard_layout',
  56. type=str,
  57. setter=_setter_kbd_layout,
  58. default='us++',
  59. doc='Keyboard layout for this VM')
  60. def __init__(self, *args, **kwargs):
  61. super().__init__(*args, **kwargs)
  62. self._qdb_connection = None
  63. self._libvirt_domain = None
  64. if not self.app.vmm.offline_mode:
  65. self.start_qdb_watch()
  66. def __str__(self):
  67. return self.name
  68. def __lt__(self, other):
  69. # order dom0 before anything
  70. return self.name != other.name
  71. @property
  72. def attached_volumes(self):
  73. return []
  74. @property
  75. def xid(self):
  76. '''Always ``0``.
  77. .. seealso:
  78. :py:attr:`qubes.vm.qubesvm.QubesVM.xid`
  79. '''
  80. return 0
  81. @qubes.stateless_property
  82. def icon(self): # pylint: disable=no-self-use
  83. """freedesktop icon name, suitable for use in
  84. :py:meth:`PyQt4.QtGui.QIcon.fromTheme`"""
  85. return 'adminvm-black'
  86. @property
  87. def libvirt_domain(self):
  88. '''Libvirt object for dom0.
  89. .. seealso:
  90. :py:attr:`qubes.vm.qubesvm.QubesVM.libvirt_domain`
  91. '''
  92. if self._libvirt_domain is None:
  93. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByID(0)
  94. return self._libvirt_domain
  95. @staticmethod
  96. def is_running():
  97. '''Always :py:obj:`True`.
  98. .. seealso:
  99. :py:meth:`qubes.vm.qubesvm.QubesVM.is_running`
  100. '''
  101. return True
  102. @staticmethod
  103. def is_halted():
  104. '''Always :py:obj:`False`.
  105. .. seealso:
  106. :py:meth:`qubes.vm.qubesvm.QubesVM.is_halted`
  107. '''
  108. return False
  109. @staticmethod
  110. def get_power_state():
  111. '''Always ``'Running'``.
  112. .. seealso:
  113. :py:meth:`qubes.vm.qubesvm.QubesVM.get_power_state`
  114. '''
  115. return 'Running'
  116. @staticmethod
  117. def get_mem():
  118. '''Get current memory usage of Dom0.
  119. Unit is KiB.
  120. .. seealso:
  121. :py:meth:`qubes.vm.qubesvm.QubesVM.get_mem`
  122. '''
  123. # return psutil.virtual_memory().total/1024
  124. with open('/proc/meminfo') as file:
  125. for line in file:
  126. if line.startswith('MemTotal:'):
  127. return int(line.split(':')[1].strip().split()[0])
  128. raise NotImplementedError()
  129. def get_mem_static_max(self):
  130. '''Get maximum memory available to Dom0.
  131. .. seealso:
  132. :py:meth:`qubes.vm.qubesvm.QubesVM.get_mem_static_max`
  133. '''
  134. if self.app.vmm.offline_mode:
  135. # default value passed on xen cmdline
  136. return 4096
  137. try:
  138. return self.app.vmm.libvirt_conn.getInfo()[1]
  139. except libvirt.libvirtError as e:
  140. self.log.warning('Failed to get memory limit for dom0: %s', e)
  141. return 4096
  142. def get_cputime(self):
  143. '''Get total CPU time burned by Dom0 since start.
  144. .. seealso:
  145. :py:meth:`qubes.vm.qubesvm.QubesVM.get_cputime`
  146. '''
  147. try:
  148. return self.libvirt_domain.info()[4]
  149. except libvirt.libvirtError as e:
  150. self.log.warning('Failed to get CPU time for dom0: %s', e)
  151. return 0
  152. def verify_files(self):
  153. '''Always :py:obj:`True`
  154. .. seealso:
  155. :py:meth:`qubes.vm.qubesvm.QubesVM.verify_files`
  156. ''' # pylint: disable=no-self-use
  157. return True
  158. def start(self, start_guid=True, notify_function=None,
  159. mem_required=None):
  160. '''Always raises an exception.
  161. .. seealso:
  162. :py:meth:`qubes.vm.qubesvm.QubesVM.start`
  163. ''' # pylint: disable=unused-argument,arguments-differ
  164. raise qubes.exc.QubesVMNotHaltedError(
  165. self, 'Cannot start Dom0 fake domain!')
  166. def suspend(self):
  167. '''Does nothing.
  168. .. seealso:
  169. :py:meth:`qubes.vm.qubesvm.QubesVM.suspend`
  170. '''
  171. raise qubes.exc.QubesVMError(self, 'Cannot suspend Dom0 fake domain!')
  172. def shutdown(self):
  173. '''Does nothing.
  174. .. seealso:
  175. :py:meth:`qubes.vm.qubesvm.QubesVM.shutdown`
  176. '''
  177. raise qubes.exc.QubesVMError(self, 'Cannot shutdown Dom0 fake domain!')
  178. def kill(self):
  179. '''Does nothing.
  180. .. seealso:
  181. :py:meth:`qubes.vm.qubesvm.QubesVM.kill`
  182. '''
  183. raise qubes.exc.QubesVMError(self, 'Cannot kill Dom0 fake domain!')
  184. @property
  185. def untrusted_qdb(self):
  186. '''QubesDB handle for this domain.'''
  187. if self._qdb_connection is None:
  188. import qubesdb # pylint: disable=import-error
  189. self._qdb_connection = qubesdb.QubesDB(self.name)
  190. return self._qdb_connection
  191. async def run_service(self, service, source=None, user=None,
  192. filter_esc=False, autostart=False, gui=False, **kwargs):
  193. '''Run service on this VM
  194. :param str service: service name
  195. :param qubes.vm.qubesvm.QubesVM source: source domain as presented to
  196. this VM
  197. :param str user: username to run service as
  198. :param bool filter_esc: filter escape sequences to protect terminal \
  199. emulator
  200. :param bool autostart: if :py:obj:`True`, machine will be started if \
  201. it is not running
  202. :param bool gui: when autostarting, also start gui daemon
  203. :rtype: asyncio.subprocess.Process
  204. .. note::
  205. User ``root`` is redefined to ``SYSTEM`` in the Windows agent code
  206. '''
  207. # pylint: disable=unused-argument
  208. source = 'dom0' if source is None else self.app.domains[source].name
  209. if filter_esc:
  210. raise NotImplementedError(
  211. 'filter_esc=True not supported on calls to dom0')
  212. if user is None:
  213. user = 'root'
  214. await self.fire_event_async('domain-cmd-pre-run', pre_event=True,
  215. start_guid=gui)
  216. if user != 'root':
  217. cmd = ['runuser', '-u', user, '--']
  218. else:
  219. cmd = []
  220. cmd.extend([
  221. qubes.config.system_path['qrexec_rpc_multiplexer'],
  222. service,
  223. source,
  224. 'name',
  225. self.name,
  226. ])
  227. return await asyncio.create_subprocess_exec(*cmd, **kwargs)
  228. async def run_service_for_stdio(self, *args, input=None, **kwargs):
  229. '''Run a service, pass an optional input and return (stdout, stderr).
  230. Raises an exception if return code != 0.
  231. *args* and *kwargs* are passed verbatim to :py:meth:`run_service`.
  232. .. warning::
  233. There are some combinations if stdio-related *kwargs*, which are
  234. not filtered for problems originating between the keyboard and the
  235. chair.
  236. ''' # pylint: disable=redefined-builtin
  237. kwargs.setdefault('stdin', subprocess.PIPE)
  238. kwargs.setdefault('stdout', subprocess.PIPE)
  239. kwargs.setdefault('stderr', subprocess.PIPE)
  240. p = await self.run_service(*args, **kwargs)
  241. # this one is actually a tuple, but there is no need to unpack it
  242. stdouterr = await p.communicate(input=input)
  243. if p.returncode:
  244. raise subprocess.CalledProcessError(p.returncode,
  245. args[0], *stdouterr)
  246. return stdouterr