admin.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2017 Wojtek Porczyk <woju@invisiblethingslab.com>
  5. #
  6. # This library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # This library 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 GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  18. #
  19. '''
  20. Qubes OS Management API
  21. '''
  22. import asyncio
  23. import functools
  24. import itertools
  25. import os
  26. import string
  27. import subprocess
  28. import libvirt
  29. import pkg_resources
  30. import yaml
  31. import qubes.api
  32. import qubes.backup
  33. import qubes.config
  34. import qubes.devices
  35. import qubes.firewall
  36. import qubes.storage
  37. import qubes.utils
  38. import qubes.vm
  39. import qubes.vm.adminvm
  40. import qubes.vm.qubesvm
  41. class QubesMgmtEventsDispatcher(object):
  42. def __init__(self, filters, send_event):
  43. self.filters = filters
  44. self.send_event = send_event
  45. def vm_handler(self, subject, event, **kwargs):
  46. # do not send internal events
  47. if event.startswith('admin-permission:'):
  48. return
  49. if event.startswith('device-get:'):
  50. return
  51. if event.startswith('device-list:'):
  52. return
  53. if event.startswith('device-list-attached:'):
  54. return
  55. if event in ('domain-is-fully-usable',):
  56. return
  57. if not list(qubes.api.apply_filters([(subject, event, kwargs)],
  58. self.filters)):
  59. return
  60. self.send_event(subject, event, **kwargs)
  61. def app_handler(self, subject, event, **kwargs):
  62. if not list(qubes.api.apply_filters([(subject, event, kwargs)],
  63. self.filters)):
  64. return
  65. self.send_event(subject, event, **kwargs)
  66. def on_domain_add(self, subject, event, vm):
  67. # pylint: disable=unused-argument
  68. vm.add_handler('*', self.vm_handler)
  69. def on_domain_delete(self, subject, event, vm):
  70. # pylint: disable=unused-argument
  71. vm.remove_handler('*', self.vm_handler)
  72. class QubesAdminAPI(qubes.api.AbstractQubesAPI):
  73. '''Implementation of Qubes Management API calls
  74. This class contains all the methods available in the main API.
  75. .. seealso::
  76. https://www.qubes-os.org/doc/mgmt1/
  77. '''
  78. SOCKNAME = '/var/run/qubesd.sock'
  79. @qubes.api.method('admin.vmclass.List', no_payload=True,
  80. scope='global', read=True)
  81. @asyncio.coroutine
  82. def vmclass_list(self):
  83. '''List all VM classes'''
  84. assert not self.arg
  85. assert self.dest.name == 'dom0'
  86. entrypoints = self.fire_event_for_filter(
  87. pkg_resources.iter_entry_points(qubes.vm.VM_ENTRY_POINT))
  88. return ''.join('{}\n'.format(ep.name)
  89. for ep in entrypoints)
  90. @qubes.api.method('admin.vm.List', no_payload=True,
  91. scope='global', read=True)
  92. @asyncio.coroutine
  93. def vm_list(self):
  94. '''List all the domains'''
  95. assert not self.arg
  96. if self.dest.name == 'dom0':
  97. domains = self.fire_event_for_filter(self.app.domains)
  98. else:
  99. domains = self.fire_event_for_filter([self.dest])
  100. return ''.join('{} class={} state={}\n'.format(
  101. vm.name,
  102. vm.__class__.__name__,
  103. vm.get_power_state())
  104. for vm in sorted(domains))
  105. @qubes.api.method('admin.vm.property.List', no_payload=True,
  106. scope='local', read=True)
  107. @asyncio.coroutine
  108. def vm_property_list(self):
  109. '''List all properties on a qube'''
  110. return self._property_list(self.dest)
  111. @qubes.api.method('admin.property.List', no_payload=True,
  112. scope='global', read=True)
  113. @asyncio.coroutine
  114. def property_list(self):
  115. '''List all global properties'''
  116. assert self.dest.name == 'dom0'
  117. return self._property_list(self.app)
  118. def _property_list(self, dest):
  119. assert not self.arg
  120. properties = self.fire_event_for_filter(dest.property_list())
  121. return ''.join('{}\n'.format(prop.__name__) for prop in properties)
  122. @qubes.api.method('admin.vm.property.Get', no_payload=True,
  123. scope='local', read=True)
  124. @asyncio.coroutine
  125. def vm_property_get(self):
  126. '''Get a value of one property'''
  127. return self._property_get(self.dest)
  128. @qubes.api.method('admin.property.Get', no_payload=True,
  129. scope='global', read=True)
  130. @asyncio.coroutine
  131. def property_get(self):
  132. '''Get a value of one global property'''
  133. assert self.dest.name == 'dom0'
  134. return self._property_get(self.app)
  135. def _property_get(self, dest):
  136. if self.arg not in dest.property_list():
  137. raise qubes.exc.QubesNoSuchPropertyError(dest, self.arg)
  138. self.fire_event_for_permission()
  139. property_def = dest.property_get_def(self.arg)
  140. # explicit list to be sure that it matches protocol spec
  141. if isinstance(property_def, qubes.vm.VMProperty):
  142. property_type = 'vm'
  143. elif property_def.type is int:
  144. property_type = 'int'
  145. elif property_def.type is bool:
  146. property_type = 'bool'
  147. elif self.arg == 'label':
  148. property_type = 'label'
  149. else:
  150. property_type = 'str'
  151. try:
  152. value = getattr(dest, self.arg)
  153. except AttributeError:
  154. return 'default=True type={} '.format(property_type)
  155. else:
  156. return 'default={} type={} {}'.format(
  157. str(dest.property_is_default(self.arg)),
  158. property_type,
  159. str(value) if value is not None else '')
  160. @qubes.api.method('admin.vm.property.GetDefault', no_payload=True,
  161. scope='local', read=True)
  162. @asyncio.coroutine
  163. def vm_property_get_default(self):
  164. '''Get a value of one property'''
  165. return self._property_get_default(self.dest)
  166. @qubes.api.method('admin.property.GetDefault', no_payload=True,
  167. scope='global', read=True)
  168. @asyncio.coroutine
  169. def property_get_default(self):
  170. '''Get a value of one global property'''
  171. assert self.dest.name == 'dom0'
  172. return self._property_get_default(self.app)
  173. def _property_get_default(self, dest):
  174. if self.arg not in dest.property_list():
  175. raise qubes.exc.QubesNoSuchPropertyError(dest, self.arg)
  176. self.fire_event_for_permission()
  177. property_def = dest.property_get_def(self.arg)
  178. # explicit list to be sure that it matches protocol spec
  179. if isinstance(property_def, qubes.vm.VMProperty):
  180. property_type = 'vm'
  181. elif property_def.type is int:
  182. property_type = 'int'
  183. elif property_def.type is bool:
  184. property_type = 'bool'
  185. elif self.arg == 'label':
  186. property_type = 'label'
  187. else:
  188. property_type = 'str'
  189. try:
  190. value = property_def.get_default(dest)
  191. except AttributeError:
  192. return None
  193. else:
  194. return 'type={} {}'.format(
  195. property_type,
  196. str(value) if value is not None else '')
  197. @qubes.api.method('admin.vm.property.Set',
  198. scope='local', write=True)
  199. @asyncio.coroutine
  200. def vm_property_set(self, untrusted_payload):
  201. '''Set property value'''
  202. return self._property_set(self.dest,
  203. untrusted_payload=untrusted_payload)
  204. @qubes.api.method('admin.property.Set',
  205. scope='global', write=True)
  206. @asyncio.coroutine
  207. def property_set(self, untrusted_payload):
  208. '''Set property value'''
  209. assert self.dest.name == 'dom0'
  210. return self._property_set(self.app,
  211. untrusted_payload=untrusted_payload)
  212. def _property_set(self, dest, untrusted_payload):
  213. if self.arg not in dest.property_list():
  214. raise qubes.exc.QubesNoSuchPropertyError(dest, self.arg)
  215. property_def = dest.property_get_def(self.arg)
  216. newvalue = property_def.sanitize(untrusted_newvalue=untrusted_payload)
  217. self.fire_event_for_permission(newvalue=newvalue)
  218. setattr(dest, self.arg, newvalue)
  219. self.app.save()
  220. @qubes.api.method('admin.vm.property.Help', no_payload=True,
  221. scope='local', read=True)
  222. @asyncio.coroutine
  223. def vm_property_help(self):
  224. '''Get help for one property'''
  225. return self._property_help(self.dest)
  226. @qubes.api.method('admin.property.Help', no_payload=True,
  227. scope='global', read=True)
  228. @asyncio.coroutine
  229. def property_help(self):
  230. '''Get help for one property'''
  231. assert self.dest.name == 'dom0'
  232. return self._property_help(self.app)
  233. def _property_help(self, dest):
  234. if self.arg not in dest.property_list():
  235. raise qubes.exc.QubesNoSuchPropertyError(dest, self.arg)
  236. self.fire_event_for_permission()
  237. try:
  238. doc = dest.property_get_def(self.arg).__doc__
  239. except AttributeError:
  240. return ''
  241. return qubes.utils.format_doc(doc)
  242. @qubes.api.method('admin.vm.property.Reset', no_payload=True,
  243. scope='local', write=True)
  244. @asyncio.coroutine
  245. def vm_property_reset(self):
  246. '''Reset a property to a default value'''
  247. return self._property_reset(self.dest)
  248. @qubes.api.method('admin.property.Reset', no_payload=True,
  249. scope='global', write=True)
  250. @asyncio.coroutine
  251. def property_reset(self):
  252. '''Reset a property to a default value'''
  253. assert self.dest.name == 'dom0'
  254. return self._property_reset(self.app)
  255. def _property_reset(self, dest):
  256. if self.arg not in dest.property_list():
  257. raise qubes.exc.QubesNoSuchPropertyError(dest, self.arg)
  258. self.fire_event_for_permission()
  259. delattr(dest, self.arg)
  260. self.app.save()
  261. @qubes.api.method('admin.vm.volume.List', no_payload=True,
  262. scope='local', read=True)
  263. @asyncio.coroutine
  264. def vm_volume_list(self):
  265. assert not self.arg
  266. volume_names = self.fire_event_for_filter(self.dest.volumes.keys())
  267. return ''.join('{}\n'.format(name) for name in volume_names)
  268. @qubes.api.method('admin.vm.volume.Info', no_payload=True,
  269. scope='local', read=True)
  270. @asyncio.coroutine
  271. def vm_volume_info(self):
  272. assert self.arg in self.dest.volumes.keys()
  273. self.fire_event_for_permission()
  274. volume = self.dest.volumes[self.arg]
  275. # properties defined in API
  276. volume_properties = [
  277. 'pool', 'vid', 'size', 'usage', 'rw', 'source',
  278. 'save_on_stop', 'snap_on_start', 'revisions_to_keep', 'is_outdated']
  279. def _serialize(value):
  280. if callable(value):
  281. value = value()
  282. if value is None:
  283. value = ''
  284. return str(value)
  285. return ''.join('{}={}\n'.format(key, _serialize(getattr(volume, key)))
  286. for key in volume_properties)
  287. @qubes.api.method('admin.vm.volume.ListSnapshots', no_payload=True,
  288. scope='local', read=True)
  289. @asyncio.coroutine
  290. def vm_volume_listsnapshots(self):
  291. assert self.arg in self.dest.volumes.keys()
  292. volume = self.dest.volumes[self.arg]
  293. id_to_timestamp = volume.revisions
  294. revisions = sorted(id_to_timestamp, key=id_to_timestamp.__getitem__)
  295. revisions = self.fire_event_for_filter(revisions)
  296. return ''.join('{}\n'.format(revision) for revision in revisions)
  297. @qubes.api.method('admin.vm.volume.Revert',
  298. scope='local', write=True)
  299. @asyncio.coroutine
  300. def vm_volume_revert(self, untrusted_payload):
  301. assert self.arg in self.dest.volumes.keys()
  302. untrusted_revision = untrusted_payload.decode('ascii').strip()
  303. del untrusted_payload
  304. volume = self.dest.volumes[self.arg]
  305. snapshots = volume.revisions
  306. assert untrusted_revision in snapshots
  307. revision = untrusted_revision
  308. self.fire_event_for_permission(volume=volume, revision=revision)
  309. ret = volume.revert(revision)
  310. if asyncio.iscoroutine(ret):
  311. yield from ret
  312. self.app.save()
  313. # write=True because this allow to clone VM - and most likely modify that
  314. # one - still having the same data
  315. @qubes.api.method('admin.vm.volume.CloneFrom', no_payload=True,
  316. scope='local', write=True)
  317. @asyncio.coroutine
  318. def vm_volume_clone_from(self):
  319. assert self.arg in self.dest.volumes.keys()
  320. volume = self.dest.volumes[self.arg]
  321. self.fire_event_for_permission(volume=volume)
  322. token = qubes.utils.random_string(32)
  323. # save token on self.app, as self is not persistent
  324. if not hasattr(self.app, 'api_admin_pending_clone'):
  325. self.app.api_admin_pending_clone = {}
  326. # don't handle collisions any better - if someone is so much out of
  327. # luck, can try again anyway
  328. assert token not in self.app.api_admin_pending_clone
  329. self.app.api_admin_pending_clone[token] = volume
  330. return token
  331. @qubes.api.method('admin.vm.volume.CloneTo',
  332. scope='local', write=True)
  333. @asyncio.coroutine
  334. def vm_volume_clone_to(self, untrusted_payload):
  335. assert self.arg in self.dest.volumes.keys()
  336. untrusted_token = untrusted_payload.decode('ascii').strip()
  337. del untrusted_payload
  338. assert untrusted_token in getattr(self.app,
  339. 'api_admin_pending_clone', {})
  340. token = untrusted_token
  341. del untrusted_token
  342. src_volume = self.app.api_admin_pending_clone[token]
  343. del self.app.api_admin_pending_clone[token]
  344. # make sure the volume still exists, but invalidate token anyway
  345. assert str(src_volume.pool) in self.app.pools
  346. assert src_volume in self.app.pools[str(src_volume.pool)].volumes
  347. dst_volume = self.dest.volumes[self.arg]
  348. self.fire_event_for_permission(src_volume=src_volume,
  349. dst_volume=dst_volume)
  350. op_retval = dst_volume.import_volume(src_volume)
  351. # clone/import functions may be either synchronous or asynchronous
  352. # in the later case, we need to wait for them to finish
  353. if asyncio.iscoroutine(op_retval):
  354. op_retval = yield from op_retval
  355. self.dest.volumes[self.arg] = op_retval
  356. self.app.save()
  357. @qubes.api.method('admin.vm.volume.Resize',
  358. scope='local', write=True)
  359. @asyncio.coroutine
  360. def vm_volume_resize(self, untrusted_payload):
  361. assert self.arg in self.dest.volumes.keys()
  362. untrusted_size = untrusted_payload.decode('ascii').strip()
  363. del untrusted_payload
  364. assert untrusted_size.isdigit() # only digits, forbid '-' too
  365. assert len(untrusted_size) <= 20 # limit to about 2^64
  366. size = int(untrusted_size)
  367. self.fire_event_for_permission(size=size)
  368. yield from self.dest.storage.resize(self.arg, size)
  369. self.app.save()
  370. @qubes.api.method('admin.vm.volume.Import', no_payload=True,
  371. scope='local', write=True)
  372. @asyncio.coroutine
  373. def vm_volume_import(self):
  374. '''Import volume data.
  375. Note that this function only returns a path to where data should be
  376. written, actual importing is done by a script in /etc/qubes-rpc
  377. When the script finish importing, it will trigger
  378. internal.vm.volume.ImportEnd (with either b'ok' or b'fail' as a
  379. payload) and response from that call will be actually send to the
  380. caller.
  381. '''
  382. assert self.arg in self.dest.volumes.keys()
  383. self.fire_event_for_permission()
  384. if not self.dest.is_halted():
  385. raise qubes.exc.QubesVMNotHaltedError(self.dest)
  386. path = self.dest.storage.import_data(self.arg)
  387. assert ' ' not in path
  388. size = self.dest.volumes[self.arg].size
  389. # when we know the action is allowed, inform extensions that it will
  390. # be performed
  391. self.dest.fire_event('domain-volume-import-begin', volume=self.arg)
  392. return '{} {}'.format(size, path)
  393. @qubes.api.method('admin.vm.volume.Set.revisions_to_keep',
  394. scope='local', write=True)
  395. @asyncio.coroutine
  396. def vm_volume_set_revisions_to_keep(self, untrusted_payload):
  397. assert self.arg in self.dest.volumes.keys()
  398. try:
  399. untrusted_value = int(untrusted_payload.decode('ascii'))
  400. except (UnicodeDecodeError, ValueError):
  401. raise qubes.api.ProtocolError('Invalid value')
  402. del untrusted_payload
  403. assert untrusted_value >= 0
  404. newvalue = untrusted_value
  405. del untrusted_value
  406. self.fire_event_for_permission(newvalue=newvalue)
  407. self.dest.volumes[self.arg].revisions_to_keep = newvalue
  408. self.app.save()
  409. @qubes.api.method('admin.vm.volume.Set.rw',
  410. scope='local', write=True)
  411. @asyncio.coroutine
  412. def vm_volume_set_rw(self, untrusted_payload):
  413. assert self.arg in self.dest.volumes.keys()
  414. try:
  415. newvalue = qubes.property.bool(None, None,
  416. untrusted_payload.decode('ascii'))
  417. except (UnicodeDecodeError, ValueError):
  418. raise qubes.api.ProtocolError('Invalid value')
  419. del untrusted_payload
  420. self.fire_event_for_permission(newvalue=newvalue)
  421. if not self.dest.is_halted():
  422. raise qubes.exc.QubesVMNotHaltedError(self.dest)
  423. self.dest.volumes[self.arg].rw = newvalue
  424. self.app.save()
  425. @qubes.api.method('admin.vm.tag.List', no_payload=True,
  426. scope='local', read=True)
  427. @asyncio.coroutine
  428. def vm_tag_list(self):
  429. assert not self.arg
  430. tags = self.dest.tags
  431. tags = self.fire_event_for_filter(tags)
  432. return ''.join('{}\n'.format(tag) for tag in sorted(tags))
  433. @qubes.api.method('admin.vm.tag.Get', no_payload=True,
  434. scope='local', read=True)
  435. @asyncio.coroutine
  436. def vm_tag_get(self):
  437. qubes.vm.Tags.validate_tag(self.arg)
  438. self.fire_event_for_permission()
  439. return '1' if self.arg in self.dest.tags else '0'
  440. @qubes.api.method('admin.vm.tag.Set', no_payload=True,
  441. scope='local', write=True)
  442. @asyncio.coroutine
  443. def vm_tag_set(self):
  444. qubes.vm.Tags.validate_tag(self.arg)
  445. self.fire_event_for_permission()
  446. self.dest.tags.add(self.arg)
  447. self.app.save()
  448. @qubes.api.method('admin.vm.tag.Remove', no_payload=True,
  449. scope='local', write=True)
  450. @asyncio.coroutine
  451. def vm_tag_remove(self):
  452. qubes.vm.Tags.validate_tag(self.arg)
  453. self.fire_event_for_permission()
  454. try:
  455. self.dest.tags.remove(self.arg)
  456. except KeyError:
  457. raise qubes.exc.QubesTagNotFoundError(self.dest, self.arg)
  458. self.app.save()
  459. @qubes.api.method('admin.pool.List', no_payload=True,
  460. scope='global', read=True)
  461. @asyncio.coroutine
  462. def pool_list(self):
  463. assert not self.arg
  464. assert self.dest.name == 'dom0'
  465. pools = self.fire_event_for_filter(self.app.pools)
  466. return ''.join('{}\n'.format(pool) for pool in pools)
  467. @qubes.api.method('admin.pool.ListDrivers', no_payload=True,
  468. scope='global', read=True)
  469. @asyncio.coroutine
  470. def pool_listdrivers(self):
  471. assert self.dest.name == 'dom0'
  472. assert not self.arg
  473. drivers = self.fire_event_for_filter(qubes.storage.pool_drivers())
  474. return ''.join('{} {}\n'.format(
  475. driver,
  476. ' '.join(qubes.storage.driver_parameters(driver)))
  477. for driver in drivers)
  478. @qubes.api.method('admin.pool.Info', no_payload=True,
  479. scope='global', read=True)
  480. @asyncio.coroutine
  481. def pool_info(self):
  482. assert self.dest.name == 'dom0'
  483. assert self.arg in self.app.pools.keys()
  484. pool = self.app.pools[self.arg]
  485. self.fire_event_for_permission(pool=pool)
  486. other_info = ''
  487. try:
  488. other_info += 'size={}\n'.format(pool.size)
  489. except NotImplementedError:
  490. pass
  491. try:
  492. other_info += 'usage={}\n'.format(pool.usage)
  493. except NotImplementedError:
  494. pass
  495. try:
  496. included_in = pool.included_in(self.app)
  497. if included_in:
  498. other_info += 'included_in={}\n'.format(str(included_in))
  499. except NotImplementedError:
  500. pass
  501. return ''.join('{}={}\n'.format(prop, val)
  502. for prop, val in sorted(pool.config.items())) + \
  503. other_info
  504. @qubes.api.method('admin.pool.Add',
  505. scope='global', write=True)
  506. @asyncio.coroutine
  507. def pool_add(self, untrusted_payload):
  508. assert self.dest.name == 'dom0'
  509. drivers = qubes.storage.pool_drivers()
  510. assert self.arg in drivers
  511. untrusted_pool_config = untrusted_payload.decode('ascii').splitlines()
  512. del untrusted_payload
  513. assert all(('=' in line) for line in untrusted_pool_config)
  514. # pairs of (option, value)
  515. untrusted_pool_config = [line.split('=', 1)
  516. for line in untrusted_pool_config]
  517. # reject duplicated options
  518. assert len(set(x[0] for x in untrusted_pool_config)) == \
  519. len([x[0] for x in untrusted_pool_config])
  520. # and convert to dict
  521. untrusted_pool_config = dict(untrusted_pool_config)
  522. assert 'name' in untrusted_pool_config
  523. untrusted_pool_name = untrusted_pool_config.pop('name')
  524. allowed_chars = string.ascii_letters + string.digits + '-_.'
  525. assert all(c in allowed_chars for c in untrusted_pool_name)
  526. pool_name = untrusted_pool_name
  527. assert pool_name not in self.app.pools
  528. driver_parameters = qubes.storage.driver_parameters(self.arg)
  529. assert all(key in driver_parameters for key in untrusted_pool_config)
  530. pool_config = untrusted_pool_config
  531. self.fire_event_for_permission(name=pool_name,
  532. pool_config=pool_config)
  533. self.app.add_pool(name=pool_name, driver=self.arg, **pool_config)
  534. self.app.save()
  535. @qubes.api.method('admin.pool.Remove', no_payload=True,
  536. scope='global', write=True)
  537. @asyncio.coroutine
  538. def pool_remove(self):
  539. assert self.dest.name == 'dom0'
  540. assert self.arg in self.app.pools.keys()
  541. self.fire_event_for_permission()
  542. self.app.remove_pool(self.arg)
  543. self.app.save()
  544. @qubes.api.method('admin.pool.Set.revisions_to_keep',
  545. scope='global', write=True)
  546. @asyncio.coroutine
  547. def pool_set_revisions_to_keep(self, untrusted_payload):
  548. assert self.dest.name == 'dom0'
  549. assert self.arg in self.app.pools.keys()
  550. pool = self.app.pools[self.arg]
  551. try:
  552. untrusted_value = int(untrusted_payload.decode('ascii'))
  553. except (UnicodeDecodeError, ValueError):
  554. raise qubes.api.ProtocolError('Invalid value')
  555. del untrusted_payload
  556. assert untrusted_value >= 0
  557. newvalue = untrusted_value
  558. del untrusted_value
  559. self.fire_event_for_permission(newvalue=newvalue)
  560. pool.revisions_to_keep = newvalue
  561. self.app.save()
  562. @qubes.api.method('admin.label.List', no_payload=True,
  563. scope='global', read=True)
  564. @asyncio.coroutine
  565. def label_list(self):
  566. assert self.dest.name == 'dom0'
  567. assert not self.arg
  568. labels = self.fire_event_for_filter(self.app.labels.values())
  569. return ''.join('{}\n'.format(label.name) for label in labels)
  570. @qubes.api.method('admin.label.Get', no_payload=True,
  571. scope='global', read=True)
  572. @asyncio.coroutine
  573. def label_get(self):
  574. assert self.dest.name == 'dom0'
  575. try:
  576. label = self.app.get_label(self.arg)
  577. except KeyError:
  578. raise qubes.exc.QubesValueError
  579. self.fire_event_for_permission(label=label)
  580. return label.color
  581. @qubes.api.method('admin.label.Index', no_payload=True,
  582. scope='global', read=True)
  583. @asyncio.coroutine
  584. def label_index(self):
  585. assert self.dest.name == 'dom0'
  586. try:
  587. label = self.app.get_label(self.arg)
  588. except KeyError:
  589. raise qubes.exc.QubesValueError
  590. self.fire_event_for_permission(label=label)
  591. return str(label.index)
  592. @qubes.api.method('admin.label.Create',
  593. scope='global', write=True)
  594. @asyncio.coroutine
  595. def label_create(self, untrusted_payload):
  596. assert self.dest.name == 'dom0'
  597. # don't confuse label name with label index
  598. assert not self.arg.isdigit()
  599. allowed_chars = string.ascii_letters + string.digits + '-_.'
  600. assert all(c in allowed_chars for c in self.arg)
  601. try:
  602. self.app.get_label(self.arg)
  603. except KeyError:
  604. # ok, no such label yet
  605. pass
  606. else:
  607. raise qubes.exc.QubesValueError('label already exists')
  608. untrusted_payload = untrusted_payload.decode('ascii').strip()
  609. assert len(untrusted_payload) == 8
  610. assert untrusted_payload.startswith('0x')
  611. # besides prefix, only hex digits are allowed
  612. assert all(x in string.hexdigits for x in untrusted_payload[2:])
  613. # SEE: #2732
  614. color = untrusted_payload
  615. self.fire_event_for_permission(color=color)
  616. # allocate new index, but make sure it's outside of default labels set
  617. new_index = max(
  618. qubes.config.max_default_label, *self.app.labels.keys()) + 1
  619. label = qubes.Label(new_index, color, self.arg)
  620. self.app.labels[new_index] = label
  621. self.app.save()
  622. @qubes.api.method('admin.label.Remove', no_payload=True,
  623. scope='global', write=True)
  624. @asyncio.coroutine
  625. def label_remove(self):
  626. assert self.dest.name == 'dom0'
  627. try:
  628. label = self.app.get_label(self.arg)
  629. except KeyError:
  630. raise qubes.exc.QubesValueError
  631. # don't allow removing default labels
  632. assert label.index > qubes.config.max_default_label
  633. # FIXME: this should be in app.add_label()
  634. for vm in self.app.domains:
  635. if vm.label == label:
  636. raise qubes.exc.QubesException('label still in use')
  637. self.fire_event_for_permission(label=label)
  638. del self.app.labels[label.index]
  639. self.app.save()
  640. @qubes.api.method('admin.vm.Start', no_payload=True,
  641. scope='local', execute=True)
  642. @asyncio.coroutine
  643. def vm_start(self):
  644. assert not self.arg
  645. self.fire_event_for_permission()
  646. try:
  647. yield from self.dest.start()
  648. except libvirt.libvirtError as e:
  649. # change to QubesException, so will be reported to the user
  650. raise qubes.exc.QubesException('Start failed: ' + str(e) +
  651. ', see /var/log/libvirt/libxl/libxl-driver.log for details')
  652. @qubes.api.method('admin.vm.Shutdown', no_payload=True,
  653. scope='local', execute=True)
  654. @asyncio.coroutine
  655. def vm_shutdown(self):
  656. assert not self.arg
  657. self.fire_event_for_permission()
  658. yield from self.dest.shutdown()
  659. @qubes.api.method('admin.vm.Pause', no_payload=True,
  660. scope='local', execute=True)
  661. @asyncio.coroutine
  662. def vm_pause(self):
  663. assert not self.arg
  664. self.fire_event_for_permission()
  665. yield from self.dest.pause()
  666. @qubes.api.method('admin.vm.Unpause', no_payload=True,
  667. scope='local', execute=True)
  668. @asyncio.coroutine
  669. def vm_unpause(self):
  670. assert not self.arg
  671. self.fire_event_for_permission()
  672. yield from self.dest.unpause()
  673. @qubes.api.method('admin.vm.Kill', no_payload=True,
  674. scope='local', execute=True)
  675. @asyncio.coroutine
  676. def vm_kill(self):
  677. assert not self.arg
  678. self.fire_event_for_permission()
  679. yield from self.dest.kill()
  680. @qubes.api.method('admin.Events', no_payload=True,
  681. scope='global', read=True)
  682. @asyncio.coroutine
  683. def events(self):
  684. assert not self.arg
  685. # run until client connection is terminated
  686. self.cancellable = True
  687. wait_for_cancel = asyncio.get_event_loop().create_future()
  688. # cache event filters, to not call an event each time an event arrives
  689. event_filters = self.fire_event_for_permission()
  690. dispatcher = QubesMgmtEventsDispatcher(event_filters, self.send_event)
  691. if self.dest.name == 'dom0':
  692. self.app.add_handler('*', dispatcher.app_handler)
  693. self.app.add_handler('domain-add', dispatcher.on_domain_add)
  694. self.app.add_handler('domain-delete', dispatcher.on_domain_delete)
  695. for vm in self.app.domains:
  696. vm.add_handler('*', dispatcher.vm_handler)
  697. else:
  698. self.dest.add_handler('*', dispatcher.vm_handler)
  699. # send artificial event as a confirmation that connection is established
  700. self.send_event(self.app, 'connection-established')
  701. try:
  702. yield from wait_for_cancel
  703. except asyncio.CancelledError:
  704. # the above waiting was already interrupted, this is all we need
  705. pass
  706. if self.dest.name == 'dom0':
  707. self.app.remove_handler('*', dispatcher.app_handler)
  708. self.app.remove_handler('domain-add', dispatcher.on_domain_add)
  709. self.app.remove_handler('domain-delete',
  710. dispatcher.on_domain_delete)
  711. for vm in self.app.domains:
  712. vm.remove_handler('*', dispatcher.vm_handler)
  713. else:
  714. self.dest.remove_handler('*', dispatcher.vm_handler)
  715. @qubes.api.method('admin.vm.feature.List', no_payload=True,
  716. scope='local', read=True)
  717. @asyncio.coroutine
  718. def vm_feature_list(self):
  719. assert not self.arg
  720. features = self.fire_event_for_filter(self.dest.features.keys())
  721. return ''.join('{}\n'.format(feature) for feature in features)
  722. @qubes.api.method('admin.vm.feature.Get', no_payload=True,
  723. scope='local', read=True)
  724. @asyncio.coroutine
  725. def vm_feature_get(self):
  726. # validation of self.arg done by qrexec-policy is enough
  727. self.fire_event_for_permission()
  728. try:
  729. value = self.dest.features[self.arg]
  730. except KeyError:
  731. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  732. return value
  733. @qubes.api.method('admin.vm.feature.CheckWithTemplate', no_payload=True,
  734. scope='local', read=True)
  735. @asyncio.coroutine
  736. def vm_feature_checkwithtemplate(self):
  737. # validation of self.arg done by qrexec-policy is enough
  738. self.fire_event_for_permission()
  739. try:
  740. value = self.dest.features.check_with_template(self.arg)
  741. except KeyError:
  742. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  743. return value
  744. @qubes.api.method('admin.vm.feature.CheckWithNetvm', no_payload=True,
  745. scope='local', read=True)
  746. @asyncio.coroutine
  747. def vm_feature_checkwithnetvm(self):
  748. # validation of self.arg done by qrexec-policy is enough
  749. self.fire_event_for_permission()
  750. try:
  751. value = self.dest.features.check_with_netvm(self.arg)
  752. except KeyError:
  753. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  754. return value
  755. @qubes.api.method('admin.vm.feature.Remove', no_payload=True,
  756. scope='local', write=True)
  757. @asyncio.coroutine
  758. def vm_feature_remove(self):
  759. # validation of self.arg done by qrexec-policy is enough
  760. self.fire_event_for_permission()
  761. try:
  762. del self.dest.features[self.arg]
  763. except KeyError:
  764. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  765. self.app.save()
  766. @qubes.api.method('admin.vm.feature.Set',
  767. scope='local', write=True)
  768. @asyncio.coroutine
  769. def vm_feature_set(self, untrusted_payload):
  770. # validation of self.arg done by qrexec-policy is enough
  771. value = untrusted_payload.decode('ascii', errors='strict')
  772. del untrusted_payload
  773. self.fire_event_for_permission(value=value)
  774. self.dest.features[self.arg] = value
  775. self.app.save()
  776. @qubes.api.method('admin.vm.Create.{endpoint}', endpoints=(ep.name
  777. for ep in pkg_resources.iter_entry_points(qubes.vm.VM_ENTRY_POINT)),
  778. scope='global', write=True)
  779. @asyncio.coroutine
  780. def vm_create(self, endpoint, untrusted_payload=None):
  781. return self._vm_create(endpoint, allow_pool=False,
  782. untrusted_payload=untrusted_payload)
  783. @qubes.api.method('admin.vm.CreateInPool.{endpoint}', endpoints=(ep.name
  784. for ep in pkg_resources.iter_entry_points(qubes.vm.VM_ENTRY_POINT)),
  785. scope='global', write=True)
  786. @asyncio.coroutine
  787. def vm_create_in_pool(self, endpoint, untrusted_payload=None):
  788. return self._vm_create(endpoint, allow_pool=True,
  789. untrusted_payload=untrusted_payload)
  790. def _vm_create(self, vm_type, allow_pool=False, untrusted_payload=None):
  791. assert self.dest.name == 'dom0'
  792. kwargs = {}
  793. pool = None
  794. pools = {}
  795. # this will raise exception if none is found
  796. vm_class = qubes.utils.get_entry_point_one(qubes.vm.VM_ENTRY_POINT,
  797. vm_type)
  798. # if argument is given, it needs to be a valid template, and only
  799. # when given VM class do need a template
  800. if hasattr(vm_class, 'template'):
  801. if self.arg:
  802. assert self.arg in self.app.domains
  803. kwargs['template'] = self.app.domains[self.arg]
  804. else:
  805. assert not self.arg
  806. for untrusted_param in untrusted_payload.decode('ascii',
  807. errors='strict').split(' '):
  808. untrusted_key, untrusted_value = untrusted_param.split('=', 1)
  809. if untrusted_key in kwargs:
  810. raise qubes.api.ProtocolError('duplicated parameters')
  811. if untrusted_key == 'name':
  812. qubes.vm.validate_name(None, None, untrusted_value)
  813. kwargs['name'] = untrusted_value
  814. elif untrusted_key == 'label':
  815. # don't confuse label name with label index
  816. assert not untrusted_value.isdigit()
  817. allowed_chars = string.ascii_letters + string.digits + '-_.'
  818. assert all(c in allowed_chars for c in untrusted_value)
  819. try:
  820. kwargs['label'] = self.app.get_label(untrusted_value)
  821. except KeyError:
  822. raise qubes.exc.QubesValueError
  823. elif untrusted_key == 'pool' and allow_pool:
  824. if pool is not None:
  825. raise qubes.api.ProtocolError('duplicated pool parameter')
  826. pool = self.app.get_pool(untrusted_value)
  827. elif untrusted_key.startswith('pool:') and allow_pool:
  828. untrusted_volume = untrusted_key.split(':', 1)[1]
  829. # kind of ugly, but actual list of volumes is available only
  830. # after creating a VM
  831. assert untrusted_volume in ['root', 'private', 'volatile',
  832. 'kernel']
  833. volume = untrusted_volume
  834. if volume in pools:
  835. raise qubes.api.ProtocolError(
  836. 'duplicated pool:{} parameter'.format(volume))
  837. pools[volume] = self.app.get_pool(untrusted_value)
  838. else:
  839. raise qubes.api.ProtocolError('Invalid param name')
  840. del untrusted_payload
  841. if 'name' not in kwargs or 'label' not in kwargs:
  842. raise qubes.api.ProtocolError('Missing name or label')
  843. if pool and pools:
  844. raise qubes.api.ProtocolError(
  845. 'Only one of \'pool=\' and \'pool:volume=\' can be used')
  846. if kwargs['name'] in self.app.domains:
  847. raise qubes.exc.QubesValueError(
  848. 'VM {} already exists'.format(kwargs['name']))
  849. self.fire_event_for_permission(pool=pool, pools=pools, **kwargs)
  850. vm = self.app.add_new_vm(vm_class, **kwargs)
  851. # TODO: move this to extension (in race-free fashion)
  852. vm.tags.add('created-by-' + str(self.src))
  853. try:
  854. yield from vm.create_on_disk(pool=pool, pools=pools)
  855. except:
  856. del self.app.domains[vm]
  857. raise
  858. self.app.save()
  859. @qubes.api.method('admin.vm.CreateDisposable', no_payload=True,
  860. scope='global', write=True)
  861. @asyncio.coroutine
  862. def create_disposable(self):
  863. assert not self.arg
  864. if self.dest.name == 'dom0':
  865. dispvm_template = self.src.default_dispvm
  866. else:
  867. dispvm_template = self.dest
  868. self.fire_event_for_permission(dispvm_template=dispvm_template)
  869. dispvm = yield from qubes.vm.dispvm.DispVM.from_appvm(dispvm_template)
  870. # TODO: move this to extension (in race-free fashion, better than here)
  871. dispvm.tags.add('disp-created-by-' + str(self.src))
  872. return dispvm.name
  873. @qubes.api.method('admin.vm.Remove', no_payload=True,
  874. scope='global', write=True)
  875. @asyncio.coroutine
  876. def vm_remove(self):
  877. assert not self.arg
  878. self.fire_event_for_permission()
  879. if not self.dest.is_halted():
  880. raise qubes.exc.QubesVMNotHaltedError(self.dest)
  881. if self.dest.installed_by_rpm:
  882. raise qubes.exc.QubesVMInUseError(self.dest, \
  883. "VM installed by package manager: " + self.dest.name)
  884. del self.app.domains[self.dest]
  885. try:
  886. yield from self.dest.remove_from_disk()
  887. except: # pylint: disable=bare-except
  888. self.app.log.exception('Error wile removing VM \'%s\' files',
  889. self.dest.name)
  890. self.app.save()
  891. @qubes.api.method('admin.vm.device.{endpoint}.Available', endpoints=(ep.name
  892. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  893. no_payload=True,
  894. scope='local', read=True)
  895. @asyncio.coroutine
  896. def vm_device_available(self, endpoint):
  897. devclass = endpoint
  898. devices = self.dest.devices[devclass].available()
  899. if self.arg:
  900. devices = [dev for dev in devices if dev.ident == self.arg]
  901. # no duplicated devices, but device may not exists, in which case
  902. # the list is empty
  903. assert len(devices) <= 1
  904. devices = self.fire_event_for_filter(devices, devclass=devclass)
  905. dev_info = {}
  906. for dev in devices:
  907. non_default_attrs = set(attr for attr in dir(dev) if
  908. not attr.startswith('_')).difference((
  909. 'backend_domain', 'ident', 'frontend_domain',
  910. 'description', 'options', 'regex'))
  911. properties_txt = ' '.join(
  912. '{}={!s}'.format(prop, value) for prop, value
  913. in itertools.chain(
  914. ((key, getattr(dev, key)) for key in non_default_attrs),
  915. # keep description as the last one, according to API
  916. # specification
  917. (('description', dev.description),)
  918. ))
  919. assert '\n' not in properties_txt
  920. dev_info[dev.ident] = properties_txt
  921. return ''.join('{} {}\n'.format(ident, dev_info[ident])
  922. for ident in sorted(dev_info))
  923. @qubes.api.method('admin.vm.device.{endpoint}.List', endpoints=(ep.name
  924. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  925. no_payload=True,
  926. scope='local', read=True)
  927. @asyncio.coroutine
  928. def vm_device_list(self, endpoint):
  929. devclass = endpoint
  930. device_assignments = self.dest.devices[devclass].assignments()
  931. if self.arg:
  932. select_backend, select_ident = self.arg.split('+', 1)
  933. device_assignments = [dev for dev in device_assignments
  934. if (str(dev.backend_domain), dev.ident)
  935. == (select_backend, select_ident)]
  936. # no duplicated devices, but device may not exists, in which case
  937. # the list is empty
  938. assert len(device_assignments) <= 1
  939. device_assignments = self.fire_event_for_filter(device_assignments,
  940. devclass=devclass)
  941. dev_info = {}
  942. for dev in device_assignments:
  943. properties_txt = ' '.join(
  944. '{}={!s}'.format(opt, value) for opt, value
  945. in itertools.chain(
  946. dev.options.items(),
  947. (('persistent', 'yes' if dev.persistent else 'no'),)
  948. ))
  949. assert '\n' not in properties_txt
  950. ident = '{!s}+{!s}'.format(dev.backend_domain, dev.ident)
  951. dev_info[ident] = properties_txt
  952. return ''.join('{} {}\n'.format(ident, dev_info[ident])
  953. for ident in sorted(dev_info))
  954. # Attach/Detach action can both modify persistent state (with
  955. # persistent=True) and volatile state of running VM (with persistent=False).
  956. # For this reason, write=True + execute=True
  957. @qubes.api.method('admin.vm.device.{endpoint}.Attach', endpoints=(ep.name
  958. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  959. scope='local', write=True, execute=True)
  960. @asyncio.coroutine
  961. def vm_device_attach(self, endpoint, untrusted_payload):
  962. devclass = endpoint
  963. options = {}
  964. persistent = False
  965. for untrusted_option in untrusted_payload.decode('ascii').split():
  966. try:
  967. untrusted_key, untrusted_value = untrusted_option.split('=', 1)
  968. except ValueError:
  969. raise qubes.api.ProtocolError('Invalid options format')
  970. if untrusted_key == 'persistent':
  971. persistent = qubes.property.bool(None, None, untrusted_value)
  972. else:
  973. allowed_chars_key = string.digits + string.ascii_letters + '-_.'
  974. allowed_chars_value = allowed_chars_key + ',+:'
  975. if any(x not in allowed_chars_key for x in untrusted_key):
  976. raise qubes.api.ProtocolError(
  977. 'Invalid chars in option name')
  978. if any(x not in allowed_chars_value for x in untrusted_value):
  979. raise qubes.api.ProtocolError(
  980. 'Invalid chars in option value')
  981. options[untrusted_key] = untrusted_value
  982. # qrexec already verified that no strange characters are in self.arg
  983. backend_domain, ident = self.arg.split('+', 1)
  984. # may raise KeyError, either on domain or ident
  985. dev = self.app.domains[backend_domain].devices[devclass][ident]
  986. self.fire_event_for_permission(device=dev,
  987. devclass=devclass, persistent=persistent,
  988. options=options)
  989. assignment = qubes.devices.DeviceAssignment(
  990. dev.backend_domain, dev.ident,
  991. options=options, persistent=persistent)
  992. yield from self.dest.devices[devclass].attach(assignment)
  993. self.app.save()
  994. # Attach/Detach action can both modify persistent state (with
  995. # persistent=True) and volatile state of running VM (with persistent=False).
  996. # For this reason, write=True + execute=True
  997. @qubes.api.method('admin.vm.device.{endpoint}.Detach', endpoints=(ep.name
  998. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  999. no_payload=True,
  1000. scope='local', write=True, execute=True)
  1001. @asyncio.coroutine
  1002. def vm_device_detach(self, endpoint):
  1003. devclass = endpoint
  1004. # qrexec already verified that no strange characters are in self.arg
  1005. backend_domain, ident = self.arg.split('+', 1)
  1006. # may raise KeyError; if device isn't found, it will be UnknownDevice
  1007. # instance - but allow it, otherwise it will be impossible to detach
  1008. # already removed device
  1009. dev = self.app.domains[backend_domain].devices[devclass][ident]
  1010. self.fire_event_for_permission(device=dev,
  1011. devclass=devclass)
  1012. assignment = qubes.devices.DeviceAssignment(
  1013. dev.backend_domain, dev.ident)
  1014. yield from self.dest.devices[devclass].detach(assignment)
  1015. self.app.save()
  1016. # Attach/Detach action can both modify persistent state (with
  1017. # persistent=True) and volatile state of running VM (with persistent=False).
  1018. # For this reason, write=True + execute=True
  1019. @qubes.api.method('admin.vm.device.{endpoint}.Set.persistent',
  1020. endpoints=(ep.name
  1021. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  1022. scope='local', write=True, execute=True)
  1023. @asyncio.coroutine
  1024. def vm_device_set_persistent(self, endpoint, untrusted_payload):
  1025. devclass = endpoint
  1026. assert untrusted_payload in (b'True', b'False')
  1027. persistent = untrusted_payload == b'True'
  1028. del untrusted_payload
  1029. # qrexec already verified that no strange characters are in self.arg
  1030. backend_domain, ident = self.arg.split('+', 1)
  1031. # device must be already attached
  1032. matching_devices = [dev for dev
  1033. in self.dest.devices[devclass].attached()
  1034. if dev.backend_domain.name == backend_domain and dev.ident == ident]
  1035. assert len(matching_devices) == 1
  1036. dev = matching_devices[0]
  1037. self.fire_event_for_permission(device=dev,
  1038. persistent=persistent)
  1039. self.dest.devices[devclass].update_persistent(dev, persistent)
  1040. self.app.save()
  1041. @qubes.api.method('admin.vm.firewall.Get', no_payload=True,
  1042. scope='local', read=True)
  1043. @asyncio.coroutine
  1044. def vm_firewall_get(self):
  1045. assert not self.arg
  1046. self.fire_event_for_permission()
  1047. return ''.join('{}\n'.format(rule.api_rule)
  1048. for rule in self.dest.firewall.rules
  1049. if rule.api_rule is not None)
  1050. @qubes.api.method('admin.vm.firewall.Set',
  1051. scope='local', write=True)
  1052. @asyncio.coroutine
  1053. def vm_firewall_set(self, untrusted_payload):
  1054. assert not self.arg
  1055. rules = []
  1056. for untrusted_line in untrusted_payload.decode('ascii',
  1057. errors='strict').splitlines():
  1058. rule = qubes.firewall.Rule.from_api_string(
  1059. untrusted_rule=untrusted_line)
  1060. rules.append(rule)
  1061. self.fire_event_for_permission(rules=rules)
  1062. self.dest.firewall.rules = rules
  1063. self.dest.firewall.save()
  1064. @qubes.api.method('admin.vm.firewall.Reload', no_payload=True,
  1065. scope='local', execute=True)
  1066. @asyncio.coroutine
  1067. def vm_firewall_reload(self):
  1068. assert not self.arg
  1069. self.fire_event_for_permission()
  1070. self.dest.fire_event('firewall-changed')
  1071. @asyncio.coroutine
  1072. def _load_backup_profile(self, profile_name, skip_passphrase=False):
  1073. '''Load backup profile and return :py:class:`qubes.backup.Backup`
  1074. instance
  1075. :param profile_name: name of the profile
  1076. :param skip_passphrase: do not load passphrase - only backup summary
  1077. can be retrieved when this option is in use
  1078. '''
  1079. profile_path = os.path.join(
  1080. qubes.config.backup_profile_dir, profile_name + '.conf')
  1081. with open(profile_path) as profile_file:
  1082. profile_data = yaml.safe_load(profile_file)
  1083. try:
  1084. dest_vm = profile_data['destination_vm']
  1085. dest_path = profile_data['destination_path']
  1086. include_vms = profile_data['include']
  1087. if include_vms is not None:
  1088. # convert old keywords to new keywords
  1089. include_vms = [vm.replace('$', '@') for vm in include_vms]
  1090. exclude_vms = profile_data.get('exclude', [])
  1091. # convert old keywords to new keywords
  1092. exclude_vms = [vm.replace('$', '@') for vm in exclude_vms]
  1093. compression = profile_data.get('compression', True)
  1094. except KeyError as err:
  1095. raise qubes.exc.QubesException(
  1096. 'Invalid backup profile - missing {}'.format(err))
  1097. try:
  1098. dest_vm = self.app.domains[dest_vm]
  1099. except KeyError:
  1100. raise qubes.exc.QubesException(
  1101. 'Invalid destination_vm specified in backup profile')
  1102. if isinstance(dest_vm, qubes.vm.adminvm.AdminVM):
  1103. dest_vm = None
  1104. if skip_passphrase:
  1105. passphrase = None
  1106. elif 'passphrase_text' in profile_data:
  1107. passphrase = profile_data['passphrase_text']
  1108. elif 'passphrase_vm' in profile_data:
  1109. passphrase_vm_name = profile_data['passphrase_vm']
  1110. try:
  1111. passphrase_vm = self.app.domains[passphrase_vm_name]
  1112. except KeyError:
  1113. raise qubes.exc.QubesException(
  1114. 'Invalid backup profile - invalid passphrase_vm')
  1115. try:
  1116. passphrase, _ = yield from passphrase_vm.run_service_for_stdio(
  1117. 'qubes.BackupPassphrase+' + self.arg)
  1118. # make it foolproof against "echo passphrase" implementation
  1119. passphrase = passphrase.strip()
  1120. assert b'\n' not in passphrase
  1121. except subprocess.CalledProcessError:
  1122. raise qubes.exc.QubesException(
  1123. 'Failed to retrieve passphrase from \'{}\' VM'.format(
  1124. passphrase_vm_name))
  1125. else:
  1126. raise qubes.exc.QubesException(
  1127. 'Invalid backup profile - you need to '
  1128. 'specify passphrase_text or passphrase_vm')
  1129. # handle include
  1130. if include_vms is None:
  1131. vms_to_backup = None
  1132. else:
  1133. vms_to_backup = set(vm for vm in self.app.domains
  1134. if any(qubes.utils.match_vm_name_with_special(vm, name)
  1135. for name in include_vms))
  1136. # handle exclude
  1137. vms_to_backup.difference_update(vm for vm in self.app.domains
  1138. if any(qubes.utils.match_vm_name_with_special(vm, name)
  1139. for name in exclude_vms))
  1140. kwargs = {
  1141. 'target_vm': dest_vm,
  1142. 'target_dir': dest_path,
  1143. 'compressed': bool(compression),
  1144. 'passphrase': passphrase,
  1145. }
  1146. if isinstance(compression, str):
  1147. kwargs['compression_filter'] = compression
  1148. backup = qubes.backup.Backup(self.app, vms_to_backup, **kwargs)
  1149. return backup
  1150. def _backup_progress_callback(self, profile_name, progress):
  1151. self.app.fire_event('backup-progress', backup_profile=profile_name,
  1152. progress=progress)
  1153. @qubes.api.method('admin.backup.Execute', no_payload=True,
  1154. scope='global', read=True, execute=True)
  1155. @asyncio.coroutine
  1156. def backup_execute(self):
  1157. assert self.dest.name == 'dom0'
  1158. assert self.arg
  1159. assert '/' not in self.arg
  1160. self.fire_event_for_permission()
  1161. profile_path = os.path.join(qubes.config.backup_profile_dir,
  1162. self.arg + '.conf')
  1163. if not os.path.exists(profile_path):
  1164. raise qubes.api.PermissionDenied(
  1165. 'Backup profile {} does not exist'.format(self.arg))
  1166. if not hasattr(self.app, 'api_admin_running_backups'):
  1167. self.app.api_admin_running_backups = {}
  1168. backup = yield from self._load_backup_profile(self.arg)
  1169. backup.progress_callback = functools.partial(
  1170. self._backup_progress_callback, self.arg)
  1171. # forbid running the same backup operation twice at the time
  1172. assert self.arg not in self.app.api_admin_running_backups
  1173. backup_task = asyncio.ensure_future(backup.backup_do())
  1174. self.app.api_admin_running_backups[self.arg] = backup_task
  1175. try:
  1176. yield from backup_task
  1177. except asyncio.CancelledError:
  1178. raise qubes.exc.QubesException('Backup cancelled')
  1179. finally:
  1180. del self.app.api_admin_running_backups[self.arg]
  1181. @qubes.api.method('admin.backup.Cancel', no_payload=True,
  1182. scope='global', execute=True)
  1183. @asyncio.coroutine
  1184. def backup_cancel(self):
  1185. assert self.dest.name == 'dom0'
  1186. assert self.arg
  1187. assert '/' not in self.arg
  1188. self.fire_event_for_permission()
  1189. if not hasattr(self.app, 'api_admin_running_backups'):
  1190. self.app.api_admin_running_backups = {}
  1191. if self.arg not in self.app.api_admin_running_backups:
  1192. raise qubes.exc.QubesException('Backup operation not running')
  1193. self.app.api_admin_running_backups[self.arg].cancel()
  1194. @qubes.api.method('admin.backup.Info', no_payload=True,
  1195. scope='local', read=True)
  1196. @asyncio.coroutine
  1197. def backup_info(self):
  1198. assert self.dest.name == 'dom0'
  1199. assert self.arg
  1200. assert '/' not in self.arg
  1201. self.fire_event_for_permission()
  1202. profile_path = os.path.join(qubes.config.backup_profile_dir,
  1203. self.arg + '.conf')
  1204. if not os.path.exists(profile_path):
  1205. raise qubes.api.PermissionDenied(
  1206. 'Backup profile {} does not exist'.format(self.arg))
  1207. backup = yield from self._load_backup_profile(self.arg,
  1208. skip_passphrase=True)
  1209. return backup.get_backup_summary()
  1210. def _send_stats_single(self, info_time, info, only_vm, filters,
  1211. id_to_name_map):
  1212. '''A single iteration of sending VM stats
  1213. :param info_time: time of previous iteration
  1214. :param info: information retrieved in previous iteration
  1215. :param only_vm: send information only about this VM
  1216. :param filters: filters to apply on stats before sending
  1217. :param id_to_name_map: ID->VM name map, may be modified
  1218. :return: tuple(info_time, info) - new information (to be passed to
  1219. the next iteration)
  1220. '''
  1221. (info_time, info) = self.app.host.get_vm_stats(info_time, info,
  1222. only_vm=only_vm)
  1223. for vm_id, vm_info in info.items():
  1224. if vm_id not in id_to_name_map:
  1225. try:
  1226. name = \
  1227. self.app.vmm.libvirt_conn.lookupByID(vm_id).name()
  1228. except libvirt.libvirtError as err:
  1229. if err.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1230. # stubdomain or so
  1231. name = None
  1232. else:
  1233. raise
  1234. id_to_name_map[vm_id] = name
  1235. else:
  1236. name = id_to_name_map[vm_id]
  1237. # skip VMs with unknown name
  1238. if name is None:
  1239. continue
  1240. if not list(qubes.api.apply_filters([name], filters)):
  1241. continue
  1242. self.send_event(name, 'vm-stats',
  1243. memory_kb=int(vm_info['memory_kb']),
  1244. cpu_time=int(vm_info['cpu_time'] / 1000000),
  1245. cpu_usage=int(vm_info['cpu_usage']))
  1246. return info_time, info
  1247. @qubes.api.method('admin.vm.Stats', no_payload=True,
  1248. scope='global', read=True)
  1249. @asyncio.coroutine
  1250. def vm_stats(self):
  1251. assert not self.arg
  1252. # run until client connection is terminated
  1253. self.cancellable = True
  1254. # cache event filters, to not call an event each time an event arrives
  1255. stats_filters = self.fire_event_for_permission()
  1256. only_vm = None
  1257. if self.dest.name != 'dom0':
  1258. only_vm = self.dest
  1259. self.send_event(self.app, 'connection-established')
  1260. info_time = None
  1261. info = None
  1262. id_to_name_map = {0: 'dom0'}
  1263. try:
  1264. while True:
  1265. info_time, info = self._send_stats_single(info_time, info,
  1266. only_vm, stats_filters, id_to_name_map)
  1267. yield from asyncio.sleep(self.app.stats_interval)
  1268. except asyncio.CancelledError:
  1269. # valid method to terminate this loop
  1270. pass