admin.py 60 KB

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