admin.py 60 KB

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