admin.py 54 KB

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