adminvm.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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.QubesVMError(self, 'Cannot start Dom0 fake domain!')
  160. def suspend(self):
  161. '''Does nothing.
  162. .. seealso:
  163. :py:meth:`qubes.vm.qubesvm.QubesVM.suspend`
  164. '''
  165. raise qubes.exc.QubesVMError(self, 'Cannot suspend Dom0 fake domain!')
  166. def shutdown(self):
  167. '''Does nothing.
  168. .. seealso:
  169. :py:meth:`qubes.vm.qubesvm.QubesVM.shutdown`
  170. '''
  171. raise qubes.exc.QubesVMError(self, 'Cannot shutdown Dom0 fake domain!')
  172. def kill(self):
  173. '''Does nothing.
  174. .. seealso:
  175. :py:meth:`qubes.vm.qubesvm.QubesVM.kill`
  176. '''
  177. raise qubes.exc.QubesVMError(self, 'Cannot kill Dom0 fake domain!')
  178. @property
  179. def icon_path(self):
  180. pass
  181. @property
  182. def untrusted_qdb(self):
  183. '''QubesDB handle for this domain.'''
  184. if self._qdb_connection is None:
  185. import qubesdb # pylint: disable=import-error
  186. self._qdb_connection = qubesdb.QubesDB(self.name)
  187. return self._qdb_connection
  188. @asyncio.coroutine
  189. def run_service(self, service, source=None, user=None,
  190. filter_esc=False, autostart=False, gui=False, **kwargs):
  191. '''Run service on this VM
  192. :param str service: service name
  193. :param qubes.vm.qubesvm.QubesVM source: source domain as presented to
  194. this VM
  195. :param str user: username to run service as
  196. :param bool filter_esc: filter escape sequences to protect terminal \
  197. emulator
  198. :param bool autostart: if :py:obj:`True`, machine will be started if \
  199. it is not running
  200. :param bool gui: when autostarting, also start gui daemon
  201. :rtype: asyncio.subprocess.Process
  202. .. note::
  203. User ``root`` is redefined to ``SYSTEM`` in the Windows agent code
  204. '''
  205. # pylint: disable=unused-argument
  206. source = 'dom0' if source is None else self.app.domains[source].name
  207. if filter_esc:
  208. raise NotImplementedError(
  209. 'filter_esc=True not supported on calls to dom0')
  210. if user is None:
  211. user = 'root'
  212. yield from self.fire_event_async('domain-cmd-pre-run', pre_event=True,
  213. start_guid=gui)
  214. if user != 'root':
  215. cmd = ['runuser', '-u', user, '--']
  216. else:
  217. cmd = []
  218. cmd.extend([
  219. qubes.config.system_path['qrexec_rpc_multiplexer'],
  220. service,
  221. source,
  222. 'name',
  223. self.name,
  224. ])
  225. return (yield from asyncio.create_subprocess_exec(
  226. *cmd,
  227. **kwargs))
  228. @asyncio.coroutine
  229. def run_service_for_stdio(self, *args, input=None, **kwargs):
  230. '''Run a service, pass an optional input and return (stdout, stderr).
  231. Raises an exception if return code != 0.
  232. *args* and *kwargs* are passed verbatim to :py:meth:`run_service`.
  233. .. warning::
  234. There are some combinations if stdio-related *kwargs*, which are
  235. not filtered for problems originating between the keyboard and the
  236. chair.
  237. ''' # pylint: disable=redefined-builtin
  238. kwargs.setdefault('stdin', subprocess.PIPE)
  239. kwargs.setdefault('stdout', subprocess.PIPE)
  240. kwargs.setdefault('stderr', subprocess.PIPE)
  241. p = yield from self.run_service(*args, **kwargs)
  242. # this one is actually a tuple, but there is no need to unpack it
  243. stdouterr = yield from p.communicate(input=input)
  244. if p.returncode:
  245. raise subprocess.CalledProcessError(p.returncode,
  246. args[0], *stdouterr)
  247. return stdouterr