admin.py 59 KB

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