admin.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  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 string
  25. import itertools
  26. import pkg_resources
  27. import libvirt
  28. import qubes.api
  29. import qubes.devices
  30. import qubes.storage
  31. import qubes.utils
  32. import qubes.vm
  33. import qubes.vm.qubesvm
  34. class QubesMgmtEventsDispatcher(object):
  35. def __init__(self, filters, send_event):
  36. self.filters = filters
  37. self.send_event = send_event
  38. def vm_handler(self, subject, event, **kwargs):
  39. if event.startswith('mgmt-permission:'):
  40. return
  41. if not list(qubes.api.apply_filters([(subject, event, kwargs)],
  42. self.filters)):
  43. return
  44. self.send_event(subject, event, **kwargs)
  45. def app_handler(self, subject, event, **kwargs):
  46. if not list(qubes.api.apply_filters([(subject, event, kwargs)],
  47. self.filters)):
  48. return
  49. self.send_event(subject, event, **kwargs)
  50. def on_domain_add(self, subject, event, vm):
  51. # pylint: disable=unused-argument
  52. vm.add_handler('*', self.vm_handler)
  53. def on_domain_delete(self, subject, event, vm):
  54. # pylint: disable=unused-argument
  55. vm.remove_handler('*', self.vm_handler)
  56. class QubesAdminAPI(qubes.api.AbstractQubesAPI):
  57. '''Implementation of Qubes Management API calls
  58. This class contains all the methods available in the main API.
  59. .. seealso::
  60. https://www.qubes-os.org/doc/mgmt1/
  61. '''
  62. @qubes.api.method('admin.vmclass.List', no_payload=True)
  63. @asyncio.coroutine
  64. def vmclass_list(self):
  65. '''List all VM classes'''
  66. assert not self.arg
  67. assert self.dest.name == 'dom0'
  68. entrypoints = self.fire_event_for_filter(
  69. pkg_resources.iter_entry_points(qubes.vm.VM_ENTRY_POINT))
  70. return ''.join('{}\n'.format(ep.name)
  71. for ep in entrypoints)
  72. @qubes.api.method('admin.vm.List', no_payload=True)
  73. @asyncio.coroutine
  74. def vm_list(self):
  75. '''List all the domains'''
  76. assert not self.arg
  77. if self.dest.name == 'dom0':
  78. domains = self.fire_event_for_filter(self.app.domains)
  79. else:
  80. domains = self.fire_event_for_filter([self.dest])
  81. return ''.join('{} class={} state={}\n'.format(
  82. vm.name,
  83. vm.__class__.__name__,
  84. vm.get_power_state())
  85. for vm in sorted(domains))
  86. @qubes.api.method('admin.vm.property.List', no_payload=True)
  87. @asyncio.coroutine
  88. def vm_property_list(self):
  89. '''List all properties on a qube'''
  90. return self._property_list(self.dest)
  91. @qubes.api.method('admin.property.List', no_payload=True)
  92. @asyncio.coroutine
  93. def property_list(self):
  94. '''List all global properties'''
  95. assert self.dest.name == 'dom0'
  96. return self._property_list(self.app)
  97. def _property_list(self, dest):
  98. assert not self.arg
  99. properties = self.fire_event_for_filter(dest.property_list())
  100. return ''.join('{}\n'.format(prop.__name__) for prop in properties)
  101. @qubes.api.method('admin.vm.property.Get', no_payload=True)
  102. @asyncio.coroutine
  103. def vm_property_get(self):
  104. '''Get a value of one property'''
  105. return self._property_get(self.dest)
  106. @qubes.api.method('admin.property.Get', no_payload=True)
  107. @asyncio.coroutine
  108. def property_get(self):
  109. '''Get a value of one global property'''
  110. assert self.dest.name == 'dom0'
  111. return self._property_get(self.app)
  112. def _property_get(self, dest):
  113. if self.arg not in dest.property_list():
  114. raise qubes.exc.QubesNoSuchPropertyError(dest, self.arg)
  115. self.fire_event_for_permission()
  116. property_def = dest.property_get_def(self.arg)
  117. # explicit list to be sure that it matches protocol spec
  118. if isinstance(property_def, qubes.vm.VMProperty):
  119. property_type = 'vm'
  120. elif property_def.type is int:
  121. property_type = 'int'
  122. elif property_def.type is bool:
  123. property_type = 'bool'
  124. elif self.arg == 'label':
  125. property_type = 'label'
  126. else:
  127. property_type = 'str'
  128. try:
  129. value = getattr(dest, self.arg)
  130. except AttributeError:
  131. return 'default=True type={} '.format(property_type)
  132. else:
  133. return 'default={} type={} {}'.format(
  134. str(dest.property_is_default(self.arg)),
  135. property_type,
  136. str(value) if value is not None else '')
  137. @qubes.api.method('admin.vm.property.Set')
  138. @asyncio.coroutine
  139. def vm_property_set(self, untrusted_payload):
  140. '''Set property value'''
  141. return self._property_set(self.dest,
  142. untrusted_payload=untrusted_payload)
  143. @qubes.api.method('admin.property.Set')
  144. @asyncio.coroutine
  145. def property_set(self, untrusted_payload):
  146. '''Set property value'''
  147. assert self.dest.name == 'dom0'
  148. return self._property_set(self.app,
  149. untrusted_payload=untrusted_payload)
  150. def _property_set(self, dest, untrusted_payload):
  151. if self.arg not in dest.property_list():
  152. raise qubes.exc.QubesNoSuchPropertyError(dest, self.arg)
  153. property_def = dest.property_get_def(self.arg)
  154. newvalue = property_def.sanitize(untrusted_newvalue=untrusted_payload)
  155. self.fire_event_for_permission(newvalue=newvalue)
  156. setattr(dest, self.arg, newvalue)
  157. self.app.save()
  158. @qubes.api.method('admin.vm.property.Help', no_payload=True)
  159. @asyncio.coroutine
  160. def vm_property_help(self):
  161. '''Get help for one property'''
  162. return self._property_help(self.dest)
  163. @qubes.api.method('admin.property.Help', no_payload=True)
  164. @asyncio.coroutine
  165. def property_help(self):
  166. '''Get help for one property'''
  167. assert self.dest.name == 'dom0'
  168. return self._property_help(self.app)
  169. def _property_help(self, dest):
  170. if self.arg not in dest.property_list():
  171. raise qubes.exc.QubesNoSuchPropertyError(dest, self.arg)
  172. self.fire_event_for_permission()
  173. try:
  174. doc = dest.property_get_def(self.arg).__doc__
  175. except AttributeError:
  176. return ''
  177. return qubes.utils.format_doc(doc)
  178. @qubes.api.method('admin.vm.property.Reset', no_payload=True)
  179. @asyncio.coroutine
  180. def vm_property_reset(self):
  181. '''Reset a property to a default value'''
  182. return self._property_reset(self.dest)
  183. @qubes.api.method('admin.property.Reset', no_payload=True)
  184. @asyncio.coroutine
  185. def property_reset(self):
  186. '''Reset a property to a default value'''
  187. assert self.dest.name == 'dom0'
  188. return self._property_reset(self.app)
  189. def _property_reset(self, dest):
  190. if self.arg not in dest.property_list():
  191. raise qubes.exc.QubesNoSuchPropertyError(dest, self.arg)
  192. self.fire_event_for_permission()
  193. delattr(dest, self.arg)
  194. self.app.save()
  195. @qubes.api.method('admin.vm.volume.List', no_payload=True)
  196. @asyncio.coroutine
  197. def vm_volume_list(self):
  198. assert not self.arg
  199. volume_names = self.fire_event_for_filter(self.dest.volumes.keys())
  200. return ''.join('{}\n'.format(name) for name in volume_names)
  201. @qubes.api.method('admin.vm.volume.Info', no_payload=True)
  202. @asyncio.coroutine
  203. def vm_volume_info(self):
  204. assert self.arg in self.dest.volumes.keys()
  205. self.fire_event_for_permission()
  206. volume = self.dest.volumes[self.arg]
  207. # properties defined in API
  208. volume_properties = [
  209. 'pool', 'vid', 'size', 'usage', 'rw', 'internal', 'source',
  210. 'save_on_stop', 'snap_on_start']
  211. return ''.join('{}={}\n'.format(key, getattr(volume, key)) for key in
  212. volume_properties)
  213. @qubes.api.method('admin.vm.volume.ListSnapshots', no_payload=True)
  214. @asyncio.coroutine
  215. def vm_volume_listsnapshots(self):
  216. assert self.arg in self.dest.volumes.keys()
  217. volume = self.dest.volumes[self.arg]
  218. revisions = [revision for revision in volume.revisions]
  219. revisions = self.fire_event_for_filter(revisions)
  220. return ''.join('{}\n'.format(revision) for revision in revisions)
  221. @qubes.api.method('admin.vm.volume.Revert')
  222. @asyncio.coroutine
  223. def vm_volume_revert(self, untrusted_payload):
  224. assert self.arg in self.dest.volumes.keys()
  225. untrusted_revision = untrusted_payload.decode('ascii').strip()
  226. del untrusted_payload
  227. volume = self.dest.volumes[self.arg]
  228. snapshots = volume.revisions
  229. assert untrusted_revision in snapshots
  230. revision = untrusted_revision
  231. self.fire_event_for_permission(revision=revision)
  232. self.dest.storage.get_pool(volume).revert(revision)
  233. self.app.save()
  234. @qubes.api.method('admin.vm.volume.Resize')
  235. @asyncio.coroutine
  236. def vm_volume_resize(self, untrusted_payload):
  237. assert self.arg in self.dest.volumes.keys()
  238. untrusted_size = untrusted_payload.decode('ascii').strip()
  239. del untrusted_payload
  240. assert untrusted_size.isdigit() # only digits, forbid '-' too
  241. assert len(untrusted_size) <= 20 # limit to about 2^64
  242. size = int(untrusted_size)
  243. self.fire_event_for_permission(size=size)
  244. self.dest.storage.resize(self.arg, size)
  245. self.app.save()
  246. @qubes.api.method('admin.vm.volume.Import', no_payload=True)
  247. @asyncio.coroutine
  248. def vm_volume_import(self):
  249. '''Import volume data.
  250. Note that this function only returns a path to where data should be
  251. written, actual importing is done by a script in /etc/qubes-rpc
  252. When the script finish importing, it will trigger
  253. internal.vm.volume.ImportEnd (with either b'ok' or b'fail' as a
  254. payload) and response from that call will be actually send to the
  255. caller.
  256. '''
  257. assert self.arg in self.dest.volumes.keys()
  258. self.fire_event_for_permission()
  259. if not self.dest.is_halted():
  260. raise qubes.exc.QubesVMNotHaltedError(self.dest)
  261. path = self.dest.storage.import_data(self.arg)
  262. assert ' ' not in path
  263. size = self.dest.volumes[self.arg].size
  264. # when we know the action is allowed, inform extensions that it will
  265. # be performed
  266. self.dest.fire_event('domain-volume-import-begin', volume=self.arg)
  267. return '{} {}'.format(size, path)
  268. @qubes.api.method('admin.pool.List', no_payload=True)
  269. @asyncio.coroutine
  270. def pool_list(self):
  271. assert not self.arg
  272. assert self.dest.name == 'dom0'
  273. pools = self.fire_event_for_filter(self.app.pools)
  274. return ''.join('{}\n'.format(pool) for pool in pools)
  275. @qubes.api.method('admin.pool.ListDrivers', no_payload=True)
  276. @asyncio.coroutine
  277. def pool_listdrivers(self):
  278. assert self.dest.name == 'dom0'
  279. assert not self.arg
  280. drivers = self.fire_event_for_filter(qubes.storage.pool_drivers())
  281. return ''.join('{} {}\n'.format(
  282. driver,
  283. ' '.join(qubes.storage.driver_parameters(driver)))
  284. for driver in drivers)
  285. @qubes.api.method('admin.pool.Info', no_payload=True)
  286. @asyncio.coroutine
  287. def pool_info(self):
  288. assert self.dest.name == 'dom0'
  289. assert self.arg in self.app.pools.keys()
  290. pool = self.app.pools[self.arg]
  291. self.fire_event_for_permission(pool=pool)
  292. return ''.join('{}={}\n'.format(prop, val)
  293. for prop, val in sorted(pool.config.items()))
  294. @qubes.api.method('admin.pool.Add')
  295. @asyncio.coroutine
  296. def pool_add(self, untrusted_payload):
  297. assert self.dest.name == 'dom0'
  298. drivers = qubes.storage.pool_drivers()
  299. assert self.arg in drivers
  300. untrusted_pool_config = untrusted_payload.decode('ascii').splitlines()
  301. del untrusted_payload
  302. assert all(('=' in line) for line in untrusted_pool_config)
  303. # pairs of (option, value)
  304. untrusted_pool_config = [line.split('=', 1)
  305. for line in untrusted_pool_config]
  306. # reject duplicated options
  307. assert len(set(x[0] for x in untrusted_pool_config)) == \
  308. len([x[0] for x in untrusted_pool_config])
  309. # and convert to dict
  310. untrusted_pool_config = dict(untrusted_pool_config)
  311. assert 'name' in untrusted_pool_config
  312. untrusted_pool_name = untrusted_pool_config.pop('name')
  313. allowed_chars = string.ascii_letters + string.digits + '-_.'
  314. assert all(c in allowed_chars for c in untrusted_pool_name)
  315. pool_name = untrusted_pool_name
  316. assert pool_name not in self.app.pools
  317. driver_parameters = qubes.storage.driver_parameters(self.arg)
  318. assert all(key in driver_parameters for key in untrusted_pool_config)
  319. pool_config = untrusted_pool_config
  320. self.fire_event_for_permission(name=pool_name,
  321. pool_config=pool_config)
  322. self.app.add_pool(name=pool_name, driver=self.arg, **pool_config)
  323. self.app.save()
  324. @qubes.api.method('admin.pool.Remove', no_payload=True)
  325. @asyncio.coroutine
  326. def pool_remove(self):
  327. assert self.dest.name == 'dom0'
  328. assert self.arg in self.app.pools.keys()
  329. self.fire_event_for_permission()
  330. self.app.remove_pool(self.arg)
  331. self.app.save()
  332. @qubes.api.method('admin.label.List', no_payload=True)
  333. @asyncio.coroutine
  334. def label_list(self):
  335. assert self.dest.name == 'dom0'
  336. assert not self.arg
  337. labels = self.fire_event_for_filter(self.app.labels.values())
  338. return ''.join('{}\n'.format(label.name) for label in labels)
  339. @qubes.api.method('admin.label.Get', no_payload=True)
  340. @asyncio.coroutine
  341. def label_get(self):
  342. assert self.dest.name == 'dom0'
  343. try:
  344. label = self.app.get_label(self.arg)
  345. except KeyError:
  346. raise qubes.exc.QubesValueError
  347. self.fire_event_for_permission(label=label)
  348. return label.color
  349. @qubes.api.method('admin.label.Index', no_payload=True)
  350. @asyncio.coroutine
  351. def label_index(self):
  352. assert self.dest.name == 'dom0'
  353. try:
  354. label = self.app.get_label(self.arg)
  355. except KeyError:
  356. raise qubes.exc.QubesValueError
  357. self.fire_event_for_permission(label=label)
  358. return str(label.index)
  359. @qubes.api.method('admin.label.Create')
  360. @asyncio.coroutine
  361. def label_create(self, untrusted_payload):
  362. assert self.dest.name == 'dom0'
  363. # don't confuse label name with label index
  364. assert not self.arg.isdigit()
  365. allowed_chars = string.ascii_letters + string.digits + '-_.'
  366. assert all(c in allowed_chars for c in self.arg)
  367. try:
  368. self.app.get_label(self.arg)
  369. except KeyError:
  370. # ok, no such label yet
  371. pass
  372. else:
  373. raise qubes.exc.QubesValueError('label already exists')
  374. untrusted_payload = untrusted_payload.decode('ascii').strip()
  375. assert len(untrusted_payload) == 8
  376. assert untrusted_payload.startswith('0x')
  377. # besides prefix, only hex digits are allowed
  378. assert all(x in string.hexdigits for x in untrusted_payload[2:])
  379. # SEE: #2732
  380. color = untrusted_payload
  381. self.fire_event_for_permission(color=color)
  382. # allocate new index, but make sure it's outside of default labels set
  383. new_index = max(
  384. qubes.config.max_default_label, *self.app.labels.keys()) + 1
  385. label = qubes.Label(new_index, color, self.arg)
  386. self.app.labels[new_index] = label
  387. self.app.save()
  388. @qubes.api.method('admin.label.Remove', no_payload=True)
  389. @asyncio.coroutine
  390. def label_remove(self):
  391. assert self.dest.name == 'dom0'
  392. try:
  393. label = self.app.get_label(self.arg)
  394. except KeyError:
  395. raise qubes.exc.QubesValueError
  396. # don't allow removing default labels
  397. assert label.index > qubes.config.max_default_label
  398. # FIXME: this should be in app.add_label()
  399. for vm in self.app.domains:
  400. if vm.label == label:
  401. raise qubes.exc.QubesException('label still in use')
  402. self.fire_event_for_permission(label=label)
  403. del self.app.labels[label.index]
  404. self.app.save()
  405. @qubes.api.method('admin.vm.Start', no_payload=True)
  406. @asyncio.coroutine
  407. def vm_start(self):
  408. assert not self.arg
  409. self.fire_event_for_permission()
  410. try:
  411. yield from self.dest.start()
  412. except libvirt.libvirtError as e:
  413. # change to QubesException, so will be reported to the user
  414. raise qubes.exc.QubesException('Start failed: ' + str(e))
  415. @qubes.api.method('admin.vm.Shutdown', no_payload=True)
  416. @asyncio.coroutine
  417. def vm_shutdown(self):
  418. assert not self.arg
  419. self.fire_event_for_permission()
  420. yield from self.dest.shutdown()
  421. @qubes.api.method('admin.vm.Pause', no_payload=True)
  422. @asyncio.coroutine
  423. def vm_pause(self):
  424. assert not self.arg
  425. self.fire_event_for_permission()
  426. yield from self.dest.pause()
  427. @qubes.api.method('admin.vm.Unpause', no_payload=True)
  428. @asyncio.coroutine
  429. def vm_unpause(self):
  430. assert not self.arg
  431. self.fire_event_for_permission()
  432. yield from self.dest.unpause()
  433. @qubes.api.method('admin.vm.Kill', no_payload=True)
  434. @asyncio.coroutine
  435. def vm_kill(self):
  436. assert not self.arg
  437. self.fire_event_for_permission()
  438. yield from self.dest.kill()
  439. @qubes.api.method('admin.Events', no_payload=True)
  440. @asyncio.coroutine
  441. def events(self):
  442. assert not self.arg
  443. # run until client connection is terminated
  444. self.cancellable = True
  445. wait_for_cancel = asyncio.get_event_loop().create_future()
  446. # cache event filters, to not call an event each time an event arrives
  447. event_filters = self.fire_event_for_permission()
  448. dispatcher = QubesMgmtEventsDispatcher(event_filters, self.send_event)
  449. if self.dest.name == 'dom0':
  450. self.app.add_handler('*', dispatcher.app_handler)
  451. self.app.add_handler('domain-add', dispatcher.on_domain_add)
  452. self.app.add_handler('domain-delete', dispatcher.on_domain_delete)
  453. for vm in self.app.domains:
  454. vm.add_handler('*', dispatcher.vm_handler)
  455. else:
  456. self.dest.add_handler('*', dispatcher.vm_handler)
  457. # send artificial event as a confirmation that connection is established
  458. self.send_event(self.app, 'connection-established')
  459. try:
  460. yield from wait_for_cancel
  461. except asyncio.CancelledError:
  462. # the above waiting was already interrupted, this is all we need
  463. pass
  464. if self.dest.name == 'dom0':
  465. self.app.remove_handler('*', dispatcher.app_handler)
  466. self.app.remove_handler('domain-add', dispatcher.on_domain_add)
  467. self.app.remove_handler('domain-delete',
  468. dispatcher.on_domain_delete)
  469. for vm in self.app.domains:
  470. vm.remove_handler('*', dispatcher.vm_handler)
  471. else:
  472. self.dest.remove_handler('*', dispatcher.vm_handler)
  473. @qubes.api.method('admin.vm.feature.List', no_payload=True)
  474. @asyncio.coroutine
  475. def vm_feature_list(self):
  476. assert not self.arg
  477. features = self.fire_event_for_filter(self.dest.features.keys())
  478. return ''.join('{}\n'.format(feature) for feature in features)
  479. @qubes.api.method('admin.vm.feature.Get', no_payload=True)
  480. @asyncio.coroutine
  481. def vm_feature_get(self):
  482. # validation of self.arg done by qrexec-policy is enough
  483. self.fire_event_for_permission()
  484. try:
  485. value = self.dest.features[self.arg]
  486. except KeyError:
  487. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  488. return value
  489. @qubes.api.method('admin.vm.feature.CheckWithTemplate', no_payload=True)
  490. @asyncio.coroutine
  491. def vm_feature_checkwithtemplate(self):
  492. # validation of self.arg done by qrexec-policy is enough
  493. self.fire_event_for_permission()
  494. try:
  495. value = self.dest.features.check_with_template(self.arg)
  496. except KeyError:
  497. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  498. return value
  499. @qubes.api.method('admin.vm.feature.Remove', no_payload=True)
  500. @asyncio.coroutine
  501. def vm_feature_remove(self):
  502. # validation of self.arg done by qrexec-policy is enough
  503. self.fire_event_for_permission()
  504. try:
  505. del self.dest.features[self.arg]
  506. except KeyError:
  507. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  508. self.app.save()
  509. @qubes.api.method('admin.vm.feature.Set')
  510. @asyncio.coroutine
  511. def vm_feature_set(self, untrusted_payload):
  512. # validation of self.arg done by qrexec-policy is enough
  513. value = untrusted_payload.decode('ascii', errors='strict')
  514. del untrusted_payload
  515. self.fire_event_for_permission(value=value)
  516. self.dest.features[self.arg] = value
  517. self.app.save()
  518. @qubes.api.method('admin.vm.Create.{endpoint}', endpoints=(ep.name
  519. for ep in pkg_resources.iter_entry_points(qubes.vm.VM_ENTRY_POINT)))
  520. @asyncio.coroutine
  521. def vm_create(self, endpoint, untrusted_payload=None):
  522. return self._vm_create(endpoint, allow_pool=False,
  523. untrusted_payload=untrusted_payload)
  524. @qubes.api.method('admin.vm.CreateInPool.{endpoint}', endpoints=(ep.name
  525. for ep in pkg_resources.iter_entry_points(qubes.vm.VM_ENTRY_POINT)))
  526. @asyncio.coroutine
  527. def vm_create_in_pool(self, endpoint, untrusted_payload=None):
  528. return self._vm_create(endpoint, allow_pool=True,
  529. untrusted_payload=untrusted_payload)
  530. def _vm_create(self, vm_type, allow_pool=False, untrusted_payload=None):
  531. assert self.dest.name == 'dom0'
  532. kwargs = {}
  533. pool = None
  534. pools = {}
  535. # this will raise exception if none is found
  536. vm_class = qubes.utils.get_entry_point_one(qubes.vm.VM_ENTRY_POINT,
  537. vm_type)
  538. # if argument is given, it needs to be a valid template, and only
  539. # when given VM class do need a template
  540. if hasattr(vm_class, 'template'):
  541. if self.arg:
  542. assert self.arg in self.app.domains
  543. kwargs['template'] = self.app.domains[self.arg]
  544. else:
  545. assert not self.arg
  546. for untrusted_param in untrusted_payload.decode('ascii',
  547. errors='strict').split(' '):
  548. untrusted_key, untrusted_value = untrusted_param.split('=', 1)
  549. if untrusted_key in kwargs:
  550. raise qubes.api.ProtocolError('duplicated parameters')
  551. if untrusted_key == 'name':
  552. qubes.vm.validate_name(None, None, untrusted_value)
  553. kwargs['name'] = untrusted_value
  554. elif untrusted_key == 'label':
  555. # don't confuse label name with label index
  556. assert not untrusted_value.isdigit()
  557. allowed_chars = string.ascii_letters + string.digits + '-_.'
  558. assert all(c in allowed_chars for c in untrusted_value)
  559. try:
  560. kwargs['label'] = self.app.get_label(untrusted_value)
  561. except KeyError:
  562. raise qubes.exc.QubesValueError
  563. elif untrusted_key == 'pool' and allow_pool:
  564. if pool is not None:
  565. raise qubes.api.ProtocolError('duplicated pool parameter')
  566. pool = self.app.get_pool(untrusted_value)
  567. elif untrusted_key.startswith('pool:') and allow_pool:
  568. untrusted_volume = untrusted_key.split(':', 1)[1]
  569. # kind of ugly, but actual list of volumes is available only
  570. # after creating a VM
  571. assert untrusted_volume in ['root', 'private', 'volatile',
  572. 'kernel']
  573. volume = untrusted_volume
  574. if volume in pools:
  575. raise qubes.api.ProtocolError(
  576. 'duplicated pool:{} parameter'.format(volume))
  577. pools[volume] = self.app.get_pool(untrusted_value)
  578. else:
  579. raise qubes.api.ProtocolError('Invalid param name')
  580. del untrusted_payload
  581. if 'name' not in kwargs or 'label' not in kwargs:
  582. raise qubes.api.ProtocolError('Missing name or label')
  583. if pool and pools:
  584. raise qubes.api.ProtocolError(
  585. 'Only one of \'pool=\' and \'pool:volume=\' can be used')
  586. if kwargs['name'] in self.app.domains:
  587. raise qubes.exc.QubesValueError(
  588. 'VM {} already exists'.format(kwargs['name']))
  589. self.fire_event_for_permission(pool=pool, pools=pools, **kwargs)
  590. vm = self.app.add_new_vm(vm_class, **kwargs)
  591. # TODO: move this to extension (in race-free fashion)
  592. vm.tags.add('created-by-' + str(self.src))
  593. try:
  594. yield from vm.create_on_disk(pool=pool, pools=pools)
  595. except:
  596. del self.app.domains[vm]
  597. raise
  598. self.app.save()
  599. @qubes.api.method('admin.vm.Remove', no_payload=True)
  600. @asyncio.coroutine
  601. def vm_remove(self):
  602. assert not self.arg
  603. self.fire_event_for_permission()
  604. if not self.dest.is_halted():
  605. raise qubes.exc.QubesVMNotHaltedError(self.dest)
  606. del self.app.domains[self.dest]
  607. try:
  608. yield from self.dest.remove_from_disk()
  609. except: # pylint: disable=bare-except
  610. self.app.log.exception('Error wile removing VM \'%s\' files',
  611. self.dest.name)
  612. self.app.save()
  613. @qubes.api.method('admin.vm.Clone')
  614. @asyncio.coroutine
  615. def vm_clone(self, untrusted_payload):
  616. assert not self.arg
  617. assert untrusted_payload.startswith(b'name=')
  618. untrusted_name = untrusted_payload[5:].decode('ascii')
  619. qubes.vm.validate_name(None, None, untrusted_name)
  620. new_name = untrusted_name
  621. del untrusted_payload
  622. if new_name in self.app.domains:
  623. raise qubes.exc.QubesValueError('Already exists')
  624. self.fire_event_for_permission(new_name=new_name)
  625. src_vm = self.dest
  626. dst_vm = self.app.add_new_vm(src_vm.__class__, name=new_name)
  627. try:
  628. dst_vm.clone_properties(src_vm)
  629. dst_vm.tags.update(src_vm.tags)
  630. dst_vm.features.update(src_vm.features)
  631. dst_vm.firewall.clone(src_vm.firewall)
  632. for devclass in src_vm.devices:
  633. for device_assignment in src_vm.devices[devclass].assignments():
  634. dst_vm.devices[devclass].attach(device_assignment.clone())
  635. yield from dst_vm.clone_disk_files(src_vm)
  636. except:
  637. del self.app.domains[dst_vm]
  638. raise
  639. self.app.save()
  640. @qubes.api.method('admin.vm.device.{endpoint}.Available', endpoints=(ep.name
  641. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  642. no_payload=True)
  643. @asyncio.coroutine
  644. def vm_device_available(self, endpoint):
  645. devclass = endpoint
  646. devices = self.dest.devices[devclass].available()
  647. if self.arg:
  648. devices = [dev for dev in devices if dev.ident == self.arg]
  649. # no duplicated devices, but device may not exists, in which case
  650. # the list is empty
  651. assert len(devices) <= 1
  652. devices = self.fire_event_for_filter(devices, devclass=devclass)
  653. dev_info = {}
  654. for dev in devices:
  655. non_default_attrs = set(attr for attr in dir(dev) if
  656. not attr.startswith('_')).difference((
  657. 'backend_domain', 'ident', 'frontend_domain',
  658. 'description', 'options'))
  659. properties_txt = ' '.join(
  660. '{}={!s}'.format(prop, value) for prop, value
  661. in itertools.chain(
  662. ((key, getattr(dev, key)) for key in non_default_attrs),
  663. # keep description as the last one, according to API
  664. # specification
  665. (('description', dev.description),)
  666. ))
  667. assert '\n' not in properties_txt
  668. dev_info[dev.ident] = properties_txt
  669. return ''.join('{} {}\n'.format(ident, dev_info[ident])
  670. for ident in sorted(dev_info))
  671. @qubes.api.method('admin.vm.device.{endpoint}.List', endpoints=(ep.name
  672. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  673. no_payload=True)
  674. @asyncio.coroutine
  675. def vm_device_list(self, endpoint):
  676. devclass = endpoint
  677. device_assignments = self.dest.devices[devclass].assignments()
  678. if self.arg:
  679. select_backend, select_ident = self.arg.split('+', 1)
  680. device_assignments = [dev for dev in device_assignments
  681. if (str(dev.backend_domain), dev.ident)
  682. == (select_backend, select_ident)]
  683. # no duplicated devices, but device may not exists, in which case
  684. # the list is empty
  685. assert len(device_assignments) <= 1
  686. device_assignments = self.fire_event_for_filter(device_assignments,
  687. devclass=devclass)
  688. dev_info = {}
  689. for dev in device_assignments:
  690. properties_txt = ' '.join(
  691. '{}={!s}'.format(opt, value) for opt, value
  692. in itertools.chain(
  693. dev.options.items(),
  694. (('persistent', 'yes' if dev.persistent else 'no'),)
  695. ))
  696. assert '\n' not in properties_txt
  697. ident = '{!s}+{!s}'.format(dev.backend_domain, dev.ident)
  698. dev_info[ident] = properties_txt
  699. return ''.join('{} {}\n'.format(ident, dev_info[ident])
  700. for ident in sorted(dev_info))
  701. @qubes.api.method('admin.vm.device.{endpoint}.Attach', endpoints=(ep.name
  702. for ep in pkg_resources.iter_entry_points('qubes.devices')))
  703. @asyncio.coroutine
  704. def vm_device_attach(self, endpoint, untrusted_payload):
  705. devclass = endpoint
  706. options = {}
  707. persistent = False
  708. for untrusted_option in untrusted_payload.decode('ascii').split():
  709. try:
  710. untrusted_key, untrusted_value = untrusted_option.split('=', 1)
  711. except ValueError:
  712. raise qubes.api.ProtocolError('Invalid options format')
  713. if untrusted_key == 'persistent':
  714. persistent = qubes.property.bool(None, None, untrusted_value)
  715. else:
  716. allowed_chars_key = string.digits + string.ascii_letters + '-_.'
  717. allowed_chars_value = allowed_chars_key + ',+:'
  718. if any(x not in allowed_chars_key for x in untrusted_key):
  719. raise qubes.api.ProtocolError(
  720. 'Invalid chars in option name')
  721. if any(x not in allowed_chars_value for x in untrusted_value):
  722. raise qubes.api.ProtocolError(
  723. 'Invalid chars in option value')
  724. options[untrusted_key] = untrusted_value
  725. # qrexec already verified that no strange characters are in self.arg
  726. backend_domain, ident = self.arg.split('+', 1)
  727. # may raise KeyError, either on domain or ident
  728. dev = self.app.domains[backend_domain].devices[devclass][ident]
  729. self.fire_event_for_permission(device=dev,
  730. devclass=devclass, persistent=persistent,
  731. options=options)
  732. assignment = qubes.devices.DeviceAssignment(
  733. dev.backend_domain, dev.ident,
  734. options=options, persistent=persistent)
  735. self.dest.devices[devclass].attach(assignment)
  736. self.app.save()
  737. @qubes.api.method('admin.vm.device.{endpoint}.Detach', endpoints=(ep.name
  738. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  739. no_payload=True)
  740. @asyncio.coroutine
  741. def vm_device_detach(self, endpoint):
  742. devclass = endpoint
  743. # qrexec already verified that no strange characters are in self.arg
  744. backend_domain, ident = self.arg.split('+', 1)
  745. # may raise KeyError; if device isn't found, it will be UnknownDevice
  746. # instance - but allow it, otherwise it will be impossible to detach
  747. # already removed device
  748. dev = self.app.domains[backend_domain].devices[devclass][ident]
  749. self.fire_event_for_permission(device=dev,
  750. devclass=devclass)
  751. assignment = qubes.devices.DeviceAssignment(
  752. dev.backend_domain, dev.ident)
  753. self.dest.devices[devclass].detach(assignment)
  754. self.app.save()