app.py 28 KB

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