vm_qrexec_gui.py 48 KB

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