app.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. # -*- encoding: utf-8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU Lesser General Public License as published by
  10. # the Free Software Foundation; either version 2.1 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. """
  21. Main Qubes() class and related classes.
  22. """
  23. import os
  24. import shlex
  25. import socket
  26. import shutil
  27. import subprocess
  28. import sys
  29. import logging
  30. import qubesadmin.base
  31. import qubesadmin.exc
  32. import qubesadmin.label
  33. import qubesadmin.storage
  34. import qubesadmin.utils
  35. import qubesadmin.vm
  36. import qubesadmin.config
  37. import qubesadmin.devices
  38. class VMCollection(object):
  39. """Collection of VMs objects"""
  40. def __init__(self, app):
  41. self.app = app
  42. self._vm_list = None
  43. self._vm_objects = {}
  44. def clear_cache(self):
  45. """Clear cached list of VMs"""
  46. self._vm_list = None
  47. def refresh_cache(self, force=False):
  48. """Refresh cached list of VMs"""
  49. if not force and self._vm_list is not None:
  50. return
  51. vm_list_data = self.app.qubesd_call(
  52. 'dom0',
  53. 'admin.vm.List'
  54. )
  55. new_vm_list = {}
  56. # FIXME: this will probably change
  57. for vm_data in vm_list_data.splitlines():
  58. vm_name, props = vm_data.decode('ascii').split(' ', 1)
  59. vm_name = str(vm_name)
  60. props = props.split(' ')
  61. new_vm_list[vm_name] = dict(
  62. [vm_prop.split('=', 1) for vm_prop in props])
  63. self._vm_list = new_vm_list
  64. for name, vm in list(self._vm_objects.items()):
  65. if vm.name not in self._vm_list:
  66. # VM no longer exists
  67. del self._vm_objects[name]
  68. elif vm.__class__.__name__ != self._vm_list[vm.name]['class']:
  69. # VM class have changed
  70. del self._vm_objects[name]
  71. # TODO: some generation ID, to detect VM re-creation
  72. elif name != vm.name:
  73. # renamed
  74. self._vm_objects[vm.name] = vm
  75. del self._vm_objects[name]
  76. def __getitem__(self, item):
  77. if isinstance(item, qubesadmin.vm.QubesVM):
  78. item = item.name
  79. if not self.app.blind_mode and item not in self:
  80. raise KeyError(item)
  81. return self.get_blind(item)
  82. def get_blind(self, item):
  83. """
  84. Get a vm without downloading the list
  85. and checking if exists
  86. """
  87. if item not in self._vm_objects:
  88. cls = qubesadmin.vm.QubesVM
  89. # provide class name to constructor, if already cached (which can be
  90. # done by 'item not in self' check above, unless blind_mode is
  91. # enabled
  92. klass = None
  93. if self._vm_list and item in self._vm_list:
  94. klass = self._vm_list[item]['class']
  95. self._vm_objects[item] = cls(self.app, item, klass=klass)
  96. return self._vm_objects[item]
  97. def __contains__(self, item):
  98. if isinstance(item, qubesadmin.vm.QubesVM):
  99. item = item.name
  100. self.refresh_cache()
  101. return item in self._vm_list
  102. def __delitem__(self, key):
  103. self.app.qubesd_call(key, 'admin.vm.Remove')
  104. self.clear_cache()
  105. def __iter__(self):
  106. self.refresh_cache()
  107. for vm in sorted(self._vm_list):
  108. yield self[vm]
  109. def keys(self):
  110. """Get list of VM names."""
  111. self.refresh_cache()
  112. return self._vm_list.keys()
  113. def values(self):
  114. """Get list of VM objects."""
  115. self.refresh_cache()
  116. return [self[name] for name in self._vm_list]
  117. class QubesBase(qubesadmin.base.PropertyHolder):
  118. """Main Qubes application.
  119. This is a base abstract class, don't use it directly. Use specialized
  120. class in py:class:`qubesadmin.Qubes` instead, which points at
  121. :py:class:`QubesLocal` or :py:class:`QubesRemote`.
  122. """
  123. #: domains (VMs) collection
  124. domains = None
  125. #: labels collection
  126. labels = None
  127. #: storage pools
  128. pools = None
  129. #: type of qubesd connection: either 'socket' or 'qrexec'
  130. qubesd_connection_type = None
  131. #: logger
  132. log = None
  133. #: do not check for object (VM, label etc) existence before really needed
  134. blind_mode = False
  135. #: cache retrieved properties values
  136. cache_enabled = False
  137. def __init__(self):
  138. super(QubesBase, self).__init__(self, 'admin.property.', 'dom0')
  139. self.domains = VMCollection(self)
  140. self.labels = qubesadmin.base.WrapperObjectsCollection(
  141. self, 'admin.label.List', qubesadmin.label.Label)
  142. self.pools = qubesadmin.base.WrapperObjectsCollection(
  143. self, 'admin.pool.List', qubesadmin.storage.Pool)
  144. #: cache for available storage pool drivers and options to create them
  145. self._pool_drivers = None
  146. self.log = logging.getLogger('app')
  147. self._local_name = None
  148. def list_vmclass(self):
  149. """Call Qubesd in order to obtain the vm classes list"""
  150. vmclass = self.qubesd_call('dom0', 'admin.vmclass.List') \
  151. .decode().splitlines()
  152. return sorted(vmclass)
  153. def list_deviceclass(self):
  154. """Call Qubesd in order to obtain the device classes list"""
  155. deviceclasses = self.qubesd_call('dom0', 'admin.deviceclass.List') \
  156. .decode().splitlines()
  157. return sorted(deviceclasses)
  158. def _refresh_pool_drivers(self):
  159. """
  160. Refresh cached storage pool drivers and their parameters.
  161. :return: None
  162. """
  163. if self._pool_drivers is None:
  164. pool_drivers_data = self.qubesd_call(
  165. 'dom0', 'admin.pool.ListDrivers', None, None)
  166. assert pool_drivers_data.endswith(b'\n')
  167. pool_drivers = {}
  168. for driver_line in pool_drivers_data.decode('ascii').splitlines():
  169. if not driver_line:
  170. continue
  171. driver_name, driver_options = driver_line.split(' ', 1)
  172. pool_drivers[driver_name] = driver_options.split(' ')
  173. self._pool_drivers = pool_drivers
  174. @property
  175. def pool_drivers(self):
  176. """ Available storage pool drivers """
  177. self._refresh_pool_drivers()
  178. return self._pool_drivers.keys()
  179. def pool_driver_parameters(self, driver):
  180. """ Parameters to initialize storage pool using given driver """
  181. self._refresh_pool_drivers()
  182. return self._pool_drivers[driver]
  183. def add_pool(self, name, driver, **kwargs):
  184. """ Add a storage pool to config
  185. :param name: name of storage pool to create
  186. :param driver: driver to use, see :py:meth:`pool_drivers` for
  187. available drivers
  188. :param kwargs: configuration parameters for storage pool,
  189. see :py:meth:`pool_driver_parameters` for a list
  190. """
  191. # sort parameters only to ease testing, not required by API
  192. payload = 'name={}\n'.format(name) + \
  193. ''.join('{}={}\n'.format(key, value)
  194. for key, value in sorted(kwargs.items()))
  195. self.qubesd_call('dom0', 'admin.pool.Add', driver,
  196. payload.encode('utf-8'))
  197. def remove_pool(self, name):
  198. """ Remove a storage pool """
  199. self.qubesd_call('dom0', 'admin.pool.Remove', name, None)
  200. @property
  201. def local_name(self):
  202. """ Get localhost name """
  203. if not self._local_name:
  204. self._local_name = os.uname()[1]
  205. return self._local_name
  206. def get_label(self, label):
  207. """Get label as identified by index or name
  208. :throws KeyError: when label is not found
  209. """
  210. # first search for name, verbatim
  211. try:
  212. return self.labels[label]
  213. except KeyError:
  214. pass
  215. # then search for index
  216. if isinstance(label, int) or label.isdigit():
  217. for i in self.labels.values():
  218. if i.index == int(label):
  219. return i
  220. raise KeyError(label)
  221. @staticmethod
  222. def get_vm_class(clsname):
  223. """Find the class for a domain.
  224. Compatibility function, client tools use str to identify domain classes.
  225. :param str clsname: name of the class
  226. :return str: class
  227. """
  228. return clsname
  229. def add_new_vm(self, cls, name, label, template=None, pool=None,
  230. pools=None):
  231. """Create new Virtual Machine
  232. Example usage with custom storage pools:
  233. >>> app = qubesadmin.Qubes()
  234. >>> pools = {'private': 'external'}
  235. >>> vm = app.add_new_vm('AppVM', 'my-new-vm', 'red',
  236. >>> 'my-template', pools=pools)
  237. >>> vm.netvm = app.domains['sys-whonix']
  238. :param str cls: name of VM class (`AppVM`, `TemplateVM` etc)
  239. :param str name: name of VM
  240. :param str label: label color for new VM
  241. :param str template: template to use (if apply for given VM class),
  242. can be also VM object; use None for default value
  243. :param str pool: storage pool to use instead of default one
  244. :param dict pools: storage pool for specific volumes
  245. :return new VM object
  246. """
  247. if not isinstance(cls, str):
  248. cls = cls.__name__
  249. if template is qubesadmin.DEFAULT:
  250. template = None
  251. elif template is not None:
  252. template = str(template)
  253. if pool and pools:
  254. raise ValueError('only one of pool= and pools= can be used')
  255. method_prefix = 'admin.vm.Create.'
  256. payload = 'name={} label={}'.format(name, label)
  257. if pool:
  258. payload += ' pool={}'.format(str(pool))
  259. method_prefix = 'admin.vm.CreateInPool.'
  260. if pools:
  261. payload += ''.join(' pool:{}={}'.format(vol, str(pool))
  262. for vol, pool in sorted(pools.items()))
  263. method_prefix = 'admin.vm.CreateInPool.'
  264. self.qubesd_call('dom0', method_prefix + cls, template,
  265. payload.encode('utf-8'))
  266. self.domains.clear_cache()
  267. return self.domains[name]
  268. def clone_vm(self, src_vm, new_name, new_cls=None, pool=None, pools=None,
  269. ignore_errors=False, ignore_volumes=None,
  270. ignore_devices=False):
  271. # pylint: disable=too-many-statements
  272. """Clone Virtual Machine
  273. Example usage with custom storage pools:
  274. >>> app = qubesadmin.Qubes()
  275. >>> pools = {'private': 'external'}
  276. >>> src_vm = app.domains['personal']
  277. >>> vm = app.clone_vm(src_vm, 'my-new-vm', pools=pools)
  278. >>> vm.label = app.labels['green']
  279. :param QubesVM or str src_vm: source VM
  280. :param str new_name: name of new VM
  281. :param str new_cls: name of VM class (`AppVM`, `TemplateVM` etc) - use
  282. None to copy it from *src_vm*
  283. :param str pool: storage pool to use instead of default one
  284. :param dict pools: storage pool for specific volumes
  285. :param bool ignore_errors: should errors on meta-data setting be only
  286. logged, or abort the whole operation?
  287. :param list ignore_volumes: do not clone volumes on this list,
  288. like 'private' or 'root'
  289. :param bool ignore_devices: if True, do not copy device assignments
  290. :return new VM object
  291. """
  292. if pool and pools:
  293. raise ValueError('only one of pool= and pools= can be used')
  294. if isinstance(src_vm, str):
  295. src_vm = self.domains[src_vm]
  296. if new_cls is None:
  297. new_cls = src_vm.klass
  298. template = getattr(src_vm, 'template', None)
  299. if template is not None:
  300. template = str(template)
  301. label = src_vm.label
  302. if pool is None and pools is None:
  303. # use the same pools as the source - check if non default is used
  304. for volume in sorted(src_vm.volumes.values()):
  305. if not volume.save_on_stop:
  306. # clone only persistent volumes
  307. continue
  308. if ignore_volumes and volume.name in ignore_volumes:
  309. continue
  310. default_pool = getattr(self.app, 'default_pool_' + volume.name,
  311. volume.pool)
  312. if default_pool != volume.pool:
  313. if pools is None:
  314. pools = {}
  315. pools[volume.name] = volume.pool
  316. method_prefix = 'admin.vm.Create.'
  317. payload = 'name={} label={}'.format(new_name, label)
  318. if pool:
  319. payload += ' pool={}'.format(str(pool))
  320. method_prefix = 'admin.vm.CreateInPool.'
  321. if pools:
  322. payload += ''.join(' pool:{}={}'.format(vol, str(pool))
  323. for vol, pool in sorted(pools.items()))
  324. method_prefix = 'admin.vm.CreateInPool.'
  325. self.qubesd_call('dom0', method_prefix + new_cls, template,
  326. payload.encode('utf-8'))
  327. self.domains.clear_cache()
  328. dst_vm = self.domains[new_name]
  329. try:
  330. assert isinstance(dst_vm, qubesadmin.vm.QubesVM)
  331. for prop in src_vm.property_list():
  332. # handled by admin.vm.Create call
  333. if prop in ('name', 'qid', 'template', 'label', 'uuid',
  334. 'installed_by_rpm'):
  335. continue
  336. if src_vm.property_is_default(prop):
  337. continue
  338. try:
  339. setattr(dst_vm, prop, getattr(src_vm, prop))
  340. except AttributeError:
  341. pass
  342. except qubesadmin.exc.QubesException as e:
  343. dst_vm.log.error(
  344. 'Failed to set {!s} property: {!s}'.format(prop, e))
  345. if not ignore_errors:
  346. raise
  347. for tag in src_vm.tags:
  348. if tag.startswith('created-by-'):
  349. continue
  350. try:
  351. dst_vm.tags.add(tag)
  352. except qubesadmin.exc.QubesException as e:
  353. dst_vm.log.error(
  354. 'Failed to add {!s} tag: {!s}'.format(tag, e))
  355. if not ignore_errors:
  356. raise
  357. for feature, value in src_vm.features.items():
  358. try:
  359. dst_vm.features[feature] = value
  360. except qubesadmin.exc.QubesException as e:
  361. dst_vm.log.error(
  362. 'Failed to set {!s} feature: {!s}'.format(feature, e))
  363. if not ignore_errors:
  364. raise
  365. try:
  366. dst_vm.firewall.save_rules(src_vm.firewall.rules)
  367. except qubesadmin.exc.QubesException as e:
  368. self.log.error('Failed to set firewall: %s', e)
  369. if not ignore_errors:
  370. raise
  371. try:
  372. # FIXME: convert to qrexec calls to dom0/GUI VM
  373. appmenus_cmd = \
  374. ['qvm-appmenus', '--init', '--update',
  375. '--source', src_vm.name, dst_vm.name]
  376. subprocess.check_output(appmenus_cmd, stderr=subprocess.STDOUT)
  377. except OSError:
  378. # this file needs to be python 2.7 compatible,
  379. # so no FileNotFoundError
  380. self.log.error('Failed to clone appmenus, qvm-appmenus missing')
  381. if not ignore_errors:
  382. raise qubesadmin.exc.QubesException(
  383. 'Failed to clone appmenus')
  384. except subprocess.CalledProcessError as e:
  385. self.log.error('Failed to clone appmenus: %s',
  386. e.output.decode())
  387. if not ignore_errors:
  388. raise qubesadmin.exc.QubesException(
  389. 'Failed to clone appmenus')
  390. except qubesadmin.exc.QubesException:
  391. if not ignore_errors:
  392. del self.domains[dst_vm.name]
  393. raise
  394. try:
  395. for dst_volume in sorted(dst_vm.volumes.values()):
  396. if not dst_volume.save_on_stop:
  397. # clone only persistent volumes
  398. continue
  399. if ignore_volumes and dst_volume.name in ignore_volumes:
  400. continue
  401. src_volume = src_vm.volumes[dst_volume.name]
  402. dst_vm.log.info('Cloning {} volume'.format(dst_volume.name))
  403. dst_volume.clone(src_volume)
  404. except qubesadmin.exc.QubesException:
  405. del self.domains[dst_vm.name]
  406. raise
  407. if not ignore_devices:
  408. try:
  409. for devclass in src_vm.devices:
  410. for assignment in src_vm.devices[devclass].assignments(
  411. persistent=True):
  412. new_assignment = qubesadmin.devices.DeviceAssignment(
  413. backend_domain=assignment.backend_domain,
  414. ident=assignment.ident,
  415. options=assignment.options,
  416. persistent=assignment.persistent)
  417. dst_vm.devices[devclass].attach(new_assignment)
  418. except qubesadmin.exc.QubesException:
  419. if not ignore_errors:
  420. del self.domains[dst_vm.name]
  421. raise
  422. return dst_vm
  423. def qubesd_call(self, dest, method, arg=None, payload=None,
  424. payload_stream=None):
  425. """
  426. Execute Admin API method.
  427. If `payload` and `payload_stream` are both specified, they will be sent
  428. in that order.
  429. :param dest: Destination VM name
  430. :param method: Full API method name ('admin...')
  431. :param arg: Method argument (if any)
  432. :param payload: Payload send to the method
  433. :param payload_stream: file-like object to read payload from
  434. :return: Data returned by qubesd (string)
  435. .. warning:: *payload_stream* will get closed by this function
  436. """
  437. raise NotImplementedError(
  438. 'qubesd_call not implemented in QubesBase class; use specialized '
  439. 'class: qubesadmin.Qubes()')
  440. def run_service(self, dest, service, filter_esc=False, user=None,
  441. localcmd=None, wait=True, autostart=True, **kwargs):
  442. """Run qrexec service in a given destination
  443. *kwargs* are passed verbatim to :py:meth:`subprocess.Popen`.
  444. :param str dest: Destination - may be a VM name or empty
  445. string for default (for a given service)
  446. :param str service: service name
  447. :param bool filter_esc: filter escape sequences to protect terminal \
  448. emulator
  449. :param str user: username to run service as
  450. :param str localcmd: Command to connect stdin/stdout to
  451. :param bool wait: Wait service run
  452. :param bool autostart: Automatically start the target VM
  453. :rtype: subprocess.Popen
  454. """
  455. raise NotImplementedError(
  456. 'run_service not implemented in QubesBase class; use specialized '
  457. 'class: qubesadmin.Qubes()')
  458. @staticmethod
  459. def _call_with_stream(command, payload, payload_stream):
  460. """Helper method to pass data to qubesd. Calls a command with
  461. payload and payload_stream as input.
  462. :param command: command to run
  463. :param payload: Initial payload, or None
  464. :param payload_stream: File-like object with the rest of data
  465. :return: (process, stdout, stderr)
  466. """
  467. if payload:
  468. # It's not strictly correct to write data to stdin in this way,
  469. # because the process can get blocked on stdout or stderr pipe.
  470. # However, in practice the output should be always smaller than 4K.
  471. proc = subprocess.Popen(
  472. command,
  473. stdin=subprocess.PIPE,
  474. stdout=subprocess.PIPE,
  475. stderr=subprocess.PIPE)
  476. proc.stdin.write(payload)
  477. try:
  478. shutil.copyfileobj(payload_stream, proc.stdin)
  479. except BrokenPipeError:
  480. # We might receive an error from qubesd before we sent
  481. # everything (for instance, because we are sending too much
  482. # data).
  483. pass
  484. else:
  485. # Connect the stream directly.
  486. proc = subprocess.Popen(
  487. command,
  488. stdin=payload_stream,
  489. stdout=subprocess.PIPE,
  490. stderr=subprocess.PIPE)
  491. payload_stream.close()
  492. stdout, stderr = proc.communicate()
  493. return proc, stdout, stderr
  494. def _invalidate_cache(self, subject, event, name, **kwargs):
  495. """Invalidate cached value of a property.
  496. This method is designed to be hooked as an event handler for:
  497. - property-set:*
  498. - property-del:*
  499. This is done in :py:class:`qubesadmin.events.EventsDispatcher` class
  500. directly, before calling other handlers.
  501. It handles both VM and global properties.
  502. Note: even if the new value is given in the event arguments, it is
  503. ignored because it comes without type information.
  504. :param subject: either VM object or None
  505. :param event: name of the event
  506. :param name: name of the property
  507. :param kwargs: other arguments
  508. :return: none
  509. """ # pylint: disable=unused-argument
  510. if subject is None:
  511. subject = self
  512. try:
  513. # pylint: disable=protected-access
  514. del subject._properties_cache[name]
  515. except KeyError:
  516. pass
  517. class QubesLocal(QubesBase):
  518. """Application object communicating through local socket.
  519. Used when running in dom0.
  520. """
  521. qubesd_connection_type = 'socket'
  522. def qubesd_call(self, dest, method, arg=None, payload=None,
  523. payload_stream=None):
  524. """
  525. Execute Admin API method.
  526. If `payload` and `payload_stream` are both specified, they will be sent
  527. in that order.
  528. :param dest: Destination VM name
  529. :param method: Full API method name ('admin...')
  530. :param arg: Method argument (if any)
  531. :param payload: Payload send to the method
  532. :param payload_stream: file-like object to read payload from
  533. :return: Data returned by qubesd (string)
  534. .. warning:: *payload_stream* will get closed by this function
  535. """
  536. if payload_stream:
  537. # payload_stream can be used for large amount of data,
  538. # so optimize for throughput, not latency: spawn actual qrexec
  539. # service implementation, which may use some optimization there (
  540. # see admin.vm.volume.Import - actual data handling is done with dd)
  541. method_path = os.path.join(
  542. qubesadmin.config.QREXEC_SERVICES_DIR, method)
  543. if not os.path.exists(method_path):
  544. raise qubesadmin.exc.QubesDaemonCommunicationError(
  545. '{} not found'.format(method_path))
  546. command = ['env', 'QREXEC_REMOTE_DOMAIN=dom0',
  547. 'QREXEC_REQUESTED_TARGET=' + dest, method_path, arg]
  548. if os.getuid() != 0:
  549. command.insert(0, 'sudo')
  550. (_, stdout, _) = self._call_with_stream(
  551. command, payload, payload_stream)
  552. return self._parse_qubesd_response(stdout)
  553. try:
  554. client_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  555. client_socket.connect(qubesadmin.config.QUBESD_SOCKET)
  556. except (IOError, OSError) as e:
  557. raise qubesadmin.exc.QubesDaemonCommunicationError(
  558. 'Failed to connect to qubesd service: %s', str(e))
  559. # src, method, dest, arg
  560. for call_arg in ('dom0', method, dest, arg):
  561. if call_arg is not None:
  562. client_socket.sendall(call_arg.encode('ascii'))
  563. client_socket.sendall(b'\0')
  564. if payload is not None:
  565. client_socket.sendall(payload)
  566. client_socket.shutdown(socket.SHUT_WR)
  567. return_data = client_socket.makefile('rb').read()
  568. client_socket.close()
  569. return self._parse_qubesd_response(return_data)
  570. def run_service(self, dest, service, filter_esc=False, user=None,
  571. localcmd=None, wait=True, autostart=True, **kwargs):
  572. """Run qrexec service in a given destination
  573. :param str dest: Destination - may be a VM name or empty
  574. string for default (for a given service)
  575. :param str service: service name
  576. :param bool filter_esc: filter escape sequences to protect terminal \
  577. emulator
  578. :param str user: username to run service as
  579. :param str localcmd: Command to connect stdin/stdout to
  580. :param bool wait: wait for remote process to finish
  581. :rtype: subprocess.Popen
  582. """
  583. if not dest:
  584. raise ValueError('Empty destination name allowed only from a VM')
  585. if not wait and localcmd:
  586. raise ValueError('wait=False incompatible with localcmd')
  587. if autostart:
  588. try:
  589. self.qubesd_call(dest, 'admin.vm.Start')
  590. except qubesadmin.exc.QubesVMNotHaltedError:
  591. pass
  592. elif not self.domains.get_blind(dest).is_running():
  593. raise qubesadmin.exc.QubesVMNotRunningError(
  594. '%s is not running', dest)
  595. qrexec_opts = ['-d', dest]
  596. if filter_esc:
  597. qrexec_opts.extend(['-t'])
  598. if filter_esc or os.isatty(sys.stderr.fileno()):
  599. qrexec_opts.extend(['-T'])
  600. if localcmd:
  601. qrexec_opts.extend(['-l', localcmd])
  602. if user is None:
  603. user = 'DEFAULT'
  604. if not wait:
  605. qrexec_opts.extend(['-e'])
  606. if 'connect_timeout' in kwargs:
  607. qrexec_opts.extend(['-w', str(kwargs.pop('connect_timeout'))])
  608. kwargs.setdefault('stdin', subprocess.PIPE)
  609. kwargs.setdefault('stdout', subprocess.PIPE)
  610. kwargs.setdefault('stderr', subprocess.PIPE)
  611. proc = subprocess.Popen(
  612. [qubesadmin.config.QREXEC_CLIENT] + qrexec_opts + [
  613. '{}:QUBESRPC {} dom0'.format(user, service)], **kwargs)
  614. return proc
  615. class QubesRemote(QubesBase):
  616. """Application object communicating through qrexec services.
  617. Used when running in VM.
  618. """
  619. qubesd_connection_type = 'qrexec'
  620. def qubesd_call(self, dest, method, arg=None, payload=None,
  621. payload_stream=None):
  622. """
  623. Execute Admin API method.
  624. If `payload` and `payload_stream` are both specified, they will be sent
  625. in that order.
  626. :param dest: Destination VM name
  627. :param method: Full API method name ('admin...')
  628. :param arg: Method argument (if any)
  629. :param payload: Payload send to the method
  630. :param payload_stream: file-like object to read payload from
  631. :return: Data returned by qubesd (string)
  632. .. warning:: *payload_stream* will get closed by this function
  633. """
  634. service_name = method
  635. if arg is not None:
  636. service_name += '+' + arg
  637. command = [qubesadmin.config.QREXEC_CLIENT_VM,
  638. dest, service_name]
  639. if payload_stream:
  640. (p, stdout, stderr) = self._call_with_stream(
  641. command, payload, payload_stream)
  642. else:
  643. p = subprocess.Popen(command,
  644. stdin=subprocess.PIPE,
  645. stdout=subprocess.PIPE,
  646. stderr=subprocess.PIPE)
  647. (stdout, stderr) = p.communicate(payload)
  648. if p.returncode != 0:
  649. raise qubesadmin.exc.QubesDaemonNoResponseError(
  650. 'Service call error: %s', stderr.decode())
  651. return self._parse_qubesd_response(stdout)
  652. def run_service(self, dest, service, filter_esc=False, user=None,
  653. localcmd=None, wait=True, autostart=True, **kwargs):
  654. """Run qrexec service in a given destination
  655. :param str dest: Destination - may be a VM name or empty
  656. string for default (for a given service)
  657. :param str service: service name
  658. :param bool filter_esc: filter escape sequences to protect terminal \
  659. emulator
  660. :param str user: username to run service as
  661. :param str localcmd: Command to connect stdin/stdout to
  662. :param bool wait: wait for process to finish
  663. :rtype: subprocess.Popen
  664. """
  665. if not autostart and not dest:
  666. raise ValueError(
  667. 'autostart=False makes sense only with a defined target')
  668. if user:
  669. raise ValueError(
  670. 'non-default user not possible for calls from VM')
  671. if not wait and localcmd:
  672. raise ValueError('wait=False incompatible with localcmd')
  673. qrexec_opts = []
  674. if filter_esc:
  675. qrexec_opts.extend(['-t'])
  676. if filter_esc or (
  677. os.isatty(sys.stderr.fileno()) and 'stderr' not in kwargs):
  678. qrexec_opts.extend(['-T'])
  679. if not autostart and not self.domains.get_blind(dest).is_running():
  680. raise qubesadmin.exc.QubesVMNotRunningError(
  681. '%s is not running', dest)
  682. if not wait:
  683. # qrexec-client-vm can only request service calls, which are
  684. # started using MSG_EXEC_CMDLINE qrexec protocol message; this
  685. # message means "start the process, pipe its stdin/out/err,
  686. # and when it terminates, send exit code back".
  687. # According to the protocol qrexec-client-vm needs to wait for
  688. # MSG_DATA_EXIT_CODE, so implementing wait=False would require
  689. # some protocol change (or protocol violation).
  690. raise NotImplementedError(
  691. 'wait=False not implemented for calls from VM')
  692. kwargs.setdefault('stdin', subprocess.PIPE)
  693. kwargs.setdefault('stdout', subprocess.PIPE)
  694. kwargs.setdefault('stderr', subprocess.PIPE)
  695. proc = subprocess.Popen(
  696. [qubesadmin.config.QREXEC_CLIENT_VM] +
  697. qrexec_opts +
  698. [dest or '', service] +
  699. (shlex.split(localcmd) if localcmd else []),
  700. **kwargs)
  701. return proc