basic.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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 program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program 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
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. from distutils import spawn
  24. import asyncio
  25. import os
  26. import subprocess
  27. import tempfile
  28. import time
  29. import unittest
  30. import qubes
  31. import qubes.firewall
  32. import qubes.tests
  33. import qubes.vm.appvm
  34. import qubes.vm.qubesvm
  35. import qubes.vm.standalonevm
  36. import qubes.vm.templatevm
  37. import libvirt # pylint: disable=import-error
  38. class TC_00_Basic(qubes.tests.SystemTestCase):
  39. def setUp(self):
  40. super(TC_00_Basic, self).setUp()
  41. self.init_default_template()
  42. def test_000_qubes_create(self):
  43. self.assertIsInstance(self.app, qubes.Qubes)
  44. def test_100_qvm_create(self):
  45. vmname = self.make_vm_name('appvm')
  46. vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  47. name=vmname, template=self.app.default_template,
  48. label='red')
  49. self.assertIsNotNone(vm)
  50. self.assertEqual(vm.name, vmname)
  51. self.assertEqual(vm.template, self.app.default_template)
  52. self.loop.run_until_complete(vm.create_on_disk())
  53. with self.assertNotRaises(qubes.exc.QubesException):
  54. self.loop.run_until_complete(vm.storage.verify())
  55. def test_040_qdb_watch(self):
  56. flag = set()
  57. def handler(vm, event, path):
  58. if path == '/test-watch-path':
  59. flag.add(True)
  60. vm = self.app.domains[0]
  61. vm.watch_qdb_path('/test-watch-path')
  62. vm.add_handler('domain-qdb-change:/test-watch-path', handler)
  63. self.assertFalse(flag)
  64. vm.untrusted_qdb.write('/test-watch-path', 'test-value')
  65. self.loop.run_until_complete(asyncio.sleep(0.1))
  66. self.assertTrue(flag)
  67. class TC_01_Properties(qubes.tests.SystemTestCase):
  68. # pylint: disable=attribute-defined-outside-init
  69. def setUp(self):
  70. super(TC_01_Properties, self).setUp()
  71. self.init_default_template()
  72. self.vmname = self.make_vm_name('appvm')
  73. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM, name=self.vmname,
  74. template=self.app.default_template,
  75. label='red')
  76. self.loop.run_until_complete(self.vm.create_on_disk())
  77. self.addCleanup(self.cleanup_props)
  78. def cleanup_props(self):
  79. del self.vm
  80. @unittest.expectedFailure
  81. def test_030_clone(self):
  82. try:
  83. testvm1 = self.app.add_new_vm(
  84. qubes.vm.appvm.AppVM,
  85. name=self.make_vm_name("vm"),
  86. template=self.app.default_template,
  87. label='red')
  88. self.loop.run_until_complete(testvm1.create_on_disk())
  89. testvm2 = self.app.add_new_vm(testvm1.__class__,
  90. name=self.make_vm_name("clone"),
  91. template=testvm1.template,
  92. label='red')
  93. testvm2.clone_properties(testvm1)
  94. self.loop.run_until_complete(testvm2.clone_disk_files(testvm1))
  95. self.assertTrue(self.loop.run_until_complete(testvm1.storage.verify()))
  96. self.assertIn('source', testvm1.volumes['root'].config)
  97. self.assertNotEquals(testvm2, None)
  98. self.assertNotEquals(testvm2.volumes, {})
  99. self.assertIn('source', testvm2.volumes['root'].config)
  100. # qubes.xml reload
  101. self.app.save()
  102. testvm1 = self.app.domains[testvm1.qid]
  103. testvm2 = self.app.domains[testvm2.qid]
  104. self.assertEqual(testvm1.label, testvm2.label)
  105. self.assertEqual(testvm1.netvm, testvm2.netvm)
  106. self.assertEqual(testvm1.property_is_default('netvm'),
  107. testvm2.property_is_default('netvm'))
  108. self.assertEqual(testvm1.kernel, testvm2.kernel)
  109. self.assertEqual(testvm1.kernelopts, testvm2.kernelopts)
  110. self.assertEqual(testvm1.property_is_default('kernel'),
  111. testvm2.property_is_default('kernel'))
  112. self.assertEqual(testvm1.property_is_default('kernelopts'),
  113. testvm2.property_is_default('kernelopts'))
  114. self.assertEqual(testvm1.memory, testvm2.memory)
  115. self.assertEqual(testvm1.maxmem, testvm2.maxmem)
  116. self.assertEqual(testvm1.devices, testvm2.devices)
  117. self.assertEqual(testvm1.include_in_backups,
  118. testvm2.include_in_backups)
  119. self.assertEqual(testvm1.default_user, testvm2.default_user)
  120. self.assertEqual(testvm1.features, testvm2.features)
  121. self.assertEqual(testvm1.firewall.rules,
  122. testvm2.firewall.rules)
  123. # now some non-default values
  124. testvm1.netvm = None
  125. testvm1.label = 'orange'
  126. testvm1.memory = 512
  127. firewall = testvm1.firewall
  128. firewall.rules = [
  129. qubes.firewall.Rule(None, action='accept', dsthost='1.2.3.0/24',
  130. proto='tcp', dstports=22)]
  131. firewall.save()
  132. testvm3 = self.app.add_new_vm(testvm1.__class__,
  133. name=self.make_vm_name("clone2"),
  134. template=testvm1.template,
  135. label='red',)
  136. testvm3.clone_properties(testvm1)
  137. self.loop.run_until_complete(testvm3.clone_disk_files(testvm1))
  138. # qubes.xml reload
  139. self.app.save()
  140. testvm1 = self.app.domains[testvm1.qid]
  141. testvm3 = self.app.domains[testvm3.qid]
  142. self.assertEqual(testvm1.label, testvm3.label)
  143. self.assertEqual(testvm1.netvm, testvm3.netvm)
  144. self.assertEqual(testvm1.property_is_default('netvm'),
  145. testvm3.property_is_default('netvm'))
  146. self.assertEqual(testvm1.kernel, testvm3.kernel)
  147. self.assertEqual(testvm1.kernelopts, testvm3.kernelopts)
  148. self.assertEqual(testvm1.property_is_default('kernel'),
  149. testvm3.property_is_default('kernel'))
  150. self.assertEqual(testvm1.property_is_default('kernelopts'),
  151. testvm3.property_is_default('kernelopts'))
  152. self.assertEqual(testvm1.memory, testvm3.memory)
  153. self.assertEqual(testvm1.maxmem, testvm3.maxmem)
  154. self.assertEqual(testvm1.devices, testvm3.devices)
  155. self.assertEqual(testvm1.include_in_backups,
  156. testvm3.include_in_backups)
  157. self.assertEqual(testvm1.default_user, testvm3.default_user)
  158. self.assertEqual(testvm1.features, testvm3.features)
  159. self.assertEqual(testvm1.firewall.rules,
  160. testvm2.firewall.rules)
  161. finally:
  162. try:
  163. del testvm1
  164. except NameError:
  165. pass
  166. try:
  167. del testvm2
  168. except NameError:
  169. pass
  170. try:
  171. del testvm3
  172. except NameError:
  173. pass
  174. def test_020_name_conflict_app(self):
  175. # TODO decide what exception should be here
  176. with self.assertRaises((qubes.exc.QubesException, ValueError)):
  177. self.vm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  178. name=self.vmname, template=self.app.default_template,
  179. label='red')
  180. self.loop.run_until_complete(self.vm2.create_on_disk())
  181. def test_021_name_conflict_template(self):
  182. # TODO decide what exception should be here
  183. with self.assertRaises((qubes.exc.QubesException, ValueError)):
  184. self.vm2 = self.app.add_new_vm(qubes.vm.templatevm.TemplateVM,
  185. name=self.vmname, label='red')
  186. self.loop.run_until_complete(self.vm2.create_on_disk())
  187. class TC_02_QvmPrefs(qubes.tests.SystemTestCase):
  188. # pylint: disable=attribute-defined-outside-init
  189. def setUp(self):
  190. super(TC_02_QvmPrefs, self).setUp()
  191. self.init_default_template()
  192. self.sharedopts = ['--qubesxml', qubes.tests.XMLPATH]
  193. def setup_appvm(self):
  194. self.testvm = self.app.add_new_vm(
  195. qubes.vm.appvm.AppVM,
  196. name=self.make_vm_name("vm"),
  197. label='red')
  198. self.loop.run_until_complete(self.testvm.create_on_disk())
  199. self.app.save()
  200. def setup_hvm(self):
  201. self.testvm = self.app.add_new_vm(
  202. qubes.vm.appvm.AppVM,
  203. name=self.make_vm_name("hvm"),
  204. label='red')
  205. self.testvm.virt_mode = 'hvm'
  206. self.loop.run_until_complete(self.testvm.create_on_disk())
  207. self.app.save()
  208. def pref_set(self, name, value, valid=True):
  209. self.loop.run_until_complete(self._pref_set(name, value, valid))
  210. @asyncio.coroutine
  211. def _pref_set(self, name, value, valid=True):
  212. cmd = ['qvm-prefs']
  213. if value != '-D':
  214. cmd.append('--')
  215. cmd.extend((self.testvm.name, name, value))
  216. p = yield from asyncio.create_subprocess_exec(*cmd,
  217. stdout=subprocess.PIPE,
  218. stderr=subprocess.PIPE)
  219. (stdout, stderr) = yield from p.communicate()
  220. if valid:
  221. self.assertEqual(p.returncode, 0,
  222. "qvm-prefs .. '{}' '{}' failed: {}{}".format(
  223. name, value, stdout, stderr
  224. ))
  225. else:
  226. self.assertNotEquals(p.returncode, 0,
  227. "qvm-prefs should reject value '{}' for "
  228. "property '{}'".format(value, name))
  229. def pref_get(self, name):
  230. self.loop.run_until_complete(self._pref_get(name))
  231. @asyncio.coroutine
  232. def _pref_get(self, name):
  233. p = yield from asyncio.create_subprocess_exec(
  234. 'qvm-prefs', *self.sharedopts, '--', self.testvm.name, name,
  235. stdout=subprocess.PIPE)
  236. (stdout, _) = yield from p.communicate()
  237. self.assertEqual(p.returncode, 0)
  238. return stdout.strip()
  239. bool_test_values = [
  240. ('true', 'True', True),
  241. ('False', 'False', True),
  242. ('0', 'False', True),
  243. ('1', 'True', True),
  244. ('invalid', '', False)
  245. ]
  246. def execute_tests(self, name, values):
  247. """
  248. Helper function, which executes tests for given property.
  249. :param values: list of tuples (value, expected, valid),
  250. where 'value' is what should be set and 'expected' is what should
  251. qvm-prefs returns as a property value and 'valid' marks valid and
  252. invalid values - if it's False, qvm-prefs should reject the value
  253. :return: None
  254. """
  255. for (value, expected, valid) in values:
  256. self.pref_set(name, value, valid)
  257. if valid:
  258. self.assertEqual(self.pref_get(name), expected)
  259. @unittest.skip('test not converted to core3 API')
  260. def test_006_template(self):
  261. templates = [tpl for tpl in self.app.domains.values() if
  262. isinstance(tpl, qubes.vm.templatevm.TemplateVM)]
  263. if not templates:
  264. self.skipTest("No templates installed")
  265. some_template = templates[0].name
  266. self.setup_appvm()
  267. self.execute_tests('template', [
  268. (some_template, some_template, True),
  269. ('invalid', '', False),
  270. ])
  271. @unittest.skip('test not converted to core3 API')
  272. def test_014_pcidevs(self):
  273. self.setup_appvm()
  274. self.execute_tests('pcidevs', [
  275. ('[]', '[]', True),
  276. ('[ "00:00.0" ]', "['00:00.0']", True),
  277. ('invalid', '', False),
  278. ('[invalid]', '', False),
  279. # TODO:
  280. # ('["12:12.0"]', '', False)
  281. ])
  282. @unittest.skip('test not converted to core3 API')
  283. def test_024_pv_reject_hvm_props(self):
  284. self.setup_appvm()
  285. self.execute_tests('guiagent_installed', [('False', '', False)])
  286. self.execute_tests('qrexec_installed', [('False', '', False)])
  287. self.execute_tests('drive', [('/tmp/drive.img', '', False)])
  288. self.execute_tests('timezone', [('localtime', '', False)])
  289. @unittest.skip('test not converted to core3 API')
  290. def test_025_hvm_reject_pv_props(self):
  291. self.setup_hvm()
  292. self.execute_tests('kernel', [('default', '', False)])
  293. self.execute_tests('kernelopts', [('default', '', False)])
  294. class TC_03_QvmRevertTemplateChanges(qubes.tests.SystemTestCase):
  295. # pylint: disable=attribute-defined-outside-init
  296. def setUp(self):
  297. super(TC_03_QvmRevertTemplateChanges, self).setUp()
  298. self.init_default_template()
  299. def cleanup_template(self):
  300. del self.test_template
  301. def setup_pv_template(self):
  302. self.test_template = self.app.add_new_vm(
  303. qubes.vm.templatevm.TemplateVM,
  304. name=self.make_vm_name("pv-clone"),
  305. label='red'
  306. )
  307. self.addCleanup(self.cleanup_template)
  308. self.test_template.clone_properties(self.app.default_template)
  309. self.loop.run_until_complete(
  310. self.test_template.clone_disk_files(self.app.default_template))
  311. self.app.save()
  312. def setup_hvm_template(self):
  313. self.test_template = self.app.add_new_vm(
  314. qubes.vm.templatevm.TemplateVM,
  315. name=self.make_vm_name("hvm"),
  316. label='red',
  317. virt_mode='hvm',
  318. )
  319. self.addCleanup(self.cleanup_template)
  320. self.loop.run_until_complete(self.test_template.create_on_disk())
  321. self.app.save()
  322. def get_rootimg_checksum(self):
  323. p = subprocess.Popen(
  324. ['sha1sum', self.test_template.volumes['root'].path],
  325. stdout=subprocess.PIPE)
  326. return p.communicate()[0]
  327. def _do_test(self):
  328. checksum_before = self.get_rootimg_checksum()
  329. self.loop.run_until_complete(self.test_template.start())
  330. self.shutdown_and_wait(self.test_template)
  331. checksum_changed = self.get_rootimg_checksum()
  332. if checksum_before == checksum_changed:
  333. self.log.warning("template not modified, test result will be "
  334. "unreliable")
  335. self.assertNotEqual(self.test_template.volumes['root'].revisions, {})
  336. pool_vid = repr(self.test_template.volumes['root']).strip("'")
  337. revert_cmd = ['qvm-block', 'revert', pool_vid]
  338. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  339. *revert_cmd))
  340. self.loop.run_until_complete(p.wait())
  341. self.assertEqual(p.returncode, 0)
  342. checksum_after = self.get_rootimg_checksum()
  343. self.assertEqual(checksum_before, checksum_after)
  344. @unittest.expectedFailure
  345. def test_000_revert_pv(self):
  346. """
  347. Test qvm-revert-template-changes for PV template
  348. """
  349. self.setup_pv_template()
  350. self._do_test()
  351. @unittest.skip('HVM not yet implemented')
  352. def test_000_revert_hvm(self):
  353. """
  354. Test qvm-revert-template-changes for HVM template
  355. """
  356. # TODO: have some system there, so the root.img will get modified
  357. self.setup_hvm_template()
  358. self._do_test()
  359. class TC_30_Gui_daemon(qubes.tests.SystemTestCase):
  360. def setUp(self):
  361. super(TC_30_Gui_daemon, self).setUp()
  362. self.init_default_template()
  363. @unittest.skipUnless(
  364. spawn.find_executable('xdotool'),
  365. "xdotool not installed")
  366. def test_000_clipboard(self):
  367. testvm1 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  368. name=self.make_vm_name('vm1'), label='red')
  369. self.loop.run_until_complete(testvm1.create_on_disk())
  370. testvm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  371. name=self.make_vm_name('vm2'), label='red')
  372. self.loop.run_until_complete(testvm2.create_on_disk())
  373. self.app.save()
  374. self.loop.run_until_complete(asyncio.wait([
  375. testvm1.start(),
  376. testvm2.start()]))
  377. self.loop.run_until_complete(asyncio.wait([
  378. self.wait_for_session(testvm1),
  379. self.wait_for_session(testvm2)]))
  380. window_title = 'user@{}'.format(testvm1.name)
  381. self.loop.run_until_complete(testvm1.run(
  382. 'zenity --text-info --editable --title={}'.format(window_title)))
  383. self.wait_for_window(window_title)
  384. time.sleep(0.5)
  385. test_string = "test{}".format(testvm1.xid)
  386. # Type and copy some text
  387. subprocess.check_call(['xdotool', 'search', '--name', window_title,
  388. 'windowactivate', '--sync',
  389. 'type', test_string])
  390. # second xdotool call because type --terminator do not work (SEGV)
  391. # additionally do not use search here, so window stack will be empty
  392. # and xdotool will use XTEST instead of generating events manually -
  393. # this will be much better - at least because events will have
  394. # correct timestamp (so gui-daemon would not drop the copy request)
  395. subprocess.check_call(['xdotool',
  396. 'key', 'ctrl+a', 'ctrl+c', 'ctrl+shift+c',
  397. 'Escape'])
  398. clipboard_content = \
  399. open('/var/run/qubes/qubes-clipboard.bin', 'r').read().strip()
  400. self.assertEqual(clipboard_content, test_string,
  401. "Clipboard copy operation failed - content")
  402. clipboard_source = \
  403. open('/var/run/qubes/qubes-clipboard.bin.source',
  404. 'r').read().strip()
  405. self.assertEqual(clipboard_source, testvm1.name,
  406. "Clipboard copy operation failed - owner")
  407. # Then paste it to the other window
  408. window_title = 'user@{}'.format(testvm2.name)
  409. p = self.loop.run_until_complete(testvm2.run(
  410. 'zenity --entry --title={} > /tmp/test.txt'.format(window_title)))
  411. self.wait_for_window(window_title)
  412. subprocess.check_call(['xdotool', 'key', '--delay', '100',
  413. 'ctrl+shift+v', 'ctrl+v', 'Return'])
  414. self.loop.run_until_complete(p.wait())
  415. # And compare the result
  416. (test_output, _) = self.loop.run_until_complete(
  417. testvm2.run_for_stdio('cat /tmp/test.txt'))
  418. self.assertEqual(test_string, test_output.strip().decode('ascii'))
  419. clipboard_content = \
  420. open('/var/run/qubes/qubes-clipboard.bin', 'r').read().strip()
  421. self.assertEqual(clipboard_content, "",
  422. "Clipboard not wiped after paste - content")
  423. clipboard_source = \
  424. open('/var/run/qubes/qubes-clipboard.bin.source', 'r').\
  425. read().strip()
  426. self.assertEqual(clipboard_source, "",
  427. "Clipboard not wiped after paste - owner")
  428. class TC_05_StandaloneVM(qubes.tests.SystemTestCase):
  429. def setUp(self):
  430. super(TC_05_StandaloneVM, self).setUp()
  431. self.init_default_template()
  432. def test_000_create_start(self):
  433. testvm1 = self.app.add_new_vm(qubes.vm.standalonevm.StandaloneVM,
  434. name=self.make_vm_name('vm1'), label='red')
  435. testvm1.features['qrexec'] = True
  436. self.loop.run_until_complete(
  437. testvm1.clone_disk_files(self.app.default_template))
  438. self.app.save()
  439. self.loop.run_until_complete(testvm1.start())
  440. self.assertEqual(testvm1.get_power_state(), "Running")
  441. def test_100_resize_root_img(self):
  442. testvm1 = self.app.add_new_vm(qubes.vm.standalonevm.StandaloneVM,
  443. name=self.make_vm_name('vm1'), label='red')
  444. testvm1.features['qrexec'] = True
  445. self.loop.run_until_complete(
  446. testvm1.clone_disk_files(self.app.default_template))
  447. self.app.save()
  448. self.loop.run_until_complete(
  449. testvm1.storage.resize(testvm1.volumes['root'], 20 * 1024 ** 3))
  450. self.assertEqual(testvm1.volumes['root'].size, 20 * 1024 ** 3)
  451. self.loop.run_until_complete(testvm1.start())
  452. # new_size in 1k-blocks
  453. (new_size, _) = self.loop.run_until_complete(
  454. testvm1.run_for_stdio('df --output=size /|tail -n 1'))
  455. # some safety margin for FS metadata
  456. self.assertGreater(int(new_size.strip()), 19 * 1024 ** 2)
  457. # vim: ts=4 sw=4 et