basic.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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 sys
  33. import qubes
  34. import qubes.firewall
  35. import qubes.tests
  36. import qubes.storage
  37. import qubes.vm.appvm
  38. import qubes.vm.qubesvm
  39. import qubes.vm.standalonevm
  40. import qubes.vm.templatevm
  41. import libvirt # pylint: disable=import-error
  42. class TC_00_Basic(qubes.tests.SystemTestCase):
  43. def setUp(self):
  44. super(TC_00_Basic, self).setUp()
  45. self.init_default_template()
  46. def test_000_qubes_create(self):
  47. self.assertIsInstance(self.app, qubes.Qubes)
  48. def test_100_qvm_create(self):
  49. vmname = self.make_vm_name('appvm')
  50. vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  51. name=vmname, template=self.app.default_template,
  52. label='red')
  53. self.assertIsNotNone(vm)
  54. self.assertEqual(vm.name, vmname)
  55. self.assertEqual(vm.template, self.app.default_template)
  56. self.loop.run_until_complete(vm.create_on_disk())
  57. with self.assertNotRaises(qubes.exc.QubesException):
  58. self.loop.run_until_complete(vm.storage.verify())
  59. def test_040_qdb_watch(self):
  60. flag = set()
  61. def handler(vm, event, path):
  62. if path == '/test-watch-path':
  63. flag.add(True)
  64. vm = self.app.domains[0]
  65. vm.watch_qdb_path('/test-watch-path')
  66. vm.add_handler('domain-qdb-change:/test-watch-path', handler)
  67. self.assertFalse(flag)
  68. vm.untrusted_qdb.write('/test-watch-path', 'test-value')
  69. self.loop.run_until_complete(asyncio.sleep(0.1))
  70. self.assertTrue(flag)
  71. @unittest.skipUnless(
  72. spawn.find_executable('xdotool'), "xdotool not installed")
  73. def test_120_start_standalone_with_cdrom_dom0(self):
  74. vmname = self.make_vm_name('appvm')
  75. self.vm = self.app.add_new_vm('StandaloneVM', label='red', name=vmname)
  76. self.loop.run_until_complete(self.vm.create_on_disk())
  77. self.vm.kernel = None
  78. self.vm.virt_mode = 'hvm'
  79. iso_path = self.create_bootable_iso()
  80. # start the VM using qvm-start tool, to test --cdrom option there
  81. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  82. 'qvm-start', '--cdrom=dom0:' + iso_path, self.vm.name,
  83. stdout=subprocess.PIPE, stderr=subprocess.STDOUT))
  84. (stdout, _) = self.loop.run_until_complete(p.communicate())
  85. self.assertEqual(p.returncode, 0, stdout)
  86. # check if VM do not crash instantly
  87. self.loop.run_until_complete(asyncio.sleep(5))
  88. self.assertTrue(self.vm.is_running())
  89. # Type 'poweroff'
  90. subprocess.check_call(['xdotool', 'search', '--name', self.vm.name,
  91. 'type', 'poweroff\r'])
  92. for _ in range(5):
  93. if not self.vm.is_running():
  94. break
  95. self.loop.run_until_complete(asyncio.sleep(1))
  96. self.assertFalse(self.vm.is_running())
  97. def _test_200_on_domain_start(self, vm, event, **_kwargs):
  98. '''Simulate domain crash just after startup'''
  99. vm.libvirt_domain.destroy()
  100. def test_200_shutdown_event_race(self):
  101. '''Regression test for 3164'''
  102. vmname = self.make_vm_name('appvm')
  103. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  104. name=vmname, template=self.app.default_template,
  105. label='red')
  106. # help the luck a little - don't wait for qrexec to easier win the race
  107. self.vm.features['qrexec'] = False
  108. self.loop.run_until_complete(self.vm.create_on_disk())
  109. # another way to help the luck a little - make sure the private
  110. # volume is first in (normally unordered) dict - this way if any
  111. # volume action fails, it will be at or after private volume - not
  112. # before (preventing private volume action)
  113. old_volumes = self.vm.volumes
  114. self.vm.volumes = collections.OrderedDict()
  115. self.vm.volumes['private'] = old_volumes.pop('private')
  116. self.vm.volumes.update(old_volumes.items())
  117. del old_volumes
  118. self.loop.run_until_complete(self.vm.start())
  119. # kill it the way it does not give a chance for domain-shutdown it
  120. # execute
  121. self.vm.libvirt_domain.destroy()
  122. # now, lets try to start the VM again, before domain-shutdown event
  123. # got handled (#3164), and immediately trigger second domain-shutdown
  124. self.vm.add_handler('domain-start', self._test_200_on_domain_start)
  125. self.loop.run_until_complete(self.vm.start())
  126. # and give a chance for both domain-shutdown handlers to execute
  127. self.loop.run_until_complete(asyncio.sleep(1))
  128. with self.assertNotRaises(qubes.exc.QubesException):
  129. # if the above caused two domain-shutdown handlers being called
  130. # one after another, private volume is gone
  131. self.loop.run_until_complete(self.vm.storage.verify())
  132. def _test_201_on_domain_pre_start(self, vm, event, **_kwargs):
  133. '''Simulate domain crash just after startup'''
  134. if not self.domain_shutdown_handled and not self.test_failure_reason:
  135. self.test_failure_reason = \
  136. 'domain-shutdown event was not dispatched before subsequent ' \
  137. 'start'
  138. self.domain_shutdown_handled = False
  139. def _test_201_domain_shutdown_handler(self, vm, event, **kwargs):
  140. if self.domain_shutdown_handled and not self.test_failure_reason:
  141. self.test_failure_reason = 'domain-shutdown event received twice'
  142. self.domain_shutdown_handled = True
  143. def test_201_shutdown_event_race(self):
  144. '''Regression test for 3164 - pure events edition'''
  145. vmname = self.make_vm_name('appvm')
  146. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  147. name=vmname, template=self.app.default_template,
  148. label='red')
  149. # help the luck a little - don't wait for qrexec to easier win the race
  150. self.vm.features['qrexec'] = False
  151. self.loop.run_until_complete(self.vm.create_on_disk())
  152. # do not throw exception from inside event handler - test framework
  153. # will not recover from it (various objects leaks)
  154. self.test_failure_reason = None
  155. self.domain_shutdown_handled = False
  156. self.vm.add_handler('domain-shutdown',
  157. self._test_201_domain_shutdown_handler)
  158. self.loop.run_until_complete(self.vm.start())
  159. if self.test_failure_reason:
  160. self.fail(self.test_failure_reason)
  161. self.vm.add_handler('domain-pre-start',
  162. self._test_201_on_domain_pre_start)
  163. # kill it the way it does not give a chance for domain-shutdown it
  164. # execute
  165. self.vm.libvirt_domain.destroy()
  166. # now, lets try to start the VM again, before domain-shutdown event
  167. # got handled (#3164), and immediately trigger second domain-shutdown
  168. self.vm.add_handler('domain-start', self._test_200_on_domain_start)
  169. self.loop.run_until_complete(self.vm.start())
  170. if self.test_failure_reason:
  171. self.fail(self.test_failure_reason)
  172. while self.vm.get_power_state() != 'Halted':
  173. self.loop.run_until_complete(asyncio.sleep(1))
  174. # and give a chance for both domain-shutdown handlers to execute
  175. self.loop.run_until_complete(asyncio.sleep(1))
  176. if self.test_failure_reason:
  177. self.fail(self.test_failure_reason)
  178. self.assertTrue(self.domain_shutdown_handled,
  179. 'second domain-shutdown event was not dispatched after domain '
  180. 'shutdown')
  181. def _check_udev_for_uuid(self, uuid_value):
  182. udev_data_path = '/run/udev/data'
  183. for udev_item in os.listdir(udev_data_path):
  184. # check only block devices
  185. if not udev_item.startswith('b'):
  186. continue
  187. with open(os.path.join(udev_data_path, udev_item)) as udev_file:
  188. self.assertNotIn(uuid_value, udev_file.read(),
  189. 'udev parsed filesystem UUID! ' + udev_item)
  190. def assertVolumesExcludedFromUdev(self, vm):
  191. try:
  192. # first boot, mkfs private volume
  193. self.loop.run_until_complete(vm.start())
  194. # get private volume UUID
  195. private_uuid, _ = self.loop.run_until_complete(
  196. vm.run_for_stdio('blkid -o value /dev/xvdb', user='root'))
  197. private_uuid = private_uuid.decode().splitlines()[0]
  198. # now check if dom0 udev know about it - it shouldn't
  199. self._check_udev_for_uuid(private_uuid)
  200. # now restart the VM and check again
  201. self.loop.run_until_complete(vm.shutdown(wait=True))
  202. self.loop.run_until_complete(vm.start())
  203. self._check_udev_for_uuid(private_uuid)
  204. finally:
  205. del vm
  206. def test_202_udev_block_exclude_default(self):
  207. '''Check if VM images are excluded from udev parsing -
  208. default volume pool'''
  209. vmname = self.make_vm_name('appvm')
  210. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  211. name=vmname, template=self.app.default_template,
  212. label='red')
  213. self.loop.run_until_complete(self.vm.create_on_disk())
  214. self.assertVolumesExcludedFromUdev(self.vm)
  215. def test_203_udev_block_exclude_varlibqubes(self):
  216. '''Check if VM images are excluded from udev parsing -
  217. varlibqubes pool'''
  218. vmname = self.make_vm_name('appvm')
  219. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  220. name=vmname, template=self.app.default_template,
  221. label='red')
  222. self.loop.run_until_complete(self.vm.create_on_disk(
  223. pool=self.app.pools['varlibqubes']))
  224. self.assertVolumesExcludedFromUdev(self.vm)
  225. def test_204_udev_block_exclude_custom_file(self):
  226. '''Check if VM images are excluded from udev parsing -
  227. custom file pool'''
  228. vmname = self.make_vm_name('appvm')
  229. pool_path = tempfile.mkdtemp(
  230. prefix='qubes-pool-', dir='/var/tmp')
  231. self.addCleanup(shutil.rmtree, pool_path)
  232. pool = self.app.add_pool('test-filep', dir_path=pool_path,
  233. driver='file')
  234. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  235. name=vmname, template=self.app.default_template,
  236. label='red')
  237. self.loop.run_until_complete(self.vm.create_on_disk(
  238. pool=pool))
  239. self.assertVolumesExcludedFromUdev(self.vm)
  240. class TC_01_Properties(qubes.tests.SystemTestCase):
  241. # pylint: disable=attribute-defined-outside-init
  242. def setUp(self):
  243. super(TC_01_Properties, self).setUp()
  244. self.init_default_template()
  245. self.vmname = self.make_vm_name('appvm')
  246. self.vm = self.app.add_new_vm(qubes.vm.appvm.AppVM, name=self.vmname,
  247. template=self.app.default_template,
  248. label='red')
  249. self.loop.run_until_complete(self.vm.create_on_disk())
  250. self.addCleanup(self.cleanup_props)
  251. def cleanup_props(self):
  252. del self.vm
  253. def test_030_clone(self):
  254. try:
  255. testvm1 = self.app.add_new_vm(
  256. qubes.vm.appvm.AppVM,
  257. name=self.make_vm_name("vm"),
  258. template=self.app.default_template,
  259. label='red')
  260. self.loop.run_until_complete(testvm1.create_on_disk())
  261. testvm2 = self.app.add_new_vm(testvm1.__class__,
  262. name=self.make_vm_name("clone"),
  263. template=testvm1.template,
  264. label='red')
  265. testvm2.clone_properties(testvm1)
  266. testvm2.firewall.clone(testvm1.firewall)
  267. self.loop.run_until_complete(testvm2.clone_disk_files(testvm1))
  268. self.assertTrue(self.loop.run_until_complete(testvm1.storage.verify()))
  269. self.assertIn('source', testvm1.volumes['root'].config)
  270. self.assertNotEquals(testvm2, None)
  271. self.assertNotEquals(testvm2.volumes, {})
  272. self.assertIn('source', testvm2.volumes['root'].config)
  273. # qubes.xml reload
  274. self.app.save()
  275. testvm1 = self.app.domains[testvm1.qid]
  276. testvm2 = self.app.domains[testvm2.qid]
  277. self.assertEqual(testvm1.label, testvm2.label)
  278. self.assertEqual(testvm1.netvm, testvm2.netvm)
  279. self.assertEqual(testvm1.property_is_default('netvm'),
  280. testvm2.property_is_default('netvm'))
  281. self.assertEqual(testvm1.kernel, testvm2.kernel)
  282. self.assertEqual(testvm1.kernelopts, testvm2.kernelopts)
  283. self.assertEqual(testvm1.property_is_default('kernel'),
  284. testvm2.property_is_default('kernel'))
  285. self.assertEqual(testvm1.property_is_default('kernelopts'),
  286. testvm2.property_is_default('kernelopts'))
  287. self.assertEqual(testvm1.memory, testvm2.memory)
  288. self.assertEqual(testvm1.maxmem, testvm2.maxmem)
  289. self.assertEqual(testvm1.devices, testvm2.devices)
  290. self.assertEqual(testvm1.include_in_backups,
  291. testvm2.include_in_backups)
  292. self.assertEqual(testvm1.default_user, testvm2.default_user)
  293. self.assertEqual(testvm1.features, testvm2.features)
  294. self.assertEqual(testvm1.firewall.rules,
  295. testvm2.firewall.rules)
  296. # now some non-default values
  297. testvm1.netvm = None
  298. testvm1.label = 'orange'
  299. testvm1.memory = 512
  300. firewall = testvm1.firewall
  301. firewall.rules = [
  302. qubes.firewall.Rule(None, action='accept', dsthost='1.2.3.0/24',
  303. proto='tcp', dstports=22)]
  304. firewall.save()
  305. testvm3 = self.app.add_new_vm(testvm1.__class__,
  306. name=self.make_vm_name("clone2"),
  307. template=testvm1.template,
  308. label='red',)
  309. testvm3.clone_properties(testvm1)
  310. testvm3.firewall.clone(testvm1.firewall)
  311. self.loop.run_until_complete(testvm3.clone_disk_files(testvm1))
  312. # qubes.xml reload
  313. self.app.save()
  314. testvm1 = self.app.domains[testvm1.qid]
  315. testvm3 = self.app.domains[testvm3.qid]
  316. self.assertEqual(testvm1.label, testvm3.label)
  317. self.assertEqual(testvm1.netvm, testvm3.netvm)
  318. self.assertEqual(testvm1.property_is_default('netvm'),
  319. testvm3.property_is_default('netvm'))
  320. self.assertEqual(testvm1.kernel, testvm3.kernel)
  321. self.assertEqual(testvm1.kernelopts, testvm3.kernelopts)
  322. self.assertEqual(testvm1.property_is_default('kernel'),
  323. testvm3.property_is_default('kernel'))
  324. self.assertEqual(testvm1.property_is_default('kernelopts'),
  325. testvm3.property_is_default('kernelopts'))
  326. self.assertEqual(testvm1.memory, testvm3.memory)
  327. self.assertEqual(testvm1.maxmem, testvm3.maxmem)
  328. self.assertEqual(testvm1.devices, testvm3.devices)
  329. self.assertEqual(testvm1.include_in_backups,
  330. testvm3.include_in_backups)
  331. self.assertEqual(testvm1.default_user, testvm3.default_user)
  332. self.assertEqual(testvm1.features, testvm3.features)
  333. self.assertEqual(testvm1.firewall.rules,
  334. testvm3.firewall.rules)
  335. finally:
  336. try:
  337. del firewall
  338. except NameError:
  339. pass
  340. try:
  341. del testvm1
  342. except NameError:
  343. pass
  344. try:
  345. del testvm2
  346. except NameError:
  347. pass
  348. try:
  349. del testvm3
  350. except NameError:
  351. pass
  352. def test_020_name_conflict_app(self):
  353. # TODO decide what exception should be here
  354. with self.assertRaises((qubes.exc.QubesException, ValueError)):
  355. self.vm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  356. name=self.vmname, template=self.app.default_template,
  357. label='red')
  358. self.loop.run_until_complete(self.vm2.create_on_disk())
  359. def test_021_name_conflict_template(self):
  360. # TODO decide what exception should be here
  361. with self.assertRaises((qubes.exc.QubesException, ValueError)):
  362. self.vm2 = self.app.add_new_vm(qubes.vm.templatevm.TemplateVM,
  363. name=self.vmname, label='red')
  364. self.loop.run_until_complete(self.vm2.create_on_disk())
  365. class TC_03_QvmRevertTemplateChanges(qubes.tests.SystemTestCase):
  366. # pylint: disable=attribute-defined-outside-init
  367. def setUp(self):
  368. super(TC_03_QvmRevertTemplateChanges, self).setUp()
  369. self.init_default_template()
  370. def cleanup_template(self):
  371. del self.test_template
  372. def setup_template(self):
  373. self.test_template = self.app.add_new_vm(
  374. qubes.vm.templatevm.TemplateVM,
  375. name=self.make_vm_name("pv-clone"),
  376. label='red'
  377. )
  378. self.addCleanup(self.cleanup_template)
  379. self.test_template.clone_properties(self.app.default_template)
  380. self.test_template.features.update(self.app.default_template.features)
  381. self.test_template.tags.update(self.app.default_template.tags)
  382. self.loop.run_until_complete(
  383. self.test_template.clone_disk_files(self.app.default_template))
  384. self.test_template.volumes['root'].revisions_to_keep = 3
  385. self.app.save()
  386. def get_rootimg_checksum(self):
  387. return subprocess.check_output(
  388. ['sha1sum', self.test_template.volumes['root'].export()]).\
  389. decode().split(' ')[0]
  390. def _do_test(self):
  391. checksum_before = self.get_rootimg_checksum()
  392. self.loop.run_until_complete(self.test_template.start())
  393. self.shutdown_and_wait(self.test_template)
  394. checksum_changed = self.get_rootimg_checksum()
  395. if checksum_before == checksum_changed:
  396. self.log.warning("template not modified, test result will be "
  397. "unreliable")
  398. self.assertNotEqual(self.test_template.volumes['root'].revisions, {})
  399. revert_cmd = ['qvm-volume', 'revert', self.test_template.name + ':root']
  400. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  401. *revert_cmd))
  402. self.loop.run_until_complete(p.wait())
  403. self.assertEqual(p.returncode, 0)
  404. del p
  405. checksum_after = self.get_rootimg_checksum()
  406. self.assertEqual(checksum_before, checksum_after)
  407. def test_000_revert_linux(self):
  408. """
  409. Test qvm-revert-template-changes for PV template
  410. """
  411. self.setup_template()
  412. self._do_test()
  413. @unittest.skip('TODO: some non-linux system')
  414. def test_001_revert_non_linux(self):
  415. """
  416. Test qvm-revert-template-changes for HVM template
  417. """
  418. # TODO: have some system there, so the root.img will get modified
  419. self.setup_template()
  420. self._do_test()
  421. class TC_30_Gui_daemon(qubes.tests.SystemTestCase):
  422. def setUp(self):
  423. super(TC_30_Gui_daemon, self).setUp()
  424. self.init_default_template()
  425. @unittest.skipUnless(
  426. spawn.find_executable('xdotool'),
  427. "xdotool not installed")
  428. def test_000_clipboard(self):
  429. testvm1 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  430. name=self.make_vm_name('vm1'), label='red')
  431. self.loop.run_until_complete(testvm1.create_on_disk())
  432. testvm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  433. name=self.make_vm_name('vm2'), label='red')
  434. self.loop.run_until_complete(testvm2.create_on_disk())
  435. self.app.save()
  436. self.loop.run_until_complete(asyncio.wait([
  437. testvm1.start(),
  438. testvm2.start()]))
  439. self.loop.run_until_complete(asyncio.wait([
  440. self.wait_for_session(testvm1),
  441. self.wait_for_session(testvm2)]))
  442. window_title = 'user@{}'.format(testvm1.name)
  443. self.loop.run_until_complete(testvm1.run(
  444. 'zenity --text-info --editable --title={}'.format(window_title)))
  445. self.wait_for_window(window_title)
  446. time.sleep(0.5)
  447. test_string = "test{}".format(testvm1.xid)
  448. # Type and copy some text
  449. subprocess.check_call(['xdotool', 'search', '--name', window_title,
  450. 'windowactivate', '--sync',
  451. 'type', test_string])
  452. # second xdotool call because type --terminator do not work (SEGV)
  453. # additionally do not use search here, so window stack will be empty
  454. # and xdotool will use XTEST instead of generating events manually -
  455. # this will be much better - at least because events will have
  456. # correct timestamp (so gui-daemon would not drop the copy request)
  457. subprocess.check_call(['xdotool',
  458. 'key', 'ctrl+a', 'ctrl+c', 'ctrl+shift+c',
  459. 'Escape'])
  460. clipboard_content = \
  461. open('/var/run/qubes/qubes-clipboard.bin', 'r').read().strip()
  462. self.assertEqual(clipboard_content, test_string,
  463. "Clipboard copy operation failed - content")
  464. clipboard_source = \
  465. open('/var/run/qubes/qubes-clipboard.bin.source',
  466. 'r').read().strip()
  467. self.assertEqual(clipboard_source, testvm1.name,
  468. "Clipboard copy operation failed - owner")
  469. # Then paste it to the other window
  470. window_title = 'user@{}'.format(testvm2.name)
  471. p = self.loop.run_until_complete(testvm2.run(
  472. 'zenity --entry --title={} > /tmp/test.txt'.format(window_title)))
  473. self.wait_for_window(window_title)
  474. subprocess.check_call(['xdotool', 'key', '--delay', '100',
  475. 'ctrl+shift+v', 'ctrl+v', 'Return'])
  476. self.loop.run_until_complete(p.wait())
  477. # And compare the result
  478. (test_output, _) = self.loop.run_until_complete(
  479. testvm2.run_for_stdio('cat /tmp/test.txt'))
  480. self.assertEqual(test_string, test_output.strip().decode('ascii'))
  481. clipboard_content = \
  482. open('/var/run/qubes/qubes-clipboard.bin', 'r').read().strip()
  483. self.assertEqual(clipboard_content, "",
  484. "Clipboard not wiped after paste - content")
  485. clipboard_source = \
  486. open('/var/run/qubes/qubes-clipboard.bin.source', 'r').\
  487. read().strip()
  488. self.assertEqual(clipboard_source, "",
  489. "Clipboard not wiped after paste - owner")
  490. class TC_05_StandaloneVMMixin(object):
  491. def setUp(self):
  492. super(TC_05_StandaloneVMMixin, self).setUp()
  493. self.init_default_template(self.template)
  494. def test_000_create_start(self):
  495. self.testvm1 = self.app.add_new_vm(qubes.vm.standalonevm.StandaloneVM,
  496. name=self.make_vm_name('vm1'), label='red')
  497. self.testvm1.features.update(self.app.default_template.features)
  498. self.loop.run_until_complete(
  499. self.testvm1.clone_disk_files(self.app.default_template))
  500. self.app.save()
  501. self.loop.run_until_complete(self.testvm1.start())
  502. self.assertEqual(self.testvm1.get_power_state(), "Running")
  503. def test_100_resize_root_img(self):
  504. self.testvm1 = self.app.add_new_vm(qubes.vm.standalonevm.StandaloneVM,
  505. name=self.make_vm_name('vm1'), label='red')
  506. self.testvm1.features.update(self.app.default_template.features)
  507. self.loop.run_until_complete(
  508. self.testvm1.clone_disk_files(self.app.default_template))
  509. self.app.save()
  510. try:
  511. self.loop.run_until_complete(
  512. self.testvm1.storage.resize(self.testvm1.volumes['root'],
  513. 20 * 1024 ** 3))
  514. except (subprocess.CalledProcessError,
  515. qubes.storage.StoragePoolException) as e:
  516. # exception object would leak VM reference
  517. self.fail(str(e))
  518. self.assertEqual(self.testvm1.volumes['root'].size, 20 * 1024 ** 3)
  519. self.loop.run_until_complete(self.testvm1.start())
  520. # new_size in 1k-blocks
  521. (new_size, _) = self.loop.run_until_complete(
  522. self.testvm1.run_for_stdio('df --output=size /|tail -n 1'))
  523. # some safety margin for FS metadata
  524. self.assertGreater(int(new_size.strip()), 19 * 1024 ** 2)
  525. def test_101_resize_root_img_online(self):
  526. self.testvm1 = self.app.add_new_vm(qubes.vm.standalonevm.StandaloneVM,
  527. name=self.make_vm_name('vm1'), label='red')
  528. self.testvm1.features['qrexec'] = True
  529. self.loop.run_until_complete(
  530. self.testvm1.clone_disk_files(self.app.default_template))
  531. self.testvm1.features.update(self.app.default_template.features)
  532. self.app.save()
  533. self.loop.run_until_complete(self.testvm1.start())
  534. try:
  535. self.loop.run_until_complete(
  536. self.testvm1.storage.resize(self.testvm1.volumes['root'],
  537. 20 * 1024 ** 3))
  538. except (subprocess.CalledProcessError,
  539. qubes.storage.StoragePoolException) as e:
  540. # exception object would leak VM reference
  541. self.fail(str(e))
  542. self.assertEqual(self.testvm1.volumes['root'].size, 20 * 1024 ** 3)
  543. # new_size in 1k-blocks
  544. (new_size, _) = self.loop.run_until_complete(
  545. self.testvm1.run_for_stdio('df --output=size /|tail -n 1'))
  546. # some safety margin for FS metadata
  547. self.assertGreater(int(new_size.strip()), 19 * 1024 ** 2)
  548. class TC_06_AppVMMixin(object):
  549. template = None
  550. def setUp(self):
  551. super(TC_06_AppVMMixin, self).setUp()
  552. self.init_default_template(self.template)
  553. @unittest.skipUnless(
  554. spawn.find_executable('xdotool'), "xdotool not installed")
  555. def test_121_start_standalone_with_cdrom_vm(self):
  556. cdrom_vmname = self.make_vm_name('cdrom')
  557. self.cdrom_vm = self.app.add_new_vm('AppVM', label='red',
  558. name=cdrom_vmname)
  559. self.loop.run_until_complete(self.cdrom_vm.create_on_disk())
  560. self.loop.run_until_complete(self.cdrom_vm.start())
  561. iso_path = self.create_bootable_iso()
  562. with open(iso_path, 'rb') as iso_f:
  563. self.loop.run_until_complete(
  564. self.cdrom_vm.run_for_stdio('cat > /home/user/boot.iso',
  565. stdin=iso_f))
  566. vmname = self.make_vm_name('appvm')
  567. self.vm = self.app.add_new_vm('StandaloneVM', label='red', name=vmname)
  568. self.loop.run_until_complete(self.vm.create_on_disk())
  569. self.vm.kernel = None
  570. self.vm.virt_mode = 'hvm'
  571. # start the VM using qvm-start tool, to test --cdrom option there
  572. p = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  573. 'qvm-start', '--cdrom=' + cdrom_vmname + ':/home/user/boot.iso',
  574. self.vm.name,
  575. stdout=subprocess.PIPE, stderr=subprocess.STDOUT))
  576. (stdout, _) = self.loop.run_until_complete(p.communicate())
  577. self.assertEqual(p.returncode, 0, stdout)
  578. # check if VM do not crash instantly
  579. self.loop.run_until_complete(asyncio.sleep(5))
  580. self.assertTrue(self.vm.is_running())
  581. # Type 'poweroff'
  582. subprocess.check_call(['xdotool', 'search', '--name', self.vm.name,
  583. 'type', 'poweroff\r'])
  584. for _ in range(5):
  585. if not self.vm.is_running():
  586. break
  587. self.loop.run_until_complete(asyncio.sleep(1))
  588. self.assertFalse(self.vm.is_running())
  589. def load_tests(loader, tests, pattern):
  590. tests.addTests(loader.loadTestsFromNames(
  591. qubes.tests.create_testcases_for_templates('TC_05_StandaloneVM',
  592. TC_05_StandaloneVMMixin, qubes.tests.SystemTestCase,
  593. module=sys.modules[__name__])))
  594. tests.addTests(loader.loadTestsFromNames(
  595. qubes.tests.create_testcases_for_templates('TC_06_AppVM',
  596. TC_06_AppVMMixin, qubes.tests.SystemTestCase,
  597. module=sys.modules[__name__])))
  598. return tests
  599. # vim: ts=4 sw=4 et