admin.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609
  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. pool_size = pool.size
  503. if pool_size is not None:
  504. other_info += 'size={}\n'.format(pool_size)
  505. pool_usage = pool.usage
  506. if pool_usage is not None:
  507. other_info += 'usage={}\n'.format(pool_usage)
  508. try:
  509. included_in = pool.included_in(self.app)
  510. if included_in:
  511. other_info += 'included_in={}\n'.format(str(included_in))
  512. except NotImplementedError:
  513. pass
  514. return ''.join('{}={}\n'.format(prop, val)
  515. for prop, val in sorted(pool.config.items())) + \
  516. other_info
  517. @qubes.api.method('admin.pool.Add',
  518. scope='global', write=True)
  519. @asyncio.coroutine
  520. def pool_add(self, untrusted_payload):
  521. self.enforce(self.dest.name == 'dom0')
  522. drivers = qubes.storage.pool_drivers()
  523. self.enforce(self.arg in drivers)
  524. untrusted_pool_config = untrusted_payload.decode('ascii').splitlines()
  525. del untrusted_payload
  526. self.enforce(all(('=' in line) for line in untrusted_pool_config))
  527. # pairs of (option, value)
  528. untrusted_pool_config = [line.split('=', 1)
  529. for line in untrusted_pool_config]
  530. # reject duplicated options
  531. self.enforce(
  532. len(set(x[0] for x in untrusted_pool_config)) ==
  533. len([x[0] for x in untrusted_pool_config]))
  534. # and convert to dict
  535. untrusted_pool_config = dict(untrusted_pool_config)
  536. self.enforce('name' in untrusted_pool_config)
  537. untrusted_pool_name = untrusted_pool_config.pop('name')
  538. allowed_chars = string.ascii_letters + string.digits + '-_.'
  539. self.enforce(all(c in allowed_chars for c in untrusted_pool_name))
  540. pool_name = untrusted_pool_name
  541. self.enforce(pool_name not in self.app.pools)
  542. driver_parameters = qubes.storage.driver_parameters(self.arg)
  543. self.enforce(
  544. all(key in driver_parameters for key in untrusted_pool_config))
  545. pool_config = untrusted_pool_config
  546. self.fire_event_for_permission(name=pool_name,
  547. pool_config=pool_config)
  548. yield from self.app.add_pool(name=pool_name, driver=self.arg,
  549. **pool_config)
  550. self.app.save()
  551. @qubes.api.method('admin.pool.Remove', no_payload=True,
  552. scope='global', write=True)
  553. @asyncio.coroutine
  554. def pool_remove(self):
  555. self.enforce(self.dest.name == 'dom0')
  556. self.enforce(self.arg in self.app.pools.keys())
  557. self.fire_event_for_permission()
  558. yield from self.app.remove_pool(self.arg)
  559. self.app.save()
  560. @qubes.api.method('admin.pool.Set.revisions_to_keep',
  561. scope='global', write=True)
  562. @asyncio.coroutine
  563. def pool_set_revisions_to_keep(self, untrusted_payload):
  564. self.enforce(self.dest.name == 'dom0')
  565. self.enforce(self.arg in self.app.pools.keys())
  566. pool = self.app.pools[self.arg]
  567. try:
  568. untrusted_value = int(untrusted_payload.decode('ascii'))
  569. except (UnicodeDecodeError, ValueError):
  570. raise qubes.api.ProtocolError('Invalid value')
  571. del untrusted_payload
  572. self.enforce(untrusted_value >= 0)
  573. newvalue = untrusted_value
  574. del untrusted_value
  575. self.fire_event_for_permission(newvalue=newvalue)
  576. pool.revisions_to_keep = newvalue
  577. self.app.save()
  578. @qubes.api.method('admin.label.List', no_payload=True,
  579. scope='global', read=True)
  580. @asyncio.coroutine
  581. def label_list(self):
  582. self.enforce(self.dest.name == 'dom0')
  583. self.enforce(not self.arg)
  584. labels = self.fire_event_for_filter(self.app.labels.values())
  585. return ''.join('{}\n'.format(label.name) for label in labels)
  586. @qubes.api.method('admin.label.Get', no_payload=True,
  587. scope='global', read=True)
  588. @asyncio.coroutine
  589. def label_get(self):
  590. self.enforce(self.dest.name == 'dom0')
  591. try:
  592. label = self.app.get_label(self.arg)
  593. except KeyError:
  594. raise qubes.exc.QubesValueError
  595. self.fire_event_for_permission(label=label)
  596. return label.color
  597. @qubes.api.method('admin.label.Index', no_payload=True,
  598. scope='global', read=True)
  599. @asyncio.coroutine
  600. def label_index(self):
  601. self.enforce(self.dest.name == 'dom0')
  602. try:
  603. label = self.app.get_label(self.arg)
  604. except KeyError:
  605. raise qubes.exc.QubesValueError
  606. self.fire_event_for_permission(label=label)
  607. return str(label.index)
  608. @qubes.api.method('admin.label.Create',
  609. scope='global', write=True)
  610. @asyncio.coroutine
  611. def label_create(self, untrusted_payload):
  612. self.enforce(self.dest.name == 'dom0')
  613. # don't confuse label name with label index
  614. self.enforce(not self.arg.isdigit())
  615. allowed_chars = string.ascii_letters + string.digits + '-_.'
  616. self.enforce(all(c in allowed_chars for c in self.arg))
  617. try:
  618. self.app.get_label(self.arg)
  619. except KeyError:
  620. # ok, no such label yet
  621. pass
  622. else:
  623. raise qubes.exc.QubesValueError('label already exists')
  624. untrusted_payload = untrusted_payload.decode('ascii').strip()
  625. self.enforce(len(untrusted_payload) == 8)
  626. self.enforce(untrusted_payload.startswith('0x'))
  627. # besides prefix, only hex digits are allowed
  628. self.enforce(all(x in string.hexdigits for x in untrusted_payload[2:]))
  629. # SEE: #2732
  630. color = untrusted_payload
  631. self.fire_event_for_permission(color=color)
  632. # allocate new index, but make sure it's outside of default labels set
  633. new_index = max(
  634. qubes.config.max_default_label, *self.app.labels.keys()) + 1
  635. label = qubes.Label(new_index, color, self.arg)
  636. self.app.labels[new_index] = label
  637. self.app.save()
  638. @qubes.api.method('admin.label.Remove', no_payload=True,
  639. scope='global', write=True)
  640. @asyncio.coroutine
  641. def label_remove(self):
  642. self.enforce(self.dest.name == 'dom0')
  643. try:
  644. label = self.app.get_label(self.arg)
  645. except KeyError:
  646. raise qubes.exc.QubesValueError
  647. # don't allow removing default labels
  648. self.enforce(label.index > qubes.config.max_default_label)
  649. # FIXME: this should be in app.add_label()
  650. for vm in self.app.domains:
  651. if vm.label == label:
  652. raise qubes.exc.QubesException('label still in use')
  653. self.fire_event_for_permission(label=label)
  654. del self.app.labels[label.index]
  655. self.app.save()
  656. @qubes.api.method('admin.vm.Start', no_payload=True,
  657. scope='local', execute=True)
  658. @asyncio.coroutine
  659. def vm_start(self):
  660. self.enforce(not self.arg)
  661. self.fire_event_for_permission()
  662. try:
  663. yield from self.dest.start()
  664. except libvirt.libvirtError as e:
  665. # change to QubesException, so will be reported to the user
  666. raise qubes.exc.QubesException('Start failed: ' + str(e) +
  667. ', see /var/log/libvirt/libxl/libxl-driver.log for details')
  668. @qubes.api.method('admin.vm.Shutdown', no_payload=True,
  669. scope='local', execute=True)
  670. @asyncio.coroutine
  671. def vm_shutdown(self):
  672. self.enforce(not self.arg)
  673. self.fire_event_for_permission()
  674. yield from self.dest.shutdown()
  675. @qubes.api.method('admin.vm.Pause', no_payload=True,
  676. scope='local', execute=True)
  677. @asyncio.coroutine
  678. def vm_pause(self):
  679. self.enforce(not self.arg)
  680. self.fire_event_for_permission()
  681. yield from self.dest.pause()
  682. @qubes.api.method('admin.vm.Unpause', no_payload=True,
  683. scope='local', execute=True)
  684. @asyncio.coroutine
  685. def vm_unpause(self):
  686. self.enforce(not self.arg)
  687. self.fire_event_for_permission()
  688. yield from self.dest.unpause()
  689. @qubes.api.method('admin.vm.Kill', no_payload=True,
  690. scope='local', execute=True)
  691. @asyncio.coroutine
  692. def vm_kill(self):
  693. self.enforce(not self.arg)
  694. self.fire_event_for_permission()
  695. yield from self.dest.kill()
  696. @qubes.api.method('admin.Events', no_payload=True,
  697. scope='global', read=True)
  698. @asyncio.coroutine
  699. def events(self):
  700. self.enforce(not self.arg)
  701. # run until client connection is terminated
  702. self.cancellable = True
  703. wait_for_cancel = asyncio.get_event_loop().create_future()
  704. # cache event filters, to not call an event each time an event arrives
  705. event_filters = self.fire_event_for_permission()
  706. dispatcher = QubesMgmtEventsDispatcher(event_filters, self.send_event)
  707. if self.dest.name == 'dom0':
  708. self.app.add_handler('*', dispatcher.app_handler)
  709. self.app.add_handler('domain-add', dispatcher.on_domain_add)
  710. self.app.add_handler('domain-delete', dispatcher.on_domain_delete)
  711. for vm in self.app.domains:
  712. vm.add_handler('*', dispatcher.vm_handler)
  713. else:
  714. self.dest.add_handler('*', dispatcher.vm_handler)
  715. # send artificial event as a confirmation that connection is established
  716. self.send_event(self.app, 'connection-established')
  717. try:
  718. yield from wait_for_cancel
  719. except asyncio.CancelledError:
  720. # the above waiting was already interrupted, this is all we need
  721. pass
  722. if self.dest.name == 'dom0':
  723. self.app.remove_handler('*', dispatcher.app_handler)
  724. self.app.remove_handler('domain-add', dispatcher.on_domain_add)
  725. self.app.remove_handler('domain-delete',
  726. dispatcher.on_domain_delete)
  727. for vm in self.app.domains:
  728. vm.remove_handler('*', dispatcher.vm_handler)
  729. else:
  730. self.dest.remove_handler('*', dispatcher.vm_handler)
  731. @qubes.api.method('admin.vm.feature.List', no_payload=True,
  732. scope='local', read=True)
  733. @asyncio.coroutine
  734. def vm_feature_list(self):
  735. self.enforce(not self.arg)
  736. features = self.fire_event_for_filter(self.dest.features.keys())
  737. return ''.join('{}\n'.format(feature) for feature in features)
  738. @qubes.api.method('admin.vm.feature.Get', no_payload=True,
  739. scope='local', read=True)
  740. @asyncio.coroutine
  741. def vm_feature_get(self):
  742. # validation of self.arg done by qrexec-policy is enough
  743. self.fire_event_for_permission()
  744. try:
  745. value = self.dest.features[self.arg]
  746. except KeyError:
  747. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  748. return value
  749. @qubes.api.method('admin.vm.feature.CheckWithTemplate', no_payload=True,
  750. scope='local', read=True)
  751. @asyncio.coroutine
  752. def vm_feature_checkwithtemplate(self):
  753. # validation of self.arg done by qrexec-policy is enough
  754. self.fire_event_for_permission()
  755. try:
  756. value = self.dest.features.check_with_template(self.arg)
  757. except KeyError:
  758. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  759. return value
  760. @qubes.api.method('admin.vm.feature.CheckWithNetvm', no_payload=True,
  761. scope='local', read=True)
  762. @asyncio.coroutine
  763. def vm_feature_checkwithnetvm(self):
  764. # validation of self.arg done by qrexec-policy is enough
  765. self.fire_event_for_permission()
  766. try:
  767. value = self.dest.features.check_with_netvm(self.arg)
  768. except KeyError:
  769. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  770. return value
  771. @qubes.api.method('admin.vm.feature.CheckWithAdminVM', no_payload=True,
  772. scope='local', read=True)
  773. @asyncio.coroutine
  774. def vm_feature_checkwithadminvm(self):
  775. # validation of self.arg done by qrexec-policy is enough
  776. self.fire_event_for_permission()
  777. try:
  778. value = self.dest.features.check_with_adminvm(self.arg)
  779. except KeyError:
  780. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  781. return value
  782. @qubes.api.method('admin.vm.feature.CheckWithTemplateAndAdminVM',
  783. no_payload=True, scope='local', read=True)
  784. @asyncio.coroutine
  785. def vm_feature_checkwithtpladminvm(self):
  786. # validation of self.arg done by qrexec-policy is enough
  787. self.fire_event_for_permission()
  788. try:
  789. value = self.dest.features.check_with_template_and_adminvm(self.arg)
  790. except KeyError:
  791. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  792. return value
  793. @qubes.api.method('admin.vm.feature.Remove', no_payload=True,
  794. scope='local', write=True)
  795. @asyncio.coroutine
  796. def vm_feature_remove(self):
  797. # validation of self.arg done by qrexec-policy is enough
  798. self.fire_event_for_permission()
  799. try:
  800. del self.dest.features[self.arg]
  801. except KeyError:
  802. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  803. self.app.save()
  804. @qubes.api.method('admin.vm.feature.Set',
  805. scope='local', write=True)
  806. @asyncio.coroutine
  807. def vm_feature_set(self, untrusted_payload):
  808. # validation of self.arg done by qrexec-policy is enough
  809. value = untrusted_payload.decode('ascii', errors='strict')
  810. del untrusted_payload
  811. self.fire_event_for_permission(value=value)
  812. self.dest.features[self.arg] = value
  813. self.app.save()
  814. @qubes.api.method('admin.vm.Create.{endpoint}', endpoints=(ep.name
  815. for ep in pkg_resources.iter_entry_points(qubes.vm.VM_ENTRY_POINT)),
  816. scope='global', write=True)
  817. @asyncio.coroutine
  818. def vm_create(self, endpoint, untrusted_payload=None):
  819. return self._vm_create(endpoint, allow_pool=False,
  820. untrusted_payload=untrusted_payload)
  821. @qubes.api.method('admin.vm.CreateInPool.{endpoint}', endpoints=(ep.name
  822. for ep in pkg_resources.iter_entry_points(qubes.vm.VM_ENTRY_POINT)),
  823. scope='global', write=True)
  824. @asyncio.coroutine
  825. def vm_create_in_pool(self, endpoint, untrusted_payload=None):
  826. return self._vm_create(endpoint, allow_pool=True,
  827. untrusted_payload=untrusted_payload)
  828. def _vm_create(self, vm_type, allow_pool=False, untrusted_payload=None):
  829. self.enforce(self.dest.name == 'dom0')
  830. kwargs = {}
  831. pool = None
  832. pools = {}
  833. # this will raise exception if none is found
  834. vm_class = qubes.utils.get_entry_point_one(qubes.vm.VM_ENTRY_POINT,
  835. vm_type)
  836. # if argument is given, it needs to be a valid template, and only
  837. # when given VM class do need a template
  838. if self.arg:
  839. if hasattr(vm_class, 'template'):
  840. if self.arg not in self.app.domains:
  841. raise qubes.api.PermissionDenied(
  842. 'Template {} does not exist'.format(self.arg))
  843. kwargs['template'] = self.app.domains[self.arg]
  844. else:
  845. raise qubes.exc.QubesValueError(
  846. '{} cannot be based on template'.format(vm_type))
  847. for untrusted_param in untrusted_payload.decode('ascii',
  848. errors='strict').split(' '):
  849. untrusted_key, untrusted_value = untrusted_param.split('=', 1)
  850. if untrusted_key in kwargs:
  851. raise qubes.api.ProtocolError('duplicated parameters')
  852. if untrusted_key == 'name':
  853. qubes.vm.validate_name(None, None, untrusted_value)
  854. kwargs['name'] = untrusted_value
  855. elif untrusted_key == 'label':
  856. # don't confuse label name with label index
  857. self.enforce(not untrusted_value.isdigit())
  858. allowed_chars = string.ascii_letters + string.digits + '-_.'
  859. self.enforce(all(c in allowed_chars for c in untrusted_value))
  860. try:
  861. kwargs['label'] = self.app.get_label(untrusted_value)
  862. except KeyError:
  863. raise qubes.exc.QubesValueError
  864. elif untrusted_key == 'pool' and allow_pool:
  865. if pool is not None:
  866. raise qubes.api.ProtocolError('duplicated pool parameter')
  867. pool = self.app.get_pool(untrusted_value)
  868. elif untrusted_key.startswith('pool:') and allow_pool:
  869. untrusted_volume = untrusted_key.split(':', 1)[1]
  870. # kind of ugly, but actual list of volumes is available only
  871. # after creating a VM
  872. self.enforce(untrusted_volume in [
  873. 'root', 'private', 'volatile', 'kernel'])
  874. volume = untrusted_volume
  875. if volume in pools:
  876. raise qubes.api.ProtocolError(
  877. 'duplicated pool:{} parameter'.format(volume))
  878. pools[volume] = self.app.get_pool(untrusted_value)
  879. else:
  880. raise qubes.api.ProtocolError('Invalid param name')
  881. del untrusted_payload
  882. if 'name' not in kwargs or 'label' not in kwargs:
  883. raise qubes.api.ProtocolError('Missing name or label')
  884. if pool and pools:
  885. raise qubes.api.ProtocolError(
  886. 'Only one of \'pool=\' and \'pool:volume=\' can be used')
  887. if kwargs['name'] in self.app.domains:
  888. raise qubes.exc.QubesValueError(
  889. 'VM {} already exists'.format(kwargs['name']))
  890. self.fire_event_for_permission(pool=pool, pools=pools, **kwargs)
  891. vm = self.app.add_new_vm(vm_class, **kwargs)
  892. # TODO: move this to extension (in race-free fashion)
  893. vm.tags.add('created-by-' + str(self.src))
  894. try:
  895. yield from vm.create_on_disk(pool=pool, pools=pools)
  896. except:
  897. del self.app.domains[vm]
  898. raise
  899. self.app.save()
  900. @qubes.api.method('admin.vm.CreateDisposable', no_payload=True,
  901. scope='global', write=True)
  902. @asyncio.coroutine
  903. def create_disposable(self):
  904. self.enforce(not self.arg)
  905. if self.dest.name == 'dom0':
  906. dispvm_template = self.src.default_dispvm
  907. else:
  908. dispvm_template = self.dest
  909. self.fire_event_for_permission(dispvm_template=dispvm_template)
  910. dispvm = yield from qubes.vm.dispvm.DispVM.from_appvm(dispvm_template)
  911. # TODO: move this to extension (in race-free fashion, better than here)
  912. dispvm.tags.add('disp-created-by-' + str(self.src))
  913. return dispvm.name
  914. @qubes.api.method('admin.vm.Remove', no_payload=True,
  915. scope='global', write=True)
  916. @asyncio.coroutine
  917. def vm_remove(self):
  918. self.enforce(not self.arg)
  919. self.fire_event_for_permission()
  920. if not self.dest.is_halted():
  921. raise qubes.exc.QubesVMNotHaltedError(self.dest)
  922. if self.dest.installed_by_rpm:
  923. raise qubes.exc.QubesVMInUseError(self.dest, \
  924. "VM installed by package manager: " + self.dest.name)
  925. del self.app.domains[self.dest]
  926. try:
  927. yield from self.dest.remove_from_disk()
  928. except: # pylint: disable=bare-except
  929. self.app.log.exception('Error while removing VM \'%s\' files',
  930. self.dest.name)
  931. self.app.save()
  932. @qubes.api.method('admin.deviceclass.List', no_payload=True,
  933. scope='global', read=True)
  934. @asyncio.coroutine
  935. def deviceclass_list(self):
  936. """List all DEVICES classes"""
  937. self.enforce(not self.arg)
  938. self.enforce(self.dest.name == 'dom0')
  939. entrypoints = self.fire_event_for_filter(
  940. pkg_resources.iter_entry_points('qubes.devices'))
  941. return ''.join('{}\n'.format(ep.name) for ep in entrypoints)
  942. @qubes.api.method('admin.vm.device.{endpoint}.Available', endpoints=(ep.name
  943. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  944. no_payload=True,
  945. scope='local', read=True)
  946. @asyncio.coroutine
  947. def vm_device_available(self, endpoint):
  948. devclass = endpoint
  949. devices = self.dest.devices[devclass].available()
  950. if self.arg:
  951. devices = [dev for dev in devices if dev.ident == self.arg]
  952. # no duplicated devices, but device may not exists, in which case
  953. # the list is empty
  954. self.enforce(len(devices) <= 1)
  955. devices = self.fire_event_for_filter(devices, devclass=devclass)
  956. dev_info = {}
  957. for dev in devices:
  958. non_default_attrs = set(attr for attr in dir(dev) if
  959. not attr.startswith('_')).difference((
  960. 'backend_domain', 'ident', 'frontend_domain',
  961. 'description', 'options', 'regex'))
  962. properties_txt = ' '.join(
  963. '{}={!s}'.format(prop, value) for prop, value
  964. in itertools.chain(
  965. ((key, getattr(dev, key)) for key in non_default_attrs),
  966. # keep description as the last one, according to API
  967. # specification
  968. (('description', dev.description),)
  969. ))
  970. self.enforce('\n' not in properties_txt)
  971. dev_info[dev.ident] = properties_txt
  972. return ''.join('{} {}\n'.format(ident, dev_info[ident])
  973. for ident in sorted(dev_info))
  974. @qubes.api.method('admin.vm.device.{endpoint}.List', endpoints=(ep.name
  975. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  976. no_payload=True,
  977. scope='local', read=True)
  978. @asyncio.coroutine
  979. def vm_device_list(self, endpoint):
  980. devclass = endpoint
  981. device_assignments = self.dest.devices[devclass].assignments()
  982. if self.arg:
  983. select_backend, select_ident = self.arg.split('+', 1)
  984. device_assignments = [dev for dev in device_assignments
  985. if (str(dev.backend_domain), dev.ident)
  986. == (select_backend, select_ident)]
  987. # no duplicated devices, but device may not exists, in which case
  988. # the list is empty
  989. self.enforce(len(device_assignments) <= 1)
  990. device_assignments = self.fire_event_for_filter(device_assignments,
  991. devclass=devclass)
  992. dev_info = {}
  993. for dev in device_assignments:
  994. properties_txt = ' '.join(
  995. '{}={!s}'.format(opt, value) for opt, value
  996. in itertools.chain(
  997. dev.options.items(),
  998. (('persistent', 'yes' if dev.persistent else 'no'),)
  999. ))
  1000. self.enforce('\n' not in properties_txt)
  1001. ident = '{!s}+{!s}'.format(dev.backend_domain, dev.ident)
  1002. dev_info[ident] = properties_txt
  1003. return ''.join('{} {}\n'.format(ident, dev_info[ident])
  1004. for ident in sorted(dev_info))
  1005. # Attach/Detach action can both modify persistent state (with
  1006. # persistent=True) and volatile state of running VM (with persistent=False).
  1007. # For this reason, write=True + execute=True
  1008. @qubes.api.method('admin.vm.device.{endpoint}.Attach', endpoints=(ep.name
  1009. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  1010. scope='local', write=True, execute=True)
  1011. @asyncio.coroutine
  1012. def vm_device_attach(self, endpoint, untrusted_payload):
  1013. devclass = endpoint
  1014. options = {}
  1015. persistent = False
  1016. for untrusted_option in untrusted_payload.decode('ascii').split():
  1017. try:
  1018. untrusted_key, untrusted_value = untrusted_option.split('=', 1)
  1019. except ValueError:
  1020. raise qubes.api.ProtocolError('Invalid options format')
  1021. if untrusted_key == 'persistent':
  1022. persistent = qubes.property.bool(None, None, untrusted_value)
  1023. else:
  1024. allowed_chars_key = string.digits + string.ascii_letters + '-_.'
  1025. allowed_chars_value = allowed_chars_key + ',+:'
  1026. if any(x not in allowed_chars_key for x in untrusted_key):
  1027. raise qubes.api.ProtocolError(
  1028. 'Invalid chars in option name')
  1029. if any(x not in allowed_chars_value for x in untrusted_value):
  1030. raise qubes.api.ProtocolError(
  1031. 'Invalid chars in option value')
  1032. options[untrusted_key] = untrusted_value
  1033. # qrexec already verified that no strange characters are in self.arg
  1034. backend_domain, ident = self.arg.split('+', 1)
  1035. # may raise KeyError, either on domain or ident
  1036. dev = self.app.domains[backend_domain].devices[devclass][ident]
  1037. self.fire_event_for_permission(device=dev,
  1038. devclass=devclass, persistent=persistent,
  1039. options=options)
  1040. assignment = qubes.devices.DeviceAssignment(
  1041. dev.backend_domain, dev.ident,
  1042. options=options, persistent=persistent)
  1043. yield from self.dest.devices[devclass].attach(assignment)
  1044. self.app.save()
  1045. # Attach/Detach action can both modify persistent state (with
  1046. # persistent=True) and volatile state of running VM (with persistent=False).
  1047. # For this reason, write=True + execute=True
  1048. @qubes.api.method('admin.vm.device.{endpoint}.Detach', endpoints=(ep.name
  1049. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  1050. no_payload=True,
  1051. scope='local', write=True, execute=True)
  1052. @asyncio.coroutine
  1053. def vm_device_detach(self, endpoint):
  1054. devclass = endpoint
  1055. # qrexec already verified that no strange characters are in self.arg
  1056. backend_domain, ident = self.arg.split('+', 1)
  1057. # may raise KeyError; if device isn't found, it will be UnknownDevice
  1058. # instance - but allow it, otherwise it will be impossible to detach
  1059. # already removed device
  1060. dev = self.app.domains[backend_domain].devices[devclass][ident]
  1061. self.fire_event_for_permission(device=dev,
  1062. devclass=devclass)
  1063. assignment = qubes.devices.DeviceAssignment(
  1064. dev.backend_domain, dev.ident)
  1065. yield from self.dest.devices[devclass].detach(assignment)
  1066. self.app.save()
  1067. # Attach/Detach action can both modify persistent state (with
  1068. # persistent=True) and volatile state of running VM (with persistent=False).
  1069. # For this reason, write=True + execute=True
  1070. @qubes.api.method('admin.vm.device.{endpoint}.Set.persistent',
  1071. endpoints=(ep.name
  1072. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  1073. scope='local', write=True, execute=True)
  1074. @asyncio.coroutine
  1075. def vm_device_set_persistent(self, endpoint, untrusted_payload):
  1076. devclass = endpoint
  1077. self.enforce(untrusted_payload in (b'True', b'False'))
  1078. persistent = untrusted_payload == b'True'
  1079. del untrusted_payload
  1080. # qrexec already verified that no strange characters are in self.arg
  1081. backend_domain, ident = self.arg.split('+', 1)
  1082. # device must be already attached
  1083. matching_devices = [dev for dev
  1084. in self.dest.devices[devclass].attached()
  1085. if dev.backend_domain.name == backend_domain and dev.ident == ident]
  1086. self.enforce(len(matching_devices) == 1)
  1087. dev = matching_devices[0]
  1088. self.fire_event_for_permission(device=dev,
  1089. persistent=persistent)
  1090. self.dest.devices[devclass].update_persistent(dev, persistent)
  1091. self.app.save()
  1092. @qubes.api.method('admin.vm.firewall.Get', no_payload=True,
  1093. scope='local', read=True)
  1094. @asyncio.coroutine
  1095. def vm_firewall_get(self):
  1096. self.enforce(not self.arg)
  1097. self.fire_event_for_permission()
  1098. return ''.join('{}\n'.format(rule.api_rule)
  1099. for rule in self.dest.firewall.rules
  1100. if rule.api_rule is not None)
  1101. @qubes.api.method('admin.vm.firewall.Set',
  1102. scope='local', write=True)
  1103. @asyncio.coroutine
  1104. def vm_firewall_set(self, untrusted_payload):
  1105. self.enforce(not self.arg)
  1106. rules = []
  1107. for untrusted_line in untrusted_payload.decode('ascii',
  1108. errors='strict').splitlines():
  1109. rule = qubes.firewall.Rule.from_api_string(
  1110. untrusted_rule=untrusted_line)
  1111. rules.append(rule)
  1112. self.fire_event_for_permission(rules=rules)
  1113. self.dest.firewall.rules = rules
  1114. self.dest.firewall.save()
  1115. @qubes.api.method('admin.vm.firewall.Reload', no_payload=True,
  1116. scope='local', execute=True)
  1117. @asyncio.coroutine
  1118. def vm_firewall_reload(self):
  1119. self.enforce(not self.arg)
  1120. self.fire_event_for_permission()
  1121. self.dest.fire_event('firewall-changed')
  1122. @asyncio.coroutine
  1123. def _load_backup_profile(self, profile_name, skip_passphrase=False):
  1124. """Load backup profile and return :py:class:`qubes.backup.Backup`
  1125. instance
  1126. :param profile_name: name of the profile
  1127. :param skip_passphrase: do not load passphrase - only backup summary
  1128. can be retrieved when this option is in use
  1129. """
  1130. profile_path = os.path.join(
  1131. qubes.config.backup_profile_dir, profile_name + '.conf')
  1132. with open(profile_path) as profile_file:
  1133. profile_data = yaml.safe_load(profile_file)
  1134. try:
  1135. dest_vm = profile_data['destination_vm']
  1136. dest_path = profile_data['destination_path']
  1137. include_vms = profile_data['include']
  1138. if include_vms is not None:
  1139. # convert old keywords to new keywords
  1140. include_vms = [vm.replace('$', '@') for vm in include_vms]
  1141. exclude_vms = profile_data.get('exclude', [])
  1142. # convert old keywords to new keywords
  1143. exclude_vms = [vm.replace('$', '@') for vm in exclude_vms]
  1144. compression = profile_data.get('compression', True)
  1145. except KeyError as err:
  1146. raise qubes.exc.QubesException(
  1147. 'Invalid backup profile - missing {}'.format(err))
  1148. try:
  1149. dest_vm = self.app.domains[dest_vm]
  1150. except KeyError:
  1151. raise qubes.exc.QubesException(
  1152. 'Invalid destination_vm specified in backup profile')
  1153. if isinstance(dest_vm, qubes.vm.adminvm.AdminVM):
  1154. dest_vm = None
  1155. if skip_passphrase:
  1156. passphrase = None
  1157. elif 'passphrase_text' in profile_data:
  1158. passphrase = profile_data['passphrase_text']
  1159. elif 'passphrase_vm' in profile_data:
  1160. passphrase_vm_name = profile_data['passphrase_vm']
  1161. try:
  1162. passphrase_vm = self.app.domains[passphrase_vm_name]
  1163. except KeyError:
  1164. raise qubes.exc.QubesException(
  1165. 'Invalid backup profile - invalid passphrase_vm')
  1166. try:
  1167. passphrase, _ = yield from passphrase_vm.run_service_for_stdio(
  1168. 'qubes.BackupPassphrase+' + self.arg)
  1169. # make it foolproof against "echo passphrase" implementation
  1170. passphrase = passphrase.strip()
  1171. self.enforce(b'\n' not in passphrase)
  1172. except subprocess.CalledProcessError:
  1173. raise qubes.exc.QubesException(
  1174. 'Failed to retrieve passphrase from \'{}\' VM'.format(
  1175. passphrase_vm_name))
  1176. else:
  1177. raise qubes.exc.QubesException(
  1178. 'Invalid backup profile - you need to '
  1179. 'specify passphrase_text or passphrase_vm')
  1180. # handle include
  1181. if include_vms is None:
  1182. vms_to_backup = None
  1183. else:
  1184. vms_to_backup = set(vm for vm in self.app.domains
  1185. if any(qubes.utils.match_vm_name_with_special(vm, name)
  1186. for name in include_vms))
  1187. # handle exclude
  1188. vms_to_exclude = set(vm.name for vm in self.app.domains
  1189. if any(qubes.utils.match_vm_name_with_special(vm, name)
  1190. for name in exclude_vms))
  1191. kwargs = {
  1192. 'target_vm': dest_vm,
  1193. 'target_dir': dest_path,
  1194. 'compressed': bool(compression),
  1195. 'passphrase': passphrase,
  1196. }
  1197. if isinstance(compression, str):
  1198. kwargs['compression_filter'] = compression
  1199. backup = qubes.backup.Backup(self.app, vms_to_backup, vms_to_exclude,
  1200. **kwargs)
  1201. return backup
  1202. def _backup_progress_callback(self, profile_name, progress):
  1203. self.app.fire_event('backup-progress', backup_profile=profile_name,
  1204. progress=progress)
  1205. @qubes.api.method('admin.backup.Execute', no_payload=True,
  1206. scope='global', read=True, execute=True)
  1207. @asyncio.coroutine
  1208. def backup_execute(self):
  1209. self.enforce(self.dest.name == 'dom0')
  1210. self.enforce(self.arg)
  1211. self.enforce('/' not in self.arg)
  1212. self.fire_event_for_permission()
  1213. profile_path = os.path.join(qubes.config.backup_profile_dir,
  1214. self.arg + '.conf')
  1215. if not os.path.exists(profile_path):
  1216. raise qubes.api.PermissionDenied(
  1217. 'Backup profile {} does not exist'.format(self.arg))
  1218. if not hasattr(self.app, 'api_admin_running_backups'):
  1219. self.app.api_admin_running_backups = {}
  1220. backup = yield from self._load_backup_profile(self.arg)
  1221. backup.progress_callback = functools.partial(
  1222. self._backup_progress_callback, self.arg)
  1223. # forbid running the same backup operation twice at the time
  1224. self.enforce(self.arg not in self.app.api_admin_running_backups)
  1225. backup_task = asyncio.ensure_future(backup.backup_do())
  1226. self.app.api_admin_running_backups[self.arg] = backup_task
  1227. try:
  1228. yield from backup_task
  1229. except asyncio.CancelledError:
  1230. raise qubes.exc.QubesException('Backup cancelled')
  1231. finally:
  1232. del self.app.api_admin_running_backups[self.arg]
  1233. @qubes.api.method('admin.backup.Cancel', no_payload=True,
  1234. scope='global', execute=True)
  1235. @asyncio.coroutine
  1236. def backup_cancel(self):
  1237. self.enforce(self.dest.name == 'dom0')
  1238. self.enforce(self.arg)
  1239. self.enforce('/' not in self.arg)
  1240. self.fire_event_for_permission()
  1241. if not hasattr(self.app, 'api_admin_running_backups'):
  1242. self.app.api_admin_running_backups = {}
  1243. if self.arg not in self.app.api_admin_running_backups:
  1244. raise qubes.exc.QubesException('Backup operation not running')
  1245. self.app.api_admin_running_backups[self.arg].cancel()
  1246. @qubes.api.method('admin.backup.Info', no_payload=True,
  1247. scope='local', read=True)
  1248. @asyncio.coroutine
  1249. def backup_info(self):
  1250. self.enforce(self.dest.name == 'dom0')
  1251. self.enforce(self.arg)
  1252. self.enforce('/' not in self.arg)
  1253. self.fire_event_for_permission()
  1254. profile_path = os.path.join(qubes.config.backup_profile_dir,
  1255. self.arg + '.conf')
  1256. if not os.path.exists(profile_path):
  1257. raise qubes.api.PermissionDenied(
  1258. 'Backup profile {} does not exist'.format(self.arg))
  1259. backup = yield from self._load_backup_profile(self.arg,
  1260. skip_passphrase=True)
  1261. return backup.get_backup_summary()
  1262. def _send_stats_single(self, info_time, info, only_vm, filters,
  1263. id_to_name_map):
  1264. """A single iteration of sending VM stats
  1265. :param info_time: time of previous iteration
  1266. :param info: information retrieved in previous iteration
  1267. :param only_vm: send information only about this VM
  1268. :param filters: filters to apply on stats before sending
  1269. :param id_to_name_map: ID->VM name map, may be modified
  1270. :return: tuple(info_time, info) - new information (to be passed to
  1271. the next iteration)
  1272. """
  1273. (info_time, info) = self.app.host.get_vm_stats(info_time, info,
  1274. only_vm=only_vm)
  1275. for vm_id, vm_info in info.items():
  1276. if vm_id not in id_to_name_map:
  1277. try:
  1278. name = \
  1279. self.app.vmm.libvirt_conn.lookupByID(vm_id).name()
  1280. except libvirt.libvirtError as err:
  1281. if err.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1282. # stubdomain or so
  1283. name = None
  1284. else:
  1285. raise
  1286. id_to_name_map[vm_id] = name
  1287. else:
  1288. name = id_to_name_map[vm_id]
  1289. # skip VMs with unknown name
  1290. if name is None:
  1291. continue
  1292. if not list(qubes.api.apply_filters([name], filters)):
  1293. continue
  1294. self.send_event(name, 'vm-stats',
  1295. memory_kb=int(vm_info['memory_kb']),
  1296. cpu_time=int(vm_info['cpu_time'] / 1000000),
  1297. cpu_usage=int(vm_info['cpu_usage']))
  1298. return info_time, info
  1299. @qubes.api.method('admin.vm.Stats', no_payload=True,
  1300. scope='global', read=True)
  1301. @asyncio.coroutine
  1302. def vm_stats(self):
  1303. self.enforce(not self.arg)
  1304. # run until client connection is terminated
  1305. self.cancellable = True
  1306. # cache event filters, to not call an event each time an event arrives
  1307. stats_filters = self.fire_event_for_permission()
  1308. only_vm = None
  1309. if self.dest.name != 'dom0':
  1310. only_vm = self.dest
  1311. self.send_event(self.app, 'connection-established')
  1312. info_time = None
  1313. info = None
  1314. id_to_name_map = {0: 'dom0'}
  1315. try:
  1316. while True:
  1317. info_time, info = self._send_stats_single(info_time, info,
  1318. only_vm, stats_filters, id_to_name_map)
  1319. yield from asyncio.sleep(self.app.stats_interval)
  1320. except asyncio.CancelledError:
  1321. # valid method to terminate this loop
  1322. pass