vm_qrexec_gui.py 42 KB

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