app.py 32 KB

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