adminvm.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. @property
  82. def libvirt_domain(self):
  83. '''Libvirt object for dom0.
  84. .. seealso:
  85. :py:attr:`qubes.vm.qubesvm.QubesVM.libvirt_domain`
  86. '''
  87. if self._libvirt_domain is None:
  88. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByID(0)
  89. return self._libvirt_domain
  90. @staticmethod
  91. def is_running():
  92. '''Always :py:obj:`True`.
  93. .. seealso:
  94. :py:meth:`qubes.vm.qubesvm.QubesVM.is_running`
  95. '''
  96. return True
  97. @staticmethod
  98. def is_halted():
  99. '''Always :py:obj:`False`.
  100. .. seealso:
  101. :py:meth:`qubes.vm.qubesvm.QubesVM.is_halted`
  102. '''
  103. return False
  104. @staticmethod
  105. def get_power_state():
  106. '''Always ``'Running'``.
  107. .. seealso:
  108. :py:meth:`qubes.vm.qubesvm.QubesVM.get_power_state`
  109. '''
  110. return 'Running'
  111. @staticmethod
  112. def get_mem():
  113. '''Get current memory usage of Dom0.
  114. Unit is KiB.
  115. .. seealso:
  116. :py:meth:`qubes.vm.qubesvm.QubesVM.get_mem`
  117. '''
  118. # return psutil.virtual_memory().total/1024
  119. with open('/proc/meminfo') as file:
  120. for line in file:
  121. if line.startswith('MemTotal:'):
  122. return int(line.split(':')[1].strip().split()[0])
  123. raise NotImplementedError()
  124. def get_mem_static_max(self):
  125. '''Get maximum memory available to Dom0.
  126. .. seealso:
  127. :py:meth:`qubes.vm.qubesvm.QubesVM.get_mem_static_max`
  128. '''
  129. if self.app.vmm.offline_mode:
  130. # default value passed on xen cmdline
  131. return 4096
  132. try:
  133. return self.app.vmm.libvirt_conn.getInfo()[1]
  134. except libvirt.libvirtError as e:
  135. self.log.warning('Failed to get memory limit for dom0: %s', e)
  136. return 4096
  137. def get_cputime(self):
  138. '''Get total CPU time burned by Dom0 since start.
  139. .. seealso:
  140. :py:meth:`qubes.vm.qubesvm.QubesVM.get_cputime`
  141. '''
  142. try:
  143. return self.libvirt_domain.info()[4]
  144. except libvirt.libvirtError as e:
  145. self.log.warning('Failed to get CPU time for dom0: %s', e)
  146. return 0
  147. def verify_files(self):
  148. '''Always :py:obj:`True`
  149. .. seealso:
  150. :py:meth:`qubes.vm.qubesvm.QubesVM.verify_files`
  151. ''' # pylint: disable=no-self-use
  152. return True
  153. def start(self, start_guid=True, notify_function=None,
  154. mem_required=None):
  155. '''Always raises an exception.
  156. .. seealso:
  157. :py:meth:`qubes.vm.qubesvm.QubesVM.start`
  158. ''' # pylint: disable=unused-argument,arguments-differ
  159. raise qubes.exc.QubesVMNotHaltedError(
  160. self, 'Cannot start Dom0 fake domain!')
  161. def suspend(self):
  162. '''Does nothing.
  163. .. seealso:
  164. :py:meth:`qubes.vm.qubesvm.QubesVM.suspend`
  165. '''
  166. raise qubes.exc.QubesVMError(self, 'Cannot suspend Dom0 fake domain!')
  167. def shutdown(self):
  168. '''Does nothing.
  169. .. seealso:
  170. :py:meth:`qubes.vm.qubesvm.QubesVM.shutdown`
  171. '''
  172. raise qubes.exc.QubesVMError(self, 'Cannot shutdown Dom0 fake domain!')
  173. def kill(self):
  174. '''Does nothing.
  175. .. seealso:
  176. :py:meth:`qubes.vm.qubesvm.QubesVM.kill`
  177. '''
  178. raise qubes.exc.QubesVMError(self, 'Cannot kill Dom0 fake domain!')
  179. @property
  180. def untrusted_qdb(self):
  181. '''QubesDB handle for this domain.'''
  182. if self._qdb_connection is None:
  183. import qubesdb # pylint: disable=import-error
  184. self._qdb_connection = qubesdb.QubesDB(self.name)
  185. return self._qdb_connection
  186. @asyncio.coroutine
  187. def run_service(self, service, source=None, user=None,
  188. filter_esc=False, autostart=False, gui=False, **kwargs):
  189. '''Run service on this VM
  190. :param str service: service name
  191. :param qubes.vm.qubesvm.QubesVM source: source domain as presented to
  192. this VM
  193. :param str user: username to run service as
  194. :param bool filter_esc: filter escape sequences to protect terminal \
  195. emulator
  196. :param bool autostart: if :py:obj:`True`, machine will be started if \
  197. it is not running
  198. :param bool gui: when autostarting, also start gui daemon
  199. :rtype: asyncio.subprocess.Process
  200. .. note::
  201. User ``root`` is redefined to ``SYSTEM`` in the Windows agent code
  202. '''
  203. # pylint: disable=unused-argument
  204. source = 'dom0' if source is None else self.app.domains[source].name
  205. if filter_esc:
  206. raise NotImplementedError(
  207. 'filter_esc=True not supported on calls to dom0')
  208. if user is None:
  209. user = 'root'
  210. yield from self.fire_event_async('domain-cmd-pre-run', pre_event=True,
  211. start_guid=gui)
  212. if user != 'root':
  213. cmd = ['runuser', '-u', user, '--']
  214. else:
  215. cmd = []
  216. cmd.extend([
  217. qubes.config.system_path['qrexec_rpc_multiplexer'],
  218. service,
  219. source,
  220. 'name',
  221. self.name,
  222. ])
  223. return (yield from asyncio.create_subprocess_exec(
  224. *cmd,
  225. **kwargs))
  226. @asyncio.coroutine
  227. def run_service_for_stdio(self, *args, input=None, **kwargs):
  228. '''Run a service, pass an optional input and return (stdout, stderr).
  229. Raises an exception if return code != 0.
  230. *args* and *kwargs* are passed verbatim to :py:meth:`run_service`.
  231. .. warning::
  232. There are some combinations if stdio-related *kwargs*, which are
  233. not filtered for problems originating between the keyboard and the
  234. chair.
  235. ''' # pylint: disable=redefined-builtin
  236. kwargs.setdefault('stdin', subprocess.PIPE)
  237. kwargs.setdefault('stdout', subprocess.PIPE)
  238. kwargs.setdefault('stderr', subprocess.PIPE)
  239. p = yield from self.run_service(*args, **kwargs)
  240. # this one is actually a tuple, but there is no need to unpack it
  241. stdouterr = yield from p.communicate(input=input)
  242. if p.returncode:
  243. raise subprocess.CalledProcessError(p.returncode,
  244. args[0], *stdouterr)
  245. return stdouterr