mgmt.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2017 Wojtek Porczyk <woju@invisiblethingslab.com>
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License along
  17. # with this program; if not, write to the Free Software Foundation, Inc.,
  18. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. #
  20. '''
  21. Qubes OS Management API
  22. '''
  23. import functools
  24. import string
  25. import pkg_resources
  26. import qubes.vm.qubesvm
  27. import qubes.storage
  28. class ProtocolError(AssertionError):
  29. '''Raised when something is wrong with data received'''
  30. pass
  31. class PermissionDenied(Exception):
  32. '''Raised deliberately by handlers when we decide not to cooperate'''
  33. pass
  34. def api(name, *, no_payload=False):
  35. '''Decorator factory for methods intended to appear in API.
  36. The decorated method can be called from public API using a child of
  37. :py:class:`AbstractQubesMgmt` class. The method becomes "public", and can be
  38. called using remote management interface.
  39. :param str name: qrexec rpc method name
  40. :param bool no_payload: if :py:obj:`True`, will barf on non-empty payload; \
  41. also will not pass payload at all to the method
  42. The expected function method should have one argument (other than usual
  43. *self*), ``untrusted_payload``, which will contain the payload.
  44. .. warning::
  45. This argument has to be named such, to remind the programmer that the
  46. content of this variable is indeed untrusted.
  47. If *no_payload* is true, then the method is called with no arguments.
  48. '''
  49. # TODO regexp for vm/dev classess; supply regexp groups as untrusted_ kwargs
  50. def decorator(func):
  51. if no_payload:
  52. # the following assignment is needed for how closures work in Python
  53. _func = func
  54. @functools.wraps(_func)
  55. def wrapper(self, untrusted_payload):
  56. if untrusted_payload != b'':
  57. raise ProtocolError('unexpected payload')
  58. return _func(self)
  59. func = wrapper
  60. func._rpcname = name # pylint: disable=protected-access
  61. return func
  62. return decorator
  63. class AbstractQubesMgmt(object):
  64. '''Common code for Qubes Management Protocol handling
  65. Different interfaces can expose different API call sets, however they share
  66. common protocol and common implementation framework. This class is the
  67. latter.
  68. To implement a new interface, inherit from this class and write at least one
  69. method and decorate it with :py:func:`api` decorator. It will have access to
  70. pre-defined attributes: :py:attr:`app`, :py:attr:`src`, :py:attr:`dest`,
  71. :py:attr:`arg` and :py:attr:`method`.
  72. There are also two helper functions for firing events associated with API
  73. calls.
  74. '''
  75. def __init__(self, app, src, method, dest, arg):
  76. #: :py:class:`qubes.Qubes` object
  77. self.app = app
  78. #: source qube
  79. self.src = self.app.domains[src.decode('ascii')]
  80. #: destination qube
  81. self.dest = self.app.domains[dest.decode('ascii')]
  82. #: argument
  83. self.arg = arg.decode('ascii')
  84. #: name of the method
  85. self.method = method.decode('ascii')
  86. untrusted_candidates = []
  87. for attr in dir(self):
  88. untrusted_func = getattr(self, attr)
  89. if not callable(untrusted_func):
  90. continue
  91. try:
  92. # pylint: disable=protected-access
  93. if untrusted_func._rpcname != self.method:
  94. continue
  95. except AttributeError:
  96. continue
  97. untrusted_candidates.append(untrusted_func)
  98. if not untrusted_candidates:
  99. raise ProtocolError('no such method: {!r}'.format(self.method))
  100. assert len(untrusted_candidates) == 1, \
  101. 'multiple candidates for method {!r}'.format(self.method)
  102. #: the method to execute
  103. self.execute = untrusted_candidates[0]
  104. del untrusted_candidates
  105. def fire_event_for_permission(self, **kwargs):
  106. '''Fire an event on the source qube to check for permission'''
  107. return self.src.fire_event_pre('mgmt-permission:{}'.format(self.method),
  108. dest=self.dest, arg=self.arg, **kwargs)
  109. def fire_event_for_filter(self, iterable, **kwargs):
  110. '''Fire an event on the source qube to filter for permission'''
  111. for selector in self.fire_event_for_permission(**kwargs):
  112. iterable = filter(selector, iterable)
  113. return iterable
  114. class QubesMgmt(AbstractQubesMgmt):
  115. '''Implementation of Qubes Management API calls
  116. This class contains all the methods available in the main API.
  117. .. seealso::
  118. https://www.qubes-os.org/doc/mgmt1/
  119. '''
  120. @api('mgmt.vm.List', no_payload=True)
  121. async def vm_list(self):
  122. '''List all the domains'''
  123. assert not self.arg
  124. if self.dest.name == 'dom0':
  125. domains = self.fire_event_for_filter(self.app.domains)
  126. else:
  127. domains = self.fire_event_for_filter([self.dest])
  128. return ''.join('{} class={} state={}\n'.format(
  129. vm.name,
  130. vm.__class__.__name__,
  131. vm.get_power_state())
  132. for vm in sorted(domains))
  133. @api('mgmt.vm.property.List', no_payload=True)
  134. async def vm_property_list(self):
  135. '''List all properties on a qube'''
  136. assert not self.arg
  137. properties = self.fire_event_for_filter(self.dest.property_list())
  138. return ''.join('{}\n'.format(prop.__name__) for prop in properties)
  139. @api('mgmt.vm.property.Get', no_payload=True)
  140. async def vm_property_get(self):
  141. '''Get a value of one property'''
  142. assert self.arg in self.dest.property_list()
  143. self.fire_event_for_permission()
  144. property_def = self.dest.property_get_def(self.arg)
  145. # explicit list to be sure that it matches protocol spec
  146. if isinstance(property_def, qubes.vm.VMProperty):
  147. property_type = 'vm'
  148. elif property_def.type is int:
  149. property_type = 'int'
  150. elif property_def.type is bool:
  151. property_type = 'bool'
  152. elif self.arg == 'label':
  153. property_type = 'label'
  154. else:
  155. property_type = 'str'
  156. try:
  157. value = getattr(self.dest, self.arg)
  158. except AttributeError:
  159. return 'default=True type={} '.format(property_type)
  160. else:
  161. return 'default={} type={} {}'.format(
  162. str(self.dest.property_is_default(self.arg)),
  163. property_type,
  164. str(value) if value is not None else '')
  165. @api('mgmt.vm.property.Set')
  166. async def vm_property_set(self, untrusted_payload):
  167. assert self.arg in self.dest.property_list()
  168. property_def = self.dest.property_get_def(self.arg)
  169. newvalue = property_def.sanitize(untrusted_newvalue=untrusted_payload)
  170. self.fire_event_for_permission(newvalue=newvalue)
  171. setattr(self.dest, self.arg, newvalue)
  172. self.app.save()
  173. @api('mgmt.vm.property.Help', no_payload=True)
  174. async def vm_property_help(self):
  175. '''Get help for one property'''
  176. assert self.arg in self.dest.property_list()
  177. self.fire_event_for_permission()
  178. try:
  179. doc = self.dest.property_get_def(self.arg).__doc__
  180. except AttributeError:
  181. return ''
  182. return qubes.utils.format_doc(doc)
  183. @api('mgmt.vm.property.Reset', no_payload=True)
  184. async def vm_property_reset(self):
  185. '''Reset a property to a default value'''
  186. assert self.arg in self.dest.property_list()
  187. self.fire_event_for_permission()
  188. delattr(self.dest, self.arg)
  189. self.app.save()
  190. @api('mgmt.vm.volume.List', no_payload=True)
  191. async def vm_volume_list(self):
  192. assert not self.arg
  193. volume_names = self.fire_event_for_filter(self.dest.volumes.keys())
  194. return ''.join('{}\n'.format(name) for name in volume_names)
  195. @api('mgmt.vm.volume.Info', no_payload=True)
  196. async def vm_volume_info(self):
  197. assert self.arg in self.dest.volumes.keys()
  198. self.fire_event_for_permission()
  199. volume = self.dest.volumes[self.arg]
  200. # properties defined in API
  201. volume_properties = [
  202. 'pool', 'vid', 'size', 'usage', 'rw', 'internal', 'source',
  203. 'save_on_stop', 'snap_on_start']
  204. return ''.join('{}={}\n'.format(key, getattr(volume, key)) for key in
  205. volume_properties)
  206. @api('mgmt.vm.volume.ListSnapshots', no_payload=True)
  207. async def vm_volume_listsnapshots(self):
  208. assert self.arg in self.dest.volumes.keys()
  209. volume = self.dest.volumes[self.arg]
  210. revisions = [revision for revision in volume.revisions]
  211. revisions = self.fire_event_for_filter(revisions)
  212. return ''.join('{}\n'.format(revision) for revision in revisions)
  213. @api('mgmt.vm.volume.Revert')
  214. async def vm_volume_revert(self, untrusted_payload):
  215. assert self.arg in self.dest.volumes.keys()
  216. untrusted_revision = untrusted_payload.decode('ascii').strip()
  217. del untrusted_payload
  218. volume = self.dest.volumes[self.arg]
  219. snapshots = volume.revisions
  220. assert untrusted_revision in snapshots
  221. revision = untrusted_revision
  222. self.fire_event_for_permission(revision=revision)
  223. self.dest.storage.get_pool(volume).revert(revision)
  224. self.app.save()
  225. @api('mgmt.vm.volume.Resize')
  226. async def vm_volume_resize(self, untrusted_payload):
  227. assert self.arg in self.dest.volumes.keys()
  228. untrusted_size = untrusted_payload.decode('ascii').strip()
  229. del untrusted_payload
  230. assert untrusted_size.isdigit() # only digits, forbid '-' too
  231. assert len(untrusted_size) <= 20 # limit to about 2^64
  232. size = int(untrusted_size)
  233. self.fire_event_for_permission(size=size)
  234. self.dest.storage.resize(self.arg, size)
  235. self.app.save()
  236. @api('mgmt.pool.List', no_payload=True)
  237. async def pool_list(self):
  238. assert not self.arg
  239. assert self.dest.name == 'dom0'
  240. pools = self.fire_event_for_filter(self.app.pools)
  241. return ''.join('{}\n'.format(pool) for pool in pools)
  242. @api('mgmt.pool.ListDrivers', no_payload=True)
  243. async def pool_listdrivers(self):
  244. assert self.dest.name == 'dom0'
  245. assert not self.arg
  246. drivers = self.fire_event_for_filter(qubes.storage.pool_drivers())
  247. return ''.join('{} {}\n'.format(
  248. driver,
  249. ' '.join(qubes.storage.driver_parameters(driver)))
  250. for driver in drivers)
  251. @api('mgmt.pool.Info', no_payload=True)
  252. async def pool_info(self):
  253. assert self.dest.name == 'dom0'
  254. assert self.arg in self.app.pools.keys()
  255. pool = self.app.pools[self.arg]
  256. self.fire_event_for_permission(pool=pool)
  257. return ''.join('{}={}\n'.format(prop, val)
  258. for prop, val in sorted(pool.config.items()))
  259. @api('mgmt.pool.Add')
  260. async def pool_add(self, untrusted_payload):
  261. assert self.dest.name == 'dom0'
  262. drivers = qubes.storage.pool_drivers()
  263. assert self.arg in drivers
  264. untrusted_pool_config = untrusted_payload.decode('ascii').splitlines()
  265. del untrusted_payload
  266. assert all(('=' in line) for line in untrusted_pool_config)
  267. # pairs of (option, value)
  268. untrusted_pool_config = [line.split('=', 1)
  269. for line in untrusted_pool_config]
  270. # reject duplicated options
  271. assert len(set(x[0] for x in untrusted_pool_config)) == \
  272. len([x[0] for x in untrusted_pool_config])
  273. # and convert to dict
  274. untrusted_pool_config = dict(untrusted_pool_config)
  275. assert 'name' in untrusted_pool_config
  276. untrusted_pool_name = untrusted_pool_config.pop('name')
  277. allowed_chars = string.ascii_letters + string.digits + '-_.'
  278. assert all(c in allowed_chars for c in untrusted_pool_name)
  279. pool_name = untrusted_pool_name
  280. assert pool_name not in self.app.pools
  281. driver_parameters = qubes.storage.driver_parameters(self.arg)
  282. assert all(key in driver_parameters for key in untrusted_pool_config)
  283. pool_config = untrusted_pool_config
  284. self.fire_event_for_permission(name=pool_name,
  285. pool_config=pool_config)
  286. self.app.add_pool(name=pool_name, driver=self.arg, **pool_config)
  287. self.app.save()
  288. @api('mgmt.pool.Remove', no_payload=True)
  289. async def pool_remove(self):
  290. assert self.dest.name == 'dom0'
  291. assert self.arg in self.app.pools.keys()
  292. self.fire_event_for_permission()
  293. self.app.remove_pool(self.arg)
  294. self.app.save()
  295. @api('mgmt.label.List', no_payload=True)
  296. async def label_list(self):
  297. assert self.dest.name == 'dom0'
  298. assert not self.arg
  299. labels = self.fire_event_for_filter(self.app.labels.values())
  300. return ''.join('{}\n'.format(label.name) for label in labels)
  301. @api('mgmt.label.Get', no_payload=True)
  302. async def label_get(self):
  303. assert self.dest.name == 'dom0'
  304. try:
  305. label = self.app.get_label(self.arg)
  306. except KeyError:
  307. raise qubes.exc.QubesValueError
  308. self.fire_event_for_permission(label=label)
  309. return label.color
  310. @api('mgmt.label.Create')
  311. async def label_create(self, untrusted_payload):
  312. assert self.dest.name == 'dom0'
  313. # don't confuse label name with label index
  314. assert not self.arg.isdigit()
  315. allowed_chars = string.ascii_letters + string.digits + '-_.'
  316. assert all(c in allowed_chars for c in self.arg)
  317. try:
  318. self.app.get_label(self.arg)
  319. except KeyError:
  320. # ok, no such label yet
  321. pass
  322. else:
  323. raise qubes.exc.QubesValueError('label already exists')
  324. untrusted_payload = untrusted_payload.decode('ascii').strip()
  325. assert len(untrusted_payload) == 8
  326. assert untrusted_payload.startswith('0x')
  327. # besides prefix, only hex digits are allowed
  328. assert all(x in string.hexdigits for x in untrusted_payload[2:])
  329. # SEE: #2732
  330. color = untrusted_payload
  331. self.fire_event_for_permission(color=color)
  332. # allocate new index, but make sure it's outside of default labels set
  333. new_index = max(
  334. qubes.config.max_default_label, *self.app.labels.keys()) + 1
  335. label = qubes.Label(new_index, color, self.arg)
  336. self.app.labels[new_index] = label
  337. self.app.save()
  338. @api('mgmt.label.Remove', no_payload=True)
  339. async def label_remove(self):
  340. assert self.dest.name == 'dom0'
  341. try:
  342. label = self.app.get_label(self.arg)
  343. except KeyError:
  344. raise qubes.exc.QubesValueError
  345. # don't allow removing default labels
  346. assert label.index > qubes.config.max_default_label
  347. # FIXME: this should be in app.add_label()
  348. for vm in self.app.domains:
  349. if vm.label == label:
  350. raise qubes.exc.QubesException('label still in use')
  351. self.fire_event_for_permission(label=label)
  352. del self.app.labels[label.index]
  353. self.app.save()