app.py 22 KB

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