adminvm.py 9.1 KB

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