backup.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2014-2015
  5. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  6. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 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 General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. #
  22. import hashlib
  23. import logging
  24. import multiprocessing
  25. import os
  26. import shutil
  27. import sys
  28. import qubes
  29. import qubes.backup
  30. import qubes.exc
  31. import qubes.storage.lvm
  32. import qubes.tests
  33. import qubes.tests.storage_lvm
  34. import qubes.vm
  35. import qubes.vm.appvm
  36. import qubes.vm.templatevm
  37. import qubes.vm.qubesvm
  38. # noinspection PyAttributeOutsideInit
  39. class BackupTestsMixin(object):
  40. class BackupErrorHandler(logging.Handler):
  41. def __init__(self, errors_queue, level=logging.NOTSET):
  42. super(BackupTestsMixin.BackupErrorHandler, self).__init__(level)
  43. self.errors_queue = errors_queue
  44. def emit(self, record):
  45. self.errors_queue.put(record.getMessage())
  46. def setUp(self):
  47. super(BackupTestsMixin, self).setUp()
  48. try:
  49. self.init_default_template(self.template)
  50. except AttributeError:
  51. self.init_default_template()
  52. self.error_detected = multiprocessing.Queue()
  53. self.log.debug("Creating backupvm")
  54. self.backupdir = os.path.join(os.environ["HOME"], "test-backup")
  55. if os.path.exists(self.backupdir):
  56. shutil.rmtree(self.backupdir)
  57. os.mkdir(self.backupdir)
  58. self.error_handler = self.BackupErrorHandler(self.error_detected,
  59. level=logging.WARNING)
  60. backup_log = logging.getLogger('qubes.backup')
  61. backup_log.addHandler(self.error_handler)
  62. def tearDown(self):
  63. super(BackupTestsMixin, self).tearDown()
  64. shutil.rmtree(self.backupdir)
  65. backup_log = logging.getLogger('qubes.backup')
  66. backup_log.removeHandler(self.error_handler)
  67. def fill_image(self, path, size=None, sparse=False):
  68. block_size = 4096
  69. self.log.debug("Filling %s" % path)
  70. f = open(path, 'wb+')
  71. if size is None:
  72. f.seek(0, 2)
  73. size = f.tell()
  74. f.seek(0)
  75. for block_num in range(int(size/block_size)):
  76. if sparse:
  77. f.seek(block_size, 1)
  78. f.write(b'a' * block_size)
  79. f.close()
  80. # NOTE: this was create_basic_vms
  81. def create_backup_vms(self, pool=None):
  82. template = self.app.default_template
  83. vms = []
  84. vmname = self.make_vm_name('test-net')
  85. self.log.debug("Creating %s" % vmname)
  86. testnet = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  87. name=vmname, template=template, provides_network=True,
  88. label='red')
  89. testnet.create_on_disk(pool=pool)
  90. testnet.features['service.ntpd'] = True
  91. vms.append(testnet)
  92. self.fill_image(testnet.storage.export('private'), 20*1024*1024)
  93. vmname = self.make_vm_name('test1')
  94. self.log.debug("Creating %s" % vmname)
  95. testvm1 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  96. name=vmname, template=template, label='red')
  97. testvm1.uses_default_netvm = False
  98. testvm1.netvm = testnet
  99. testvm1.create_on_disk(pool=pool)
  100. vms.append(testvm1)
  101. self.fill_image(testvm1.storage.export('private'), 100 * 1024 * 1024)
  102. vmname = self.make_vm_name('testhvm1')
  103. self.log.debug("Creating %s" % vmname)
  104. testvm2 = self.app.add_new_vm(qubes.vm.standalonevm.StandaloneVM,
  105. name=vmname,
  106. virt_mode='hvm',
  107. label='red')
  108. testvm2.create_on_disk(pool=pool)
  109. self.fill_image(testvm2.storage.export('root'), 1024 * 1024 * 1024, \
  110. True)
  111. vms.append(testvm2)
  112. vmname = self.make_vm_name('template')
  113. self.log.debug("Creating %s" % vmname)
  114. testvm3 = self.app.add_new_vm(qubes.vm.templatevm.TemplateVM,
  115. name=vmname, label='red')
  116. testvm3.create_on_disk(pool=pool)
  117. self.fill_image(testvm3.storage.export('root'), 100 * 1024 * 1024, True)
  118. vms.append(testvm3)
  119. vmname = self.make_vm_name('custom')
  120. self.log.debug("Creating %s" % vmname)
  121. testvm4 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  122. name=vmname, template=testvm3, label='red')
  123. testvm4.create_on_disk(pool=pool)
  124. vms.append(testvm4)
  125. self.app.save()
  126. return vms
  127. def make_backup(self, vms, target=None, expect_failure=False, **kwargs):
  128. if target is None:
  129. target = self.backupdir
  130. try:
  131. backup = qubes.backup.Backup(self.app, vms, **kwargs)
  132. except qubes.exc.QubesException as e:
  133. if not expect_failure:
  134. self.fail("QubesException during backup_prepare: %s" % str(e))
  135. else:
  136. raise
  137. if 'passphrase' not in kwargs:
  138. backup.passphrase = 'qubes'
  139. backup.target_dir = target
  140. try:
  141. backup.backup_do()
  142. except qubes.exc.QubesException as e:
  143. if not expect_failure:
  144. self.fail("QubesException during backup_do: %s" % str(e))
  145. else:
  146. raise
  147. def restore_backup(self, source=None, appvm=None, options=None,
  148. expect_errors=None, manipulate_restore_info=None,
  149. passphrase='qubes'):
  150. if source is None:
  151. backupfile = os.path.join(self.backupdir,
  152. sorted(os.listdir(self.backupdir))[-1])
  153. else:
  154. backupfile = source
  155. with self.assertNotRaises(qubes.exc.QubesException):
  156. restore_op = qubes.backup.BackupRestore(
  157. self.app, backupfile, appvm, passphrase)
  158. if options:
  159. for key, value in options.items():
  160. setattr(restore_op.options, key, value)
  161. restore_info = restore_op.get_restore_info()
  162. if callable(manipulate_restore_info):
  163. restore_info = manipulate_restore_info(restore_info)
  164. self.log.debug(restore_op.get_restore_summary(restore_info))
  165. with self.assertNotRaises(qubes.exc.QubesException):
  166. restore_op.restore_do(restore_info)
  167. errors = []
  168. if expect_errors is None:
  169. expect_errors = []
  170. else:
  171. self.assertFalse(self.error_detected.empty(),
  172. "Restore errors expected, but none detected")
  173. while not self.error_detected.empty():
  174. current_error = self.error_detected.get()
  175. if any(map(current_error.startswith, expect_errors)):
  176. continue
  177. errors.append(current_error)
  178. self.assertTrue(len(errors) == 0,
  179. "Error(s) detected during backup_restore_do: %s" %
  180. '\n'.join(errors))
  181. if not appvm and not os.path.isdir(backupfile):
  182. os.unlink(backupfile)
  183. def create_sparse(self, path, size):
  184. f = open(path, "w")
  185. f.truncate(size)
  186. f.close()
  187. def vm_checksum(self, vms):
  188. hashes = {}
  189. for vm in vms:
  190. assert isinstance(vm, qubes.vm.qubesvm.QubesVM)
  191. hashes[vm.name] = {}
  192. for name, volume in vm.volumes.items():
  193. if not volume.rw or not volume.save_on_stop:
  194. continue
  195. vol_path = vm.storage.get_pool(volume).export(volume)
  196. hasher = hashlib.sha1()
  197. with open(vol_path, 'rb') as afile:
  198. for buf in iter(lambda: afile.read(4096000), b''):
  199. hasher.update(buf)
  200. hashes[vm.name][name] = hasher.hexdigest()
  201. return hashes
  202. def assertCorrectlyRestored(self, orig_vms, orig_hashes):
  203. ''' Verify if restored VMs are identical to those before backup.
  204. :param orig_vms: collection of original QubesVM objects
  205. :param orig_hashes: result of :py:meth:`vm_checksum` on original VMs,
  206. before backup
  207. :return:
  208. '''
  209. for vm in orig_vms:
  210. self.assertIn(vm.name, self.app.domains)
  211. restored_vm = self.app.domains[vm.name]
  212. for prop in ('name', 'kernel',
  213. 'memory', 'maxmem', 'kernelopts',
  214. 'services', 'vcpus', 'features'
  215. 'include_in_backups', 'default_user', 'qrexec_timeout',
  216. 'autostart', 'pci_strictreset', 'debug',
  217. 'internal'):
  218. if not hasattr(vm, prop):
  219. continue
  220. self.assertEqual(
  221. getattr(vm, prop), getattr(restored_vm, prop),
  222. "VM {} - property {} not properly restored".format(
  223. vm.name, prop))
  224. for prop in ('netvm', 'template', 'label'):
  225. if not hasattr(vm, prop):
  226. continue
  227. orig_value = getattr(vm, prop)
  228. restored_value = getattr(restored_vm, prop)
  229. if orig_value and restored_value:
  230. self.assertEqual(orig_value.name, restored_value.name,
  231. "VM {} - property {} not properly restored".format(
  232. vm.name, prop))
  233. else:
  234. self.assertEqual(orig_value, restored_value,
  235. "VM {} - property {} not properly restored".format(
  236. vm.name, prop))
  237. for dev_class in vm.devices.keys():
  238. for dev in vm.devices[dev_class]:
  239. self.assertIn(dev, restored_vm.devices[dev_class],
  240. "VM {} - {} device not restored".format(
  241. vm.name, dev_class))
  242. if orig_hashes:
  243. hashes = self.vm_checksum([restored_vm])[restored_vm.name]
  244. self.assertEqual(orig_hashes[vm.name], hashes,
  245. "VM {} - disk images are not properly restored".format(
  246. vm.name))
  247. class TC_00_Backup(BackupTestsMixin, qubes.tests.SystemTestCase):
  248. def test_000_basic_backup(self):
  249. vms = self.create_backup_vms()
  250. orig_hashes = self.vm_checksum(vms)
  251. self.make_backup(vms)
  252. self.remove_vms(reversed(vms))
  253. self.restore_backup()
  254. self.assertCorrectlyRestored(vms, orig_hashes)
  255. self.remove_vms(reversed(vms))
  256. def test_001_compressed_backup(self):
  257. vms = self.create_backup_vms()
  258. orig_hashes = self.vm_checksum(vms)
  259. self.make_backup(vms, compressed=True)
  260. self.remove_vms(reversed(vms))
  261. self.restore_backup()
  262. self.assertCorrectlyRestored(vms, orig_hashes)
  263. def test_002_encrypted_backup(self):
  264. vms = self.create_backup_vms()
  265. orig_hashes = self.vm_checksum(vms)
  266. self.make_backup(vms, encrypted=True)
  267. self.remove_vms(reversed(vms))
  268. self.restore_backup()
  269. self.assertCorrectlyRestored(vms, orig_hashes)
  270. def test_003_compressed_encrypted_backup(self):
  271. vms = self.create_backup_vms()
  272. orig_hashes = self.vm_checksum(vms)
  273. self.make_backup(vms, compressed=True, encrypted=True)
  274. self.remove_vms(reversed(vms))
  275. self.restore_backup()
  276. self.assertCorrectlyRestored(vms, orig_hashes)
  277. def test_004_sparse_multipart(self):
  278. vms = []
  279. vmname = self.make_vm_name('testhvm2')
  280. self.log.debug("Creating %s" % vmname)
  281. hvmtemplate = self.app.add_new_vm(
  282. qubes.vm.templatevm.TemplateVM, name=vmname, virt_mode='hvm', label='red')
  283. hvmtemplate.create_on_disk()
  284. self.fill_image(
  285. os.path.join(hvmtemplate.dir_path, '00file'),
  286. 195 * 1024 * 1024 - 4096 * 3)
  287. self.fill_image(hvmtemplate.storage.export('private'),
  288. 195 * 1024 * 1024 - 4096 * 3)
  289. self.fill_image(hvmtemplate.storage.export('root'), 1024 * 1024 * 1024,
  290. sparse=True)
  291. vms.append(hvmtemplate)
  292. self.app.save()
  293. orig_hashes = self.vm_checksum(vms)
  294. self.make_backup(vms)
  295. self.remove_vms(reversed(vms))
  296. self.restore_backup()
  297. self.assertCorrectlyRestored(vms, orig_hashes)
  298. # TODO check vm.backup_timestamp
  299. def test_005_compressed_custom(self):
  300. vms = self.create_backup_vms()
  301. orig_hashes = self.vm_checksum(vms)
  302. self.make_backup(vms, compression_filter="bzip2")
  303. self.remove_vms(reversed(vms))
  304. self.restore_backup()
  305. self.assertCorrectlyRestored(vms, orig_hashes)
  306. def test_010_selective_restore(self):
  307. # create backup with internal dependencies (template, netvm etc)
  308. # try restoring only AppVMs (but not templates, netvms) - should
  309. # handle according to options set
  310. exclude = [
  311. self.make_vm_name('test-net'),
  312. self.make_vm_name('template')
  313. ]
  314. def exclude_some(restore_info):
  315. for name in exclude:
  316. restore_info.pop(name)
  317. return restore_info
  318. vms = self.create_backup_vms()
  319. orig_hashes = self.vm_checksum(vms)
  320. self.make_backup(vms, compression_filter="bzip2")
  321. self.remove_vms(reversed(vms))
  322. self.restore_backup(manipulate_restore_info=exclude_some)
  323. for vm in vms:
  324. if vm.name == self.make_vm_name('test1'):
  325. # netvm was set to 'test-inst-test-net' - excluded
  326. vm.netvm = qubes.property.DEFAULT
  327. elif vm.name == self.make_vm_name('custom'):
  328. # template was set to 'test-inst-template' - excluded
  329. vm.template = self.app.default_template
  330. vms = [vm for vm in vms if vm.name not in exclude]
  331. self.assertCorrectlyRestored(vms, orig_hashes)
  332. def test_020_encrypted_backup_non_ascii(self):
  333. vms = self.create_backup_vms()
  334. orig_hashes = self.vm_checksum(vms)
  335. self.make_backup(vms, encrypted=True, passphrase=u'zażółć gęślą jaźń')
  336. self.remove_vms(reversed(vms))
  337. self.restore_backup(passphrase=u'zażółć gęślą jaźń')
  338. self.assertCorrectlyRestored(vms, orig_hashes)
  339. def test_100_backup_dom0_no_restore(self):
  340. # do not write it into dom0 home itself...
  341. os.mkdir('/var/tmp/test-backup')
  342. self.backupdir = '/var/tmp/test-backup'
  343. self.make_backup([self.app.domains[0]])
  344. # TODO: think of some safe way to test restore...
  345. def test_200_restore_over_existing_directory(self):
  346. """
  347. Regression test for #1386
  348. :return:
  349. """
  350. vms = self.create_backup_vms()
  351. orig_hashes = self.vm_checksum(vms)
  352. self.make_backup(vms)
  353. self.remove_vms(reversed(vms))
  354. test_dir = vms[0].dir_path
  355. os.mkdir(test_dir)
  356. with open(os.path.join(test_dir, 'some-file.txt'), 'w') as f:
  357. f.write('test file\n')
  358. self.restore_backup(
  359. expect_errors=[
  360. '*** Directory {} already exists! It has been moved'.format(
  361. test_dir)
  362. ])
  363. self.assertCorrectlyRestored(vms, orig_hashes)
  364. def test_210_auto_rename(self):
  365. """
  366. Test for #869
  367. :return:
  368. """
  369. vms = self.create_backup_vms()
  370. self.make_backup(vms)
  371. self.restore_backup(options={
  372. 'rename_conflicting': True
  373. })
  374. for vm in vms:
  375. with self.assertNotRaises(
  376. (qubes.exc.QubesVMNotFoundError, KeyError)):
  377. restored_vm = self.app.domains[vm.name + '1']
  378. if vm.netvm and not vm.property_is_default('netvm'):
  379. self.assertEqual(restored_vm.netvm.name, vm.netvm.name + '1')
  380. def _find_pool(self, volume_group, thin_pool):
  381. ''' Returns the pool matching the specified ``volume_group`` &
  382. ``thin_pool``, or None.
  383. '''
  384. pools = [p for p in self.app.pools
  385. if issubclass(p.__class__, qubes.storage.lvm.ThinPool)]
  386. for pool in pools:
  387. if pool.volume_group == volume_group \
  388. and pool.thin_pool == thin_pool:
  389. return pool
  390. return None
  391. @qubes.tests.storage_lvm.skipUnlessLvmPoolExists
  392. def test_300_backup_lvm(self):
  393. volume_group, thin_pool = \
  394. qubes.tests.storage_lvm.DEFAULT_LVM_POOL.split('/', 1)
  395. self.pool = self._find_pool(volume_group, thin_pool)
  396. if not self.pool:
  397. self.pool = self.app.add_pool(
  398. **qubes.tests.storage_lvm.POOL_CONF)
  399. self.created_pool = True
  400. vms = self.create_backup_vms(pool=self.pool)
  401. orig_hashes = self.vm_checksum(vms)
  402. self.make_backup(vms)
  403. self.remove_vms(reversed(vms))
  404. self.restore_backup()
  405. self.assertCorrectlyRestored(vms, orig_hashes)
  406. self.remove_vms(reversed(vms))
  407. @qubes.tests.storage_lvm.skipUnlessLvmPoolExists
  408. def test_301_restore_to_lvm(self):
  409. volume_group, thin_pool = \
  410. qubes.tests.storage_lvm.DEFAULT_LVM_POOL.split('/', 1)
  411. self.pool = self._find_pool(volume_group, thin_pool)
  412. if not self.pool:
  413. self.pool = self.app.add_pool(
  414. **qubes.tests.storage_lvm.POOL_CONF)
  415. self.created_pool = True
  416. vms = self.create_backup_vms()
  417. orig_hashes = self.vm_checksum(vms)
  418. self.make_backup(vms)
  419. self.remove_vms(reversed(vms))
  420. self.restore_backup(options={'override_pool': self.pool.name})
  421. self.assertCorrectlyRestored(vms, orig_hashes)
  422. for vm in vms:
  423. vm = self.app.domains[vm.name]
  424. for volume in vm.volumes.values():
  425. if volume.save_on_stop:
  426. self.assertEqual(volume.pool, self.pool.name)
  427. self.remove_vms(reversed(vms))
  428. class TC_10_BackupVMMixin(BackupTestsMixin):
  429. def setUp(self):
  430. super(TC_10_BackupVMMixin, self).setUp()
  431. self.backupvm = self.app.add_new_vm(
  432. qubes.vm.appvm.AppVM,
  433. label='red',
  434. name=self.make_vm_name('backupvm'),
  435. template=self.template
  436. )
  437. self.backupvm.create_on_disk()
  438. def test_100_send_to_vm_file_with_spaces(self):
  439. vms = self.create_backup_vms()
  440. self.backupvm.start()
  441. self.loop.run_until_complete(self.backupvm.run_for_stdio(
  442. "mkdir '/var/tmp/backup directory'"))
  443. self.make_backup(vms, target_vm=self.backupvm,
  444. compressed=True, encrypted=True,
  445. target='/var/tmp/backup directory')
  446. self.remove_vms(reversed(vms))
  447. (backup_path, _) = self.loop.run_until_complete(
  448. self.backupvm.run_for_stdio("ls /var/tmp/backup*/qubes-backup*"))
  449. backup_path = backup_path.decode().strip()
  450. self.restore_backup(source=backup_path,
  451. appvm=self.backupvm)
  452. def test_110_send_to_vm_command(self):
  453. vms = self.create_backup_vms()
  454. self.backupvm.start()
  455. self.make_backup(vms, target_vm=self.backupvm,
  456. compressed=True, encrypted=True,
  457. target='dd of=/var/tmp/backup-test')
  458. self.remove_vms(reversed(vms))
  459. self.restore_backup(source='dd if=/var/tmp/backup-test',
  460. appvm=self.backupvm)
  461. def test_110_send_to_vm_no_space(self):
  462. """
  463. Check whether backup properly report failure when no enough space is
  464. available
  465. :return:
  466. """
  467. vms = self.create_backup_vms()
  468. self.backupvm.start()
  469. self.loop.run_until_complete(self.backupvm.run_for_stdio(
  470. # Debian 7 has too old losetup to handle loop-control device
  471. "mknod /dev/loop0 b 7 0;"
  472. "truncate -s 50M /home/user/backup.img && "
  473. "mkfs.ext4 -F /home/user/backup.img && "
  474. "mkdir /home/user/backup && "
  475. "mount /home/user/backup.img /home/user/backup -o loop &&"
  476. "chmod 777 /home/user/backup",
  477. user="root"))
  478. with self.assertRaises(qubes.exc.QubesException):
  479. self.make_backup(vms, target_vm=self.backupvm,
  480. compressed=False, encrypted=True,
  481. target='/home/user/backup',
  482. expect_failure=True)
  483. def load_tests(loader, tests, pattern):
  484. try:
  485. app = qubes.Qubes()
  486. templates = [vm.name for vm in app.domains if
  487. isinstance(vm, qubes.vm.templatevm.TemplateVM)]
  488. except OSError:
  489. templates = []
  490. for template in templates:
  491. tests.addTests(loader.loadTestsFromTestCase(
  492. type(
  493. 'TC_10_BackupVM_' + template,
  494. (TC_10_BackupVMMixin, qubes.tests.QubesTestCase),
  495. {'template': template})))
  496. return tests