app.py 22 KB

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