app.py 22 KB

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