vm_qrexec_gui.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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. import qubes.config
  31. import qubes.tests
  32. import qubes.vm.appvm
  33. import qubes.vm.templatevm
  34. import re
  35. TEST_DATA = "0123456789" * 1024
  36. class TC_00_AppVMMixin(qubes.tests.SystemTestsMixin):
  37. def setUp(self):
  38. super(TC_00_AppVMMixin, self).setUp()
  39. self.init_default_template(self.template)
  40. if self._testMethodName == 'test_210_time_sync':
  41. self.init_networking()
  42. self.testvm1 = self.app.add_new_vm(
  43. qubes.vm.appvm.AppVM,
  44. label='red',
  45. name=self.make_vm_name('vm1'),
  46. template=self.app.domains[self.template])
  47. self.testvm1.create_on_disk()
  48. self.testvm2 = self.app.add_new_vm(
  49. qubes.vm.appvm.AppVM,
  50. label='red',
  51. name=self.make_vm_name('vm2'),
  52. template=self.app.domains[self.template])
  53. self.testvm2.create_on_disk()
  54. self.app.save()
  55. def test_000_start_shutdown(self):
  56. self.testvm1.start()
  57. self.assertEquals(self.testvm1.get_power_state(), "Running")
  58. self.testvm1.shutdown()
  59. shutdown_counter = 0
  60. while self.testvm1.is_running():
  61. if shutdown_counter > qubes.config.defaults["shutdown_counter_max"]:
  62. self.fail("VM hanged during shutdown")
  63. shutdown_counter += 1
  64. time.sleep(1)
  65. time.sleep(1)
  66. self.assertEquals(self.testvm1.get_power_state(), "Halted")
  67. @unittest.skipUnless(spawn.find_executable('xdotool'),
  68. "xdotool not installed")
  69. def test_010_run_xterm(self):
  70. self.testvm1.start()
  71. self.assertEquals(self.testvm1.get_power_state(), "Running")
  72. self.testvm1.run("xterm")
  73. wait_count = 0
  74. title = 'user@{}'.format(self.testvm1.name)
  75. if self.template.count("whonix"):
  76. title = 'user@host'
  77. while subprocess.call(
  78. ['xdotool', 'search', '--name', title],
  79. stdout=open(os.path.devnull, 'w'),
  80. stderr=subprocess.STDOUT) > 0:
  81. wait_count += 1
  82. if wait_count > 100:
  83. self.fail("Timeout while waiting for xterm window")
  84. time.sleep(0.1)
  85. time.sleep(0.5)
  86. subprocess.check_call(
  87. ['xdotool', 'search', '--name', title,
  88. 'windowactivate', 'type', 'exit\n'])
  89. wait_count = 0
  90. while subprocess.call(['xdotool', 'search', '--name', title],
  91. stdout=open(os.path.devnull, 'w'),
  92. stderr=subprocess.STDOUT) == 0:
  93. wait_count += 1
  94. if wait_count > 100:
  95. self.fail("Timeout while waiting for xterm "
  96. "termination")
  97. time.sleep(0.1)
  98. @unittest.skipUnless(spawn.find_executable('xdotool'),
  99. "xdotool not installed")
  100. def test_011_run_gnome_terminal(self):
  101. if "minimal" in self.template:
  102. self.skipTest("Minimal template doesn't have 'gnome-terminal'")
  103. self.testvm1.start()
  104. self.assertEquals(self.testvm1.get_power_state(), "Running")
  105. self.testvm1.run("gnome-terminal")
  106. title = 'user@{}'.format(self.testvm1.name)
  107. if self.template.count("whonix"):
  108. title = 'user@host'
  109. wait_count = 0
  110. while subprocess.call(
  111. ['xdotool', 'search', '--name', title],
  112. stdout=open(os.path.devnull, 'w'),
  113. stderr=subprocess.STDOUT) > 0:
  114. wait_count += 1
  115. if wait_count > 100:
  116. self.fail("Timeout while waiting for gnome-terminal window")
  117. time.sleep(0.1)
  118. time.sleep(0.5)
  119. subprocess.check_call(
  120. ['xdotool', 'search', '--name', title,
  121. 'windowactivate', '--sync', 'type', 'exit\n'])
  122. wait_count = 0
  123. while subprocess.call(['xdotool', 'search', '--name', title],
  124. stdout=open(os.path.devnull, 'w'),
  125. stderr=subprocess.STDOUT) == 0:
  126. wait_count += 1
  127. if wait_count > 100:
  128. self.fail("Timeout while waiting for gnome-terminal "
  129. "termination")
  130. time.sleep(0.1)
  131. @unittest.skipUnless(spawn.find_executable('xdotool'),
  132. "xdotool not installed")
  133. def test_012_qubes_desktop_run(self):
  134. self.testvm1.start()
  135. self.assertEquals(self.testvm1.get_power_state(), "Running")
  136. xterm_desktop_path = "/usr/share/applications/xterm.desktop"
  137. # Debian has it different...
  138. xterm_desktop_path_debian = \
  139. "/usr/share/applications/debian-xterm.desktop"
  140. if self.testvm1.run("test -r {}".format(xterm_desktop_path_debian),
  141. wait=True) == 0:
  142. xterm_desktop_path = xterm_desktop_path_debian
  143. self.testvm1.run("qubes-desktop-run {}".format(xterm_desktop_path))
  144. title = 'user@{}'.format(self.testvm1.name)
  145. if self.template.count("whonix"):
  146. title = 'user@host'
  147. wait_count = 0
  148. while subprocess.call(
  149. ['xdotool', 'search', '--name', title],
  150. stdout=open(os.path.devnull, 'w'),
  151. stderr=subprocess.STDOUT) > 0:
  152. wait_count += 1
  153. if wait_count > 100:
  154. self.fail("Timeout while waiting for xterm window")
  155. time.sleep(0.1)
  156. time.sleep(0.5)
  157. subprocess.check_call(
  158. ['xdotool', 'search', '--name', title,
  159. 'windowactivate', '--sync', 'type', 'exit\n'])
  160. wait_count = 0
  161. while subprocess.call(['xdotool', 'search', '--name', title],
  162. stdout=open(os.path.devnull, 'w'),
  163. stderr=subprocess.STDOUT) == 0:
  164. wait_count += 1
  165. if wait_count > 100:
  166. self.fail("Timeout while waiting for xterm "
  167. "termination")
  168. time.sleep(0.1)
  169. def test_050_qrexec_simple_eof(self):
  170. """Test for data and EOF transmission dom0->VM"""
  171. result = multiprocessing.Value('i', 0)
  172. def run(self, result):
  173. p = self.testvm1.run("cat", passio_popen=True,
  174. passio_stderr=True)
  175. (stdout, stderr) = p.communicate(TEST_DATA)
  176. if stdout != TEST_DATA:
  177. result.value = 1
  178. if len(stderr) > 0:
  179. result.value = 2
  180. self.testvm1.start()
  181. t = multiprocessing.Process(target=run, args=(self, result))
  182. t.start()
  183. t.join(timeout=10)
  184. if t.is_alive():
  185. t.terminate()
  186. self.fail("Timeout, probably EOF wasn't transferred to the VM "
  187. "process")
  188. if result.value == 1:
  189. self.fail("Received data differs from what was sent")
  190. elif result.value == 2:
  191. self.fail("Some data was printed to stderr")
  192. def test_051_qrexec_simple_eof_reverse(self):
  193. """Test for EOF transmission VM->dom0"""
  194. result = multiprocessing.Value('i', 0)
  195. def run(self, result):
  196. p = self.testvm1.run("echo test; exec >&-; cat > /dev/null",
  197. passio_popen=True, passio_stderr=True)
  198. # this will hang on test failure
  199. stdout = p.stdout.read()
  200. p.stdin.write(TEST_DATA)
  201. p.stdin.close()
  202. if stdout.strip() != "test":
  203. result.value = 1
  204. # this may hang in some buggy cases
  205. elif len(p.stderr.read()) > 0:
  206. result.value = 2
  207. elif p.poll() is None:
  208. time.sleep(1)
  209. if p.poll() is None:
  210. result.value = 3
  211. self.testvm1.start()
  212. t = multiprocessing.Process(target=run, args=(self, result))
  213. t.start()
  214. t.join(timeout=10)
  215. if t.is_alive():
  216. t.terminate()
  217. self.fail("Timeout, probably EOF wasn't transferred from the VM "
  218. "process")
  219. if result.value == 1:
  220. self.fail("Received data differs from what was expected")
  221. elif result.value == 2:
  222. self.fail("Some data was printed to stderr")
  223. elif result.value == 3:
  224. self.fail("VM proceess didn't terminated on EOF")
  225. def test_052_qrexec_vm_service_eof(self):
  226. """Test for EOF transmission VM(src)->VM(dst)"""
  227. result = multiprocessing.Value('i', 0)
  228. def run(self, result):
  229. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm %s test.EOF "
  230. "/bin/sh -c 'echo test; exec >&-; cat "
  231. ">&$SAVED_FD_1'" % self.testvm2.name,
  232. passio_popen=True)
  233. (stdout, stderr) = p.communicate()
  234. if stdout != "test\n":
  235. result.value = 1
  236. self.testvm1.start()
  237. self.testvm2.start()
  238. p = self.testvm2.run("cat > /etc/qubes-rpc/test.EOF", user="root",
  239. passio_popen=True)
  240. p.stdin.write("/bin/cat")
  241. p.stdin.close()
  242. p.wait()
  243. policy = open("/etc/qubes-rpc/policy/test.EOF", "w")
  244. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  245. policy.close()
  246. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.EOF")
  247. t = multiprocessing.Process(target=run, args=(self, result))
  248. t.start()
  249. t.join(timeout=10)
  250. if t.is_alive():
  251. t.terminate()
  252. self.fail("Timeout, probably EOF wasn't transferred")
  253. if result.value == 1:
  254. self.fail("Received data differs from what was expected")
  255. @unittest.expectedFailure
  256. def test_053_qrexec_vm_service_eof_reverse(self):
  257. """Test for EOF transmission VM(src)<-VM(dst)"""
  258. result = multiprocessing.Value('i', 0)
  259. def run(self, result):
  260. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm %s test.EOF "
  261. "/bin/sh -c 'cat >&$SAVED_FD_1'"
  262. % self.testvm2.name,
  263. passio_popen=True)
  264. (stdout, stderr) = p.communicate()
  265. if stdout != "test\n":
  266. result.value = 1
  267. self.testvm1.start()
  268. self.testvm2.start()
  269. p = self.testvm2.run("cat > /etc/qubes-rpc/test.EOF", user="root",
  270. passio_popen=True)
  271. p.stdin.write("echo test; exec >&-; cat >/dev/null")
  272. p.stdin.close()
  273. p.wait()
  274. policy = open("/etc/qubes-rpc/policy/test.EOF", "w")
  275. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  276. policy.close()
  277. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.EOF")
  278. t = multiprocessing.Process(target=run, args=(self, result))
  279. t.start()
  280. t.join(timeout=10)
  281. if t.is_alive():
  282. t.terminate()
  283. self.fail("Timeout, probably EOF wasn't transferred")
  284. if result.value == 1:
  285. self.fail("Received data differs from what was expected")
  286. def test_055_qrexec_dom0_service_abort(self):
  287. """
  288. Test if service abort (by dom0) is properly handled by source VM.
  289. If "remote" part of the service terminates, the source part should
  290. properly be notified. This includes closing its stdin (which is
  291. already checked by test_053_qrexec_vm_service_eof_reverse), but also
  292. its stdout - otherwise such service might hang on write(2) call.
  293. """
  294. def run (src):
  295. p = src.run("/usr/lib/qubes/qrexec-client-vm dom0 "
  296. "test.Abort /bin/cat /dev/zero",
  297. passio_popen=True)
  298. p.communicate()
  299. p.wait()
  300. self.testvm1.start()
  301. service = open("/etc/qubes-rpc/test.Abort", "w")
  302. service.write("sleep 1")
  303. service.close()
  304. self.addCleanup(os.unlink, "/etc/qubes-rpc/test.Abort")
  305. policy = open("/etc/qubes-rpc/policy/test.Abort", "w")
  306. policy.write("%s dom0 allow" % (self.testvm1.name))
  307. policy.close()
  308. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.Abort")
  309. t = multiprocessing.Process(target=run, args=(self.testvm1,))
  310. t.start()
  311. t.join(timeout=10)
  312. if t.is_alive():
  313. t.terminate()
  314. self.fail("Timeout, probably stdout wasn't closed")
  315. def test_060_qrexec_exit_code_dom0(self):
  316. self.testvm1.start()
  317. p = self.testvm1.run("exit 0", passio_popen=True)
  318. p.wait()
  319. self.assertEqual(0, p.returncode)
  320. p = self.testvm1.run("exit 3", passio_popen=True)
  321. p.wait()
  322. self.assertEqual(3, p.returncode)
  323. @unittest.expectedFailure
  324. def test_065_qrexec_exit_code_vm(self):
  325. self.testvm1.start()
  326. self.testvm2.start()
  327. policy = open("/etc/qubes-rpc/policy/test.Retcode", "w")
  328. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  329. policy.close()
  330. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.Retcode")
  331. p = self.testvm2.run("cat > /etc/qubes-rpc/test.Retcode", user="root",
  332. passio_popen=True)
  333. p.stdin.write("exit 0")
  334. p.stdin.close()
  335. p.wait()
  336. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm %s test.Retcode "
  337. "/bin/sh -c 'cat >/dev/null'; echo $?"
  338. % self.testvm1.name,
  339. passio_popen=True)
  340. (stdout, stderr) = p.communicate()
  341. self.assertEqual(stdout, "0\n")
  342. p = self.testvm2.run("cat > /etc/qubes-rpc/test.Retcode", user="root",
  343. passio_popen=True)
  344. p.stdin.write("exit 3")
  345. p.stdin.close()
  346. p.wait()
  347. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm %s test.Retcode "
  348. "/bin/sh -c 'cat >/dev/null'; echo $?"
  349. % self.testvm1.name,
  350. passio_popen=True)
  351. (stdout, stderr) = p.communicate()
  352. self.assertEqual(stdout, "3\n")
  353. def test_070_qrexec_vm_simultaneous_write(self):
  354. """Test for simultaneous write in VM(src)->VM(dst) connection
  355. This is regression test for #1347
  356. Check for deadlock when initially both sides writes a lot of data
  357. (and not read anything). When one side starts reading, it should
  358. get the data and the remote side should be possible to write then more.
  359. There was a bug where remote side was waiting on write(2) and not
  360. handling anything else.
  361. """
  362. result = multiprocessing.Value('i', -1)
  363. def run(self):
  364. p = self.testvm1.run(
  365. "/usr/lib/qubes/qrexec-client-vm %s test.write "
  366. "/bin/sh -c '"
  367. # first write a lot of data to fill all the buffers
  368. "dd if=/dev/zero bs=993 count=10000 iflag=fullblock & "
  369. # then after some time start reading
  370. "sleep 1; "
  371. "dd of=/dev/null bs=993 count=10000 iflag=fullblock; "
  372. "wait"
  373. "'" % self.testvm2.name, passio_popen=True)
  374. p.communicate()
  375. result.value = p.returncode
  376. self.testvm1.start()
  377. self.testvm2.start()
  378. p = self.testvm2.run("cat > /etc/qubes-rpc/test.write", user="root",
  379. passio_popen=True)
  380. # first write a lot of data
  381. p.stdin.write("dd if=/dev/zero bs=993 count=10000 iflag=fullblock\n")
  382. # and only then read something
  383. p.stdin.write("dd of=/dev/null bs=993 count=10000 iflag=fullblock\n")
  384. p.stdin.close()
  385. p.wait()
  386. policy = open("/etc/qubes-rpc/policy/test.write", "w")
  387. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  388. policy.close()
  389. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.write")
  390. t = multiprocessing.Process(target=run, args=(self,))
  391. t.start()
  392. t.join(timeout=10)
  393. if t.is_alive():
  394. t.terminate()
  395. self.fail("Timeout, probably deadlock")
  396. self.assertEqual(result.value, 0, "Service call failed")
  397. def test_071_qrexec_dom0_simultaneous_write(self):
  398. """Test for simultaneous write in dom0(src)->VM(dst) connection
  399. Similar to test_070_qrexec_vm_simultaneous_write, but with dom0
  400. as a source.
  401. """
  402. result = multiprocessing.Value('i', -1)
  403. def run(self):
  404. result.value = self.testvm2.run_service(
  405. "test.write", localcmd="/bin/sh -c '"
  406. # first write a lot of data to fill all the buffers
  407. "dd if=/dev/zero bs=993 count=10000 iflag=fullblock & "
  408. # then after some time start reading
  409. "sleep 1; "
  410. "dd of=/dev/null bs=993 count=10000 iflag=fullblock; "
  411. "wait"
  412. "'")
  413. self.testvm2.start()
  414. p = self.testvm2.run("cat > /etc/qubes-rpc/test.write", user="root",
  415. passio_popen=True)
  416. # first write a lot of data
  417. p.stdin.write("dd if=/dev/zero bs=993 count=10000 iflag=fullblock\n")
  418. # and only then read something
  419. p.stdin.write("dd of=/dev/null bs=993 count=10000 iflag=fullblock\n")
  420. p.stdin.close()
  421. p.wait()
  422. policy = open("/etc/qubes-rpc/policy/test.write", "w")
  423. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  424. policy.close()
  425. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.write")
  426. t = multiprocessing.Process(target=run, args=(self,))
  427. t.start()
  428. t.join(timeout=10)
  429. if t.is_alive():
  430. t.terminate()
  431. self.fail("Timeout, probably deadlock")
  432. self.assertEqual(result.value, 0, "Service call failed")
  433. def test_072_qrexec_to_dom0_simultaneous_write(self):
  434. """Test for simultaneous write in dom0(src)<-VM(dst) connection
  435. Similar to test_071_qrexec_dom0_simultaneous_write, but with dom0
  436. as a "hanging" side.
  437. """
  438. result = multiprocessing.Value('i', -1)
  439. def run(self):
  440. result.value = self.testvm2.run_service(
  441. "test.write", localcmd="/bin/sh -c '"
  442. # first write a lot of data to fill all the buffers
  443. "dd if=/dev/zero bs=993 count=10000 iflag=fullblock "
  444. # then, only when all written, read something
  445. "dd of=/dev/null bs=993 count=10000 iflag=fullblock; "
  446. "'")
  447. self.testvm2.start()
  448. p = self.testvm2.run("cat > /etc/qubes-rpc/test.write", user="root",
  449. passio_popen=True)
  450. # first write a lot of data
  451. p.stdin.write("dd if=/dev/zero bs=993 count=10000 iflag=fullblock &\n")
  452. # and only then read something
  453. p.stdin.write("dd of=/dev/null bs=993 count=10000 iflag=fullblock\n")
  454. p.stdin.write("sleep 1; \n")
  455. p.stdin.write("wait\n")
  456. p.stdin.close()
  457. p.wait()
  458. policy = open("/etc/qubes-rpc/policy/test.write", "w")
  459. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  460. policy.close()
  461. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.write")
  462. t = multiprocessing.Process(target=run, args=(self,))
  463. t.start()
  464. t.join(timeout=10)
  465. if t.is_alive():
  466. t.terminate()
  467. self.fail("Timeout, probably deadlock")
  468. self.assertEqual(result.value, 0, "Service call failed")
  469. def test_080_qrexec_service_argument_allow_default(self):
  470. """Qrexec service call with argument"""
  471. self.testvm1.start()
  472. self.testvm2.start()
  473. p = self.testvm2.run("cat > /etc/qubes-rpc/test.Argument", user="root",
  474. passio_popen=True)
  475. p.communicate("/bin/echo $1")
  476. with open("/etc/qubes-rpc/policy/test.Argument", "w") as policy:
  477. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  478. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.Argument")
  479. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm {} "
  480. "test.Argument+argument".format(self.testvm2.name),
  481. passio_popen=True)
  482. (stdout, stderr) = p.communicate()
  483. self.assertEqual(stdout, "argument\n")
  484. def test_081_qrexec_service_argument_allow_specific(self):
  485. """Qrexec service call with argument - allow only specific value"""
  486. self.testvm1.start()
  487. self.testvm2.start()
  488. p = self.testvm2.run("cat > /etc/qubes-rpc/test.Argument", user="root",
  489. passio_popen=True)
  490. p.communicate("/bin/echo $1")
  491. with open("/etc/qubes-rpc/policy/test.Argument", "w") as policy:
  492. policy.write("$anyvm $anyvm deny")
  493. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.Argument")
  494. with open("/etc/qubes-rpc/policy/test.Argument+argument", "w") as \
  495. policy:
  496. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  497. self.addCleanup(os.unlink,
  498. "/etc/qubes-rpc/policy/test.Argument+argument")
  499. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm {} "
  500. "test.Argument+argument".format(self.testvm2.name),
  501. passio_popen=True)
  502. (stdout, stderr) = p.communicate()
  503. self.assertEqual(stdout, "argument\n")
  504. def test_082_qrexec_service_argument_deny_specific(self):
  505. """Qrexec service call with argument - deny specific value"""
  506. self.testvm1.start()
  507. self.testvm2.start()
  508. p = self.testvm2.run("cat > /etc/qubes-rpc/test.Argument", user="root",
  509. passio_popen=True)
  510. p.communicate("/bin/echo $1")
  511. with open("/etc/qubes-rpc/policy/test.Argument", "w") as policy:
  512. policy.write("$anyvm $anyvm allow")
  513. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.Argument")
  514. with open("/etc/qubes-rpc/policy/test.Argument+argument", "w") as \
  515. policy:
  516. policy.write("%s %s deny" % (self.testvm1.name, self.testvm2.name))
  517. self.addCleanup(os.unlink,
  518. "/etc/qubes-rpc/policy/test.Argument+argument")
  519. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm {} "
  520. "test.Argument+argument".format(self.testvm2.name),
  521. passio_popen=True)
  522. (stdout, stderr) = p.communicate()
  523. self.assertEqual(stdout, "")
  524. self.assertEqual(p.returncode, 1, "Service request should be denied")
  525. def test_083_qrexec_service_argument_specific_implementation(self):
  526. """Qrexec service call with argument - argument specific
  527. implementatation"""
  528. self.testvm1.start()
  529. self.testvm2.start()
  530. p = self.testvm2.run("cat > /etc/qubes-rpc/test.Argument", user="root",
  531. passio_popen=True)
  532. p.communicate("/bin/echo $1")
  533. p = self.testvm2.run("cat > /etc/qubes-rpc/test.Argument+argument",
  534. user="root", passio_popen=True)
  535. p.communicate("/bin/echo specific: $1")
  536. with open("/etc/qubes-rpc/policy/test.Argument", "w") as policy:
  537. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  538. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.Argument")
  539. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm {} "
  540. "test.Argument+argument".format(self.testvm2.name),
  541. passio_popen=True)
  542. (stdout, stderr) = p.communicate()
  543. self.assertEqual(stdout, "specific: argument\n")
  544. def test_084_qrexec_service_argument_extra_env(self):
  545. """Qrexec service call with argument - extra env variables"""
  546. self.testvm1.start()
  547. self.testvm2.start()
  548. p = self.testvm2.run("cat > /etc/qubes-rpc/test.Argument", user="root",
  549. passio_popen=True)
  550. p.communicate("/bin/echo $QREXEC_SERVICE_FULL_NAME "
  551. "$QREXEC_SERVICE_ARGUMENT")
  552. with open("/etc/qubes-rpc/policy/test.Argument", "w") as policy:
  553. policy.write("%s %s allow" % (self.testvm1.name, self.testvm2.name))
  554. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.Argument")
  555. p = self.testvm1.run("/usr/lib/qubes/qrexec-client-vm {} "
  556. "test.Argument+argument".format(self.testvm2.name),
  557. passio_popen=True)
  558. (stdout, stderr) = p.communicate()
  559. self.assertEqual(stdout, "test.Argument+argument argument\n")
  560. def test_100_qrexec_filecopy(self):
  561. self.testvm1.start()
  562. self.testvm2.start()
  563. self.qrexec_policy('qubes.Filecopy', self.testvm1.name,
  564. self.testvm2.name)
  565. p = self.testvm1.run("qvm-copy-to-vm %s /etc/passwd" %
  566. self.testvm2.name, passio_popen=True,
  567. passio_stderr=True)
  568. p.wait()
  569. self.assertEqual(p.returncode, 0, "qvm-copy-to-vm failed: %s" %
  570. p.stderr.read())
  571. retcode = self.testvm2.run("diff /etc/passwd "
  572. "/home/user/QubesIncoming/{}/passwd".format(
  573. self.testvm1.name),
  574. wait=True)
  575. self.assertEqual(retcode, 0, "file differs")
  576. def test_105_qrexec_filemove(self):
  577. self.testvm1.start()
  578. self.testvm2.start()
  579. self.qrexec_policy('qubes.Filecopy', self.testvm1.name,
  580. self.testvm2.name)
  581. retcode = self.testvm1.run("cp /etc/passwd passwd", wait=True)
  582. assert retcode == 0, "Failed to prepare source file"
  583. p = self.testvm1.run("qvm-move-to-vm %s passwd" %
  584. self.testvm2.name, passio_popen=True,
  585. passio_stderr=True)
  586. p.wait()
  587. self.assertEqual(p.returncode, 0, "qvm-move-to-vm failed: %s" %
  588. p.stderr.read())
  589. retcode = self.testvm2.run("diff /etc/passwd "
  590. "/home/user/QubesIncoming/{}/passwd".format(
  591. self.testvm1.name),
  592. wait=True)
  593. self.assertEqual(retcode, 0, "file differs")
  594. retcode = self.testvm1.run("test -f passwd", wait=True)
  595. self.assertEqual(retcode, 1, "source file not removed")
  596. def test_101_qrexec_filecopy_with_autostart(self):
  597. self.testvm1.start()
  598. self.qrexec_policy('qubes.Filecopy', self.testvm1.name,
  599. self.testvm2.name)
  600. p = self.testvm1.run("qvm-copy-to-vm %s /etc/passwd" %
  601. self.testvm2.name, passio_popen=True,
  602. passio_stderr=True)
  603. p.wait()
  604. self.assertEqual(p.returncode, 0, "qvm-copy-to-vm failed: %s" %
  605. p.stderr.read())
  606. # workaround for libvirt bug (domain ID isn't updated when is started
  607. # from other application) - details in
  608. # QubesOS/qubes-core-libvirt@63ede4dfb4485c4161dd6a2cc809e8fb45ca664f
  609. self.testvm2._libvirt_domain = None
  610. self.assertTrue(self.testvm2.is_running())
  611. retcode = self.testvm2.run("diff /etc/passwd "
  612. "/home/user/QubesIncoming/{}/passwd".format(
  613. self.testvm1.name),
  614. wait=True)
  615. self.assertEqual(retcode, 0, "file differs")
  616. def test_110_qrexec_filecopy_deny(self):
  617. self.testvm1.start()
  618. self.testvm2.start()
  619. self.qrexec_policy('qubes.Filecopy', self.testvm1.name,
  620. self.testvm2.name, allow=False)
  621. p = self.testvm1.run("qvm-copy-to-vm %s /etc/passwd" %
  622. self.testvm2.name, passio_popen=True)
  623. p.wait()
  624. self.assertNotEqual(p.returncode, 0, "qvm-copy-to-vm unexpectedly "
  625. "succeeded")
  626. retcode = self.testvm1.run("ls /home/user/QubesIncoming/%s" %
  627. self.testvm1.name, wait=True,
  628. ignore_stderr=True)
  629. self.assertNotEqual(retcode, 0, "QubesIncoming exists although file "
  630. "copy was denied")
  631. @unittest.skip("Xen gntalloc driver crashes when page is mapped in the "
  632. "same domain")
  633. def test_120_qrexec_filecopy_self(self):
  634. self.testvm1.start()
  635. self.qrexec_policy('qubes.Filecopy', self.testvm1.name,
  636. self.testvm1.name)
  637. p = self.testvm1.run("qvm-copy-to-vm %s /etc/passwd" %
  638. self.testvm1.name, passio_popen=True,
  639. passio_stderr=True)
  640. p.wait()
  641. self.assertEqual(p.returncode, 0, "qvm-copy-to-vm failed: %s" %
  642. p.stderr.read())
  643. retcode = self.testvm1.run(
  644. "diff /etc/passwd /home/user/QubesIncoming/{}/passwd".format(
  645. self.testvm1.name),
  646. wait=True)
  647. self.assertEqual(retcode, 0, "file differs")
  648. @unittest.skipUnless(spawn.find_executable('xdotool'),
  649. "xdotool not installed")
  650. def test_130_qrexec_filemove_disk_full(self):
  651. self.testvm1.start()
  652. self.testvm2.start()
  653. self.qrexec_policy('qubes.Filecopy', self.testvm1.name,
  654. self.testvm2.name)
  655. # Prepare test file
  656. prepare_cmd = ("yes teststring | dd of=testfile bs=1M "
  657. "count=50 iflag=fullblock")
  658. retcode = self.testvm1.run(prepare_cmd, wait=True)
  659. if retcode != 0:
  660. raise RuntimeError("Failed '{}' in {}".format(prepare_cmd,
  661. self.testvm1.name))
  662. # Prepare target directory with limited size
  663. prepare_cmd = (
  664. "mkdir -p /home/user/QubesIncoming && "
  665. "chown user /home/user/QubesIncoming && "
  666. "mount -t tmpfs none /home/user/QubesIncoming -o size=48M"
  667. )
  668. retcode = self.testvm2.run(prepare_cmd, user="root", wait=True)
  669. if retcode != 0:
  670. raise RuntimeError("Failed '{}' in {}".format(prepare_cmd,
  671. self.testvm2.name))
  672. p = self.testvm1.run("qvm-move-to-vm %s testfile" %
  673. self.testvm2.name, passio_popen=True,
  674. passio_stderr=True)
  675. # Close GUI error message
  676. self.enter_keys_in_window('Error', ['Return'])
  677. p.wait()
  678. self.assertNotEqual(p.returncode, 0, "qvm-move-to-vm should fail")
  679. retcode = self.testvm1.run("test -f testfile", wait=True)
  680. self.assertEqual(retcode, 0, "testfile should not be deleted in "
  681. "source VM")
  682. def test_200_timezone(self):
  683. """Test whether timezone setting is properly propagated to the VM"""
  684. if "whonix" in self.template:
  685. self.skipTest("Timezone propagation disabled on Whonix templates")
  686. self.testvm1.start()
  687. (vm_tz, _) = self.testvm1.run("date +%Z",
  688. passio_popen=True).communicate()
  689. (dom0_tz, _) = subprocess.Popen(["date", "+%Z"],
  690. stdout=subprocess.PIPE).communicate()
  691. self.assertEqual(vm_tz.strip(), dom0_tz.strip())
  692. # Check if reverting back to UTC works
  693. (vm_tz, _) = self.testvm1.run("TZ=UTC date +%Z",
  694. passio_popen=True).communicate()
  695. self.assertEqual(vm_tz.strip(), "UTC")
  696. def test_210_time_sync(self):
  697. """Test time synchronization mechanism"""
  698. if self.template.startswith('whonix-'):
  699. self.skipTest('qvm-sync-clock disabled for Whonix VMs')
  700. self.testvm1.start()
  701. self.testvm2.start()
  702. (start_time, _) = subprocess.Popen(["date", "-u", "+%s"],
  703. stdout=subprocess.PIPE).communicate()
  704. try:
  705. self.app.clockvm = self.testvm1
  706. self.app.save()
  707. # break vm and dom0 time, to check if qvm-sync-clock would fix it
  708. subprocess.check_call(["sudo", "date", "-s",
  709. "2001-01-01T12:34:56"],
  710. stdout=open(os.devnull, 'w'))
  711. retcode = self.testvm1.run("date -s 2001-01-01T12:34:56",
  712. user="root", wait=True)
  713. self.assertEquals(retcode, 0, "Failed to break the VM(1) time")
  714. retcode = self.testvm2.run("date -s 2001-01-01T12:34:56",
  715. user="root", wait=True)
  716. self.assertEquals(retcode, 0, "Failed to break the VM(2) time")
  717. retcode = subprocess.call(["qvm-sync-clock"])
  718. self.assertEquals(retcode, 0,
  719. "qvm-sync-clock failed with code {}".
  720. format(retcode))
  721. # qvm-sync-clock is asynchronous - it spawns qubes.SetDateTime
  722. # service, send it timestamp value and exists without waiting for
  723. # actual time set
  724. time.sleep(1)
  725. (vm_time, _) = self.testvm1.run("date -u +%s",
  726. passio_popen=True).communicate()
  727. self.assertAlmostEquals(int(vm_time), int(start_time), delta=30)
  728. (vm_time, _) = self.testvm2.run("date -u +%s",
  729. passio_popen=True).communicate()
  730. self.assertAlmostEquals(int(vm_time), int(start_time), delta=30)
  731. (dom0_time, _) = subprocess.Popen(["date", "-u", "+%s"],
  732. stdout=subprocess.PIPE
  733. ).communicate()
  734. self.assertAlmostEquals(int(dom0_time), int(start_time), delta=30)
  735. except:
  736. # reset time to some approximation of the real time
  737. subprocess.Popen(["sudo", "date", "-u", "-s", "@" + start_time])
  738. raise
  739. def test_250_resize_private_img(self):
  740. """
  741. Test private.img resize, both offline and online
  742. :return:
  743. """
  744. # First offline test
  745. self.testvm1.storage.resize('private', 4*1024**3)
  746. self.testvm1.start()
  747. df_cmd = '( df --output=size /rw || df /rw | awk \'{print $2}\' )|' \
  748. 'tail -n 1'
  749. p = self.testvm1.run(df_cmd,
  750. passio_popen=True)
  751. # new_size in 1k-blocks
  752. (new_size, _) = p.communicate()
  753. # some safety margin for FS metadata
  754. self.assertGreater(int(new_size.strip()), 3.8*1024**2)
  755. # Then online test
  756. self.testvm1.storage.resize('private', 6*1024**3)
  757. p = self.testvm1.run(df_cmd,
  758. passio_popen=True)
  759. # new_size in 1k-blocks
  760. (new_size, _) = p.communicate()
  761. # some safety margin for FS metadata
  762. self.assertGreater(int(new_size.strip()), 5.8*1024**2)
  763. @unittest.skipUnless(spawn.find_executable('xdotool'),
  764. "xdotool not installed")
  765. def test_300_bug_1028_gui_memory_pinning(self):
  766. """
  767. If VM window composition buffers are relocated in memory, GUI will
  768. still use old pointers and will display old pages
  769. :return:
  770. """
  771. self.testvm1.memory = 800
  772. self.testvm1.maxmem = 800
  773. # exclude from memory balancing
  774. self.testvm1.features['services/meminfo-writer'] = False
  775. self.testvm1.start()
  776. # and allow large map count
  777. self.testvm1.run("echo 256000 > /proc/sys/vm/max_map_count",
  778. user="root", wait=True)
  779. allocator_c = (
  780. "#include <sys/mman.h>\n"
  781. "#include <stdlib.h>\n"
  782. "#include <stdio.h>\n"
  783. "\n"
  784. "int main(int argc, char **argv) {\n"
  785. " int total_pages;\n"
  786. " char *addr, *iter;\n"
  787. "\n"
  788. " total_pages = atoi(argv[1]);\n"
  789. " addr = mmap(NULL, total_pages * 0x1000, PROT_READ | "
  790. "PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_POPULATE, -1, 0);\n"
  791. " if (addr == MAP_FAILED) {\n"
  792. " perror(\"mmap\");\n"
  793. " exit(1);\n"
  794. " }\n"
  795. " printf(\"Stage1\\n\");\n"
  796. " fflush(stdout);\n"
  797. " getchar();\n"
  798. " for (iter = addr; iter < addr + total_pages*0x1000; iter += "
  799. "0x2000) {\n"
  800. " if (mlock(iter, 0x1000) == -1) {\n"
  801. " perror(\"mlock\");\n"
  802. " fprintf(stderr, \"%d of %d\\n\", (iter-addr)/0x1000, "
  803. "total_pages);\n"
  804. " exit(1);\n"
  805. " }\n"
  806. " }\n"
  807. " printf(\"Stage2\\n\");\n"
  808. " fflush(stdout);\n"
  809. " for (iter = addr+0x1000; iter < addr + total_pages*0x1000; "
  810. "iter += 0x2000) {\n"
  811. " if (munmap(iter, 0x1000) == -1) {\n"
  812. " perror(\"munmap\");\n"
  813. " exit(1);\n"
  814. " }\n"
  815. " }\n"
  816. " printf(\"Stage3\\n\");\n"
  817. " fflush(stdout);\n"
  818. " fclose(stdout);\n"
  819. " getchar();\n"
  820. "\n"
  821. " return 0;\n"
  822. "}\n")
  823. p = self.testvm1.run("cat > allocator.c", passio_popen=True)
  824. p.communicate(allocator_c)
  825. p = self.testvm1.run("gcc allocator.c -o allocator",
  826. passio_popen=True, passio_stderr=True)
  827. (stdout, stderr) = p.communicate()
  828. if p.returncode != 0:
  829. self.skipTest("allocator compile failed: {}".format(stderr))
  830. # drop caches to have even more memory pressure
  831. self.testvm1.run("echo 3 > /proc/sys/vm/drop_caches",
  832. user="root", wait=True)
  833. # now fragment all free memory
  834. p = self.testvm1.run("grep ^MemFree: /proc/meminfo|awk '{print $2}'",
  835. passio_popen=True)
  836. memory_pages = int(p.communicate()[0].strip())
  837. memory_pages /= 4 # 4k pages
  838. alloc1 = self.testvm1.run(
  839. "ulimit -l unlimited; exec /home/user/allocator {}".format(
  840. memory_pages),
  841. user="root", passio_popen=True, passio_stderr=True)
  842. # wait for memory being allocated; can't use just .read(), because EOF
  843. # passing is unreliable while the process is still running
  844. alloc1.stdin.write("\n")
  845. alloc1.stdin.flush()
  846. alloc_out = alloc1.stdout.read(len("Stage1\nStage2\nStage3\n"))
  847. if "Stage3" not in alloc_out:
  848. # read stderr only in case of failed assert, but still have nice
  849. # failure message (don't use self.fail() directly)
  850. self.assertIn("Stage3", alloc_out, alloc1.stderr.read())
  851. # now, launch some window - it should get fragmented composition buffer
  852. # it is important to have some changing content there, to generate
  853. # content update events (aka damage notify)
  854. proc = self.testvm1.run("gnome-terminal --full-screen -e top",
  855. passio_popen=True)
  856. # help xdotool a little...
  857. time.sleep(2)
  858. # get window ID
  859. search = subprocess.Popen(['xdotool', 'search', '--sync',
  860. '--onlyvisible', '--class', self.testvm1.name + ':.*erminal'],
  861. stdout=subprocess.PIPE)
  862. winid = search.communicate()[0].strip()
  863. xprop = subprocess.Popen(['xprop', '-notype', '-id', winid,
  864. '_QUBES_VMWINDOWID'], stdout=subprocess.PIPE)
  865. vm_winid = xprop.stdout.read().strip().split(' ')[4]
  866. # now free the fragmented memory and trigger compaction
  867. alloc1.stdin.write("\n")
  868. alloc1.wait()
  869. self.testvm1.run("echo 1 > /proc/sys/vm/compact_memory", user="root")
  870. # now window may be already "broken"; to be sure, allocate (=zero)
  871. # some memory
  872. alloc2 = self.testvm1.run(
  873. "ulimit -l unlimited; /home/user/allocator {}".format(memory_pages),
  874. user="root", passio_popen=True, passio_stderr=True)
  875. alloc2.stdout.read(len("Stage1\n"))
  876. # wait for damage notify - top updates every 3 sec by default
  877. time.sleep(6)
  878. # now take screenshot of the window, from dom0 and VM
  879. # choose pnm format, as it doesn't have any useless metadata - easy
  880. # to compare
  881. p = self.testvm1.run("import -window {} pnm:-".format(vm_winid),
  882. passio_popen=True, passio_stderr=True)
  883. (vm_image, stderr) = p.communicate()
  884. if p.returncode != 0:
  885. raise Exception("Failed to get VM window image: {}".format(
  886. stderr))
  887. p = subprocess.Popen(["import", "-window", winid, "pnm:-"],
  888. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  889. (dom0_image, stderr) = p.communicate()
  890. if p.returncode != 0:
  891. raise Exception("Failed to get dom0 window image: {}".format(
  892. stderr))
  893. if vm_image != dom0_image:
  894. self.fail("Dom0 window doesn't match VM window content")
  895. def load_tests(loader, tests, pattern):
  896. try:
  897. app = qubes.Qubes()
  898. templates = [vm.name for vm in app.domains if
  899. isinstance(vm, qubes.vm.templatevm.TemplateVM)]
  900. except OSError:
  901. templates = []
  902. for template in templates:
  903. tests.addTests(loader.loadTestsFromTestCase(
  904. type(
  905. 'TC_00_AppVM_' + template,
  906. (TC_00_AppVMMixin, qubes.tests.QubesTestCase),
  907. {'template': template})))
  908. return tests