vm_qrexec_gui.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2014 Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; either version 2
  11. # of the License, or (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
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. #
  22. import multiprocessing
  23. import os
  24. import subprocess
  25. import unittest
  26. import time
  27. from qubes.qubes import QubesVmCollection, defaults
  28. VM_PREFIX = "test-"
  29. TEST_DATA = "0123456789" * 1024
  30. class VmRunningTests(unittest.TestCase):
  31. def setUp(self):
  32. self.qc = QubesVmCollection()
  33. self.qc.lock_db_for_writing()
  34. self.qc.load()
  35. self.testvm1 = self.qc.add_new_vm("QubesAppVm",
  36. name="%svm1" % VM_PREFIX,
  37. template=self.qc.get_default_template())
  38. self.testvm1.create_on_disk(verbose=False)
  39. self.testvm2 = self.qc.add_new_vm("QubesAppVm",
  40. name="%svm2" % VM_PREFIX,
  41. template=self.qc.get_default_template())
  42. self.testvm2.create_on_disk(verbose=False)
  43. self.qc.save()
  44. self.qc.unlock_db()
  45. def remove_vms(self, vms):
  46. self.qc.lock_db_for_writing()
  47. self.qc.load()
  48. for vm in vms:
  49. if isinstance(vm, str):
  50. vm = self.qc.get_vm_by_name(vm)
  51. else:
  52. vm = self.qc[vm.qid]
  53. if vm.is_running():
  54. try:
  55. vm.force_shutdown()
  56. except:
  57. pass
  58. try:
  59. vm.remove_from_disk()
  60. except OSError:
  61. pass
  62. self.qc.pop(vm.qid)
  63. self.qc.save()
  64. self.qc.unlock_db()
  65. def tearDown(self):
  66. vmlist = [vm for vm in self.qc.values() if vm.name.startswith(
  67. VM_PREFIX)]
  68. self.remove_vms(vmlist)
  69. def test_000_start_shutdown(self):
  70. self.testvm1.start()
  71. self.assertEquals(self.testvm1.get_power_state(), "Running")
  72. self.testvm1.shutdown()
  73. shutdown_counter = 0
  74. while self.testvm1.is_running():
  75. if shutdown_counter > defaults["shutdown_counter_max"]:
  76. self.fail("VM hanged during shutdown")
  77. shutdown_counter += 1
  78. time.sleep(1)
  79. time.sleep(1)
  80. self.assertEquals(self.testvm1.get_power_state(), "Halted")
  81. def test_010_run_gui_app(self):
  82. self.testvm1.start()
  83. self.assertEquals(self.testvm1.get_power_state(), "Running")
  84. self.testvm1.run("gnome-terminal")
  85. wait_count = 0
  86. while subprocess.call(['xdotool', 'search', '--name', 'user@%s' %
  87. self.testvm1.name], stdout=open(os.path.devnull, 'w'),
  88. stderr=subprocess.STDOUT) > 0:
  89. wait_count += 1
  90. if wait_count > 100:
  91. self.fail("Timeout while waiting for gnome-terminal window")
  92. time.sleep(0.1)
  93. time.sleep(0.5)
  94. subprocess.check_call(['xdotool', 'search', '--name', 'user@%s' %
  95. self.testvm1.name, 'windowactivate', 'type', 'exit\n'])
  96. wait_count = 0
  97. while subprocess.call(['xdotool', 'search', '--name', 'user@%s' %
  98. self.testvm1.name], stdout=open(os.path.devnull, 'w'),
  99. stderr=subprocess.STDOUT) == 0:
  100. wait_count += 1
  101. if wait_count > 100:
  102. self.fail("Timeout while waiting for gnome-terminal "
  103. "termination")
  104. time.sleep(0.1)
  105. def test_050_qrexec_simple_eof(self):
  106. """Test for data and EOF transmission dom0->VM"""
  107. result = multiprocessing.Value('i', 0)
  108. def run(self, result):
  109. p = self.testvm1.run("cat", passio_popen=True,
  110. passio_stderr=True)
  111. (stdout, stderr) = p.communicate(TEST_DATA)
  112. if stdout != TEST_DATA:
  113. result.value = 1
  114. if len(stderr) > 0:
  115. result.value = 2
  116. self.testvm1.start()
  117. t = multiprocessing.Process(target=run, args=(self, result))
  118. t.start()
  119. t.join(timeout=10)
  120. if t.is_alive():
  121. t.terminate()
  122. self.fail("Timeout, probably EOF wasn't transferred to the VM "
  123. "process")
  124. if result.value == 1:
  125. self.fail("Received data differs from what was sent")
  126. elif result.value == 2:
  127. self.fail("Some data was printed to stderr")
  128. @unittest.expectedFailure
  129. def test_051_qrexec_simple_eof_reverse(self):
  130. """Test for EOF transmission VM->dom0"""
  131. result = multiprocessing.Value('i', 0)
  132. def run(self, result):
  133. p = self.testvm1.run("echo test; exec >&-; cat > /dev/null",
  134. passio_popen=True, passio_stderr=True)
  135. # this will hang on test failure
  136. stdout = p.stdout.read()
  137. p.stdin.write(TEST_DATA)
  138. p.stdin.close()
  139. if stdout.strip() != "test":
  140. result.value = 1
  141. # this may hang in some buggy cases
  142. elif len(p.stderr.read()) > 0:
  143. result.value = 2
  144. elif p.pull() is None:
  145. result.value = 3
  146. self.testvm1.start()
  147. t = multiprocessing.Process(target=run, args=(self, result))
  148. t.start()
  149. t.join(timeout=10)
  150. if t.is_alive():
  151. t.terminate()
  152. self.fail("Timeout, probably EOF wasn't transferred from the VM "
  153. "process")
  154. if result.value == 1:
  155. self.fail("Received data differs from what was expected")
  156. elif result.value == 2:
  157. self.fail("Some data was printed to stderr")
  158. elif result.value == 3:
  159. self.fail("VM proceess didn't terminated on EOF")
  160. def test_052_qrexec_vm_service_eof(self):
  161. """Test for EOF transmission VM(src)->VM(dst)"""
  162. result = multiprocessing.Value('i', 0)
  163. def run(self, result):
  164. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm %s test.EOF "
  165. "/bin/sh -c 'echo test; exec >&-; cat "
  166. ">&$SAVED_FD_1'" % self.testvm2.name,
  167. passio_popen=True)
  168. (stdout, stderr) = p.communicate()
  169. if stdout != "test\n":
  170. result.value = 1
  171. self.testvm1.start()
  172. self.testvm2.start()
  173. p = self.testvm2.run("cat > /etc/qubes-rpc/test.EOF", user="root",
  174. passio_popen=True)
  175. p.stdin.write("/bin/cat")
  176. p.stdin.close()
  177. p.wait()
  178. policy = open("/etc/qubes-rpc/policy/test.EOF", "w")
  179. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  180. policy.close()
  181. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.EOF")
  182. t = multiprocessing.Process(target=run, args=(self, result))
  183. t.start()
  184. t.join(timeout=10)
  185. if t.is_alive():
  186. t.terminate()
  187. self.fail("Timeout, probably EOF wasn't transferred")
  188. if result.value == 1:
  189. self.fail("Received data differs from what was expected")
  190. @unittest.expectedFailure
  191. def test_053_qrexec_vm_service_eof_reverse(self):
  192. """Test for EOF transmission VM(src)<-VM(dst)"""
  193. result = multiprocessing.Value('i', 0)
  194. def run(self, result):
  195. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm %s test.EOF "
  196. "/bin/sh -c 'cat >&$SAVED_FD_1'"
  197. % self.testvm1.name,
  198. passio_popen=True)
  199. (stdout, stderr) = p.communicate()
  200. if stdout != "test\n":
  201. result.value = 1
  202. self.testvm1.start()
  203. self.testvm2.start()
  204. p = self.testvm2.run("cat > /etc/qubes-rpc/test.EOF", user="root",
  205. passio_popen=True)
  206. p.stdin.write("echo test; exec >&-; cat >/dev/null")
  207. p.stdin.close()
  208. p.wait()
  209. policy = open("/etc/qubes-rpc/policy/test.EOF", "w")
  210. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  211. policy.close()
  212. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.EOF")
  213. t = multiprocessing.Process(target=run, args=(self, result))
  214. t.start()
  215. t.join(timeout=10)
  216. if t.is_alive():
  217. t.terminate()
  218. self.fail("Timeout, probably EOF wasn't transferred")
  219. if result.value == 1:
  220. self.fail("Received data differs from what was expected")
  221. def test_100_qrexec_filecopy(self):
  222. self.testvm1.start()
  223. self.testvm2.start()
  224. p = self.testvm1.run("qvm-copy-to-vm %s /etc/passwd" %
  225. self.testvm2.name, passio_popen=True,
  226. passio_stderr=True)
  227. # Confirm transfer
  228. subprocess.check_call(['xdotool', 'search', '--sync', '--name', 'Question',
  229. 'key', 'y'])
  230. p.wait()
  231. self.assertEqual(p.returncode, 0, "qvm-copy-to-vm failed: %s" %
  232. p.stderr.read())
  233. retcode = self.testvm2.run("diff /etc/passwd "
  234. "/home/user/QubesIncoming/%s/passwd" % self.testvm1.name, wait=True)
  235. self.assertEqual(retcode, 0, "file differs")
  236. def test_110_qrexec_filecopy_deny(self):
  237. self.testvm1.start()
  238. self.testvm2.start()
  239. p = self.testvm1.run("qvm-copy-to-vm %s /etc/passwd" %
  240. self.testvm2.name, passio_popen=True)
  241. # Deny transfer
  242. subprocess.check_call(['xdotool', 'search', '--sync', '--name', 'Question',
  243. 'key', 'n'])
  244. p.wait()
  245. self.assertEqual(p.returncode, 1, "qvm-copy-to-vm unexpectedly "
  246. "succeeded")
  247. retcode = self.testvm1.run("ls /home/user/QubesIncoming/%s" %
  248. self.testvm1.name, wait=True,
  249. ignore_stderr=True)
  250. self.assertEqual(retcode, 2, "QubesIncoming exists although file copy was "
  251. "denied")
  252. def test_120_qrexec_filecopy_self(self):
  253. self.testvm1.start()
  254. p = self.testvm1.run("qvm-copy-to-vm %s /etc/passwd" %
  255. self.testvm1.name, passio_popen=True,
  256. passio_stderr=True)
  257. # Confirm transfer
  258. subprocess.check_call(['xdotool', 'search', '--sync', '--name', 'Question',
  259. 'key', 'y'])
  260. p.wait()
  261. self.assertEqual(p.returncode, 0, "qvm-copy-to-vm failed: %s" %
  262. p.stderr.read())
  263. retcode = self.testvm1.run("diff /etc/passwd "
  264. "/home/user/QubesIncoming/%s/passwd" % self.testvm1.name, wait=True)
  265. self.assertEqual(retcode, 0, "file differs")
  266. class DispVmTests(unittest.TestCase):
  267. def setUp(self):
  268. self.qc = QubesVmCollection()
  269. self.qc.lock_db_for_reading()
  270. self.qc.load()
  271. self.qc.unlock_db()
  272. def remove_vms(self, vms):
  273. self.qc.lock_db_for_writing()
  274. self.qc.load()
  275. for vm in vms:
  276. if isinstance(vm, str):
  277. vm = self.qc.get_vm_by_name(vm)
  278. else:
  279. vm = self.qc[vm.qid]
  280. if vm.is_running():
  281. try:
  282. vm.force_shutdown()
  283. except:
  284. pass
  285. try:
  286. vm.remove_from_disk()
  287. except OSError:
  288. pass
  289. self.qc.pop(vm.qid)
  290. self.qc.save()
  291. self.qc.unlock_db()
  292. def tearDown(self):
  293. vmlist = [vm for vm in self.qc.values() if vm.name.startswith(
  294. VM_PREFIX)]
  295. self.remove_vms(vmlist)
  296. def test_000_prepare_dvm(self):
  297. retcode = subprocess.call(['/usr/bin/qvm-create-default-dvm',
  298. '--default-template'],
  299. stderr=open(os.devnull, 'w'))
  300. self.assertEqual(retcode, 0)
  301. self.qc.lock_db_for_reading()
  302. self.qc.load()
  303. self.qc.unlock_db()
  304. self.assertIsNotNone(self.qc.get_vm_by_name(
  305. self.qc.get_default_template().name + "-dvm"))
  306. # TODO: check mtime of snapshot file
  307. def test_010_simple_dvm_run(self):
  308. p = subprocess.Popen(['/usr/lib/qubes/qfile-daemon-dvm',
  309. 'qubes.VMShell', 'dom0', 'DEFAULT'],
  310. stdin=subprocess.PIPE,
  311. stdout=subprocess.PIPE,
  312. stderr=open(os.devnull, 'w'))
  313. (stdout, _) = p.communicate(input="echo test")
  314. self.assertEqual(stdout, "test\n")
  315. # TODO: check if DispVM is destroyed
  316. def test_020_gui_app(self):
  317. p = subprocess.Popen(['/usr/lib/qubes/qfile-daemon-dvm',
  318. 'qubes.VMShell', 'dom0', 'DEFAULT'],
  319. stdin=subprocess.PIPE,
  320. stdout=subprocess.PIPE,
  321. stderr=open(os.devnull, 'w'))
  322. # wait for DispVM startup:
  323. p.stdin.write("echo test\n")
  324. p.stdin.flush()
  325. l = p.stdout.readline()
  326. self.assertEqual(l, "test\n")
  327. # potential race condition, but our tests are supposed to be
  328. # running on dedicated machine, so should not be a problem
  329. self.qc.lock_db_for_reading()
  330. self.qc.load()
  331. self.qc.unlock_db()
  332. max_qid = 0
  333. for vm in self.qc.values():
  334. if not vm.is_disposablevm():
  335. continue
  336. if vm.qid > max_qid:
  337. max_qid = vm.qid
  338. dispvm = self.qc[max_qid]
  339. self.assertNotEqual(dispvm.qid, 0, "DispVM not found in qubes.xml")
  340. self.assertTrue(dispvm.is_running())
  341. p.stdin.write("gnome-terminal\n")
  342. wait_count = 0
  343. window_title = 'user@%s' % (dispvm.template.name + "-dvm")
  344. while subprocess.call(['xdotool', 'search', '--name', window_title],
  345. stdout=open(os.path.devnull, 'w'),
  346. stderr=subprocess.STDOUT) > 0:
  347. wait_count += 1
  348. if wait_count > 100:
  349. self.fail("Timeout while waiting for gnome-terminal window")
  350. time.sleep(0.1)
  351. time.sleep(0.5)
  352. subprocess.check_call(['xdotool', 'search', '--name', window_title,
  353. 'windowactivate', 'type', 'exit\n'])
  354. wait_count = 0
  355. while subprocess.call(['xdotool', 'search', '--name', window_title],
  356. stdout=open(os.path.devnull, 'w'),
  357. stderr=subprocess.STDOUT) == 0:
  358. wait_count += 1
  359. if wait_count > 100:
  360. self.fail("Timeout while waiting for gnome-terminal "
  361. "termination")
  362. time.sleep(0.1)
  363. p.stdin.close()
  364. wait_count = 0
  365. while dispvm.is_running():
  366. wait_count += 1
  367. if wait_count > 100:
  368. self.fail("Timeout while waiting for DispVM destruction")
  369. time.sleep(0.1)
  370. wait_count = 0
  371. while p.poll() is None:
  372. wait_count += 1
  373. if wait_count > 100:
  374. self.fail("Timeout while waiting for qfile-daemon-dvm "
  375. "termination")
  376. time.sleep(0.1)
  377. self.assertEqual(p.returncode, 0)
  378. self.qc.lock_db_for_reading()
  379. self.qc.load()
  380. self.qc.unlock_db()
  381. self.assertIsNone(self.qc.get_vm_by_name(dispvm.name),
  382. "DispVM not removed from qubes.xml")
  383. def test_030_edit_file(self):
  384. self.qc.lock_db_for_writing()
  385. self.qc.load()
  386. self.testvm1 = self.qc.add_new_vm("QubesAppVm",
  387. name="%svm1" % VM_PREFIX,
  388. template=self.qc.get_default_template())
  389. self.testvm1.create_on_disk(verbose=False)
  390. self.qc.save()
  391. self.qc.unlock_db()
  392. self.testvm1.start()
  393. self.testvm1.run("echo test1 > /home/user/test.txt", wait=True)
  394. p = self.testvm1.run("qvm-open-in-dvm /home/user/test.txt",
  395. passio_popen=True)
  396. wait_count = 0
  397. # TODO: ensure that gedit is default editor?
  398. window_title = '(/tmp/%s)' % self.testvm1.name
  399. while subprocess.call(['xdotool', 'search', '--name', window_title],
  400. stdout=open(os.path.devnull, 'w'),
  401. stderr=subprocess.STDOUT) > 0:
  402. wait_count += 1
  403. if wait_count > 100:
  404. self.fail("Timeout while waiting for editor window")
  405. time.sleep(0.3)
  406. time.sleep(0.5)
  407. subprocess.check_call(['xdotool', 'search', '--name', window_title,
  408. 'windowactivate', 'type', 'test line 2\n'])
  409. subprocess.check_call(['xdotool', 'search', '--name', window_title,
  410. 'key', 'ctrl+s', 'ctrl+q'])
  411. p.wait()
  412. p = self.testvm1.run("cat /home/user/test.txt",
  413. passio_popen=True)
  414. (test_txt_content, _) = p.communicate()
  415. self.assertEqual(test_txt_content, "test line 2\ntest1\n")