admin.py 58 KB

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