callback.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2020 David Hobach <david@hobach.de>
  5. #
  6. # This library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  18. #
  19. import logging
  20. import subprocess
  21. import json
  22. from shlex import quote
  23. import qubes.storage
  24. class CallbackPool(qubes.storage.Pool):
  25. ''' Proxy storage pool driver adding callback functionality to other pool drivers.
  26. This way, users can extend storage pool drivers with custom functionality using the programming language of their choice.
  27. All configuration for this pool driver must be done in `/etc/qubes_callback.json`. Each configuration ID `conf_id` can be used
  28. to create a callback pool with e.g. `qvm-pool -o conf_id=your_conf_id -a pool_name callback`.
  29. Check `/usr/share/doc/qubes/qubes_callback.json.example` for an overview of the available options.
  30. Example applications of this driver:
  31. - custom pool mounts
  32. - encryption
  33. - debugging
  34. **Integration tests**:
  35. (all of these tests assume the `qubes_callback.json.example` configuration)
  36. Tests that should **fail**:
  37. ```
  38. qvm-pool -a test callback
  39. qvm-pool -o conf_id=non-existing -a test callback
  40. qvm-pool -o conf_id=conf_id -a test callback
  41. qvm-pool -o conf_id=testing-fail-missing-all -a test callback
  42. qvm-pool -o conf_id=testing-fail-missing-bdriver-args -a test callback
  43. ```
  44. Tests that should **work**:
  45. ```
  46. qvm-pool -o conf_id=testing-succ-file-01 -a test callback
  47. qvm-pool
  48. ls /mnt/test01
  49. qvm-pool -r test && sudo rm -rf /mnt/test01
  50. echo '#!/bin/bash'$'\n''i=0 ; for arg in "$@" ; do echo "$i: $arg" >> /tmp/callback.log ; (( i++)) ; done ; exit 0' > /usr/bin/testCbLogArgs && chmod +x /usr/bin/testCbLogArgs
  51. rm -f /tmp/callback.log
  52. qvm-pool -o conf_id=testing-succ-file-02 -a test callback
  53. qvm-pool
  54. ls /mnt/test02
  55. less /tmp/callback.log (on_ctor & on_setup should be there and in that order)
  56. qvm-create -l red -P test test-vm
  57. cat /tmp/callback.log (2x on_volume_create should be added)
  58. qvm-start test-vm
  59. qvm-volume | grep test-vm
  60. grep test-vm /var/lib/qubes/qubes.xml
  61. ls /mnt/test02/appvms/
  62. cat /tmp/callback.log (2x on_volume_start should be added)
  63. qvm-shutdown test-vm
  64. cat /tmp/callback.log (2x on_volume_stop should be added)
  65. #reboot
  66. cat /tmp/callback.log (only (!) on_ctor should be there)
  67. qvm-start test-vm
  68. cat /tmp/callback.log (on_sinit & 2x on_volume_start should be added)
  69. qvm-shutdown --wait test-vm && qvm-remove test-vm
  70. qvm-pool -r test && sudo rm -rf /mnt/test02
  71. less /tmp/callback.log (2x on_volume_stop, 2x on_volume_remove, on_destroy should be added)
  72. qvm-pool -o conf_id=testing-succ-file-03 -a test callback
  73. qvm-pool
  74. ls /mnt/test03
  75. less /tmp/callback.log (on_ctor & on_setup should be there, no more arguments)
  76. qvm-pool -r test && sudo rm -rf /mnt/test03
  77. less /tmp/callback.log (nothing should have been added)
  78. #luks pool test:
  79. #(make sure /mnt/test.key & /mnt/test.luks don't exist)
  80. qvm-pool -o conf_id=testing-succ-file-luks -a tluks callback
  81. ls /mnt/
  82. qvm-pool
  83. sudo cryptsetup status test-luks
  84. sudo mount | grep test_luks
  85. ls /mnt/test_luks/
  86. qvm-create -l red -P tluks test-luks (journalctl -b0 should show two on_volume_create callbacks)
  87. ls /mnt/test_luks/appvms/test-luks/
  88. qvm-volume | grep test-luks
  89. qvm-start test-luks
  90. #reboot
  91. grep luks /var/lib/qubes/qubes.xml
  92. sudo cryptsetup status test-luks (should be inactive due to late on_sinit!)
  93. qvm-start test-luks
  94. sudo mount | grep test_luks
  95. qvm-shutdown --wait test-luks
  96. qvm-remove test-luks
  97. qvm-pool -r tluks
  98. sudo cryptsetup status test-luks
  99. ls -l /mnt/
  100. #ephemeral luks pool test (key in RAM / lost on reboot):
  101. qvm-pool -o conf_id=testing-succ-file-luks-eph -a teph callback (executes setup() twice due to signal_back)
  102. ls /mnt/
  103. ls /mnt/ram
  104. md5sum /mnt/ram/teph.key (1)
  105. sudo mount|grep -E 'ram|test'
  106. sudo cryptsetup status test-eph
  107. qvm-create -l red -P teph test-eph (should execute two on_volume_create callbacks)
  108. qvm-volume | grep test-eph
  109. ls /mnt/test_eph/appvms
  110. qvm-start test-eph
  111. #reboot
  112. ls /mnt/ram (should be empty)
  113. ls /mnt/
  114. sudo mount|grep -E 'ram|test' (should be empty)
  115. qvm-ls | grep eph (should still have test-eph)
  116. grep eph /var/lib/qubes/qubes.xml (should still have test-eph)
  117. qvm-remove test-eph (should create a new encrypted pool backend)
  118. sudo cryptsetup status test-eph
  119. grep eph /var/lib/qubes/qubes.xml (only the pool should be left)
  120. ls /mnt/test_eph/ (should have the appvms directory etc.)
  121. qvm-create -l red -P teph test-eph2
  122. ls /mnt/test_eph/appvms/
  123. ls /mnt/ram
  124. qvm-start test-eph2
  125. md5sum /mnt/ram/teph.key ((2), different than in (1))
  126. qvm-shutdown --wait test-eph2
  127. systemctl restart qubesd
  128. qvm-start test-eph2 (trigger storage re-init)
  129. md5sum /mnt/ram/teph.key (same as in (2))
  130. qvm-shutdown test-eph2
  131. sudo umount /mnt/test_eph
  132. qvm-create -l red -P teph test-eph-fail (must fail with error in journalctl)
  133. ls /mnt/test_eph/ (should be empty)
  134. systemctl restart qubesd
  135. qvm-remove test-eph2
  136. qvm-create -l red -P teph test-eph3
  137. md5sum /mnt/ram/teph.key (same as in (2))
  138. sudo mount|grep -E 'ram|test'
  139. ls /mnt/test_eph/appvms/test_eph3
  140. qvm-remove test-eph3
  141. qvm-ls | grep test-eph
  142. qvm-pool -r teph
  143. grep eph /var/lib/qubes/qubes.xml (nothing should be left)
  144. qvm-pool
  145. ls /mnt/
  146. ls /mnt/ram/ (should be empty)
  147. ```
  148. '''
  149. driver = 'callback'
  150. config_path = '/etc/qubes_callback.json'
  151. def __init__(self, *, name, conf_id):
  152. '''Constructor.
  153. :param conf_id: Identifier as found inside the user-controlled configuration at `/etc/qubes_callback.json`.
  154. Non-ASCII, non-alphanumeric characters may be disallowed.
  155. **Security Note**: Depending on your RPC policy (admin.pool.Add) this constructor and its parameters
  156. may be called from an untrusted VM (not by default though). In those cases it may be security-relevant
  157. not to pick easily guessable `conf_id` values for your configuration as untrusted VMs may otherwise
  158. execute callbacks meant for other pools.
  159. '''
  160. #NOTE: attribute names **must** start with `_cb_` unless they are meant to be stored as self._cb_impl attributes
  161. self._cb_ctor_done = False #: Boolean to indicate whether or not `__init__` successfully ran through.
  162. self._cb_log = logging.getLogger('qubes.storage.callback') #: Logger instance.
  163. if not isinstance(conf_id, str):
  164. raise qubes.storage.StoragePoolException('conf_id is no String. VM attack?!')
  165. self._cb_conf_id = conf_id #: Configuration ID as passed to `__init__`.
  166. with open(CallbackPool.config_path) as json_file:
  167. conf_all = json.load(json_file)
  168. if not isinstance(conf_all, dict):
  169. raise qubes.storage.StoragePoolException('The file %s is supposed to define a dict.' % CallbackPool.config_path)
  170. try:
  171. self._cb_conf = conf_all[self._cb_conf_id] #: Dictionary holding all configuration for the given _cb_conf_id.
  172. except KeyError:
  173. #we cannot throw KeyErrors as we'll otherwise generate incorrect error messages @qubes.app._get_pool()
  174. raise qubes.storage.StoragePoolException('The specified conf_id %s could not be found inside %s.' % (self._cb_conf_id, CallbackPool.config_path))
  175. try:
  176. bdriver = self._cb_conf['bdriver']
  177. except KeyError:
  178. raise qubes.storage.StoragePoolException('Missing bdriver for the conf_id %s inside %s.' % (self._cb_conf_id, CallbackPool.config_path))
  179. self._cb_cmd_arg = json.dumps(self._cb_conf, sort_keys=True, indent=2) #: Full configuration as string in the format required by _callback().
  180. try:
  181. cls = qubes.utils.get_entry_point_one(qubes.storage.STORAGE_ENTRY_POINT, bdriver)
  182. except KeyError:
  183. raise qubes.storage.StoragePoolException('The driver %s was not found on your system.' % bdriver)
  184. if not issubclass(cls, qubes.storage.Pool):
  185. raise qubes.storage.StoragePoolException('The class %s must be a subclass of qubes.storage.Pool.' % cls)
  186. self._cb_requires_init = self._check_init() #: Boolean indicating whether late storage initialization yet has to be done or not.
  187. bdriver_args = self._cb_conf.get('bdriver_args', {})
  188. self._cb_impl = cls(name=name, **bdriver_args) #: Instance of the backend pool driver.
  189. super().__init__(name=name, revisions_to_keep=int(bdriver_args.get('revisions_to_keep', 1)))
  190. self._cb_ctor_done = True
  191. self._callback('on_ctor')
  192. def _check_init(self):
  193. ''' Whether or not this object requires late storage initialization via callback. '''
  194. cmd = self._cb_conf.get('on_sinit')
  195. if not cmd:
  196. cmd = self._cb_conf.get('cmd')
  197. return bool(cmd and cmd != '-')
  198. def _init(self, callback=True):
  199. ''' Late storage initialization on first use for e.g. decryption on first usage request.
  200. :param callback: Whether to trigger the `on_sinit` callback or not.
  201. '''
  202. #maybe TODO: if this function is meant to be run in parallel (are Pool operations asynchronous?), a function lock is required!
  203. if callback:
  204. self._callback('on_sinit')
  205. self._cb_requires_init = False
  206. def _assert_initialized(self, **kwargs):
  207. if self._cb_requires_init:
  208. self._init(**kwargs)
  209. def _callback(self, cb, cb_args=None):
  210. '''Run a callback.
  211. :param cb: Callback identifier string.
  212. :param cb_args: Optional list of arguments to pass to the command as last arguments.
  213. Only passed on for the generic command specified as `cmd`, not for `on_xyz` callbacks.
  214. '''
  215. if self._cb_ctor_done:
  216. cmd = self._cb_conf.get(cb)
  217. args = [] #on_xyz callbacks should never receive arguments
  218. if not cmd:
  219. if cb_args is None:
  220. cb_args = []
  221. cmd = self._cb_conf.get('cmd')
  222. args = [self.name, self._cb_conf['bdriver'], cb, self._cb_cmd_arg, *cb_args]
  223. if cmd and cmd != '-':
  224. args = filter(None, args)
  225. args = ' '.join(quote(str(a)) for a in args)
  226. cmd = ' '.join(filter(None, [cmd, args]))
  227. self._cb_log.info('callback driver executing (%s, %s %s): %s', self._cb_conf_id, cb, cb_args, cmd)
  228. res = subprocess.run(['/bin/bash', '-c', cmd], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
  229. #stdout & stderr are reported if the exit code check fails
  230. self._cb_log.debug('callback driver stdout (%s, %s %s): %s', self._cb_conf_id, cb, cb_args, res.stdout)
  231. self._cb_log.debug('callback driver stderr (%s, %s %s): %s', self._cb_conf_id, cb, cb_args, res.stderr)
  232. if self._cb_conf.get('signal_back', False) is True:
  233. self._process_signals(res.stdout)
  234. def _process_signals(self, out):
  235. '''Process any signals found inside a string.
  236. :param out: String to check for signals. Each signal must be on a dedicated line.
  237. They are executed in the order they are found. Callbacks are not triggered.
  238. '''
  239. for line in out.splitlines():
  240. if line == 'SIGNAL_setup':
  241. self._cb_log.info('callback driver processing SIGNAL_setup for %s', self._cb_conf_id)
  242. self._setup_cb(callback=False)
  243. @property
  244. def config(self):
  245. return {
  246. 'name': self.name,
  247. 'driver': CallbackPool.driver,
  248. 'conf_id': self._cb_conf_id,
  249. }
  250. def destroy(self):
  251. self._assert_initialized()
  252. ret = self._cb_impl.destroy()
  253. self._callback('on_destroy')
  254. return ret
  255. def init_volume(self, vm, volume_config):
  256. return CallbackVolume(self, self._cb_impl.init_volume(vm, volume_config))
  257. def _setup_cb(self, callback=True):
  258. if callback:
  259. self._callback('on_setup')
  260. self._assert_initialized(callback=False) #setup is assumed to include storage initialization
  261. return self._cb_impl.setup()
  262. def setup(self):
  263. return self._setup_cb()
  264. @property
  265. def volumes(self):
  266. for vol in self._cb_impl.volumes:
  267. yield CallbackVolume(self, vol)
  268. def list_volumes(self):
  269. for vol in self._cb_impl.list_volumes():
  270. yield CallbackVolume(self, vol)
  271. def get_volume(self, vid):
  272. return CallbackVolume(self, self._cb_impl.get_volume(vid))
  273. def included_in(self, app):
  274. if self._cb_requires_init:
  275. return None
  276. return self._cb_impl.included_in(app)
  277. @property
  278. def size(self):
  279. if self._cb_requires_init:
  280. return None
  281. return self._cb_impl.size
  282. @property
  283. def usage(self):
  284. if self._cb_requires_init:
  285. return None
  286. return self._cb_impl.usage
  287. #remaining method & attribute delegation ("delegation pattern")
  288. #Convention: The methods of this object have priority over the delegated object's methods. All attributes are
  289. # passed to the delegated object unless their name starts with '_cb_'.
  290. def __getattr__(self, name):
  291. #NOTE: This method is only called when an attribute cannot be resolved locally (not part of the instance,
  292. # not part of the class tree). It is also called for methods that cannot be resolved.
  293. return getattr(self._cb_impl, name)
  294. def __setattr__(self, name, value):
  295. #NOTE: This method is called on every attribute assignment.
  296. if name.startswith('_cb_'):
  297. super().__setattr__(name, value)
  298. else:
  299. setattr(self._cb_impl, name, value)
  300. def __delattr__(self, name):
  301. if name.startswith('_cb_'):
  302. super().__delattr__(name)
  303. else:
  304. delattr(self._cb_impl, name)
  305. class CallbackVolume:
  306. ''' Proxy volume adding callback functionality to other volumes.
  307. Required to support the `on_sinit` callback for late storage initialization.
  308. **Important for Developers**: Even though instances of this class behave exactly as `qubes.storage.Volume` instances,
  309. they are no such instances (e.g. `assert isinstance(obj, qubes.storage.Volume)` will fail).
  310. '''
  311. def __init__(self, pool, impl):
  312. '''Constructor.
  313. :param pool: `CallbackPool` of this volume
  314. :param impl: `qubes.storage.Volume` object to wrap
  315. '''
  316. assert isinstance(impl, qubes.storage.Volume), 'impl must be a qubes.storage.Volume instance. Found a %s instance.' % impl.__class__
  317. assert isinstance(pool, CallbackPool), 'pool must use a qubes.storage.CallbackPool instance. Found a %s instance.' % pool.__class__
  318. self._cb_pool = pool #: CallbackPool instance the Volume belongs to.
  319. self._cb_impl = impl #: Backend volume implementation instance.
  320. def _assert_initialized(self, **kwargs):
  321. return self._cb_pool._assert_initialized(**kwargs) # pylint: disable=protected-access
  322. def _callback(self, cb, cb_args=None, **kwargs):
  323. if cb_args is None:
  324. cb_args = []
  325. vol_args = [self.name, self.vid, *cb_args]
  326. return self._cb_pool._callback(cb, cb_args=vol_args, **kwargs) # pylint: disable=protected-access
  327. def create(self):
  328. self._assert_initialized()
  329. self._callback('on_volume_create')
  330. return self._cb_impl.create()
  331. def remove(self):
  332. self._assert_initialized()
  333. ret = self._cb_impl.remove()
  334. self._callback('on_volume_remove')
  335. return ret
  336. def resize(self, size):
  337. self._assert_initialized()
  338. self._callback('on_volume_resize', cb_args=[size])
  339. return self._cb_impl.resize(size)
  340. def start(self):
  341. self._assert_initialized()
  342. self._callback('on_volume_start')
  343. return self._cb_impl.start()
  344. def stop(self):
  345. self._assert_initialized()
  346. ret = self._cb_impl.stop()
  347. self._callback('on_volume_stop')
  348. return ret
  349. def import_data(self):
  350. self._assert_initialized()
  351. self._callback('on_volume_import_data')
  352. return self._cb_impl.import_data()
  353. def import_data_end(self, success):
  354. self._assert_initialized()
  355. ret = self._cb_impl.import_data_end(success)
  356. self._callback('on_volume_import_data_end', cb_args=[success])
  357. return ret
  358. def import_volume(self, src_volume):
  359. self._assert_initialized()
  360. self._callback('on_volume_import', cb_args=[src_volume.vid])
  361. return self._cb_impl.import_volume(src_volume)
  362. def is_dirty(self):
  363. if self._cb_pool._cb_requires_init: # pylint: disable=protected-access
  364. return False
  365. return self._cb_impl.is_dirty()
  366. def is_outdated(self):
  367. if self._cb_pool._cb_requires_init: # pylint: disable=protected-access
  368. return False
  369. return self._cb_impl.is_outdated()
  370. #remaining method & attribute delegation
  371. def __getattr__(self, name):
  372. if name in ['block_device', 'verify', 'revert', 'export']:
  373. self._assert_initialized()
  374. return getattr(self._cb_impl, name)
  375. def __setattr__(self, name, value):
  376. if name.startswith('_cb_'):
  377. super().__setattr__(name, value)
  378. else:
  379. setattr(self._cb_impl, name, value)
  380. def __delattr__(self, name):
  381. if name.startswith('_cb_'):
  382. super().__delattr__(name)
  383. else:
  384. delattr(self._cb_impl, name)