admin.py 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  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. id_to_timestamp = volume.revisions
  288. revisions = sorted(id_to_timestamp, key=id_to_timestamp.__getitem__)
  289. revisions = self.fire_event_for_filter(revisions)
  290. return ''.join('{}\n'.format(revision) for revision in revisions)
  291. @qubes.api.method('admin.vm.volume.Revert',
  292. scope='local', write=True)
  293. @asyncio.coroutine
  294. def vm_volume_revert(self, untrusted_payload):
  295. assert self.arg in self.dest.volumes.keys()
  296. untrusted_revision = untrusted_payload.decode('ascii').strip()
  297. del untrusted_payload
  298. volume = self.dest.volumes[self.arg]
  299. snapshots = volume.revisions
  300. assert untrusted_revision in snapshots
  301. revision = untrusted_revision
  302. self.fire_event_for_permission(volume=volume, revision=revision)
  303. ret = volume.revert(revision)
  304. if asyncio.iscoroutine(ret):
  305. yield from ret
  306. self.app.save()
  307. # write=True because this allow to clone VM - and most likely modify that
  308. # one - still having the same data
  309. @qubes.api.method('admin.vm.volume.CloneFrom', no_payload=True,
  310. scope='local', write=True)
  311. @asyncio.coroutine
  312. def vm_volume_clone_from(self):
  313. assert self.arg in self.dest.volumes.keys()
  314. volume = self.dest.volumes[self.arg]
  315. self.fire_event_for_permission(volume=volume)
  316. token = qubes.utils.random_string(32)
  317. # save token on self.app, as self is not persistent
  318. if not hasattr(self.app, 'api_admin_pending_clone'):
  319. self.app.api_admin_pending_clone = {}
  320. # don't handle collisions any better - if someone is so much out of
  321. # luck, can try again anyway
  322. assert token not in self.app.api_admin_pending_clone
  323. self.app.api_admin_pending_clone[token] = volume
  324. return token
  325. @qubes.api.method('admin.vm.volume.CloneTo',
  326. scope='local', write=True)
  327. @asyncio.coroutine
  328. def vm_volume_clone_to(self, untrusted_payload):
  329. assert self.arg in self.dest.volumes.keys()
  330. untrusted_token = untrusted_payload.decode('ascii').strip()
  331. del untrusted_payload
  332. assert untrusted_token in getattr(self.app,
  333. 'api_admin_pending_clone', {})
  334. token = untrusted_token
  335. del untrusted_token
  336. src_volume = self.app.api_admin_pending_clone[token]
  337. del self.app.api_admin_pending_clone[token]
  338. # make sure the volume still exists, but invalidate token anyway
  339. assert str(src_volume.pool) in self.app.pools
  340. assert src_volume in self.app.pools[str(src_volume.pool)].volumes
  341. dst_volume = self.dest.volumes[self.arg]
  342. self.fire_event_for_permission(src_volume=src_volume,
  343. dst_volume=dst_volume)
  344. op_retval = dst_volume.import_volume(src_volume)
  345. # clone/import functions may be either synchronous or asynchronous
  346. # in the later case, we need to wait for them to finish
  347. if asyncio.iscoroutine(op_retval):
  348. op_retval = yield from op_retval
  349. self.dest.volumes[self.arg] = op_retval
  350. self.app.save()
  351. @qubes.api.method('admin.vm.volume.Resize',
  352. scope='local', write=True)
  353. @asyncio.coroutine
  354. def vm_volume_resize(self, untrusted_payload):
  355. assert self.arg in self.dest.volumes.keys()
  356. untrusted_size = untrusted_payload.decode('ascii').strip()
  357. del untrusted_payload
  358. assert untrusted_size.isdigit() # only digits, forbid '-' too
  359. assert len(untrusted_size) <= 20 # limit to about 2^64
  360. size = int(untrusted_size)
  361. self.fire_event_for_permission(size=size)
  362. yield from self.dest.storage.resize(self.arg, size)
  363. self.app.save()
  364. @qubes.api.method('admin.vm.volume.Import', no_payload=True,
  365. scope='local', write=True)
  366. @asyncio.coroutine
  367. def vm_volume_import(self):
  368. '''Import volume data.
  369. Note that this function only returns a path to where data should be
  370. written, actual importing is done by a script in /etc/qubes-rpc
  371. When the script finish importing, it will trigger
  372. internal.vm.volume.ImportEnd (with either b'ok' or b'fail' as a
  373. payload) and response from that call will be actually send to the
  374. caller.
  375. '''
  376. assert self.arg in self.dest.volumes.keys()
  377. self.fire_event_for_permission()
  378. if not self.dest.is_halted():
  379. raise qubes.exc.QubesVMNotHaltedError(self.dest)
  380. path = self.dest.storage.import_data(self.arg)
  381. assert ' ' not in path
  382. size = self.dest.volumes[self.arg].size
  383. # when we know the action is allowed, inform extensions that it will
  384. # be performed
  385. self.dest.fire_event('domain-volume-import-begin', volume=self.arg)
  386. return '{} {}'.format(size, path)
  387. @qubes.api.method('admin.vm.volume.Set.revisions_to_keep',
  388. scope='local', write=True)
  389. @asyncio.coroutine
  390. def vm_volume_set_revisions_to_keep(self, untrusted_payload):
  391. assert self.arg in self.dest.volumes.keys()
  392. try:
  393. untrusted_value = int(untrusted_payload.decode('ascii'))
  394. except (UnicodeDecodeError, ValueError):
  395. raise qubes.api.ProtocolError('Invalid value')
  396. del untrusted_payload
  397. assert untrusted_value >= 0
  398. newvalue = untrusted_value
  399. del untrusted_value
  400. self.fire_event_for_permission(newvalue=newvalue)
  401. self.dest.volumes[self.arg].revisions_to_keep = newvalue
  402. self.app.save()
  403. @qubes.api.method('admin.vm.tag.List', no_payload=True,
  404. scope='local', read=True)
  405. @asyncio.coroutine
  406. def vm_tag_list(self):
  407. assert not self.arg
  408. tags = self.dest.tags
  409. tags = self.fire_event_for_filter(tags)
  410. return ''.join('{}\n'.format(tag) for tag in sorted(tags))
  411. @qubes.api.method('admin.vm.tag.Get', no_payload=True,
  412. scope='local', read=True)
  413. @asyncio.coroutine
  414. def vm_tag_get(self):
  415. qubes.vm.Tags.validate_tag(self.arg)
  416. self.fire_event_for_permission()
  417. return '1' if self.arg in self.dest.tags else '0'
  418. @qubes.api.method('admin.vm.tag.Set', no_payload=True,
  419. scope='local', write=True)
  420. @asyncio.coroutine
  421. def vm_tag_set(self):
  422. qubes.vm.Tags.validate_tag(self.arg)
  423. self.fire_event_for_permission()
  424. self.dest.tags.add(self.arg)
  425. self.app.save()
  426. @qubes.api.method('admin.vm.tag.Remove', no_payload=True,
  427. scope='local', write=True)
  428. @asyncio.coroutine
  429. def vm_tag_remove(self):
  430. qubes.vm.Tags.validate_tag(self.arg)
  431. self.fire_event_for_permission()
  432. try:
  433. self.dest.tags.remove(self.arg)
  434. except KeyError:
  435. raise qubes.exc.QubesTagNotFoundError(self.dest, self.arg)
  436. self.app.save()
  437. @qubes.api.method('admin.pool.List', no_payload=True,
  438. scope='global', read=True)
  439. @asyncio.coroutine
  440. def pool_list(self):
  441. assert not self.arg
  442. assert self.dest.name == 'dom0'
  443. pools = self.fire_event_for_filter(self.app.pools)
  444. return ''.join('{}\n'.format(pool) for pool in pools)
  445. @qubes.api.method('admin.pool.ListDrivers', no_payload=True,
  446. scope='global', read=True)
  447. @asyncio.coroutine
  448. def pool_listdrivers(self):
  449. assert self.dest.name == 'dom0'
  450. assert not self.arg
  451. drivers = self.fire_event_for_filter(qubes.storage.pool_drivers())
  452. return ''.join('{} {}\n'.format(
  453. driver,
  454. ' '.join(qubes.storage.driver_parameters(driver)))
  455. for driver in drivers)
  456. @qubes.api.method('admin.pool.Info', no_payload=True,
  457. scope='global', read=True)
  458. @asyncio.coroutine
  459. def pool_info(self):
  460. assert self.dest.name == 'dom0'
  461. assert self.arg in self.app.pools.keys()
  462. pool = self.app.pools[self.arg]
  463. self.fire_event_for_permission(pool=pool)
  464. size_info = ''
  465. try:
  466. size_info += 'size={}\n'.format(pool.size)
  467. except NotImplementedError:
  468. pass
  469. try:
  470. size_info += 'usage={}\n'.format(pool.usage)
  471. except NotImplementedError:
  472. pass
  473. return ''.join('{}={}\n'.format(prop, val)
  474. for prop, val in sorted(pool.config.items())) + \
  475. size_info
  476. @qubes.api.method('admin.pool.Add',
  477. scope='global', write=True)
  478. @asyncio.coroutine
  479. def pool_add(self, untrusted_payload):
  480. assert self.dest.name == 'dom0'
  481. drivers = qubes.storage.pool_drivers()
  482. assert self.arg in drivers
  483. untrusted_pool_config = untrusted_payload.decode('ascii').splitlines()
  484. del untrusted_payload
  485. assert all(('=' in line) for line in untrusted_pool_config)
  486. # pairs of (option, value)
  487. untrusted_pool_config = [line.split('=', 1)
  488. for line in untrusted_pool_config]
  489. # reject duplicated options
  490. assert len(set(x[0] for x in untrusted_pool_config)) == \
  491. len([x[0] for x in untrusted_pool_config])
  492. # and convert to dict
  493. untrusted_pool_config = dict(untrusted_pool_config)
  494. assert 'name' in untrusted_pool_config
  495. untrusted_pool_name = untrusted_pool_config.pop('name')
  496. allowed_chars = string.ascii_letters + string.digits + '-_.'
  497. assert all(c in allowed_chars for c in untrusted_pool_name)
  498. pool_name = untrusted_pool_name
  499. assert pool_name not in self.app.pools
  500. driver_parameters = qubes.storage.driver_parameters(self.arg)
  501. assert all(key in driver_parameters for key in untrusted_pool_config)
  502. pool_config = untrusted_pool_config
  503. self.fire_event_for_permission(name=pool_name,
  504. pool_config=pool_config)
  505. self.app.add_pool(name=pool_name, driver=self.arg, **pool_config)
  506. self.app.save()
  507. @qubes.api.method('admin.pool.Remove', no_payload=True,
  508. scope='global', write=True)
  509. @asyncio.coroutine
  510. def pool_remove(self):
  511. assert self.dest.name == 'dom0'
  512. assert self.arg in self.app.pools.keys()
  513. self.fire_event_for_permission()
  514. self.app.remove_pool(self.arg)
  515. self.app.save()
  516. @qubes.api.method('admin.pool.Set.revisions_to_keep',
  517. scope='global', write=True)
  518. @asyncio.coroutine
  519. def pool_set_revisions_to_keep(self, untrusted_payload):
  520. assert self.dest.name == 'dom0'
  521. assert self.arg in self.app.pools.keys()
  522. pool = self.app.pools[self.arg]
  523. try:
  524. untrusted_value = int(untrusted_payload.decode('ascii'))
  525. except (UnicodeDecodeError, ValueError):
  526. raise qubes.api.ProtocolError('Invalid value')
  527. del untrusted_payload
  528. assert untrusted_value >= 0
  529. newvalue = untrusted_value
  530. del untrusted_value
  531. self.fire_event_for_permission(newvalue=newvalue)
  532. pool.revisions_to_keep = newvalue
  533. self.app.save()
  534. @qubes.api.method('admin.label.List', no_payload=True,
  535. scope='global', read=True)
  536. @asyncio.coroutine
  537. def label_list(self):
  538. assert self.dest.name == 'dom0'
  539. assert not self.arg
  540. labels = self.fire_event_for_filter(self.app.labels.values())
  541. return ''.join('{}\n'.format(label.name) for label in labels)
  542. @qubes.api.method('admin.label.Get', no_payload=True,
  543. scope='global', read=True)
  544. @asyncio.coroutine
  545. def label_get(self):
  546. assert self.dest.name == 'dom0'
  547. try:
  548. label = self.app.get_label(self.arg)
  549. except KeyError:
  550. raise qubes.exc.QubesValueError
  551. self.fire_event_for_permission(label=label)
  552. return label.color
  553. @qubes.api.method('admin.label.Index', no_payload=True,
  554. scope='global', read=True)
  555. @asyncio.coroutine
  556. def label_index(self):
  557. assert self.dest.name == 'dom0'
  558. try:
  559. label = self.app.get_label(self.arg)
  560. except KeyError:
  561. raise qubes.exc.QubesValueError
  562. self.fire_event_for_permission(label=label)
  563. return str(label.index)
  564. @qubes.api.method('admin.label.Create',
  565. scope='global', write=True)
  566. @asyncio.coroutine
  567. def label_create(self, untrusted_payload):
  568. assert self.dest.name == 'dom0'
  569. # don't confuse label name with label index
  570. assert not self.arg.isdigit()
  571. allowed_chars = string.ascii_letters + string.digits + '-_.'
  572. assert all(c in allowed_chars for c in self.arg)
  573. try:
  574. self.app.get_label(self.arg)
  575. except KeyError:
  576. # ok, no such label yet
  577. pass
  578. else:
  579. raise qubes.exc.QubesValueError('label already exists')
  580. untrusted_payload = untrusted_payload.decode('ascii').strip()
  581. assert len(untrusted_payload) == 8
  582. assert untrusted_payload.startswith('0x')
  583. # besides prefix, only hex digits are allowed
  584. assert all(x in string.hexdigits for x in untrusted_payload[2:])
  585. # SEE: #2732
  586. color = untrusted_payload
  587. self.fire_event_for_permission(color=color)
  588. # allocate new index, but make sure it's outside of default labels set
  589. new_index = max(
  590. qubes.config.max_default_label, *self.app.labels.keys()) + 1
  591. label = qubes.Label(new_index, color, self.arg)
  592. self.app.labels[new_index] = label
  593. self.app.save()
  594. @qubes.api.method('admin.label.Remove', no_payload=True,
  595. scope='global', write=True)
  596. @asyncio.coroutine
  597. def label_remove(self):
  598. assert self.dest.name == 'dom0'
  599. try:
  600. label = self.app.get_label(self.arg)
  601. except KeyError:
  602. raise qubes.exc.QubesValueError
  603. # don't allow removing default labels
  604. assert label.index > qubes.config.max_default_label
  605. # FIXME: this should be in app.add_label()
  606. for vm in self.app.domains:
  607. if vm.label == label:
  608. raise qubes.exc.QubesException('label still in use')
  609. self.fire_event_for_permission(label=label)
  610. del self.app.labels[label.index]
  611. self.app.save()
  612. @qubes.api.method('admin.vm.Start', no_payload=True,
  613. scope='local', execute=True)
  614. @asyncio.coroutine
  615. def vm_start(self):
  616. assert not self.arg
  617. self.fire_event_for_permission()
  618. try:
  619. yield from self.dest.start()
  620. except libvirt.libvirtError as e:
  621. # change to QubesException, so will be reported to the user
  622. raise qubes.exc.QubesException('Start failed: ' + str(e) +
  623. ', see /var/log/libvirt/libxl/libxl-driver.log for details')
  624. @qubes.api.method('admin.vm.Shutdown', no_payload=True,
  625. scope='local', execute=True)
  626. @asyncio.coroutine
  627. def vm_shutdown(self):
  628. assert not self.arg
  629. self.fire_event_for_permission()
  630. yield from self.dest.shutdown()
  631. @qubes.api.method('admin.vm.Pause', no_payload=True,
  632. scope='local', execute=True)
  633. @asyncio.coroutine
  634. def vm_pause(self):
  635. assert not self.arg
  636. self.fire_event_for_permission()
  637. yield from self.dest.pause()
  638. @qubes.api.method('admin.vm.Unpause', no_payload=True,
  639. scope='local', execute=True)
  640. @asyncio.coroutine
  641. def vm_unpause(self):
  642. assert not self.arg
  643. self.fire_event_for_permission()
  644. yield from self.dest.unpause()
  645. @qubes.api.method('admin.vm.Kill', no_payload=True,
  646. scope='local', execute=True)
  647. @asyncio.coroutine
  648. def vm_kill(self):
  649. assert not self.arg
  650. self.fire_event_for_permission()
  651. yield from self.dest.kill()
  652. @qubes.api.method('admin.Events', no_payload=True,
  653. scope='global', read=True)
  654. @asyncio.coroutine
  655. def events(self):
  656. assert not self.arg
  657. # run until client connection is terminated
  658. self.cancellable = True
  659. wait_for_cancel = asyncio.get_event_loop().create_future()
  660. # cache event filters, to not call an event each time an event arrives
  661. event_filters = self.fire_event_for_permission()
  662. dispatcher = QubesMgmtEventsDispatcher(event_filters, self.send_event)
  663. if self.dest.name == 'dom0':
  664. self.app.add_handler('*', dispatcher.app_handler)
  665. self.app.add_handler('domain-add', dispatcher.on_domain_add)
  666. self.app.add_handler('domain-delete', dispatcher.on_domain_delete)
  667. for vm in self.app.domains:
  668. vm.add_handler('*', dispatcher.vm_handler)
  669. else:
  670. self.dest.add_handler('*', dispatcher.vm_handler)
  671. # send artificial event as a confirmation that connection is established
  672. self.send_event(self.app, 'connection-established')
  673. try:
  674. yield from wait_for_cancel
  675. except asyncio.CancelledError:
  676. # the above waiting was already interrupted, this is all we need
  677. pass
  678. if self.dest.name == 'dom0':
  679. self.app.remove_handler('*', dispatcher.app_handler)
  680. self.app.remove_handler('domain-add', dispatcher.on_domain_add)
  681. self.app.remove_handler('domain-delete',
  682. dispatcher.on_domain_delete)
  683. for vm in self.app.domains:
  684. vm.remove_handler('*', dispatcher.vm_handler)
  685. else:
  686. self.dest.remove_handler('*', dispatcher.vm_handler)
  687. @qubes.api.method('admin.vm.feature.List', no_payload=True,
  688. scope='local', read=True)
  689. @asyncio.coroutine
  690. def vm_feature_list(self):
  691. assert not self.arg
  692. features = self.fire_event_for_filter(self.dest.features.keys())
  693. return ''.join('{}\n'.format(feature) for feature in features)
  694. @qubes.api.method('admin.vm.feature.Get', no_payload=True,
  695. scope='local', read=True)
  696. @asyncio.coroutine
  697. def vm_feature_get(self):
  698. # validation of self.arg done by qrexec-policy is enough
  699. self.fire_event_for_permission()
  700. try:
  701. value = self.dest.features[self.arg]
  702. except KeyError:
  703. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  704. return value
  705. @qubes.api.method('admin.vm.feature.CheckWithTemplate', no_payload=True,
  706. scope='local', read=True)
  707. @asyncio.coroutine
  708. def vm_feature_checkwithtemplate(self):
  709. # validation of self.arg done by qrexec-policy is enough
  710. self.fire_event_for_permission()
  711. try:
  712. value = self.dest.features.check_with_template(self.arg)
  713. except KeyError:
  714. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  715. return value
  716. @qubes.api.method('admin.vm.feature.CheckWithNetvm', no_payload=True,
  717. scope='local', read=True)
  718. @asyncio.coroutine
  719. def vm_feature_checkwithnetvm(self):
  720. # validation of self.arg done by qrexec-policy is enough
  721. self.fire_event_for_permission()
  722. try:
  723. value = self.dest.features.check_with_netvm(self.arg)
  724. except KeyError:
  725. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  726. return value
  727. @qubes.api.method('admin.vm.feature.Remove', no_payload=True,
  728. scope='local', write=True)
  729. @asyncio.coroutine
  730. def vm_feature_remove(self):
  731. # validation of self.arg done by qrexec-policy is enough
  732. self.fire_event_for_permission()
  733. try:
  734. del self.dest.features[self.arg]
  735. except KeyError:
  736. raise qubes.exc.QubesFeatureNotFoundError(self.dest, self.arg)
  737. self.app.save()
  738. @qubes.api.method('admin.vm.feature.Set',
  739. scope='local', write=True)
  740. @asyncio.coroutine
  741. def vm_feature_set(self, untrusted_payload):
  742. # validation of self.arg done by qrexec-policy is enough
  743. value = untrusted_payload.decode('ascii', errors='strict')
  744. del untrusted_payload
  745. self.fire_event_for_permission(value=value)
  746. self.dest.features[self.arg] = value
  747. self.app.save()
  748. @qubes.api.method('admin.vm.Create.{endpoint}', endpoints=(ep.name
  749. for ep in pkg_resources.iter_entry_points(qubes.vm.VM_ENTRY_POINT)),
  750. scope='global', write=True)
  751. @asyncio.coroutine
  752. def vm_create(self, endpoint, untrusted_payload=None):
  753. return self._vm_create(endpoint, allow_pool=False,
  754. untrusted_payload=untrusted_payload)
  755. @qubes.api.method('admin.vm.CreateInPool.{endpoint}', endpoints=(ep.name
  756. for ep in pkg_resources.iter_entry_points(qubes.vm.VM_ENTRY_POINT)),
  757. scope='global', write=True)
  758. @asyncio.coroutine
  759. def vm_create_in_pool(self, endpoint, untrusted_payload=None):
  760. return self._vm_create(endpoint, allow_pool=True,
  761. untrusted_payload=untrusted_payload)
  762. def _vm_create(self, vm_type, allow_pool=False, untrusted_payload=None):
  763. assert self.dest.name == 'dom0'
  764. kwargs = {}
  765. pool = None
  766. pools = {}
  767. # this will raise exception if none is found
  768. vm_class = qubes.utils.get_entry_point_one(qubes.vm.VM_ENTRY_POINT,
  769. vm_type)
  770. # if argument is given, it needs to be a valid template, and only
  771. # when given VM class do need a template
  772. if hasattr(vm_class, 'template'):
  773. if self.arg:
  774. assert self.arg in self.app.domains
  775. kwargs['template'] = self.app.domains[self.arg]
  776. else:
  777. assert not self.arg
  778. for untrusted_param in untrusted_payload.decode('ascii',
  779. errors='strict').split(' '):
  780. untrusted_key, untrusted_value = untrusted_param.split('=', 1)
  781. if untrusted_key in kwargs:
  782. raise qubes.api.ProtocolError('duplicated parameters')
  783. if untrusted_key == 'name':
  784. qubes.vm.validate_name(None, None, untrusted_value)
  785. kwargs['name'] = untrusted_value
  786. elif untrusted_key == 'label':
  787. # don't confuse label name with label index
  788. assert not untrusted_value.isdigit()
  789. allowed_chars = string.ascii_letters + string.digits + '-_.'
  790. assert all(c in allowed_chars for c in untrusted_value)
  791. try:
  792. kwargs['label'] = self.app.get_label(untrusted_value)
  793. except KeyError:
  794. raise qubes.exc.QubesValueError
  795. elif untrusted_key == 'pool' and allow_pool:
  796. if pool is not None:
  797. raise qubes.api.ProtocolError('duplicated pool parameter')
  798. pool = self.app.get_pool(untrusted_value)
  799. elif untrusted_key.startswith('pool:') and allow_pool:
  800. untrusted_volume = untrusted_key.split(':', 1)[1]
  801. # kind of ugly, but actual list of volumes is available only
  802. # after creating a VM
  803. assert untrusted_volume in ['root', 'private', 'volatile',
  804. 'kernel']
  805. volume = untrusted_volume
  806. if volume in pools:
  807. raise qubes.api.ProtocolError(
  808. 'duplicated pool:{} parameter'.format(volume))
  809. pools[volume] = self.app.get_pool(untrusted_value)
  810. else:
  811. raise qubes.api.ProtocolError('Invalid param name')
  812. del untrusted_payload
  813. if 'name' not in kwargs or 'label' not in kwargs:
  814. raise qubes.api.ProtocolError('Missing name or label')
  815. if pool and pools:
  816. raise qubes.api.ProtocolError(
  817. 'Only one of \'pool=\' and \'pool:volume=\' can be used')
  818. if kwargs['name'] in self.app.domains:
  819. raise qubes.exc.QubesValueError(
  820. 'VM {} already exists'.format(kwargs['name']))
  821. self.fire_event_for_permission(pool=pool, pools=pools, **kwargs)
  822. vm = self.app.add_new_vm(vm_class, **kwargs)
  823. # TODO: move this to extension (in race-free fashion)
  824. vm.tags.add('created-by-' + str(self.src))
  825. try:
  826. yield from vm.create_on_disk(pool=pool, pools=pools)
  827. except:
  828. del self.app.domains[vm]
  829. raise
  830. self.app.save()
  831. @qubes.api.method('admin.vm.CreateDisposable', no_payload=True,
  832. scope='global', write=True)
  833. @asyncio.coroutine
  834. def create_disposable(self):
  835. assert not self.arg
  836. if self.dest.name == 'dom0':
  837. dispvm_template = self.src.default_dispvm
  838. else:
  839. dispvm_template = self.dest
  840. self.fire_event_for_permission(dispvm_template=dispvm_template)
  841. dispvm = yield from qubes.vm.dispvm.DispVM.from_appvm(dispvm_template)
  842. # TODO: move this to extension (in race-free fashion, better than here)
  843. dispvm.tags.add('disp-created-by-' + str(self.src))
  844. return dispvm.name
  845. @qubes.api.method('admin.vm.Remove', no_payload=True,
  846. scope='global', write=True)
  847. @asyncio.coroutine
  848. def vm_remove(self):
  849. assert not self.arg
  850. self.fire_event_for_permission()
  851. if not self.dest.is_halted():
  852. raise qubes.exc.QubesVMNotHaltedError(self.dest)
  853. if self.dest.installed_by_rpm:
  854. raise qubes.exc.QubesVMInUseError(self.dest, \
  855. "VM installed by package manager: " + self.dest.name)
  856. del self.app.domains[self.dest]
  857. try:
  858. yield from self.dest.remove_from_disk()
  859. except: # pylint: disable=bare-except
  860. self.app.log.exception('Error wile removing VM \'%s\' files',
  861. self.dest.name)
  862. self.app.save()
  863. @qubes.api.method('admin.vm.device.{endpoint}.Available', endpoints=(ep.name
  864. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  865. no_payload=True,
  866. scope='local', read=True)
  867. @asyncio.coroutine
  868. def vm_device_available(self, endpoint):
  869. devclass = endpoint
  870. devices = self.dest.devices[devclass].available()
  871. if self.arg:
  872. devices = [dev for dev in devices if dev.ident == self.arg]
  873. # no duplicated devices, but device may not exists, in which case
  874. # the list is empty
  875. assert len(devices) <= 1
  876. devices = self.fire_event_for_filter(devices, devclass=devclass)
  877. dev_info = {}
  878. for dev in devices:
  879. non_default_attrs = set(attr for attr in dir(dev) if
  880. not attr.startswith('_')).difference((
  881. 'backend_domain', 'ident', 'frontend_domain',
  882. 'description', 'options', 'regex'))
  883. properties_txt = ' '.join(
  884. '{}={!s}'.format(prop, value) for prop, value
  885. in itertools.chain(
  886. ((key, getattr(dev, key)) for key in non_default_attrs),
  887. # keep description as the last one, according to API
  888. # specification
  889. (('description', dev.description),)
  890. ))
  891. assert '\n' not in properties_txt
  892. dev_info[dev.ident] = properties_txt
  893. return ''.join('{} {}\n'.format(ident, dev_info[ident])
  894. for ident in sorted(dev_info))
  895. @qubes.api.method('admin.vm.device.{endpoint}.List', endpoints=(ep.name
  896. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  897. no_payload=True,
  898. scope='local', read=True)
  899. @asyncio.coroutine
  900. def vm_device_list(self, endpoint):
  901. devclass = endpoint
  902. device_assignments = self.dest.devices[devclass].assignments()
  903. if self.arg:
  904. select_backend, select_ident = self.arg.split('+', 1)
  905. device_assignments = [dev for dev in device_assignments
  906. if (str(dev.backend_domain), dev.ident)
  907. == (select_backend, select_ident)]
  908. # no duplicated devices, but device may not exists, in which case
  909. # the list is empty
  910. assert len(device_assignments) <= 1
  911. device_assignments = self.fire_event_for_filter(device_assignments,
  912. devclass=devclass)
  913. dev_info = {}
  914. for dev in device_assignments:
  915. properties_txt = ' '.join(
  916. '{}={!s}'.format(opt, value) for opt, value
  917. in itertools.chain(
  918. dev.options.items(),
  919. (('persistent', 'yes' if dev.persistent else 'no'),)
  920. ))
  921. assert '\n' not in properties_txt
  922. ident = '{!s}+{!s}'.format(dev.backend_domain, dev.ident)
  923. dev_info[ident] = properties_txt
  924. return ''.join('{} {}\n'.format(ident, dev_info[ident])
  925. for ident in sorted(dev_info))
  926. # Attach/Detach action can both modify persistent state (with
  927. # persistent=True) and volatile state of running VM (with persistent=False).
  928. # For this reason, write=True + execute=True
  929. @qubes.api.method('admin.vm.device.{endpoint}.Attach', endpoints=(ep.name
  930. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  931. scope='local', write=True, execute=True)
  932. @asyncio.coroutine
  933. def vm_device_attach(self, endpoint, untrusted_payload):
  934. devclass = endpoint
  935. options = {}
  936. persistent = False
  937. for untrusted_option in untrusted_payload.decode('ascii').split():
  938. try:
  939. untrusted_key, untrusted_value = untrusted_option.split('=', 1)
  940. except ValueError:
  941. raise qubes.api.ProtocolError('Invalid options format')
  942. if untrusted_key == 'persistent':
  943. persistent = qubes.property.bool(None, None, untrusted_value)
  944. else:
  945. allowed_chars_key = string.digits + string.ascii_letters + '-_.'
  946. allowed_chars_value = allowed_chars_key + ',+:'
  947. if any(x not in allowed_chars_key for x in untrusted_key):
  948. raise qubes.api.ProtocolError(
  949. 'Invalid chars in option name')
  950. if any(x not in allowed_chars_value for x in untrusted_value):
  951. raise qubes.api.ProtocolError(
  952. 'Invalid chars in option value')
  953. options[untrusted_key] = untrusted_value
  954. # qrexec already verified that no strange characters are in self.arg
  955. backend_domain, ident = self.arg.split('+', 1)
  956. # may raise KeyError, either on domain or ident
  957. dev = self.app.domains[backend_domain].devices[devclass][ident]
  958. self.fire_event_for_permission(device=dev,
  959. devclass=devclass, persistent=persistent,
  960. options=options)
  961. assignment = qubes.devices.DeviceAssignment(
  962. dev.backend_domain, dev.ident,
  963. options=options, persistent=persistent)
  964. yield from self.dest.devices[devclass].attach(assignment)
  965. self.app.save()
  966. # Attach/Detach action can both modify persistent state (with
  967. # persistent=True) and volatile state of running VM (with persistent=False).
  968. # For this reason, write=True + execute=True
  969. @qubes.api.method('admin.vm.device.{endpoint}.Detach', endpoints=(ep.name
  970. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  971. no_payload=True,
  972. scope='local', write=True, execute=True)
  973. @asyncio.coroutine
  974. def vm_device_detach(self, endpoint):
  975. devclass = endpoint
  976. # qrexec already verified that no strange characters are in self.arg
  977. backend_domain, ident = self.arg.split('+', 1)
  978. # may raise KeyError; if device isn't found, it will be UnknownDevice
  979. # instance - but allow it, otherwise it will be impossible to detach
  980. # already removed device
  981. dev = self.app.domains[backend_domain].devices[devclass][ident]
  982. self.fire_event_for_permission(device=dev,
  983. devclass=devclass)
  984. assignment = qubes.devices.DeviceAssignment(
  985. dev.backend_domain, dev.ident)
  986. yield from self.dest.devices[devclass].detach(assignment)
  987. self.app.save()
  988. # Attach/Detach action can both modify persistent state (with
  989. # persistent=True) and volatile state of running VM (with persistent=False).
  990. # For this reason, write=True + execute=True
  991. @qubes.api.method('admin.vm.device.{endpoint}.Set.persistent',
  992. endpoints=(ep.name
  993. for ep in pkg_resources.iter_entry_points('qubes.devices')),
  994. scope='local', write=True, execute=True)
  995. @asyncio.coroutine
  996. def vm_device_set_persistent(self, endpoint, untrusted_payload):
  997. devclass = endpoint
  998. assert untrusted_payload in (b'True', b'False')
  999. persistent = untrusted_payload == b'True'
  1000. del untrusted_payload
  1001. # qrexec already verified that no strange characters are in self.arg
  1002. backend_domain, ident = self.arg.split('+', 1)
  1003. # device must be already attached
  1004. matching_devices = [dev for dev
  1005. in self.dest.devices[devclass].attached()
  1006. if dev.backend_domain.name == backend_domain and dev.ident == ident]
  1007. assert len(matching_devices) == 1
  1008. dev = matching_devices[0]
  1009. self.fire_event_for_permission(device=dev,
  1010. persistent=persistent)
  1011. self.dest.devices[devclass].update_persistent(dev, persistent)
  1012. self.app.save()
  1013. @qubes.api.method('admin.vm.firewall.Get', no_payload=True,
  1014. scope='local', read=True)
  1015. @asyncio.coroutine
  1016. def vm_firewall_get(self):
  1017. assert not self.arg
  1018. self.fire_event_for_permission()
  1019. return ''.join('{}\n'.format(rule.api_rule)
  1020. for rule in self.dest.firewall.rules
  1021. if rule.api_rule is not None)
  1022. @qubes.api.method('admin.vm.firewall.Set',
  1023. scope='local', write=True)
  1024. @asyncio.coroutine
  1025. def vm_firewall_set(self, untrusted_payload):
  1026. assert not self.arg
  1027. rules = []
  1028. for untrusted_line in untrusted_payload.decode('ascii',
  1029. errors='strict').splitlines():
  1030. rule = qubes.firewall.Rule.from_api_string(
  1031. untrusted_rule=untrusted_line)
  1032. rules.append(rule)
  1033. self.fire_event_for_permission(rules=rules)
  1034. self.dest.firewall.rules = rules
  1035. self.dest.firewall.save()
  1036. @qubes.api.method('admin.vm.firewall.Reload', no_payload=True,
  1037. scope='local', execute=True)
  1038. @asyncio.coroutine
  1039. def vm_firewall_reload(self):
  1040. assert not self.arg
  1041. self.fire_event_for_permission()
  1042. self.dest.fire_event('firewall-changed')
  1043. @asyncio.coroutine
  1044. def _load_backup_profile(self, profile_name, skip_passphrase=False):
  1045. '''Load backup profile and return :py:class:`qubes.backup.Backup`
  1046. instance
  1047. :param profile_name: name of the profile
  1048. :param skip_passphrase: do not load passphrase - only backup summary
  1049. can be retrieved when this option is in use
  1050. '''
  1051. profile_path = os.path.join(
  1052. qubes.config.backup_profile_dir, profile_name + '.conf')
  1053. with open(profile_path) as profile_file:
  1054. profile_data = yaml.safe_load(profile_file)
  1055. try:
  1056. dest_vm = profile_data['destination_vm']
  1057. dest_path = profile_data['destination_path']
  1058. include_vms = profile_data['include']
  1059. # convert old keywords to new keywords
  1060. include_vms = [vm.replace('$', '@') for vm in include_vms]
  1061. exclude_vms = profile_data.get('exclude', [])
  1062. # convert old keywords to new keywords
  1063. exclude_vms = [vm.replace('$', '@') for vm in exclude_vms]
  1064. compression = profile_data.get('compression', True)
  1065. except KeyError as err:
  1066. raise qubes.exc.QubesException(
  1067. 'Invalid backup profile - missing {}'.format(err))
  1068. try:
  1069. dest_vm = self.app.domains[dest_vm]
  1070. except KeyError:
  1071. raise qubes.exc.QubesException(
  1072. 'Invalid destination_vm specified in backup profile')
  1073. if isinstance(dest_vm, qubes.vm.adminvm.AdminVM):
  1074. dest_vm = None
  1075. if skip_passphrase:
  1076. passphrase = None
  1077. elif 'passphrase_text' in profile_data:
  1078. passphrase = profile_data['passphrase_text']
  1079. elif 'passphrase_vm' in profile_data:
  1080. passphrase_vm_name = profile_data['passphrase_vm']
  1081. try:
  1082. passphrase_vm = self.app.domains[passphrase_vm_name]
  1083. except KeyError:
  1084. raise qubes.exc.QubesException(
  1085. 'Invalid backup profile - invalid passphrase_vm')
  1086. try:
  1087. passphrase, _ = yield from passphrase_vm.run_service_for_stdio(
  1088. 'qubes.BackupPassphrase+' + self.arg)
  1089. # make it foolproof against "echo passphrase" implementation
  1090. passphrase = passphrase.strip()
  1091. assert b'\n' not in passphrase
  1092. except subprocess.CalledProcessError:
  1093. raise qubes.exc.QubesException(
  1094. 'Failed to retrieve passphrase from \'{}\' VM'.format(
  1095. passphrase_vm_name))
  1096. else:
  1097. raise qubes.exc.QubesException(
  1098. 'Invalid backup profile - you need to '
  1099. 'specify passphrase_text or passphrase_vm')
  1100. # handle include
  1101. vms_to_backup = set(vm for vm in self.app.domains
  1102. if any(qubes.utils.match_vm_name_with_special(vm, name)
  1103. for name in include_vms))
  1104. # handle exclude
  1105. vms_to_backup.difference_update(vm for vm in self.app.domains
  1106. if any(qubes.utils.match_vm_name_with_special(vm, name)
  1107. for name in exclude_vms))
  1108. kwargs = {
  1109. 'target_vm': dest_vm,
  1110. 'target_dir': dest_path,
  1111. 'compressed': bool(compression),
  1112. 'passphrase': passphrase,
  1113. }
  1114. if isinstance(compression, str):
  1115. kwargs['compression_filter'] = compression
  1116. backup = qubes.backup.Backup(self.app, vms_to_backup, **kwargs)
  1117. return backup
  1118. def _backup_progress_callback(self, profile_name, progress):
  1119. self.app.fire_event('backup-progress', backup_profile=profile_name,
  1120. progress=progress)
  1121. @qubes.api.method('admin.backup.Execute', no_payload=True,
  1122. scope='global', read=True, execute=True)
  1123. @asyncio.coroutine
  1124. def backup_execute(self):
  1125. assert self.dest.name == 'dom0'
  1126. assert self.arg
  1127. assert '/' not in self.arg
  1128. self.fire_event_for_permission()
  1129. profile_path = os.path.join(qubes.config.backup_profile_dir,
  1130. self.arg + '.conf')
  1131. if not os.path.exists(profile_path):
  1132. raise qubes.api.PermissionDenied(
  1133. 'Backup profile {} does not exist'.format(self.arg))
  1134. if not hasattr(self.app, 'api_admin_running_backups'):
  1135. self.app.api_admin_running_backups = {}
  1136. backup = yield from self._load_backup_profile(self.arg)
  1137. backup.progress_callback = functools.partial(
  1138. self._backup_progress_callback, self.arg)
  1139. # forbid running the same backup operation twice at the time
  1140. assert self.arg not in self.app.api_admin_running_backups
  1141. backup_task = asyncio.ensure_future(backup.backup_do())
  1142. self.app.api_admin_running_backups[self.arg] = backup_task
  1143. try:
  1144. yield from backup_task
  1145. except asyncio.CancelledError:
  1146. raise qubes.exc.QubesException('Backup cancelled')
  1147. finally:
  1148. del self.app.api_admin_running_backups[self.arg]
  1149. @qubes.api.method('admin.backup.Cancel', no_payload=True,
  1150. scope='global', execute=True)
  1151. @asyncio.coroutine
  1152. def backup_cancel(self):
  1153. assert self.dest.name == 'dom0'
  1154. assert self.arg
  1155. assert '/' not in self.arg
  1156. self.fire_event_for_permission()
  1157. if not hasattr(self.app, 'api_admin_running_backups'):
  1158. self.app.api_admin_running_backups = {}
  1159. if self.arg not in self.app.api_admin_running_backups:
  1160. raise qubes.exc.QubesException('Backup operation not running')
  1161. self.app.api_admin_running_backups[self.arg].cancel()
  1162. @qubes.api.method('admin.backup.Info', no_payload=True,
  1163. scope='local', read=True)
  1164. @asyncio.coroutine
  1165. def backup_info(self):
  1166. assert self.dest.name == 'dom0'
  1167. assert self.arg
  1168. assert '/' not in self.arg
  1169. self.fire_event_for_permission()
  1170. profile_path = os.path.join(qubes.config.backup_profile_dir,
  1171. self.arg + '.conf')
  1172. if not os.path.exists(profile_path):
  1173. raise qubes.api.PermissionDenied(
  1174. 'Backup profile {} does not exist'.format(self.arg))
  1175. backup = yield from self._load_backup_profile(self.arg,
  1176. skip_passphrase=True)
  1177. return backup.get_backup_summary()
  1178. def _send_stats_single(self, info_time, info, only_vm, filters,
  1179. id_to_name_map):
  1180. '''A single iteration of sending VM stats
  1181. :param info_time: time of previous iteration
  1182. :param info: information retrieved in previous iteration
  1183. :param only_vm: send information only about this VM
  1184. :param filters: filters to apply on stats before sending
  1185. :param id_to_name_map: ID->VM name map, may be modified
  1186. :return: tuple(info_time, info) - new information (to be passed to
  1187. the next iteration)
  1188. '''
  1189. (info_time, info) = self.app.host.get_vm_stats(info_time, info,
  1190. only_vm=only_vm)
  1191. for vm_id, vm_info in info.items():
  1192. if vm_id not in id_to_name_map:
  1193. try:
  1194. name = \
  1195. self.app.vmm.libvirt_conn.lookupByID(vm_id).name()
  1196. except libvirt.libvirtError as err:
  1197. if err.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1198. # stubdomain or so
  1199. name = None
  1200. else:
  1201. raise
  1202. id_to_name_map[vm_id] = name
  1203. else:
  1204. name = id_to_name_map[vm_id]
  1205. # skip VMs with unknown name
  1206. if name is None:
  1207. continue
  1208. if not list(qubes.api.apply_filters([name], filters)):
  1209. continue
  1210. self.send_event(name, 'vm-stats',
  1211. memory_kb=int(vm_info['memory_kb']),
  1212. cpu_time=int(vm_info['cpu_time'] / 1000000),
  1213. cpu_usage=int(vm_info['cpu_usage']))
  1214. return info_time, info
  1215. @qubes.api.method('admin.vm.Stats', no_payload=True,
  1216. scope='global', read=True)
  1217. @asyncio.coroutine
  1218. def vm_stats(self):
  1219. assert not self.arg
  1220. # run until client connection is terminated
  1221. self.cancellable = True
  1222. # cache event filters, to not call an event each time an event arrives
  1223. stats_filters = self.fire_event_for_permission()
  1224. only_vm = None
  1225. if self.dest.name != 'dom0':
  1226. only_vm = self.dest
  1227. self.send_event(self.app, 'connection-established')
  1228. info_time = None
  1229. info = None
  1230. id_to_name_map = {0: 'dom0'}
  1231. try:
  1232. while True:
  1233. info_time, info = self._send_stats_single(info_time, info,
  1234. only_vm, stats_filters, id_to_name_map)
  1235. yield from asyncio.sleep(self.app.stats_interval)
  1236. except asyncio.CancelledError:
  1237. # valid method to terminate this loop
  1238. pass