vm_qrexec_gui.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  1. #!/usr/bin/python
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2014-2015
  7. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  8. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  9. #
  10. # This program is free software; you can redistribute it and/or modify
  11. # it under the terms of the GNU General Public License as published by
  12. # the Free Software Foundation; either version 2 of the License, or
  13. # (at your option) any later version.
  14. #
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU General Public License along
  21. # with this program; if not, write to the Free Software Foundation, Inc.,
  22. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  23. #
  24. from distutils import spawn
  25. import multiprocessing
  26. import os
  27. import subprocess
  28. import unittest
  29. import time
  30. from qubes.qubes import QubesVmCollection, defaults, QubesException
  31. import qubes.tests
  32. TEST_DATA = "0123456789" * 1024
  33. class TC_00_AppVMMixin(qubes.tests.SystemTestsMixin):
  34. def setUp(self):
  35. super(TC_00_AppVMMixin, self).setUp()
  36. self.testvm1 = self.qc.add_new_vm(
  37. "QubesAppVm",
  38. name=self.make_vm_name('vm1'),
  39. template=self.qc.get_vm_by_name(self.template))
  40. self.testvm1.create_on_disk(verbose=False)
  41. self.testvm2 = self.qc.add_new_vm(
  42. "QubesAppVm",
  43. name=self.make_vm_name('vm2'),
  44. template=self.qc.get_vm_by_name(self.template))
  45. self.testvm2.create_on_disk(verbose=False)
  46. self.save_and_reload_db()
  47. self.qc.unlock_db()
  48. self.testvm1 = self.qc[self.testvm1.qid]
  49. self.testvm2 = self.qc[self.testvm2.qid]
  50. def test_000_start_shutdown(self):
  51. self.testvm1.start()
  52. self.assertEquals(self.testvm1.get_power_state(), "Running")
  53. self.testvm1.shutdown()
  54. shutdown_counter = 0
  55. while self.testvm1.is_running():
  56. if shutdown_counter > defaults["shutdown_counter_max"]:
  57. self.fail("VM hanged during shutdown")
  58. shutdown_counter += 1
  59. time.sleep(1)
  60. time.sleep(1)
  61. self.assertEquals(self.testvm1.get_power_state(), "Halted")
  62. @unittest.skipUnless(spawn.find_executable('xdotool'),
  63. "xdotool not installed")
  64. def test_010_run_xterm(self):
  65. self.testvm1.start()
  66. self.assertEquals(self.testvm1.get_power_state(), "Running")
  67. self.testvm1.run("xterm")
  68. wait_count = 0
  69. title = 'user@{}'.format(self.testvm1.name)
  70. if self.template.count("whonix"):
  71. title = 'user@host'
  72. while subprocess.call(
  73. ['xdotool', 'search', '--name', title],
  74. stdout=open(os.path.devnull, 'w'),
  75. stderr=subprocess.STDOUT) > 0:
  76. wait_count += 1
  77. if wait_count > 100:
  78. self.fail("Timeout while waiting for xterm window")
  79. time.sleep(0.1)
  80. time.sleep(0.5)
  81. subprocess.check_call(
  82. ['xdotool', 'search', '--name', title,
  83. 'windowactivate', 'type', 'exit\n'])
  84. wait_count = 0
  85. while subprocess.call(['xdotool', 'search', '--name', title],
  86. stdout=open(os.path.devnull, 'w'),
  87. stderr=subprocess.STDOUT) == 0:
  88. wait_count += 1
  89. if wait_count > 100:
  90. self.fail("Timeout while waiting for xterm "
  91. "termination")
  92. time.sleep(0.1)
  93. @unittest.skipUnless(spawn.find_executable('xdotool'),
  94. "xdotool not installed")
  95. def test_011_run_gnome_terminal(self):
  96. if "minimal" in self.template:
  97. self.skipTest("Minimal template doesn't have 'gnome-terminal'")
  98. self.testvm1.start()
  99. self.assertEquals(self.testvm1.get_power_state(), "Running")
  100. self.testvm1.run("gnome-terminal")
  101. title = 'user@{}'.format(self.testvm1.name)
  102. if self.template.count("whonix"):
  103. title = 'user@host'
  104. wait_count = 0
  105. while subprocess.call(
  106. ['xdotool', 'search', '--name', title],
  107. stdout=open(os.path.devnull, 'w'),
  108. stderr=subprocess.STDOUT) > 0:
  109. wait_count += 1
  110. if wait_count > 100:
  111. self.fail("Timeout while waiting for gnome-terminal window")
  112. time.sleep(0.1)
  113. time.sleep(0.5)
  114. subprocess.check_call(
  115. ['xdotool', 'search', '--name', title,
  116. 'windowactivate', 'type', 'exit\n'])
  117. wait_count = 0
  118. while subprocess.call(['xdotool', 'search', '--name', title],
  119. stdout=open(os.path.devnull, 'w'),
  120. stderr=subprocess.STDOUT) == 0:
  121. wait_count += 1
  122. if wait_count > 100:
  123. self.fail("Timeout while waiting for gnome-terminal "
  124. "termination")
  125. time.sleep(0.1)
  126. @unittest.skipUnless(spawn.find_executable('xdotool'),
  127. "xdotool not installed")
  128. def test_012_qubes_desktop_run(self):
  129. self.testvm1.start()
  130. self.assertEquals(self.testvm1.get_power_state(), "Running")
  131. xterm_desktop_path = "/usr/share/applications/xterm.desktop"
  132. # Debian has it different...
  133. xterm_desktop_path_debian = \
  134. "/usr/share/applications/debian-xterm.desktop"
  135. if self.testvm1.run("test -r {}".format(xterm_desktop_path_debian),
  136. wait=True) == 0:
  137. xterm_desktop_path = xterm_desktop_path_debian
  138. self.testvm1.run("qubes-desktop-run {}".format(xterm_desktop_path))
  139. title = 'user@{}'.format(self.testvm1.name)
  140. if self.template.count("whonix"):
  141. title = 'user@host'
  142. wait_count = 0
  143. while subprocess.call(
  144. ['xdotool', 'search', '--name', title],
  145. stdout=open(os.path.devnull, 'w'),
  146. stderr=subprocess.STDOUT) > 0:
  147. wait_count += 1
  148. if wait_count > 100:
  149. self.fail("Timeout while waiting for xterm window")
  150. time.sleep(0.1)
  151. time.sleep(0.5)
  152. subprocess.check_call(
  153. ['xdotool', 'search', '--name', title,
  154. 'windowactivate', 'type', 'exit\n'])
  155. wait_count = 0
  156. while subprocess.call(['xdotool', 'search', '--name', title],
  157. stdout=open(os.path.devnull, 'w'),
  158. stderr=subprocess.STDOUT) == 0:
  159. wait_count += 1
  160. if wait_count > 100:
  161. self.fail("Timeout while waiting for xterm "
  162. "termination")
  163. time.sleep(0.1)
  164. def test_050_qrexec_simple_eof(self):
  165. """Test for data and EOF transmission dom0->VM"""
  166. result = multiprocessing.Value('i', 0)
  167. def run(self, result):
  168. p = self.testvm1.run("cat", passio_popen=True,
  169. passio_stderr=True)
  170. (stdout, stderr) = p.communicate(TEST_DATA)
  171. if stdout != TEST_DATA:
  172. result.value = 1
  173. if len(stderr) > 0:
  174. result.value = 2
  175. self.testvm1.start()
  176. t = multiprocessing.Process(target=run, args=(self, result))
  177. t.start()
  178. t.join(timeout=10)
  179. if t.is_alive():
  180. t.terminate()
  181. self.fail("Timeout, probably EOF wasn't transferred to the VM "
  182. "process")
  183. if result.value == 1:
  184. self.fail("Received data differs from what was sent")
  185. elif result.value == 2:
  186. self.fail("Some data was printed to stderr")
  187. def test_051_qrexec_simple_eof_reverse(self):
  188. """Test for EOF transmission VM->dom0"""
  189. result = multiprocessing.Value('i', 0)
  190. def run(self, result):
  191. p = self.testvm1.run("echo test; exec >&-; cat > /dev/null",
  192. passio_popen=True, passio_stderr=True)
  193. # this will hang on test failure
  194. stdout = p.stdout.read()
  195. p.stdin.write(TEST_DATA)
  196. p.stdin.close()
  197. if stdout.strip() != "test":
  198. result.value = 1
  199. # this may hang in some buggy cases
  200. elif len(p.stderr.read()) > 0:
  201. result.value = 2
  202. elif p.poll() is None:
  203. time.sleep(1)
  204. if p.poll() is None:
  205. result.value = 3
  206. self.testvm1.start()
  207. t = multiprocessing.Process(target=run, args=(self, result))
  208. t.start()
  209. t.join(timeout=10)
  210. if t.is_alive():
  211. t.terminate()
  212. self.fail("Timeout, probably EOF wasn't transferred from the VM "
  213. "process")
  214. if result.value == 1:
  215. self.fail("Received data differs from what was expected")
  216. elif result.value == 2:
  217. self.fail("Some data was printed to stderr")
  218. elif result.value == 3:
  219. self.fail("VM proceess didn't terminated on EOF")
  220. def test_052_qrexec_vm_service_eof(self):
  221. """Test for EOF transmission VM(src)->VM(dst)"""
  222. result = multiprocessing.Value('i', 0)
  223. def run(self, result):
  224. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm %s test.EOF "
  225. "/bin/sh -c 'echo test; exec >&-; cat "
  226. ">&$SAVED_FD_1'" % self.testvm2.name,
  227. passio_popen=True)
  228. (stdout, stderr) = p.communicate()
  229. if stdout != "test\n":
  230. result.value = 1
  231. self.testvm1.start()
  232. self.testvm2.start()
  233. p = self.testvm2.run("cat > /etc/qubes-rpc/test.EOF", user="root",
  234. passio_popen=True)
  235. p.stdin.write("/bin/cat")
  236. p.stdin.close()
  237. p.wait()
  238. policy = open("/etc/qubes-rpc/policy/test.EOF", "w")
  239. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  240. policy.close()
  241. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.EOF")
  242. t = multiprocessing.Process(target=run, args=(self, result))
  243. t.start()
  244. t.join(timeout=10)
  245. if t.is_alive():
  246. t.terminate()
  247. self.fail("Timeout, probably EOF wasn't transferred")
  248. if result.value == 1:
  249. self.fail("Received data differs from what was expected")
  250. @unittest.expectedFailure
  251. def test_053_qrexec_vm_service_eof_reverse(self):
  252. """Test for EOF transmission VM(src)<-VM(dst)"""
  253. result = multiprocessing.Value('i', 0)
  254. def run(self, result):
  255. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm %s test.EOF "
  256. "/bin/sh -c 'cat >&$SAVED_FD_1'"
  257. % self.testvm2.name,
  258. passio_popen=True)
  259. (stdout, stderr) = p.communicate()
  260. if stdout != "test\n":
  261. result.value = 1
  262. self.testvm1.start()
  263. self.testvm2.start()
  264. p = self.testvm2.run("cat > /etc/qubes-rpc/test.EOF", user="root",
  265. passio_popen=True)
  266. p.stdin.write("echo test; exec >&-; cat >/dev/null")
  267. p.stdin.close()
  268. p.wait()
  269. policy = open("/etc/qubes-rpc/policy/test.EOF", "w")
  270. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  271. policy.close()
  272. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.EOF")
  273. t = multiprocessing.Process(target=run, args=(self, result))
  274. t.start()
  275. t.join(timeout=10)
  276. if t.is_alive():
  277. t.terminate()
  278. self.fail("Timeout, probably EOF wasn't transferred")
  279. if result.value == 1:
  280. self.fail("Received data differs from what was expected")
  281. def test_055_qrexec_dom0_service_abort(self):
  282. """
  283. Test if service abort (by dom0) is properly handled by source VM.
  284. If "remote" part of the service terminates, the source part should
  285. properly be notified. This includes closing its stdin (which is
  286. already checked by test_053_qrexec_vm_service_eof_reverse), but also
  287. its stdout - otherwise such service might hang on write(2) call.
  288. """
  289. def run (src):
  290. p = src.run("/usr/lib/qubes/qrexec-client-vm dom0 "
  291. "test.Abort /bin/cat /dev/zero",
  292. passio_popen=True)
  293. p.communicate()
  294. p.wait()
  295. self.testvm1.start()
  296. service = open("/etc/qubes-rpc/test.Abort", "w")
  297. service.write("sleep 1")
  298. service.close()
  299. self.addCleanup(os.unlink, "/etc/qubes-rpc/test.Abort")
  300. policy = open("/etc/qubes-rpc/policy/test.Abort", "w")
  301. policy.write("%s dom0 allow" % (self.testvm1.name))
  302. policy.close()
  303. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.Abort")
  304. t = multiprocessing.Process(target=run, args=(self.testvm1,))
  305. t.start()
  306. t.join(timeout=10)
  307. if t.is_alive():
  308. t.terminate()
  309. self.fail("Timeout, probably stdout wasn't closed")
  310. def test_060_qrexec_exit_code_dom0(self):
  311. self.testvm1.start()
  312. p = self.testvm1.run("exit 0", passio_popen=True)
  313. p.wait()
  314. self.assertEqual(0, p.returncode)
  315. p = self.testvm1.run("exit 3", passio_popen=True)
  316. p.wait()
  317. self.assertEqual(3, p.returncode)
  318. @unittest.expectedFailure
  319. def test_065_qrexec_exit_code_vm(self):
  320. self.testvm1.start()
  321. self.testvm2.start()
  322. policy = open("/etc/qubes-rpc/policy/test.Retcode", "w")
  323. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  324. policy.close()
  325. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.Retcode")
  326. p = self.testvm2.run("cat > /etc/qubes-rpc/test.Retcode", user="root",
  327. passio_popen=True)
  328. p.stdin.write("exit 0")
  329. p.stdin.close()
  330. p.wait()
  331. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm %s test.Retcode "
  332. "/bin/sh -c 'cat >/dev/null'; echo $?"
  333. % self.testvm1.name,
  334. passio_popen=True)
  335. (stdout, stderr) = p.communicate()
  336. self.assertEqual(stdout, "0\n")
  337. p = self.testvm2.run("cat > /etc/qubes-rpc/test.Retcode", user="root",
  338. passio_popen=True)
  339. p.stdin.write("exit 3")
  340. p.stdin.close()
  341. p.wait()
  342. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm %s test.Retcode "
  343. "/bin/sh -c 'cat >/dev/null'; echo $?"
  344. % self.testvm1.name,
  345. passio_popen=True)
  346. (stdout, stderr) = p.communicate()
  347. self.assertEqual(stdout, "3\n")
  348. def test_070_qrexec_vm_simultaneous_write(self):
  349. """Test for simultaneous write in VM(src)->VM(dst) connection
  350. This is regression test for #1347
  351. Check for deadlock when initially both sides writes a lot of data
  352. (and not read anything). When one side starts reading, it should
  353. get the data and the remote side should be possible to write then more.
  354. There was a bug where remote side was waiting on write(2) and not
  355. handling anything else.
  356. """
  357. result = multiprocessing.Value('i', -1)
  358. def run(self):
  359. p = self.testvm1.run(
  360. "/usr/lib/qubes/qrexec-client-vm %s test.write "
  361. "/bin/sh -c '"
  362. # first write a lot of data to fill all the buffers
  363. "dd if=/dev/zero bs=993 count=10000 iflag=fullblock & "
  364. # then after some time start reading
  365. "sleep 1; "
  366. "dd of=/dev/null bs=993 count=10000 iflag=fullblock; "
  367. "wait"
  368. "'" % self.testvm2.name, passio_popen=True)
  369. p.communicate()
  370. result.value = p.returncode
  371. self.testvm1.start()
  372. self.testvm2.start()
  373. p = self.testvm2.run("cat > /etc/qubes-rpc/test.write", user="root",
  374. passio_popen=True)
  375. # first write a lot of data
  376. p.stdin.write("dd if=/dev/zero bs=993 count=10000 iflag=fullblock\n")
  377. # and only then read something
  378. p.stdin.write("dd of=/dev/null bs=993 count=10000 iflag=fullblock\n")
  379. p.stdin.close()
  380. p.wait()
  381. policy = open("/etc/qubes-rpc/policy/test.write", "w")
  382. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  383. policy.close()
  384. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.write")
  385. t = multiprocessing.Process(target=run, args=(self,))
  386. t.start()
  387. t.join(timeout=10)
  388. if t.is_alive():
  389. t.terminate()
  390. self.fail("Timeout, probably deadlock")
  391. self.assertEqual(result.value, 0, "Service call failed")
  392. def test_071_qrexec_dom0_simultaneous_write(self):
  393. """Test for simultaneous write in dom0(src)->VM(dst) connection
  394. Similar to test_070_qrexec_vm_simultaneous_write, but with dom0
  395. as a source.
  396. """
  397. result = multiprocessing.Value('i', -1)
  398. def run(self):
  399. result.value = self.testvm2.run_service(
  400. "test.write", localcmd="/bin/sh -c '"
  401. # first write a lot of data to fill all the buffers
  402. "dd if=/dev/zero bs=993 count=10000 iflag=fullblock & "
  403. # then after some time start reading
  404. "sleep 1; "
  405. "dd of=/dev/null bs=993 count=10000 iflag=fullblock; "
  406. "wait"
  407. "'")
  408. self.testvm2.start()
  409. p = self.testvm2.run("cat > /etc/qubes-rpc/test.write", user="root",
  410. passio_popen=True)
  411. # first write a lot of data
  412. p.stdin.write("dd if=/dev/zero bs=993 count=10000 iflag=fullblock\n")
  413. # and only then read something
  414. p.stdin.write("dd of=/dev/null bs=993 count=10000 iflag=fullblock\n")
  415. p.stdin.close()
  416. p.wait()
  417. policy = open("/etc/qubes-rpc/policy/test.write", "w")
  418. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  419. policy.close()
  420. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.write")
  421. t = multiprocessing.Process(target=run, args=(self,))
  422. t.start()
  423. t.join(timeout=10)
  424. if t.is_alive():
  425. t.terminate()
  426. self.fail("Timeout, probably deadlock")
  427. self.assertEqual(result.value, 0, "Service call failed")
  428. def test_072_qrexec_to_dom0_simultaneous_write(self):
  429. """Test for simultaneous write in dom0(src)<-VM(dst) connection
  430. Similar to test_071_qrexec_dom0_simultaneous_write, but with dom0
  431. as a "hanging" side.
  432. """
  433. result = multiprocessing.Value('i', -1)
  434. def run(self):
  435. result.value = self.testvm2.run_service(
  436. "test.write", localcmd="/bin/sh -c '"
  437. # first write a lot of data to fill all the buffers
  438. "dd if=/dev/zero bs=993 count=10000 iflag=fullblock "
  439. # then, only when all written, read something
  440. "dd of=/dev/null bs=993 count=10000 iflag=fullblock; "
  441. "'")
  442. self.testvm2.start()
  443. p = self.testvm2.run("cat > /etc/qubes-rpc/test.write", user="root",
  444. passio_popen=True)
  445. # first write a lot of data
  446. p.stdin.write("dd if=/dev/zero bs=993 count=10000 iflag=fullblock &\n")
  447. # and only then read something
  448. p.stdin.write("dd of=/dev/null bs=993 count=10000 iflag=fullblock\n")
  449. p.stdin.write("sleep 1; \n")
  450. p.stdin.write("wait\n")
  451. p.stdin.close()
  452. p.wait()
  453. policy = open("/etc/qubes-rpc/policy/test.write", "w")
  454. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  455. policy.close()
  456. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.write")
  457. t = multiprocessing.Process(target=run, args=(self,))
  458. t.start()
  459. t.join(timeout=10)
  460. if t.is_alive():
  461. t.terminate()
  462. self.fail("Timeout, probably deadlock")
  463. self.assertEqual(result.value, 0, "Service call failed")
  464. @unittest.skipUnless(spawn.find_executable('xdotool'),
  465. "xdotool not installed")
  466. def test_100_qrexec_filecopy(self):
  467. self.testvm1.start()
  468. self.testvm2.start()
  469. p = self.testvm1.run("qvm-copy-to-vm %s /etc/passwd" %
  470. self.testvm2.name, passio_popen=True,
  471. passio_stderr=True)
  472. # Confirm transfer
  473. self.enter_keys_in_window('Question', ['y'])
  474. p.wait()
  475. self.assertEqual(p.returncode, 0, "qvm-copy-to-vm failed: %s" %
  476. p.stderr.read())
  477. retcode = self.testvm2.run("diff /etc/passwd "
  478. "/home/user/QubesIncoming/{}/passwd".format(
  479. self.testvm1.name),
  480. wait=True)
  481. self.assertEqual(retcode, 0, "file differs")
  482. @unittest.skipUnless(spawn.find_executable('xdotool'),
  483. "xdotool not installed")
  484. def test_101_qrexec_filecopy_with_autostart(self):
  485. self.testvm1.start()
  486. p = self.testvm1.run("qvm-copy-to-vm %s /etc/passwd" %
  487. self.testvm2.name, passio_popen=True,
  488. passio_stderr=True)
  489. # Confirm transfer
  490. self.enter_keys_in_window('Question', ['y'])
  491. p.wait()
  492. self.assertEqual(p.returncode, 0, "qvm-copy-to-vm failed: %s" %
  493. p.stderr.read())
  494. # workaround for libvirt bug (domain ID isn't updated when is started
  495. # from other application) - details in
  496. # QubesOS/qubes-core-libvirt@63ede4dfb4485c4161dd6a2cc809e8fb45ca664f
  497. self.testvm2._libvirt_domain = None
  498. self.assertTrue(self.testvm2.is_running())
  499. retcode = self.testvm2.run("diff /etc/passwd "
  500. "/home/user/QubesIncoming/{}/passwd".format(
  501. self.testvm1.name),
  502. wait=True)
  503. self.assertEqual(retcode, 0, "file differs")
  504. @unittest.skipUnless(spawn.find_executable('xdotool'),
  505. "xdotool not installed")
  506. def test_110_qrexec_filecopy_deny(self):
  507. self.testvm1.start()
  508. self.testvm2.start()
  509. p = self.testvm1.run("qvm-copy-to-vm %s /etc/passwd" %
  510. self.testvm2.name, passio_popen=True)
  511. # Deny transfer
  512. self.enter_keys_in_window('Question', ['n'])
  513. p.wait()
  514. self.assertNotEqual(p.returncode, 0, "qvm-copy-to-vm unexpectedly "
  515. "succeeded")
  516. retcode = self.testvm1.run("ls /home/user/QubesIncoming/%s" %
  517. self.testvm1.name, wait=True,
  518. ignore_stderr=True)
  519. self.assertNotEqual(retcode, 0, "QubesIncoming exists although file "
  520. "copy was denied")
  521. @unittest.skip("Xen gntalloc driver crashes when page is mapped in the "
  522. "same domain")
  523. @unittest.skipUnless(spawn.find_executable('xdotool'),
  524. "xdotool not installed")
  525. def test_120_qrexec_filecopy_self(self):
  526. self.testvm1.start()
  527. p = self.testvm1.run("qvm-copy-to-vm %s /etc/passwd" %
  528. self.testvm1.name, passio_popen=True,
  529. passio_stderr=True)
  530. # Confirm transfer
  531. self.enter_keys_in_window('Question', ['y'])
  532. p.wait()
  533. self.assertEqual(p.returncode, 0, "qvm-copy-to-vm failed: %s" %
  534. p.stderr.read())
  535. retcode = self.testvm1.run(
  536. "diff /etc/passwd /home/user/QubesIncoming/{}/passwd".format(
  537. self.testvm1.name),
  538. wait=True)
  539. self.assertEqual(retcode, 0, "file differs")
  540. @unittest.skipUnless(spawn.find_executable('xdotool'),
  541. "xdotool not installed")
  542. def test_130_qrexec_filemove_disk_full(self):
  543. self.testvm1.start()
  544. self.testvm2.start()
  545. # Prepare test file
  546. prepare_cmd = ("yes teststring | dd of=testfile bs=1M "
  547. "count=50 iflag=fullblock")
  548. retcode = self.testvm1.run(prepare_cmd, wait=True)
  549. if retcode != 0:
  550. raise RuntimeError("Failed '{}' in {}".format(prepare_cmd,
  551. self.testvm1.name))
  552. # Prepare target directory with limited size
  553. prepare_cmd = (
  554. "mkdir -p /home/user/QubesIncoming && "
  555. "chown user /home/user/QubesIncoming && "
  556. "mount -t tmpfs none /home/user/QubesIncoming -o size=48M"
  557. )
  558. retcode = self.testvm2.run(prepare_cmd, user="root", wait=True)
  559. if retcode != 0:
  560. raise RuntimeError("Failed '{}' in {}".format(prepare_cmd,
  561. self.testvm2.name))
  562. p = self.testvm1.run("qvm-move-to-vm %s testfile" %
  563. self.testvm2.name, passio_popen=True,
  564. passio_stderr=True)
  565. # Confirm transfer
  566. self.enter_keys_in_window('Question', ['y'])
  567. # Close GUI error message
  568. self.enter_keys_in_window('Error', ['Return'])
  569. p.wait()
  570. self.assertNotEqual(p.returncode, 0, "qvm-move-to-vm should fail")
  571. retcode = self.testvm1.run("test -f testfile", wait=True)
  572. self.assertEqual(retcode, 0, "testfile should not be deleted in "
  573. "source VM")
  574. def test_200_timezone(self):
  575. """Test whether timezone setting is properly propagated to the VM"""
  576. if "whonix" in self.template:
  577. self.skipTest("Timezone propagation disabled on Whonix templates")
  578. self.testvm1.start()
  579. (vm_tz, _) = self.testvm1.run("date +%Z",
  580. passio_popen=True).communicate()
  581. (dom0_tz, _) = subprocess.Popen(["date", "+%Z"],
  582. stdout=subprocess.PIPE).communicate()
  583. self.assertEqual(vm_tz.strip(), dom0_tz.strip())
  584. # Check if reverting back to UTC works
  585. (vm_tz, _) = self.testvm1.run("TZ=UTC date +%Z",
  586. passio_popen=True).communicate()
  587. self.assertEqual(vm_tz.strip(), "UTC")
  588. def test_210_time_sync(self):
  589. """Test time synchronization mechanism"""
  590. self.testvm1.start()
  591. self.testvm2.start()
  592. (start_time, _) = subprocess.Popen(["date", "-u", "+%s"],
  593. stdout=subprocess.PIPE).communicate()
  594. original_clockvm = self.qc.get_clockvm_vm()
  595. if original_clockvm:
  596. original_clockvm_name = original_clockvm.name
  597. else:
  598. original_clockvm_name = "none"
  599. try:
  600. # use qubes-prefs to not hassle with qubes.xml locking
  601. subprocess.check_call(["qubes-prefs", "-s", "clockvm",
  602. self.testvm1.name])
  603. # break vm and dom0 time, to check if qvm-sync-clock would fix it
  604. subprocess.check_call(["sudo", "date", "-s",
  605. "2001-01-01T12:34:56"],
  606. stdout=open(os.devnull, 'w'))
  607. retcode = self.testvm1.run("date -s 2001-01-01T12:34:56",
  608. user="root", wait=True)
  609. self.assertEquals(retcode, 0, "Failed to break the VM(1) time")
  610. retcode = self.testvm2.run("date -s 2001-01-01T12:34:56",
  611. user="root", wait=True)
  612. self.assertEquals(retcode, 0, "Failed to break the VM(2) time")
  613. retcode = subprocess.call(["qvm-sync-clock"])
  614. self.assertEquals(retcode, 0,
  615. "qvm-sync-clock failed with code {}".
  616. format(retcode))
  617. (vm_time, _) = self.testvm1.run("date -u +%s",
  618. passio_popen=True).communicate()
  619. self.assertAlmostEquals(int(vm_time), int(start_time), delta=30)
  620. (vm_time, _) = self.testvm2.run("date -u +%s",
  621. passio_popen=True).communicate()
  622. self.assertAlmostEquals(int(vm_time), int(start_time), delta=30)
  623. (dom0_time, _) = subprocess.Popen(["date", "-u", "+%s"],
  624. stdout=subprocess.PIPE
  625. ).communicate()
  626. self.assertAlmostEquals(int(dom0_time), int(start_time), delta=30)
  627. except:
  628. # reset time to some approximation of the real time
  629. subprocess.Popen(["sudo", "date", "-u", "-s", "@" + start_time])
  630. raise
  631. finally:
  632. subprocess.call(["qubes-prefs", "-s", "clockvm",
  633. original_clockvm_name])
  634. def test_250_resize_private_img(self):
  635. """
  636. Test private.img resize, both offline and online
  637. :return:
  638. """
  639. # First offline test
  640. self.testvm1.resize_private_img(4*1024**3)
  641. self.testvm1.start()
  642. df_cmd = '( df --output=size /rw || df /rw | awk \'{print $2}\' )|' \
  643. 'tail -n 1'
  644. p = self.testvm1.run(df_cmd,
  645. passio_popen=True)
  646. # new_size in 1k-blocks
  647. (new_size, _) = p.communicate()
  648. # some safety margin for FS metadata
  649. self.assertGreater(int(new_size.strip()), 3.8*1024**2)
  650. # Then online test
  651. self.testvm1.resize_private_img(6*1024**3)
  652. p = self.testvm1.run(df_cmd,
  653. passio_popen=True)
  654. # new_size in 1k-blocks
  655. (new_size, _) = p.communicate()
  656. # some safety margin for FS metadata
  657. self.assertGreater(int(new_size.strip()), 5.8*1024**2)
  658. class TC_05_StandaloneVM(qubes.tests.SystemTestsMixin, qubes.tests.QubesTestCase):
  659. def test_000_create_start(self):
  660. testvm1 = self.qc.add_new_vm("QubesAppVm",
  661. template=None,
  662. name=self.make_vm_name('vm1'))
  663. testvm1.create_on_disk(verbose=False,
  664. source_template=self.qc.get_default_template())
  665. self.qc.save()
  666. self.qc.unlock_db()
  667. testvm1.start()
  668. self.assertEquals(testvm1.get_power_state(), "Running")
  669. def test_100_resize_root_img(self):
  670. testvm1 = self.qc.add_new_vm("QubesAppVm",
  671. template=None,
  672. name=self.make_vm_name('vm1'))
  673. testvm1.create_on_disk(verbose=False,
  674. source_template=self.qc.get_default_template())
  675. self.qc.save()
  676. self.qc.unlock_db()
  677. with self.assertRaises(QubesException):
  678. testvm1.resize_root_img(20*1024**3)
  679. testvm1.resize_root_img(20*1024**3, allow_start=True)
  680. timeout = 60
  681. while testvm1.is_running():
  682. time.sleep(1)
  683. timeout -= 1
  684. if timeout == 0:
  685. self.fail("Timeout while waiting for VM shutdown")
  686. self.assertEquals(testvm1.get_root_img_sz(), 20*1024**3)
  687. testvm1.start()
  688. p = testvm1.run('df --output=size /|tail -n 1',
  689. passio_popen=True)
  690. # new_size in 1k-blocks
  691. (new_size, _) = p.communicate()
  692. # some safety margin for FS metadata
  693. self.assertGreater(int(new_size.strip()), 19*1024**2)
  694. class TC_10_HVM(qubes.tests.SystemTestsMixin, qubes.tests.QubesTestCase):
  695. # TODO: test with some OS inside
  696. # TODO: windows tools tests
  697. def test_000_create_start(self):
  698. testvm1 = self.qc.add_new_vm("QubesHVm",
  699. name=self.make_vm_name('vm1'))
  700. testvm1.create_on_disk(verbose=False)
  701. self.qc.save()
  702. self.qc.unlock_db()
  703. testvm1.start()
  704. self.assertEquals(testvm1.get_power_state(), "Running")
  705. def test_010_create_start_template(self):
  706. templatevm = self.qc.add_new_vm("QubesTemplateHVm",
  707. name=self.make_vm_name('template'))
  708. templatevm.create_on_disk(verbose=False)
  709. self.qc.save()
  710. self.qc.unlock_db()
  711. templatevm.start()
  712. self.assertEquals(templatevm.get_power_state(), "Running")
  713. def test_020_create_start_template_vm(self):
  714. templatevm = self.qc.add_new_vm("QubesTemplateHVm",
  715. name=self.make_vm_name('template'))
  716. templatevm.create_on_disk(verbose=False)
  717. testvm2 = self.qc.add_new_vm("QubesHVm",
  718. name=self.make_vm_name('vm2'),
  719. template=templatevm)
  720. testvm2.create_on_disk(verbose=False)
  721. self.qc.save()
  722. self.qc.unlock_db()
  723. testvm2.start()
  724. self.assertEquals(testvm2.get_power_state(), "Running")
  725. def test_030_prevent_simultaneus_start(self):
  726. templatevm = self.qc.add_new_vm("QubesTemplateHVm",
  727. name=self.make_vm_name('template'))
  728. templatevm.create_on_disk(verbose=False)
  729. testvm2 = self.qc.add_new_vm("QubesHVm",
  730. name=self.make_vm_name('vm2'),
  731. template=templatevm)
  732. testvm2.create_on_disk(verbose=False)
  733. self.qc.save()
  734. self.qc.unlock_db()
  735. templatevm.start()
  736. self.assertEquals(templatevm.get_power_state(), "Running")
  737. self.assertRaises(QubesException, testvm2.start)
  738. templatevm.force_shutdown()
  739. testvm2.start()
  740. self.assertEquals(testvm2.get_power_state(), "Running")
  741. self.assertRaises(QubesException, templatevm.start)
  742. def test_100_resize_root_img(self):
  743. testvm1 = self.qc.add_new_vm("QubesHVm",
  744. name=self.make_vm_name('vm1'))
  745. testvm1.create_on_disk(verbose=False)
  746. self.qc.save()
  747. self.qc.unlock_db()
  748. testvm1.resize_root_img(30*1024**3)
  749. self.assertEquals(testvm1.get_root_img_sz(), 30*1024**3)
  750. testvm1.start()
  751. self.assertEquals(testvm1.get_power_state(), "Running")
  752. # TODO: launch some OS there and check the size
  753. class TC_20_DispVMMixin(qubes.tests.SystemTestsMixin):
  754. def test_000_prepare_dvm(self):
  755. self.qc.unlock_db()
  756. retcode = subprocess.call(['/usr/bin/qvm-create-default-dvm',
  757. self.template],
  758. stderr=open(os.devnull, 'w'))
  759. self.assertEqual(retcode, 0)
  760. self.qc.lock_db_for_writing()
  761. self.qc.load()
  762. self.assertIsNotNone(self.qc.get_vm_by_name(
  763. self.template + "-dvm"))
  764. # TODO: check mtime of snapshot file
  765. def test_010_simple_dvm_run(self):
  766. self.qc.unlock_db()
  767. p = subprocess.Popen(['/usr/lib/qubes/qfile-daemon-dvm',
  768. 'qubes.VMShell', 'dom0', 'DEFAULT'],
  769. stdin=subprocess.PIPE,
  770. stdout=subprocess.PIPE,
  771. stderr=open(os.devnull, 'w'))
  772. (stdout, _) = p.communicate(input="echo test")
  773. self.assertEqual(stdout, "test\n")
  774. # TODO: check if DispVM is destroyed
  775. @unittest.skipUnless(spawn.find_executable('xdotool'),
  776. "xdotool not installed")
  777. def test_020_gui_app(self):
  778. self.qc.unlock_db()
  779. p = subprocess.Popen(['/usr/lib/qubes/qfile-daemon-dvm',
  780. 'qubes.VMShell', 'dom0', 'DEFAULT'],
  781. stdin=subprocess.PIPE,
  782. stdout=subprocess.PIPE,
  783. stderr=open(os.devnull, 'w'))
  784. # wait for DispVM startup:
  785. p.stdin.write("echo test\n")
  786. p.stdin.flush()
  787. l = p.stdout.readline()
  788. self.assertEqual(l, "test\n")
  789. # potential race condition, but our tests are supposed to be
  790. # running on dedicated machine, so should not be a problem
  791. self.qc.lock_db_for_reading()
  792. self.qc.load()
  793. self.qc.unlock_db()
  794. max_qid = 0
  795. for vm in self.qc.values():
  796. if not vm.is_disposablevm():
  797. continue
  798. if vm.qid > max_qid:
  799. max_qid = vm.qid
  800. dispvm = self.qc[max_qid]
  801. self.assertNotEqual(dispvm.qid, 0, "DispVM not found in qubes.xml")
  802. self.assertTrue(dispvm.is_running())
  803. try:
  804. window_title = 'user@%s' % (dispvm.template.name + "-dvm")
  805. p.stdin.write("xterm -e "
  806. "\"sh -s -c 'echo \\\"\033]0;{}\007\\\";read x;'\"\n".
  807. format(window_title))
  808. self.wait_for_window(window_title)
  809. time.sleep(0.5)
  810. self.enter_keys_in_window(window_title, ['Return'])
  811. # Wait for window to close
  812. self.wait_for_window(window_title, show=False)
  813. finally:
  814. p.stdin.close()
  815. wait_count = 0
  816. while dispvm.is_running():
  817. wait_count += 1
  818. if wait_count > 100:
  819. self.fail("Timeout while waiting for DispVM destruction")
  820. time.sleep(0.1)
  821. wait_count = 0
  822. while p.poll() is None:
  823. wait_count += 1
  824. if wait_count > 100:
  825. self.fail("Timeout while waiting for qfile-daemon-dvm "
  826. "termination")
  827. time.sleep(0.1)
  828. self.assertEqual(p.returncode, 0)
  829. self.qc.lock_db_for_reading()
  830. self.qc.load()
  831. self.qc.unlock_db()
  832. self.assertIsNone(self.qc.get_vm_by_name(dispvm.name),
  833. "DispVM not removed from qubes.xml")
  834. def _handle_editor(self, winid):
  835. (window_title, _) = subprocess.Popen(
  836. ['xdotool', 'getwindowname', winid], stdout=subprocess.PIPE).\
  837. communicate()
  838. window_title = window_title.strip().\
  839. replace('(', '\(').replace(')', '\)')
  840. time.sleep(1)
  841. if "gedit" in window_title:
  842. subprocess.check_call(['xdotool', 'search', '--name', window_title,
  843. 'windowactivate', 'type', 'test test 2\n'])
  844. time.sleep(0.5)
  845. subprocess.check_call(['xdotool', 'search', '--name', window_title,
  846. 'key', 'ctrl+s', 'ctrl+q'])
  847. elif "emacs" in window_title:
  848. subprocess.check_call(['xdotool', 'search', '--name', window_title,
  849. 'windowactivate', 'type', 'test test 2\n'])
  850. time.sleep(0.5)
  851. subprocess.check_call(['xdotool', 'search', '--name', window_title,
  852. 'key', 'ctrl+x', 'ctrl+s'])
  853. subprocess.check_call(['xdotool', 'search', '--name', window_title,
  854. 'key', 'ctrl+x', 'ctrl+c'])
  855. elif "vim" in window_title:
  856. subprocess.check_call(['xdotool', 'search', '--name', window_title,
  857. 'windowactivate', 'key', 'i',
  858. 'type', 'test test 2\n'])
  859. subprocess.check_call(
  860. ['xdotool', 'search', '--name', window_title,
  861. 'key', 'Escape', 'colon', 'w', 'q', 'Return'])
  862. else:
  863. self.fail("Unknown editor window: {}".format(window_title))
  864. @unittest.skipUnless(spawn.find_executable('xdotool'),
  865. "xdotool not installed")
  866. def test_030_edit_file(self):
  867. testvm1 = self.qc.add_new_vm("QubesAppVm",
  868. name=self.make_vm_name('vm1'),
  869. template=self.qc.get_vm_by_name(
  870. self.template))
  871. testvm1.create_on_disk(verbose=False)
  872. self.qc.save()
  873. testvm1.start()
  874. testvm1.run("echo test1 > /home/user/test.txt", wait=True)
  875. self.qc.unlock_db()
  876. p = testvm1.run("qvm-open-in-dvm /home/user/test.txt",
  877. passio_popen=True)
  878. wait_count = 0
  879. winid = None
  880. while True:
  881. search = subprocess.Popen(['xdotool', 'search',
  882. '--onlyvisible', '--class', 'disp*'],
  883. stdout=subprocess.PIPE,
  884. stderr=open(os.path.devnull, 'w'))
  885. retcode = search.wait()
  886. if retcode == 0:
  887. winid = search.stdout.read().strip()
  888. break
  889. wait_count += 1
  890. if wait_count > 100:
  891. self.fail("Timeout while waiting for editor window")
  892. time.sleep(0.3)
  893. self._handle_editor(winid)
  894. p.wait()
  895. p = testvm1.run("cat /home/user/test.txt",
  896. passio_popen=True)
  897. (test_txt_content, _) = p.communicate()
  898. self.assertEqual(test_txt_content, "test test 2\ntest1\n")
  899. class TC_30_Gui_daemon(qubes.tests.SystemTestsMixin, qubes.tests.QubesTestCase):
  900. @unittest.skipUnless(spawn.find_executable('xdotool'),
  901. "xdotool not installed")
  902. def test_000_clipboard(self):
  903. testvm1 = self.qc.add_new_vm("QubesAppVm",
  904. name=self.make_vm_name('vm1'),
  905. template=self.qc.get_default_template())
  906. testvm1.create_on_disk(verbose=False)
  907. testvm2 = self.qc.add_new_vm("QubesAppVm",
  908. name=self.make_vm_name('vm2'),
  909. template=self.qc.get_default_template())
  910. testvm2.create_on_disk(verbose=False)
  911. self.qc.save()
  912. self.qc.unlock_db()
  913. testvm1.start()
  914. testvm2.start()
  915. window_title = 'user@{}'.format(testvm1.name)
  916. testvm1.run('zenity --text-info --editable --title={}'.format(
  917. window_title))
  918. self.wait_for_window(window_title)
  919. time.sleep(0.5)
  920. test_string = "test{}".format(testvm1.xid)
  921. # Type and copy some text
  922. subprocess.check_call(['xdotool', 'search', '--name', window_title,
  923. 'windowactivate',
  924. 'type', '{}'.format(test_string)])
  925. # second xdotool call because type --terminator do not work (SEGV)
  926. # additionally do not use search here, so window stack will be empty
  927. # and xdotool will use XTEST instead of generating events manually -
  928. # this will be much better - at least because events will have
  929. # correct timestamp (so gui-daemon would not drop the copy request)
  930. subprocess.check_call(['xdotool',
  931. 'key', 'ctrl+a', 'ctrl+c', 'ctrl+shift+c',
  932. 'Escape'])
  933. clipboard_content = \
  934. open('/var/run/qubes/qubes-clipboard.bin', 'r').read().strip()
  935. self.assertEquals(clipboard_content, test_string,
  936. "Clipboard copy operation failed - content")
  937. clipboard_source = \
  938. open('/var/run/qubes/qubes-clipboard.bin.source',
  939. 'r').read().strip()
  940. self.assertEquals(clipboard_source, testvm1.name,
  941. "Clipboard copy operation failed - owner")
  942. # Then paste it to the other window
  943. window_title = 'user@{}'.format(testvm2.name)
  944. p = testvm2.run('zenity --entry --title={} > test.txt'.format(
  945. window_title), passio_popen=True)
  946. self.wait_for_window(window_title)
  947. subprocess.check_call(['xdotool', 'key', '--delay', '100',
  948. 'ctrl+shift+v', 'ctrl+v', 'Return'])
  949. p.wait()
  950. # And compare the result
  951. (test_output, _) = testvm2.run('cat test.txt',
  952. passio_popen=True).communicate()
  953. self.assertEquals(test_string, test_output.strip())
  954. clipboard_content = \
  955. open('/var/run/qubes/qubes-clipboard.bin', 'r').read().strip()
  956. self.assertEquals(clipboard_content, "",
  957. "Clipboard not wiped after paste - content")
  958. clipboard_source = \
  959. open('/var/run/qubes/qubes-clipboard.bin.source', 'r').read(
  960. ).strip()
  961. self.assertEquals(clipboard_source, "",
  962. "Clipboard not wiped after paste - owner")
  963. @unittest.skipUnless(os.path.exists('/var/lib/qubes/vm-kernels/pvgrub2'),
  964. 'grub-xen package not installed')
  965. class TC_40_PVGrub(qubes.tests.SystemTestsMixin):
  966. def setUp(self):
  967. super(TC_40_PVGrub, self).setUp()
  968. supported = False
  969. if self.template.startswith('fedora-'):
  970. supported = True
  971. elif self.template.startswith('debian-'):
  972. supported = True
  973. if not supported:
  974. self.skipTest("Template {} not supported by this test".format(
  975. self.template))
  976. def install_packages(self, vm):
  977. if self.template.startswith('fedora-'):
  978. cmd_install1 = 'yum clean expire-cache && ' \
  979. 'yum install -y qubes-kernel-vm-support grub2-tools'
  980. cmd_install2 = 'yum install -y kernel kernel-devel'
  981. cmd_update_grub = 'grub2-mkconfig -o /boot/grub2/grub.cfg'
  982. elif self.template.startswith('debian-'):
  983. cmd_install1 = 'apt-get update && apt-get install -y ' \
  984. 'qubes-kernel-vm-support grub2-common'
  985. cmd_install2 = 'apt-get install -y linux-image-amd64'
  986. cmd_update_grub = 'mkdir /boot/grub && update-grub2'
  987. else:
  988. assert False, "Unsupported template?!"
  989. for cmd in [cmd_install1, cmd_install2, cmd_update_grub]:
  990. p = vm.run(cmd, user="root", passio_popen=True, passio_stderr=True)
  991. (stdout, stderr) = p.communicate()
  992. self.assertEquals(p.returncode, 0,
  993. "Failed command: {}\nSTDOUT: {}\nSTDERR: {}"
  994. .format(cmd, stdout, stderr))
  995. def get_kernel_version(self, vm):
  996. if self.template.startswith('fedora-'):
  997. cmd_get_kernel_version = 'rpm -q kernel|sort -n|tail -1|' \
  998. 'cut -d - -f 2-'
  999. elif self.template.startswith('debian-'):
  1000. cmd_get_kernel_version = \
  1001. 'dpkg-query --showformat=\'${Package}\\n\' --show ' \
  1002. '\'linux-image-*-amd64\'|sort -n|tail -1|cut -d - -f 3-'
  1003. else:
  1004. raise RuntimeError("Unsupported template?!")
  1005. p = vm.run(cmd_get_kernel_version, user="root", passio_popen=True)
  1006. (kver, _) = p.communicate()
  1007. self.assertEquals(p.returncode, 0,
  1008. "Failed command: {}".format(cmd_get_kernel_version))
  1009. return kver.strip()
  1010. def test_000_standalone_vm(self):
  1011. testvm1 = self.qc.add_new_vm("QubesAppVm",
  1012. template=None,
  1013. name=self.make_vm_name('vm1'))
  1014. testvm1.create_on_disk(verbose=False,
  1015. source_template=self.qc.get_vm_by_name(
  1016. self.template))
  1017. self.save_and_reload_db()
  1018. self.qc.unlock_db()
  1019. testvm1 = self.qc[testvm1.qid]
  1020. testvm1.start()
  1021. self.install_packages(testvm1)
  1022. kver = self.get_kernel_version(testvm1)
  1023. self.shutdown_and_wait(testvm1)
  1024. self.qc.lock_db_for_writing()
  1025. self.qc.load()
  1026. testvm1 = self.qc[testvm1.qid]
  1027. testvm1.kernel = 'pvgrub2'
  1028. self.save_and_reload_db()
  1029. self.qc.unlock_db()
  1030. testvm1 = self.qc[testvm1.qid]
  1031. testvm1.start()
  1032. p = testvm1.run('uname -r', passio_popen=True)
  1033. (actual_kver, _) = p.communicate()
  1034. self.assertEquals(actual_kver.strip(), kver)
  1035. def test_010_template_based_vm(self):
  1036. test_template = self.qc.add_new_vm("QubesTemplateVm",
  1037. template=None,
  1038. name=self.make_vm_name('template'))
  1039. test_template.clone_attrs(self.qc.get_vm_by_name(self.template))
  1040. test_template.clone_disk_files(
  1041. src_vm=self.qc.get_vm_by_name(self.template),
  1042. verbose=False)
  1043. testvm1 = self.qc.add_new_vm("QubesAppVm",
  1044. template=test_template,
  1045. name=self.make_vm_name('vm1'))
  1046. testvm1.create_on_disk(verbose=False,
  1047. source_template=test_template)
  1048. self.save_and_reload_db()
  1049. self.qc.unlock_db()
  1050. test_template = self.qc[test_template.qid]
  1051. testvm1 = self.qc[testvm1.qid]
  1052. test_template.start()
  1053. self.install_packages(test_template)
  1054. kver = self.get_kernel_version(test_template)
  1055. self.shutdown_and_wait(test_template)
  1056. self.qc.lock_db_for_writing()
  1057. self.qc.load()
  1058. test_template = self.qc[test_template.qid]
  1059. test_template.kernel = 'pvgrub2'
  1060. testvm1 = self.qc[testvm1.qid]
  1061. testvm1.kernel = 'pvgrub2'
  1062. self.save_and_reload_db()
  1063. self.qc.unlock_db()
  1064. # Check if TemplateBasedVM boots and has the right kernel
  1065. testvm1 = self.qc[testvm1.qid]
  1066. testvm1.start()
  1067. p = testvm1.run('uname -r', passio_popen=True)
  1068. (actual_kver, _) = p.communicate()
  1069. self.assertEquals(actual_kver.strip(), kver)
  1070. # And the same for the TemplateVM itself
  1071. test_template = self.qc[test_template.qid]
  1072. test_template.start()
  1073. p = test_template.run('uname -r', passio_popen=True)
  1074. (actual_kver, _) = p.communicate()
  1075. self.assertEquals(actual_kver.strip(), kver)
  1076. def load_tests(loader, tests, pattern):
  1077. try:
  1078. qc = qubes.qubes.QubesVmCollection()
  1079. qc.lock_db_for_reading()
  1080. qc.load()
  1081. qc.unlock_db()
  1082. templates = [vm.name for vm in qc.values() if
  1083. isinstance(vm, qubes.qubes.QubesTemplateVm)]
  1084. except OSError:
  1085. templates = []
  1086. for template in templates:
  1087. tests.addTests(loader.loadTestsFromTestCase(
  1088. type(
  1089. 'TC_00_AppVM_' + template,
  1090. (TC_00_AppVMMixin, qubes.tests.QubesTestCase),
  1091. {'template': template})))
  1092. tests.addTests(loader.loadTestsFromTestCase(
  1093. type(
  1094. 'TC_20_DispVM_' + template,
  1095. (TC_20_DispVMMixin, qubes.tests.QubesTestCase),
  1096. {'template': template})))
  1097. tests.addTests(loader.loadTestsFromTestCase(
  1098. type(
  1099. 'TC_40_PVGrub_' + template,
  1100. (TC_40_PVGrub, qubes.tests.QubesTestCase),
  1101. {'template': template})))
  1102. return tests