basic.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. # pylint: disable=invalid-name
  2. #
  3. # The Qubes OS Project, https://www.qubes-os.org/
  4. #
  5. # Copyright (C) 2014-2015
  6. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2.1 of the License, or (at your option) any later version.
  13. #
  14. # This library is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. # Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  21. #
  22. from distutils import spawn
  23. import asyncio
  24. import os
  25. import subprocess
  26. import tempfile
  27. import time
  28. import unittest
  29. import collections
  30. import pkg_resources
  31. import shutil
  32. import qubes
  33. import qubes.firewall
  34. import qubes.tests
  35. import qubes.storage
  36. import qubes.vm.appvm
  37. import qubes.vm.qubesvm
  38. import qubes.vm.standalonevm
  39. import qubes.vm.templatevm
  40. import libvirt # pylint: disable=import-error
  41. class TC_00_Basic(qubes.tests.SystemTestCase):
  42. def setUp(self):
  43. super(TC_00_Basic, self).setUp()
  44. self.init_default_template()
  45. def test_000_qubes_create(self):
  46. self.assertIsInstance(self.app, qubes.Qubes)
  47. def test_100_qvm_create(self):
  48. vmname = self.make_vm_name('appvm')
  49. vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  50. name=vmname, template=self.app.default_template,
  51. label='red')
  52. self.assertIsNotNone(vm)
  53. self.assertEqual(vm.name, vmname)
  54. self.assertEqual(vm.template, self.app.default_template)
  55. self.loop.run_until_complete(vm.create_on_disk())
  56. with self.assertNotRaises(qubes.exc.QubesException):
  57. self.loop.run_until_complete(vm.storage.verify())
  58. def test_040_qdb_watch(self):
  59. flag = set()
  60. def handler(vm, event, path):
  61. if path == '/test-watch-path':
  62. flag.add(True)
  63. vm = self.app.domains[0]
  64. vm.watch_qdb_path('/test-watch-path')
  65. vm.add_handler('domain-qdb-change:/test-watch-path', handler)
  66. self.assertFalse(flag)
  67. vm.untrusted_qdb.write('/test-watch-path', 'test-value')
  68. self.loop.run_until_complete(asyncio.sleep(0.1))
  69. self.assertTrue(flag)
  70. @unittest.skipUnless(
  71. spawn.find_executable('xdotool'), "xdotool not installed")
  72. def test_120_start_standalone_with_cdrom_dom0(self):
  73. vmname = self.make_vm_name('appvm')
  74. self.vm = self.app.add_new_vm('StandaloneVM', label='red', name=vmname)
  75. self.loop.run_until_complete(self.vm.create_on_disk())
  76. self.vm.kernel = None
  77. self.vm.virt_mode = 'hvm'
  78. iso_path = self.create_bootable_iso()
  79. # start the VM using qvm-start tool, to test --cdrom option there
  80. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  81. 'qvm-start', '--cdrom=dom0:' + iso_path, self.vm.name,
  82. stdout=subprocess.PIPE, stderr=subprocess.STDOUT))
  83. (stdout, _) = self.loop.run_until_complete(p.communicate())
  84. self.assertEqual(p.returncode, 0, stdout)
  85. # check if VM do not crash instantly
  86. self.loop.run_until_complete(asyncio.sleep(5))
  87. self.assertTrue(self.vm.is_running())
  88. # Type 'poweroff'
  89. subprocess.check_call(['xdotool', 'search', '--name', self.vm.name,
  90. 'type', 'poweroff\r'])
  91. self.loop.run_until_complete(asyncio.sleep(1))
  92. self.assertFalse(self.vm.is_running())
  93. def _test_200_on_domain_start(self, vm, event, **_kwargs):
  94. '''Simulate domain crash just after startup'''
  95. vm.libvirt_domain.destroy()
  96. def test_200_shutdown_event_race(self):
  97. '''Regression test for 3164'''
  98. vmname = self.make_vm_name('appvm')
  99. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  100. name=vmname, template=self.app.default_template,
  101. label='red')
  102. # help the luck a little - don't wait for qrexec to easier win the race
  103. self.vm.features['qrexec'] = False
  104. self.loop.run_until_complete(self.vm.create_on_disk())
  105. # another way to help the luck a little - make sure the private
  106. # volume is first in (normally unordered) dict - this way if any
  107. # volume action fails, it will be at or after private volume - not
  108. # before (preventing private volume action)
  109. old_volumes = self.vm.volumes
  110. self.vm.volumes = collections.OrderedDict()
  111. self.vm.volumes['private'] = old_volumes.pop('private')
  112. self.vm.volumes.update(old_volumes.items())
  113. del old_volumes
  114. self.loop.run_until_complete(self.vm.start())
  115. # kill it the way it does not give a chance for domain-shutdown it
  116. # execute
  117. self.vm.libvirt_domain.destroy()
  118. # now, lets try to start the VM again, before domain-shutdown event
  119. # got handled (#3164), and immediately trigger second domain-shutdown
  120. self.vm.add_handler('domain-start', self._test_200_on_domain_start)
  121. self.loop.run_until_complete(self.vm.start())
  122. # and give a chance for both domain-shutdown handlers to execute
  123. self.loop.run_until_complete(asyncio.sleep(1))
  124. with self.assertNotRaises(qubes.exc.QubesException):
  125. # if the above caused two domain-shutdown handlers being called
  126. # one after another, private volume is gone
  127. self.loop.run_until_complete(self.vm.storage.verify())
  128. def _test_201_on_domain_pre_start(self, vm, event, **_kwargs):
  129. '''Simulate domain crash just after startup'''
  130. if not self.domain_shutdown_handled and not self.test_failure_reason:
  131. self.test_failure_reason = \
  132. 'domain-shutdown event was not dispatched before subsequent ' \
  133. 'start'
  134. self.domain_shutdown_handled = False
  135. def _test_201_domain_shutdown_handler(self, vm, event, **kwargs):
  136. if self.domain_shutdown_handled and not self.test_failure_reason:
  137. self.test_failure_reason = 'domain-shutdown event received twice'
  138. self.domain_shutdown_handled = True
  139. def test_201_shutdown_event_race(self):
  140. '''Regression test for 3164 - pure events edition'''
  141. vmname = self.make_vm_name('appvm')
  142. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  143. name=vmname, template=self.app.default_template,
  144. label='red')
  145. # help the luck a little - don't wait for qrexec to easier win the race
  146. self.vm.features['qrexec'] = False
  147. self.loop.run_until_complete(self.vm.create_on_disk())
  148. # do not throw exception from inside event handler - test framework
  149. # will not recover from it (various objects leaks)
  150. self.test_failure_reason = None
  151. self.domain_shutdown_handled = False
  152. self.vm.add_handler('domain-shutdown',
  153. self._test_201_domain_shutdown_handler)
  154. self.loop.run_until_complete(self.vm.start())
  155. if self.test_failure_reason:
  156. self.fail(self.test_failure_reason)
  157. self.vm.add_handler('domain-pre-start',
  158. self._test_201_on_domain_pre_start)
  159. # kill it the way it does not give a chance for domain-shutdown it
  160. # execute
  161. self.vm.libvirt_domain.destroy()
  162. # now, lets try to start the VM again, before domain-shutdown event
  163. # got handled (#3164), and immediately trigger second domain-shutdown
  164. self.vm.add_handler('domain-start', self._test_200_on_domain_start)
  165. self.loop.run_until_complete(self.vm.start())
  166. if self.test_failure_reason:
  167. self.fail(self.test_failure_reason)
  168. # and give a chance for both domain-shutdown handlers to execute
  169. self.loop.run_until_complete(asyncio.sleep(1))
  170. if self.test_failure_reason:
  171. self.fail(self.test_failure_reason)
  172. self.assertTrue(self.domain_shutdown_handled,
  173. 'second domain-shutdown event was not dispatched after domain '
  174. 'shutdown')
  175. def _check_udev_for_uuid(self, uuid_value):
  176. udev_data_path = '/run/udev/data'
  177. for udev_item in os.listdir(udev_data_path):
  178. # check only block devices
  179. if not udev_item.startswith('b'):
  180. continue
  181. with open(os.path.join(udev_data_path, udev_item)) as udev_file:
  182. self.assertNotIn(uuid_value, udev_file.read(),
  183. 'udev parsed filesystem UUID! ' + udev_item)
  184. def assertVolumesExcludedFromUdev(self, vm):
  185. try:
  186. # first boot, mkfs private volume
  187. self.loop.run_until_complete(vm.start())
  188. # get private volume UUID
  189. private_uuid, _ = self.loop.run_until_complete(
  190. vm.run_for_stdio('blkid -o value /dev/xvdb', user='root'))
  191. private_uuid = private_uuid.decode().splitlines()[0]
  192. # now check if dom0 udev know about it - it shouldn't
  193. self._check_udev_for_uuid(private_uuid)
  194. # now restart the VM and check again
  195. self.loop.run_until_complete(vm.shutdown(wait=True))
  196. self.loop.run_until_complete(vm.start())
  197. self._check_udev_for_uuid(private_uuid)
  198. finally:
  199. del vm
  200. def test_202_udev_block_exclude_default(self):
  201. '''Check if VM images are excluded from udev parsing -
  202. default volume pool'''
  203. vmname = self.make_vm_name('appvm')
  204. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  205. name=vmname, template=self.app.default_template,
  206. label='red')
  207. self.loop.run_until_complete(self.vm.create_on_disk())
  208. self.assertVolumesExcludedFromUdev(self.vm)
  209. def test_203_udev_block_exclude_varlibqubes(self):
  210. '''Check if VM images are excluded from udev parsing -
  211. varlibqubes pool'''
  212. vmname = self.make_vm_name('appvm')
  213. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  214. name=vmname, template=self.app.default_template,
  215. label='red')
  216. self.loop.run_until_complete(self.vm.create_on_disk(
  217. pool=self.app.pools['varlibqubes']))
  218. self.assertVolumesExcludedFromUdev(self.vm)
  219. def test_204_udev_block_exclude_custom_file(self):
  220. '''Check if VM images are excluded from udev parsing -
  221. custom file pool'''
  222. vmname = self.make_vm_name('appvm')
  223. pool_path = tempfile.mkdtemp(
  224. prefix='qubes-pool-', dir='/var/tmp')
  225. self.addCleanup(shutil.rmtree, pool_path)
  226. pool = self.app.add_pool('test-filep', dir_path=pool_path,
  227. driver='file')
  228. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  229. name=vmname, template=self.app.default_template,
  230. label='red')
  231. self.loop.run_until_complete(self.vm.create_on_disk(
  232. pool=pool))
  233. self.assertVolumesExcludedFromUdev(self.vm)
  234. class TC_01_Properties(qubes.tests.SystemTestCase):
  235. # pylint: disable=attribute-defined-outside-init
  236. def setUp(self):
  237. super(TC_01_Properties, self).setUp()
  238. self.init_default_template()
  239. self.vmname = self.make_vm_name('appvm')
  240. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM, name=self.vmname,
  241. template=self.app.default_template,
  242. label='red')
  243. self.loop.run_until_complete(self.vm.create_on_disk())
  244. self.addCleanup(self.cleanup_props)
  245. def cleanup_props(self):
  246. del self.vm
  247. def test_030_clone(self):
  248. try:
  249. testvm1 = self.app.add_new_vm(
  250. qubes.vm.appvm.AppVM,
  251. name=self.make_vm_name("vm"),
  252. template=self.app.default_template,
  253. label='red')
  254. self.loop.run_until_complete(testvm1.create_on_disk())
  255. testvm2 = self.app.add_new_vm(testvm1.__class__,
  256. name=self.make_vm_name("clone"),
  257. template=testvm1.template,
  258. label='red')
  259. testvm2.clone_properties(testvm1)
  260. testvm2.firewall.clone(testvm1.firewall)
  261. self.loop.run_until_complete(testvm2.clone_disk_files(testvm1))
  262. self.assertTrue(self.loop.run_until_complete(testvm1.storage.verify()))
  263. self.assertIn('source', testvm1.volumes['root'].config)
  264. self.assertNotEquals(testvm2, None)
  265. self.assertNotEquals(testvm2.volumes, {})
  266. self.assertIn('source', testvm2.volumes['root'].config)
  267. # qubes.xml reload
  268. self.app.save()
  269. testvm1 = self.app.domains[testvm1.qid]
  270. testvm2 = self.app.domains[testvm2.qid]
  271. self.assertEqual(testvm1.label, testvm2.label)
  272. self.assertEqual(testvm1.netvm, testvm2.netvm)
  273. self.assertEqual(testvm1.property_is_default('netvm'),
  274. testvm2.property_is_default('netvm'))
  275. self.assertEqual(testvm1.kernel, testvm2.kernel)
  276. self.assertEqual(testvm1.kernelopts, testvm2.kernelopts)
  277. self.assertEqual(testvm1.property_is_default('kernel'),
  278. testvm2.property_is_default('kernel'))
  279. self.assertEqual(testvm1.property_is_default('kernelopts'),
  280. testvm2.property_is_default('kernelopts'))
  281. self.assertEqual(testvm1.memory, testvm2.memory)
  282. self.assertEqual(testvm1.maxmem, testvm2.maxmem)
  283. self.assertEqual(testvm1.devices, testvm2.devices)
  284. self.assertEqual(testvm1.include_in_backups,
  285. testvm2.include_in_backups)
  286. self.assertEqual(testvm1.default_user, testvm2.default_user)
  287. self.assertEqual(testvm1.features, testvm2.features)
  288. self.assertEqual(testvm1.firewall.rules,
  289. testvm2.firewall.rules)
  290. # now some non-default values
  291. testvm1.netvm = None
  292. testvm1.label = 'orange'
  293. testvm1.memory = 512
  294. firewall = testvm1.firewall
  295. firewall.rules = [
  296. qubes.firewall.Rule(None, action='accept', dsthost='1.2.3.0/24',
  297. proto='tcp', dstports=22)]
  298. firewall.save()
  299. testvm3 = self.app.add_new_vm(testvm1.__class__,
  300. name=self.make_vm_name("clone2"),
  301. template=testvm1.template,
  302. label='red',)
  303. testvm3.clone_properties(testvm1)
  304. testvm3.firewall.clone(testvm1.firewall)
  305. self.loop.run_until_complete(testvm3.clone_disk_files(testvm1))
  306. # qubes.xml reload
  307. self.app.save()
  308. testvm1 = self.app.domains[testvm1.qid]
  309. testvm3 = self.app.domains[testvm3.qid]
  310. self.assertEqual(testvm1.label, testvm3.label)
  311. self.assertEqual(testvm1.netvm, testvm3.netvm)
  312. self.assertEqual(testvm1.property_is_default('netvm'),
  313. testvm3.property_is_default('netvm'))
  314. self.assertEqual(testvm1.kernel, testvm3.kernel)
  315. self.assertEqual(testvm1.kernelopts, testvm3.kernelopts)
  316. self.assertEqual(testvm1.property_is_default('kernel'),
  317. testvm3.property_is_default('kernel'))
  318. self.assertEqual(testvm1.property_is_default('kernelopts'),
  319. testvm3.property_is_default('kernelopts'))
  320. self.assertEqual(testvm1.memory, testvm3.memory)
  321. self.assertEqual(testvm1.maxmem, testvm3.maxmem)
  322. self.assertEqual(testvm1.devices, testvm3.devices)
  323. self.assertEqual(testvm1.include_in_backups,
  324. testvm3.include_in_backups)
  325. self.assertEqual(testvm1.default_user, testvm3.default_user)
  326. self.assertEqual(testvm1.features, testvm3.features)
  327. self.assertEqual(testvm1.firewall.rules,
  328. testvm3.firewall.rules)
  329. finally:
  330. try:
  331. del firewall
  332. except NameError:
  333. pass
  334. try:
  335. del testvm1
  336. except NameError:
  337. pass
  338. try:
  339. del testvm2
  340. except NameError:
  341. pass
  342. try:
  343. del testvm3
  344. except NameError:
  345. pass
  346. def test_020_name_conflict_app(self):
  347. # TODO decide what exception should be here
  348. with self.assertRaises((qubes.exc.QubesException, ValueError)):
  349. self.vm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  350. name=self.vmname, template=self.app.default_template,
  351. label='red')
  352. self.loop.run_until_complete(self.vm2.create_on_disk())
  353. def test_021_name_conflict_template(self):
  354. # TODO decide what exception should be here
  355. with self.assertRaises((qubes.exc.QubesException, ValueError)):
  356. self.vm2 = self.app.add_new_vm(qubes.vm.templatevm.TemplateVM,
  357. name=self.vmname, label='red')
  358. self.loop.run_until_complete(self.vm2.create_on_disk())
  359. class TC_02_QvmPrefs(qubes.tests.SystemTestCase):
  360. # pylint: disable=attribute-defined-outside-init
  361. def setUp(self):
  362. super(TC_02_QvmPrefs, self).setUp()
  363. self.init_default_template()
  364. self.sharedopts = ['--qubesxml', qubes.tests.XMLPATH]
  365. def setup_appvm(self):
  366. self.testvm = self.app.add_new_vm(
  367. qubes.vm.appvm.AppVM,
  368. name=self.make_vm_name("vm"),
  369. label='red')
  370. self.loop.run_until_complete(self.testvm.create_on_disk())
  371. self.app.save()
  372. def setup_hvm(self):
  373. self.testvm = self.app.add_new_vm(
  374. qubes.vm.appvm.AppVM,
  375. name=self.make_vm_name("hvm"),
  376. label='red')
  377. self.testvm.virt_mode = 'hvm'
  378. self.loop.run_until_complete(self.testvm.create_on_disk())
  379. self.app.save()
  380. def pref_set(self, name, value, valid=True):
  381. self.loop.run_until_complete(self._pref_set(name, value, valid))
  382. @asyncio.coroutine
  383. def _pref_set(self, name, value, valid=True):
  384. cmd = ['qvm-prefs']
  385. if value != '-D':
  386. cmd.append('--')
  387. cmd.extend((self.testvm.name, name, value))
  388. p = yield from asyncio.create_subprocess_exec(*cmd,
  389. stdout=subprocess.PIPE,
  390. stderr=subprocess.PIPE)
  391. (stdout, stderr) = yield from p.communicate()
  392. if valid:
  393. self.assertEqual(p.returncode, 0,
  394. "qvm-prefs .. '{}' '{}' failed: {}{}".format(
  395. name, value, stdout, stderr
  396. ))
  397. else:
  398. self.assertNotEquals(p.returncode, 0,
  399. "qvm-prefs should reject value '{}' for "
  400. "property '{}'".format(value, name))
  401. def pref_get(self, name):
  402. self.loop.run_until_complete(self._pref_get(name))
  403. @asyncio.coroutine
  404. def _pref_get(self, name):
  405. p = yield from asyncio.create_subprocess_exec(
  406. 'qvm-prefs', *self.sharedopts, '--', self.testvm.name, name,
  407. stdout=subprocess.PIPE)
  408. (stdout, _) = yield from p.communicate()
  409. self.assertEqual(p.returncode, 0)
  410. return stdout.strip()
  411. bool_test_values = [
  412. ('true', 'True', True),
  413. ('False', 'False', True),
  414. ('0', 'False', True),
  415. ('1', 'True', True),
  416. ('invalid', '', False)
  417. ]
  418. def execute_tests(self, name, values):
  419. """
  420. Helper function, which executes tests for given property.
  421. :param values: list of tuples (value, expected, valid),
  422. where 'value' is what should be set and 'expected' is what should
  423. qvm-prefs returns as a property value and 'valid' marks valid and
  424. invalid values - if it's False, qvm-prefs should reject the value
  425. :return: None
  426. """
  427. for (value, expected, valid) in values:
  428. self.pref_set(name, value, valid)
  429. if valid:
  430. self.assertEqual(self.pref_get(name), expected)
  431. @unittest.skip('test not converted to core3 API')
  432. def test_006_template(self):
  433. templates = [tpl for tpl in self.app.domains.values() if
  434. isinstance(tpl, qubes.vm.templatevm.TemplateVM)]
  435. if not templates:
  436. self.skipTest("No templates installed")
  437. some_template = templates[0].name
  438. self.setup_appvm()
  439. self.execute_tests('template', [
  440. (some_template, some_template, True),
  441. ('invalid', '', False),
  442. ])
  443. @unittest.skip('test not converted to core3 API')
  444. def test_014_pcidevs(self):
  445. self.setup_appvm()
  446. self.execute_tests('pcidevs', [
  447. ('[]', '[]', True),
  448. ('[ "00:00.0" ]', "['00:00.0']", True),
  449. ('invalid', '', False),
  450. ('[invalid]', '', False),
  451. # TODO:
  452. # ('["12:12.0"]', '', False)
  453. ])
  454. @unittest.skip('test not converted to core3 API')
  455. def test_024_pv_reject_hvm_props(self):
  456. self.setup_appvm()
  457. self.execute_tests('guiagent_installed', [('False', '', False)])
  458. self.execute_tests('qrexec_installed', [('False', '', False)])
  459. self.execute_tests('drive', [('/tmp/drive.img', '', False)])
  460. self.execute_tests('timezone', [('localtime', '', False)])
  461. @unittest.skip('test not converted to core3 API')
  462. def test_025_hvm_reject_pv_props(self):
  463. self.setup_hvm()
  464. self.execute_tests('kernel', [('default', '', False)])
  465. self.execute_tests('kernelopts', [('default', '', False)])
  466. class TC_03_QvmRevertTemplateChanges(qubes.tests.SystemTestCase):
  467. # pylint: disable=attribute-defined-outside-init
  468. def setUp(self):
  469. super(TC_03_QvmRevertTemplateChanges, self).setUp()
  470. self.init_default_template()
  471. def cleanup_template(self):
  472. del self.test_template
  473. def setup_template(self):
  474. self.test_template = self.app.add_new_vm(
  475. qubes.vm.templatevm.TemplateVM,
  476. name=self.make_vm_name("pv-clone"),
  477. label='red'
  478. )
  479. self.addCleanup(self.cleanup_template)
  480. self.test_template.clone_properties(self.app.default_template)
  481. self.test_template.features.update(self.app.default_template.features)
  482. self.test_template.tags.update(self.app.default_template.tags)
  483. self.loop.run_until_complete(
  484. self.test_template.clone_disk_files(self.app.default_template))
  485. self.test_template.volumes['root'].revisions_to_keep = 3
  486. self.app.save()
  487. def get_rootimg_checksum(self):
  488. return subprocess.check_output(
  489. ['sha1sum', self.test_template.volumes['root'].path])
  490. def _do_test(self):
  491. checksum_before = self.get_rootimg_checksum()
  492. self.loop.run_until_complete(self.test_template.start())
  493. self.shutdown_and_wait(self.test_template)
  494. checksum_changed = self.get_rootimg_checksum()
  495. if checksum_before == checksum_changed:
  496. self.log.warning("template not modified, test result will be "
  497. "unreliable")
  498. self.assertNotEqual(self.test_template.volumes['root'].revisions, {})
  499. revert_cmd = ['qvm-volume', 'revert', self.test_template.name + ':root']
  500. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  501. *revert_cmd))
  502. self.loop.run_until_complete(p.wait())
  503. self.assertEqual(p.returncode, 0)
  504. del p
  505. checksum_after = self.get_rootimg_checksum()
  506. self.assertEqual(checksum_before, checksum_after)
  507. def test_000_revert_linux(self):
  508. """
  509. Test qvm-revert-template-changes for PV template
  510. """
  511. self.setup_template()
  512. self._do_test()
  513. @unittest.skip('TODO: some non-linux system')
  514. def test_001_revert_non_linux(self):
  515. """
  516. Test qvm-revert-template-changes for HVM template
  517. """
  518. # TODO: have some system there, so the root.img will get modified
  519. self.setup_template()
  520. self._do_test()
  521. class TC_30_Gui_daemon(qubes.tests.SystemTestCase):
  522. def setUp(self):
  523. super(TC_30_Gui_daemon, self).setUp()
  524. self.init_default_template()
  525. @unittest.skipUnless(
  526. spawn.find_executable('xdotool'),
  527. "xdotool not installed")
  528. def test_000_clipboard(self):
  529. testvm1 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  530. name=self.make_vm_name('vm1'), label='red')
  531. self.loop.run_until_complete(testvm1.create_on_disk())
  532. testvm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  533. name=self.make_vm_name('vm2'), label='red')
  534. self.loop.run_until_complete(testvm2.create_on_disk())
  535. self.app.save()
  536. self.loop.run_until_complete(asyncio.wait([
  537. testvm1.start(),
  538. testvm2.start()]))
  539. self.loop.run_until_complete(asyncio.wait([
  540. self.wait_for_session(testvm1),
  541. self.wait_for_session(testvm2)]))
  542. window_title = 'user@{}'.format(testvm1.name)
  543. self.loop.run_until_complete(testvm1.run(
  544. 'zenity --text-info --editable --title={}'.format(window_title)))
  545. self.wait_for_window(window_title)
  546. time.sleep(0.5)
  547. test_string = "test{}".format(testvm1.xid)
  548. # Type and copy some text
  549. subprocess.check_call(['xdotool', 'search', '--name', window_title,
  550. 'windowactivate', '--sync',
  551. 'type', test_string])
  552. # second xdotool call because type --terminator do not work (SEGV)
  553. # additionally do not use search here, so window stack will be empty
  554. # and xdotool will use XTEST instead of generating events manually -
  555. # this will be much better - at least because events will have
  556. # correct timestamp (so gui-daemon would not drop the copy request)
  557. subprocess.check_call(['xdotool',
  558. 'key', 'ctrl+a', 'ctrl+c', 'ctrl+shift+c',
  559. 'Escape'])
  560. clipboard_content = \
  561. open('/var/run/qubes/qubes-clipboard.bin', 'r').read().strip()
  562. self.assertEqual(clipboard_content, test_string,
  563. "Clipboard copy operation failed - content")
  564. clipboard_source = \
  565. open('/var/run/qubes/qubes-clipboard.bin.source',
  566. 'r').read().strip()
  567. self.assertEqual(clipboard_source, testvm1.name,
  568. "Clipboard copy operation failed - owner")
  569. # Then paste it to the other window
  570. window_title = 'user@{}'.format(testvm2.name)
  571. p = self.loop.run_until_complete(testvm2.run(
  572. 'zenity --entry --title={} > /tmp/test.txt'.format(window_title)))
  573. self.wait_for_window(window_title)
  574. subprocess.check_call(['xdotool', 'key', '--delay', '100',
  575. 'ctrl+shift+v', 'ctrl+v', 'Return'])
  576. self.loop.run_until_complete(p.wait())
  577. # And compare the result
  578. (test_output, _) = self.loop.run_until_complete(
  579. testvm2.run_for_stdio('cat /tmp/test.txt'))
  580. self.assertEqual(test_string, test_output.strip().decode('ascii'))
  581. clipboard_content = \
  582. open('/var/run/qubes/qubes-clipboard.bin', 'r').read().strip()
  583. self.assertEqual(clipboard_content, "",
  584. "Clipboard not wiped after paste - content")
  585. clipboard_source = \
  586. open('/var/run/qubes/qubes-clipboard.bin.source', 'r').\
  587. read().strip()
  588. self.assertEqual(clipboard_source, "",
  589. "Clipboard not wiped after paste - owner")
  590. class TC_05_StandaloneVMMixin(object):
  591. def setUp(self):
  592. super(TC_05_StandaloneVMMixin, self).setUp()
  593. self.init_default_template(self.template)
  594. def test_000_create_start(self):
  595. self.testvm1 = self.app.add_new_vm(qubes.vm.standalonevm.StandaloneVM,
  596. name=self.make_vm_name('vm1'), label='red')
  597. self.testvm1.features.update(self.app.default_template.features)
  598. self.loop.run_until_complete(
  599. self.testvm1.clone_disk_files(self.app.default_template))
  600. self.app.save()
  601. self.loop.run_until_complete(self.testvm1.start())
  602. self.assertEqual(self.testvm1.get_power_state(), "Running")
  603. def test_100_resize_root_img(self):
  604. self.testvm1 = self.app.add_new_vm(qubes.vm.standalonevm.StandaloneVM,
  605. name=self.make_vm_name('vm1'), label='red')
  606. self.testvm1.features.update(self.app.default_template.features)
  607. self.loop.run_until_complete(
  608. self.testvm1.clone_disk_files(self.app.default_template))
  609. self.app.save()
  610. try:
  611. self.loop.run_until_complete(
  612. self.testvm1.storage.resize(self.testvm1.volumes['root'],
  613. 20 * 1024 ** 3))
  614. except (subprocess.CalledProcessError,
  615. qubes.storage.StoragePoolException) as e:
  616. # exception object would leak VM reference
  617. self.fail(str(e))
  618. self.assertEqual(self.testvm1.volumes['root'].size, 20 * 1024 ** 3)
  619. self.loop.run_until_complete(self.testvm1.start())
  620. # new_size in 1k-blocks
  621. (new_size, _) = self.loop.run_until_complete(
  622. self.testvm1.run_for_stdio('df --output=size /|tail -n 1'))
  623. # some safety margin for FS metadata
  624. self.assertGreater(int(new_size.strip()), 19 * 1024 ** 2)
  625. def test_101_resize_root_img_online(self):
  626. self.testvm1 = self.app.add_new_vm(qubes.vm.standalonevm.StandaloneVM,
  627. name=self.make_vm_name('vm1'), label='red')
  628. self.testvm1.features['qrexec'] = True
  629. self.loop.run_until_complete(
  630. self.testvm1.clone_disk_files(self.app.default_template))
  631. self.testvm1.features.update(self.app.default_template.features)
  632. self.app.save()
  633. self.loop.run_until_complete(self.testvm1.start())
  634. try:
  635. self.loop.run_until_complete(
  636. self.testvm1.storage.resize(self.testvm1.volumes['root'],
  637. 20 * 1024 ** 3))
  638. except (subprocess.CalledProcessError,
  639. qubes.storage.StoragePoolException) as e:
  640. # exception object would leak VM reference
  641. self.fail(str(e))
  642. self.assertEqual(self.testvm1.volumes['root'].size, 20 * 1024 ** 3)
  643. # new_size in 1k-blocks
  644. (new_size, _) = self.loop.run_until_complete(
  645. self.testvm1.run_for_stdio('df --output=size /|tail -n 1'))
  646. # some safety margin for FS metadata
  647. self.assertGreater(int(new_size.strip()), 19 * 1024 ** 2)
  648. class TC_06_AppVMMixin(object):
  649. template = None
  650. def setUp(self):
  651. super(TC_06_AppVMMixin, self).setUp()
  652. self.init_default_template(self.template)
  653. @unittest.skipUnless(
  654. spawn.find_executable('xdotool'), "xdotool not installed")
  655. def test_121_start_standalone_with_cdrom_vm(self):
  656. cdrom_vmname = self.make_vm_name('cdrom')
  657. self.cdrom_vm = self.app.add_new_vm('AppVM', label='red',
  658. name=cdrom_vmname)
  659. self.loop.run_until_complete(self.cdrom_vm.create_on_disk())
  660. self.loop.run_until_complete(self.cdrom_vm.start())
  661. iso_path = self.create_bootable_iso()
  662. with open(iso_path, 'rb') as iso_f:
  663. self.loop.run_until_complete(
  664. self.cdrom_vm.run_for_stdio('cat > /home/user/boot.iso',
  665. stdin=iso_f))
  666. vmname = self.make_vm_name('appvm')
  667. self.vm = self.app.add_new_vm('StandaloneVM', label='red', name=vmname)
  668. self.loop.run_until_complete(self.vm.create_on_disk())
  669. self.vm.kernel = None
  670. self.vm.virt_mode = 'hvm'
  671. # start the VM using qvm-start tool, to test --cdrom option there
  672. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  673. 'qvm-start', '--cdrom=' + cdrom_vmname + ':/home/user/boot.iso',
  674. self.vm.name,
  675. stdout=subprocess.PIPE, stderr=subprocess.STDOUT))
  676. (stdout, _) = self.loop.run_until_complete(p.communicate())
  677. self.assertEqual(p.returncode, 0, stdout)
  678. # check if VM do not crash instantly
  679. self.loop.run_until_complete(asyncio.sleep(5))
  680. self.assertTrue(self.vm.is_running())
  681. # Type 'poweroff'
  682. subprocess.check_call(['xdotool', 'search', '--name', self.vm.name,
  683. 'type', 'poweroff\r'])
  684. self.loop.run_until_complete(asyncio.sleep(1))
  685. self.assertFalse(self.vm.is_running())
  686. def load_tests(loader, tests, pattern):
  687. for template in qubes.tests.list_templates():
  688. tests.addTests(loader.loadTestsFromTestCase(
  689. type(
  690. 'TC_05_StandaloneVM_' + template,
  691. (TC_05_StandaloneVMMixin, qubes.tests.SystemTestCase),
  692. {'template': template})))
  693. tests.addTests(loader.loadTestsFromTestCase(
  694. type(
  695. 'TC_06_AppVM_' + template,
  696. (TC_06_AppVMMixin, qubes.tests.SystemTestCase),
  697. {'template': template})))
  698. return tests
  699. # vim: ts=4 sw=4 et