mgmt.py 17 KB

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