app.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. # -*- encoding: utf8 -*-
  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 subprocess
  27. import sys
  28. import logging
  29. import qubesadmin.base
  30. import qubesadmin.exc
  31. import qubesadmin.label
  32. import qubesadmin.storage
  33. import qubesadmin.utils
  34. import qubesadmin.vm
  35. import qubesadmin.config
  36. BUF_SIZE = 4096
  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 not self.app.blind_mode and item not in self:
  77. raise KeyError(item)
  78. if item not in self._vm_objects:
  79. cls = qubesadmin.vm.QubesVM
  80. # provide class name to constructor, if already cached (which can be
  81. # done by 'item not in self' check above, unless blind_mode is
  82. # enabled
  83. klass = None
  84. if self._vm_list and item in self._vm_list:
  85. klass = self._vm_list[item]['class']
  86. self._vm_objects[item] = cls(self.app, item, klass=klass)
  87. return self._vm_objects[item]
  88. def __contains__(self, item):
  89. self.refresh_cache()
  90. return item in self._vm_list
  91. def __delitem__(self, key):
  92. self.app.qubesd_call(key, 'admin.vm.Remove')
  93. self.clear_cache()
  94. def __iter__(self):
  95. self.refresh_cache()
  96. for vm in sorted(self._vm_list):
  97. yield self[vm]
  98. def keys(self):
  99. '''Get list of VM names.'''
  100. self.refresh_cache()
  101. return self._vm_list.keys()
  102. def values(self):
  103. '''Get list of VM objects.'''
  104. self.refresh_cache()
  105. return [self[name] for name in self._vm_list]
  106. class QubesBase(qubesadmin.base.PropertyHolder):
  107. '''Main Qubes application'''
  108. #: domains (VMs) collection
  109. domains = None
  110. #: labels collection
  111. labels = None
  112. #: storage pools
  113. pools = None
  114. #: type of qubesd connection: either 'socket' or 'qrexec'
  115. qubesd_connection_type = None
  116. #: logger
  117. log = None
  118. #: do not check for object (VM, label etc) existence before really needed
  119. blind_mode = False
  120. def __init__(self):
  121. super(QubesBase, self).__init__(self, 'admin.property.', 'dom0')
  122. self.domains = VMCollection(self)
  123. self.labels = qubesadmin.base.WrapperObjectsCollection(
  124. self, 'admin.label.List', qubesadmin.label.Label)
  125. self.pools = qubesadmin.base.WrapperObjectsCollection(
  126. self, 'admin.pool.List', qubesadmin.storage.Pool)
  127. #: cache for available storage pool drivers and options to create them
  128. self._pool_drivers = None
  129. self.log = logging.getLogger('app')
  130. def _refresh_pool_drivers(self):
  131. '''
  132. Refresh cached storage pool drivers and their parameters.
  133. :return: None
  134. '''
  135. if self._pool_drivers is None:
  136. pool_drivers_data = self.qubesd_call(
  137. 'dom0', 'admin.pool.ListDrivers', None, None)
  138. assert pool_drivers_data.endswith(b'\n')
  139. pool_drivers = {}
  140. for driver_line in pool_drivers_data.decode('ascii').splitlines():
  141. if not driver_line:
  142. continue
  143. driver_name, driver_options = driver_line.split(' ', 1)
  144. pool_drivers[driver_name] = driver_options.split(' ')
  145. self._pool_drivers = pool_drivers
  146. @property
  147. def pool_drivers(self):
  148. ''' Available storage pool drivers '''
  149. self._refresh_pool_drivers()
  150. return self._pool_drivers.keys()
  151. def pool_driver_parameters(self, driver):
  152. ''' Parameters to initialize storage pool using given driver '''
  153. self._refresh_pool_drivers()
  154. return self._pool_drivers[driver]
  155. def add_pool(self, name, driver, **kwargs):
  156. ''' Add a storage pool to config
  157. :param name: name of storage pool to create
  158. :param driver: driver to use, see :py:meth:`pool_drivers` for
  159. available drivers
  160. :param kwargs: configuration parameters for storage pool,
  161. see :py:meth:`pool_driver_parameters` for a list
  162. '''
  163. # sort parameters only to ease testing, not required by API
  164. payload = 'name={}\n'.format(name) + \
  165. ''.join('{}={}\n'.format(key, value)
  166. for key, value in sorted(kwargs.items()))
  167. self.qubesd_call('dom0', 'admin.pool.Add', driver,
  168. payload.encode('utf-8'))
  169. def remove_pool(self, name):
  170. ''' Remove a storage pool '''
  171. self.qubesd_call('dom0', 'admin.pool.Remove', name, None)
  172. def get_label(self, label):
  173. '''Get label as identified by index or name
  174. :throws KeyError: when label is not found
  175. '''
  176. # first search for name, verbatim
  177. try:
  178. return self.labels[label]
  179. except KeyError:
  180. pass
  181. # then search for index
  182. if label.isdigit():
  183. for i in self.labels:
  184. if i.index == int(label):
  185. return i
  186. raise KeyError(label)
  187. @staticmethod
  188. def get_vm_class(clsname):
  189. '''Find the class for a domain.
  190. Compatibility function, client tools use str to identify domain classes.
  191. :param str clsname: name of the class
  192. :return str: class
  193. '''
  194. return clsname
  195. def add_new_vm(self, cls, name, label, template=None, pool=None,
  196. pools=None):
  197. '''Create new Virtual Machine
  198. Example usage with custom storage pools:
  199. >>> app = qubesadmin.Qubes()
  200. >>> pools = {'private': 'external'}
  201. >>> vm = app.add_new_vm('AppVM', 'my-new-vm', 'red',
  202. >>> 'my-template', pools=pools)
  203. >>> vm.netvm = app.domains['sys-whonix']
  204. :param str cls: name of VM class (`AppVM`, `TemplateVM` etc)
  205. :param str name: name of VM
  206. :param str label: label color for new VM
  207. :param str template: template to use (if apply for given VM class),
  208. can be also VM object; use None for default value
  209. :param str pool: storage pool to use instead of default one
  210. :param dict pools: storage pool for specific volumes
  211. :return new VM object
  212. '''
  213. if not isinstance(cls, str):
  214. cls = cls.__name__
  215. if template is qubesadmin.DEFAULT:
  216. template = None
  217. elif template is not None:
  218. template = str(template)
  219. if pool and pools:
  220. raise ValueError('only one of pool= and pools= can be used')
  221. method_prefix = 'admin.vm.Create.'
  222. payload = 'name={} label={}'.format(name, label)
  223. if pool:
  224. payload += ' pool={}'.format(str(pool))
  225. method_prefix = 'admin.vm.CreateInPool.'
  226. if pools:
  227. payload += ''.join(' pool:{}={}'.format(vol, str(pool))
  228. for vol, pool in sorted(pools.items()))
  229. method_prefix = 'admin.vm.CreateInPool.'
  230. self.qubesd_call('dom0', method_prefix + cls, template,
  231. payload.encode('utf-8'))
  232. self.domains.clear_cache()
  233. return self.domains[name]
  234. def clone_vm(self, src_vm, new_name, new_cls=None,
  235. pool=None, pools=None, ignore_errors=False):
  236. '''Clone Virtual Machine
  237. Example usage with custom storage pools:
  238. >>> app = qubesadmin.Qubes()
  239. >>> pools = {'private': 'external'}
  240. >>> src_vm = app.domains['personal']
  241. >>> vm = app.clone_vm(src_vm, 'my-new-vm', pools=pools)
  242. >>> vm.label = app.labels['green']
  243. :param QubesVM or str src_vm: source VM
  244. :param str new_name: name of new VM
  245. :param str new_cls: name of VM class (`AppVM`, `TemplateVM` etc) - use
  246. None to copy it from *src_vm*
  247. :param str pool: storage pool to use instead of default one
  248. :param dict pools: storage pool for specific volumes
  249. :param bool ignore_errors: should errors on meta-data setting be only
  250. logged, or abort the whole operation?
  251. :return new VM object
  252. '''
  253. if pool and pools:
  254. raise ValueError('only one of pool= and pools= can be used')
  255. if isinstance(src_vm, str):
  256. src_vm = self.domains[src_vm]
  257. if new_cls is None:
  258. new_cls = src_vm.klass
  259. template = getattr(src_vm, 'template', None)
  260. if template is not None:
  261. template = str(template)
  262. label = src_vm.label
  263. method_prefix = 'admin.vm.Create.'
  264. payload = 'name={} label={}'.format(new_name, label)
  265. if pool:
  266. payload += ' pool={}'.format(str(pool))
  267. method_prefix = 'admin.vm.CreateInPool.'
  268. if pools:
  269. payload += ''.join(' pool:{}={}'.format(vol, str(pool))
  270. for vol, pool in sorted(pools.items()))
  271. method_prefix = 'admin.vm.CreateInPool.'
  272. self.qubesd_call('dom0', method_prefix + new_cls, template,
  273. payload.encode('utf-8'))
  274. self.domains.clear_cache()
  275. dst_vm = self.domains[new_name]
  276. try:
  277. assert isinstance(dst_vm, qubesadmin.vm.QubesVM)
  278. for prop in src_vm.property_list():
  279. # handled by admin.vm.Create call
  280. if prop in ('name', 'qid', 'template', 'label', 'uuid', \
  281. 'installed_by_rpm'):
  282. continue
  283. if src_vm.property_is_default(prop):
  284. continue
  285. try:
  286. setattr(dst_vm, prop, getattr(src_vm, prop))
  287. except AttributeError:
  288. pass
  289. except qubesadmin.exc.QubesException as e:
  290. dst_vm.log.error(
  291. 'Failed to set {!s} property: {!s}'.format(prop, e))
  292. if not ignore_errors:
  293. raise
  294. for tag in src_vm.tags:
  295. if tag.startswith('created-by-'):
  296. continue
  297. try:
  298. dst_vm.tags.add(tag)
  299. except qubesadmin.exc.QubesException as e:
  300. dst_vm.log.error(
  301. 'Failed to add {!s} tag: {!s}'.format(tag, e))
  302. if not ignore_errors:
  303. raise
  304. for feature, value in src_vm.features.items():
  305. try:
  306. dst_vm.features[feature] = value
  307. except qubesadmin.exc.QubesException as e:
  308. dst_vm.log.error(
  309. 'Failed to set {!s} feature: {!s}'.format(feature, e))
  310. if not ignore_errors:
  311. raise
  312. try:
  313. dst_vm.firewall.save_rules(src_vm.firewall.rules)
  314. except qubesadmin.exc.QubesException as e:
  315. self.log.error('Failed to set firewall: %s', e)
  316. if not ignore_errors:
  317. raise
  318. except qubesadmin.exc.QubesException:
  319. if not ignore_errors:
  320. del self.domains[dst_vm.name]
  321. raise
  322. try:
  323. for dst_volume in sorted(dst_vm.volumes.values()):
  324. if not dst_volume.save_on_stop:
  325. # clone only persistent volumes
  326. continue
  327. src_volume = src_vm.volumes[dst_volume.name]
  328. dst_vm.log.info('Cloning {} volume'.format(dst_volume.name))
  329. dst_volume.clone(src_volume)
  330. except qubesadmin.exc.QubesException:
  331. del self.domains[dst_vm.name]
  332. raise
  333. return dst_vm
  334. def run_service(self, dest, service, filter_esc=False, user=None,
  335. localcmd=None, wait=True, **kwargs):
  336. '''Run qrexec service in a given destination
  337. *kwargs* are passed verbatim to :py:meth:`subprocess.Popen`.
  338. :param str dest: Destination - may be a VM name or empty
  339. string for default (for a given service)
  340. :param str service: service name
  341. :param bool filter_esc: filter escape sequences to protect terminal \
  342. emulator
  343. :param str user: username to run service as
  344. :param str localcmd: Command to connect stdin/stdout to
  345. :rtype: subprocess.Popen
  346. '''
  347. raise NotImplementedError
  348. class QubesLocal(QubesBase):
  349. '''Application object communicating through local socket.
  350. Used when running in dom0.
  351. '''
  352. qubesd_connection_type = 'socket'
  353. def qubesd_call(self, dest, method, arg=None, payload=None,
  354. payload_stream=None):
  355. '''
  356. Execute Admin API method.
  357. Only one of `payload` and `payload_stream` can be specified.
  358. :param dest: Destination VM name
  359. :param method: Full API method name ('admin...')
  360. :param arg: Method argument (if any)
  361. :param payload: Payload send to the method
  362. :param payload_stream: file-like object to read payload from
  363. :return: Data returned by qubesd (string)
  364. .. warning:: *payload_stream* will get closed by this function
  365. '''
  366. if payload and payload_stream:
  367. raise ValueError(
  368. 'Only one of payload and payload_stream can be used')
  369. if payload_stream:
  370. # payload_stream can be used for large amount of data,
  371. # so optimize for throughput, not latency: spawn actual qrexec
  372. # service implementation, which may use some optimization there (
  373. # see admin.vm.volume.Import - actual data handling is done with dd)
  374. method_path = os.path.join(
  375. qubesadmin.config.QREXEC_SERVICES_DIR, method)
  376. if not os.path.exists(method_path):
  377. raise qubesadmin.exc.QubesDaemonCommunicationError(
  378. '{} not found'.format(method_path))
  379. command = ['env', 'QREXEC_REMOTE_DOMAIN=dom0',
  380. 'QREXEC_REQUESTED_TARGET=' + dest, method_path, arg]
  381. if os.getuid() != 0:
  382. command.insert(0, 'sudo')
  383. proc = subprocess.Popen(command, stdin=payload_stream,
  384. stdout=subprocess.PIPE)
  385. payload_stream.close()
  386. (return_data, _) = proc.communicate()
  387. return self._parse_qubesd_response(return_data)
  388. try:
  389. client_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  390. client_socket.connect(qubesadmin.config.QUBESD_SOCKET)
  391. except IOError:
  392. # TODO:
  393. raise
  394. # src, method, dest, arg
  395. for call_arg in ('dom0', method, dest, arg):
  396. if call_arg is not None:
  397. client_socket.sendall(call_arg.encode('ascii'))
  398. client_socket.sendall(b'\0')
  399. if payload is not None:
  400. client_socket.sendall(payload)
  401. client_socket.shutdown(socket.SHUT_WR)
  402. return_data = client_socket.makefile('rb').read()
  403. client_socket.close()
  404. return self._parse_qubesd_response(return_data)
  405. def run_service(self, dest, service, filter_esc=False, user=None,
  406. localcmd=None, wait=True, **kwargs):
  407. '''Run qrexec service in a given destination
  408. :param str dest: Destination - may be a VM name or empty
  409. string for default (for a given service)
  410. :param str service: service name
  411. :param bool filter_esc: filter escape sequences to protect terminal \
  412. emulator
  413. :param str user: username to run service as
  414. :param str localcmd: Command to connect stdin/stdout to
  415. :param bool wait: wait for remote process to finish
  416. :param int connect_timeout: qrexec client connection timeout
  417. :rtype: subprocess.Popen
  418. '''
  419. if not dest:
  420. raise ValueError('Empty destination name allowed only from a VM')
  421. if not wait and localcmd:
  422. raise ValueError('wait=False incompatible with localcmd')
  423. try:
  424. self.qubesd_call(dest, 'admin.vm.Start')
  425. except qubesadmin.exc.QubesVMNotHaltedError:
  426. pass
  427. qrexec_opts = ['-d', dest]
  428. if filter_esc:
  429. qrexec_opts.extend(['-t'])
  430. if filter_esc or os.isatty(sys.stderr.fileno()):
  431. qrexec_opts.extend(['-T'])
  432. if localcmd:
  433. qrexec_opts.extend(['-l', localcmd])
  434. if user is None:
  435. user = 'DEFAULT'
  436. if not wait:
  437. qrexec_opts.extend(['-e'])
  438. if 'connect_timeout' in kwargs:
  439. qrexec_opts.extend(['-w', str(kwargs.pop('connect_timeout'))])
  440. kwargs.setdefault('stdin', subprocess.PIPE)
  441. kwargs.setdefault('stdout', subprocess.PIPE)
  442. kwargs.setdefault('stderr', subprocess.PIPE)
  443. proc = subprocess.Popen([qubesadmin.config.QREXEC_CLIENT] +
  444. qrexec_opts + ['{}:QUBESRPC {} dom0'.format(user, service)],
  445. **kwargs)
  446. return proc
  447. class QubesRemote(QubesBase):
  448. '''Application object communicating through qrexec services.
  449. Used when running in VM.
  450. '''
  451. qubesd_connection_type = 'qrexec'
  452. def qubesd_call(self, dest, method, arg=None, payload=None,
  453. payload_stream=None):
  454. '''
  455. Execute Admin API method.
  456. Only one of `payload` and `payload_stream` can be specified.
  457. :param dest: Destination VM name
  458. :param method: Full API method name ('admin...')
  459. :param arg: Method argument (if any)
  460. :param payload: Payload send to the method
  461. :param payload_stream: file-like object to read payload from
  462. :return: Data returned by qubesd (string)
  463. .. warning:: *payload_stream* will get closed by this function
  464. '''
  465. if payload and payload_stream:
  466. raise ValueError(
  467. 'Only one of payload and payload_stream can be used')
  468. service_name = method
  469. if arg is not None:
  470. service_name += '+' + arg
  471. p = subprocess.Popen([qubesadmin.config.QREXEC_CLIENT_VM,
  472. dest, service_name],
  473. stdin=(payload_stream or subprocess.PIPE),
  474. stdout=subprocess.PIPE,
  475. stderr=subprocess.PIPE)
  476. if payload_stream is not None:
  477. payload_stream.close()
  478. (stdout, stderr) = p.communicate(payload)
  479. if p.returncode != 0:
  480. raise qubesadmin.exc.QubesDaemonNoResponseError(
  481. 'Service call error: %s', stderr.decode())
  482. return self._parse_qubesd_response(stdout)
  483. def run_service(self, dest, service, filter_esc=False, user=None,
  484. localcmd=None, wait=True, **kwargs):
  485. '''Run qrexec service in a given destination
  486. :param str dest: Destination - may be a VM name or empty
  487. string for default (for a given service)
  488. :param str service: service name
  489. :param bool filter_esc: filter escape sequences to protect terminal \
  490. emulator
  491. :param str user: username to run service as
  492. :param str localcmd: Command to connect stdin/stdout to
  493. :param bool wait: wait for process to finish
  494. :rtype: subprocess.Popen
  495. '''
  496. if filter_esc:
  497. raise NotImplementedError(
  498. 'filter_esc not implemented for calls from VM')
  499. if user:
  500. raise ValueError(
  501. 'non-default user not possible for calls from VM')
  502. if not wait and localcmd:
  503. raise ValueError('wait=False incompatible with localcmd')
  504. if not wait:
  505. # qrexec-client-vm can only request service calls, which are
  506. # started using MSG_EXEC_CMDLINE qrexec protocol message; this
  507. # message means "start the process, pipe its stdin/out/err,
  508. # and when it terminates, send exit code back".
  509. # According to the protocol qrexec-client-vm needs to wait for
  510. # MSG_DATA_EXIT_CODE, so implementing wait=False would require
  511. # some protocol change (or protocol violation).
  512. raise NotImplementedError(
  513. 'wait=False not implemented for calls from VM')
  514. kwargs.setdefault('stdin', subprocess.PIPE)
  515. kwargs.setdefault('stdout', subprocess.PIPE)
  516. kwargs.setdefault('stderr', subprocess.PIPE)
  517. proc = subprocess.Popen([qubesadmin.config.QREXEC_CLIENT_VM,
  518. dest or '', service] + (shlex.split(localcmd) if localcmd else []),
  519. **kwargs)
  520. return proc