admin.py 57 KB

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