vm_qrexec_gui.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  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. # two possible exit codes, depending on when exactly dom0
  249. # service terminates:
  250. # exit code 141: EPIPE (no buffered data)
  251. # exit code 1: ECONNRESET (some buffered data remains)
  252. stdout, _ = self.loop.run_until_complete(asyncio.wait_for(
  253. self.testvm1.run_for_stdio('''\
  254. /usr/lib/qubes/qrexec-client-vm dom0 test.Abort \
  255. /bin/cat /dev/zero; test $? -eq 141 -o $? -eq 1'''),
  256. timeout=10))
  257. except asyncio.TimeoutError:
  258. self.fail("Timeout, probably stdout wasn't closed")
  259. def test_060_qrexec_exit_code_dom0(self):
  260. self.loop.run_until_complete(self.testvm1.start())
  261. self.loop.run_until_complete(self.testvm1.run_for_stdio('exit 0'))
  262. with self.assertRaises(subprocess.CalledProcessError) as e:
  263. self.loop.run_until_complete(self.testvm1.run_for_stdio('exit 3'))
  264. self.assertEqual(e.exception.returncode, 3)
  265. def test_065_qrexec_exit_code_vm(self):
  266. self.loop.run_until_complete(asyncio.wait([
  267. self.testvm1.start(),
  268. self.testvm2.start()]))
  269. with self.qrexec_policy('test.Retcode', self.testvm1, self.testvm2):
  270. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.Retcode',
  271. 'exit 0')
  272. (stdout, stderr) = self.loop.run_until_complete(
  273. self.testvm1.run_for_stdio('''\
  274. /usr/lib/qubes/qrexec-client-vm {} test.Retcode;
  275. echo $?'''.format(self.testvm2.name)))
  276. self.assertEqual(stdout, b'0\n')
  277. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.Retcode',
  278. 'exit 3')
  279. (stdout, stderr) = self.loop.run_until_complete(
  280. self.testvm1.run_for_stdio('''\
  281. /usr/lib/qubes/qrexec-client-vm {} test.Retcode;
  282. echo $?'''.format(self.testvm2.name)))
  283. self.assertEqual(stdout, b'3\n')
  284. def test_070_qrexec_vm_simultaneous_write(self):
  285. """Test for simultaneous write in VM(src)->VM(dst) connection
  286. This is regression test for #1347
  287. Check for deadlock when initially both sides writes a lot of data
  288. (and not read anything). When one side starts reading, it should
  289. get the data and the remote side should be possible to write then more.
  290. There was a bug where remote side was waiting on write(2) and not
  291. handling anything else.
  292. """
  293. self.loop.run_until_complete(asyncio.wait([
  294. self.testvm1.start(),
  295. self.testvm2.start()]))
  296. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.write', '''\
  297. # first write a lot of data
  298. dd if=/dev/zero bs=993 count=10000 iflag=fullblock
  299. # and only then read something
  300. dd of=/dev/null bs=993 count=10000 iflag=fullblock
  301. ''')
  302. with self.qrexec_policy('test.write', self.testvm1, self.testvm2):
  303. try:
  304. self.loop.run_until_complete(asyncio.wait_for(
  305. # first write a lot of data to fill all the buffers
  306. # then after some time start reading
  307. self.testvm1.run_for_stdio('''\
  308. /usr/lib/qubes/qrexec-client-vm {} test.write \
  309. /bin/sh -c '
  310. dd if=/dev/zero bs=993 count=10000 iflag=fullblock &
  311. sleep 1;
  312. dd of=/dev/null bs=993 count=10000 iflag=fullblock;
  313. wait'
  314. '''.format(self.testvm2.name)), timeout=10))
  315. except subprocess.CalledProcessError:
  316. self.fail('Service call failed')
  317. except asyncio.TimeoutError:
  318. self.fail('Timeout, probably deadlock')
  319. def test_071_qrexec_dom0_simultaneous_write(self):
  320. """Test for simultaneous write in dom0(src)->VM(dst) connection
  321. Similar to test_070_qrexec_vm_simultaneous_write, but with dom0
  322. as a source.
  323. """
  324. self.loop.run_until_complete(self.testvm2.start())
  325. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.write', '''\
  326. # first write a lot of data
  327. dd if=/dev/zero bs=993 count=10000 iflag=fullblock
  328. # and only then read something
  329. dd of=/dev/null bs=993 count=10000 iflag=fullblock
  330. ''')
  331. # can't use subprocess.PIPE, because asyncio will claim those FDs
  332. pipe1_r, pipe1_w = os.pipe()
  333. pipe2_r, pipe2_w = os.pipe()
  334. try:
  335. local_proc = self.loop.run_until_complete(
  336. asyncio.create_subprocess_shell(
  337. # first write a lot of data to fill all the buffers
  338. "dd if=/dev/zero bs=993 count=10000 iflag=fullblock & "
  339. # then after some time start reading
  340. "sleep 1; "
  341. "dd of=/dev/null bs=993 count=10000 iflag=fullblock; "
  342. "wait", stdin=pipe1_r, stdout=pipe2_w))
  343. service_proc = self.loop.run_until_complete(self.testvm2.run_service(
  344. "test.write", stdin=pipe2_r, stdout=pipe1_w))
  345. finally:
  346. os.close(pipe1_r)
  347. os.close(pipe1_w)
  348. os.close(pipe2_r)
  349. os.close(pipe2_w)
  350. try:
  351. self.loop.run_until_complete(
  352. asyncio.wait_for(service_proc.wait(), timeout=10))
  353. except asyncio.TimeoutError:
  354. self.fail("Timeout, probably deadlock")
  355. else:
  356. self.assertEqual(service_proc.returncode, 0,
  357. "Service call failed")
  358. finally:
  359. try:
  360. service_proc.terminate()
  361. except ProcessLookupError:
  362. pass
  363. def test_072_qrexec_to_dom0_simultaneous_write(self):
  364. """Test for simultaneous write in dom0(src)<-VM(dst) connection
  365. Similar to test_071_qrexec_dom0_simultaneous_write, but with dom0
  366. as a "hanging" side.
  367. """
  368. self.loop.run_until_complete(self.testvm2.start())
  369. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.write', '''\
  370. # first write a lot of data
  371. dd if=/dev/zero bs=993 count=10000 iflag=fullblock &
  372. # and only then read something
  373. dd of=/dev/null bs=993 count=10000 iflag=fullblock
  374. sleep 1;
  375. wait
  376. ''')
  377. # can't use subprocess.PIPE, because asyncio will claim those FDs
  378. pipe1_r, pipe1_w = os.pipe()
  379. pipe2_r, pipe2_w = os.pipe()
  380. try:
  381. local_proc = self.loop.run_until_complete(
  382. asyncio.create_subprocess_shell(
  383. # first write a lot of data to fill all the buffers
  384. "dd if=/dev/zero bs=993 count=10000 iflag=fullblock & "
  385. # then, only when all written, read something
  386. "dd of=/dev/null bs=993 count=10000 iflag=fullblock; ",
  387. stdin=pipe1_r, stdout=pipe2_w))
  388. service_proc = self.loop.run_until_complete(self.testvm2.run_service(
  389. "test.write", stdin=pipe2_r, stdout=pipe1_w))
  390. finally:
  391. os.close(pipe1_r)
  392. os.close(pipe1_w)
  393. os.close(pipe2_r)
  394. os.close(pipe2_w)
  395. try:
  396. self.loop.run_until_complete(
  397. asyncio.wait_for(service_proc.wait(), timeout=10))
  398. except asyncio.TimeoutError:
  399. self.fail("Timeout, probably deadlock")
  400. else:
  401. self.assertEqual(service_proc.returncode, 0,
  402. "Service call failed")
  403. finally:
  404. try:
  405. service_proc.terminate()
  406. except ProcessLookupError:
  407. pass
  408. def test_080_qrexec_service_argument_allow_default(self):
  409. """Qrexec service call with argument"""
  410. self.loop.run_until_complete(asyncio.wait([
  411. self.testvm1.start(),
  412. self.testvm2.start()]))
  413. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.Argument',
  414. '/usr/bin/printf %s "$1"')
  415. with self.qrexec_policy('test.Argument', self.testvm1, self.testvm2):
  416. stdout, stderr = self.loop.run_until_complete(
  417. self.testvm1.run_for_stdio('/usr/lib/qubes/qrexec-client-vm '
  418. '{} test.Argument+argument'.format(self.testvm2.name)))
  419. self.assertEqual(stdout, b'argument')
  420. def test_081_qrexec_service_argument_allow_specific(self):
  421. """Qrexec service call with argument - allow only specific value"""
  422. self.loop.run_until_complete(asyncio.wait([
  423. self.testvm1.start(),
  424. self.testvm2.start()]))
  425. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.Argument',
  426. '/usr/bin/printf %s "$1"')
  427. with self.qrexec_policy('test.Argument', '$anyvm', '$anyvm', False):
  428. with self.qrexec_policy('test.Argument+argument',
  429. self.testvm1.name, self.testvm2.name):
  430. stdout, stderr = self.loop.run_until_complete(
  431. self.testvm1.run_for_stdio(
  432. '/usr/lib/qubes/qrexec-client-vm '
  433. '{} test.Argument+argument'.format(self.testvm2.name)))
  434. self.assertEqual(stdout, b'argument')
  435. def test_082_qrexec_service_argument_deny_specific(self):
  436. """Qrexec service call with argument - deny specific value"""
  437. self.loop.run_until_complete(asyncio.wait([
  438. self.testvm1.start(),
  439. self.testvm2.start()]))
  440. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.Argument',
  441. '/usr/bin/printf %s "$1"')
  442. with self.qrexec_policy('test.Argument', '$anyvm', '$anyvm'):
  443. with self.qrexec_policy('test.Argument+argument',
  444. self.testvm1, self.testvm2, allow=False):
  445. with self.assertRaises(subprocess.CalledProcessError,
  446. msg='Service request should be denied'):
  447. self.loop.run_until_complete(
  448. self.testvm1.run_for_stdio(
  449. '/usr/lib/qubes/qrexec-client-vm {} '
  450. 'test.Argument+argument'.format(self.testvm2.name)))
  451. def test_083_qrexec_service_argument_specific_implementation(self):
  452. """Qrexec service call with argument - argument specific
  453. implementatation"""
  454. self.loop.run_until_complete(asyncio.wait([
  455. self.testvm1.start(),
  456. self.testvm2.start()]))
  457. self.create_remote_file(self.testvm2,
  458. '/etc/qubes-rpc/test.Argument',
  459. '/usr/bin/printf %s "$1"')
  460. self.create_remote_file(self.testvm2,
  461. '/etc/qubes-rpc/test.Argument+argument',
  462. '/usr/bin/printf "specific: %s" "$1"')
  463. with self.qrexec_policy('test.Argument', self.testvm1, self.testvm2):
  464. stdout, stderr = self.loop.run_until_complete(
  465. self.testvm1.run_for_stdio('/usr/lib/qubes/qrexec-client-vm '
  466. '{} test.Argument+argument'.format(self.testvm2.name)))
  467. self.assertEqual(stdout, b'specific: argument')
  468. def test_084_qrexec_service_argument_extra_env(self):
  469. """Qrexec service call with argument - extra env variables"""
  470. self.loop.run_until_complete(asyncio.wait([
  471. self.testvm1.start(),
  472. self.testvm2.start()]))
  473. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.Argument',
  474. '/usr/bin/printf "%s %s" '
  475. '"$QREXEC_SERVICE_FULL_NAME" "$QREXEC_SERVICE_ARGUMENT"')
  476. with self.qrexec_policy('test.Argument', self.testvm1, self.testvm2):
  477. stdout, stderr = self.loop.run_until_complete(
  478. self.testvm1.run_for_stdio('/usr/lib/qubes/qrexec-client-vm '
  479. '{} test.Argument+argument'.format(self.testvm2.name)))
  480. self.assertEqual(stdout, b'test.Argument+argument argument')
  481. def test_100_qrexec_filecopy(self):
  482. self.loop.run_until_complete(asyncio.wait([
  483. self.testvm1.start(),
  484. self.testvm2.start()]))
  485. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  486. try:
  487. self.loop.run_until_complete(
  488. self.testvm1.run_for_stdio(
  489. 'qvm-copy-to-vm {} /etc/passwd'.format(
  490. self.testvm2.name)))
  491. except subprocess.CalledProcessError as e:
  492. self.fail('qvm-copy-to-vm failed: {}'.format(e.stderr))
  493. try:
  494. self.loop.run_until_complete(self.testvm2.run_for_stdio(
  495. 'diff /etc/passwd /home/user/QubesIncoming/{}/passwd'.format(
  496. self.testvm1.name)))
  497. except subprocess.CalledProcessError:
  498. self.fail('file differs')
  499. try:
  500. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  501. 'test -f /etc/passwd'))
  502. except subprocess.CalledProcessError:
  503. self.fail('source file got removed')
  504. def test_105_qrexec_filemove(self):
  505. self.loop.run_until_complete(asyncio.wait([
  506. self.testvm1.start(),
  507. self.testvm2.start()]))
  508. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  509. 'cp /etc/passwd /tmp/passwd'))
  510. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  511. try:
  512. self.loop.run_until_complete(
  513. self.testvm1.run_for_stdio(
  514. 'qvm-move-to-vm {} /tmp/passwd'.format(
  515. self.testvm2.name)))
  516. except subprocess.CalledProcessError as e:
  517. self.fail('qvm-move-to-vm failed: {}'.format(e.stderr))
  518. try:
  519. self.loop.run_until_complete(self.testvm2.run_for_stdio(
  520. 'diff /etc/passwd /home/user/QubesIncoming/{}/passwd'.format(
  521. self.testvm1.name)))
  522. except subprocess.CalledProcessError:
  523. self.fail('file differs')
  524. with self.assertRaises(subprocess.CalledProcessError):
  525. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  526. 'test -f /tmp/passwd'))
  527. def test_101_qrexec_filecopy_with_autostart(self):
  528. self.loop.run_until_complete(self.testvm1.start())
  529. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  530. try:
  531. self.loop.run_until_complete(
  532. self.testvm1.run_for_stdio(
  533. 'qvm-copy-to-vm {} /etc/passwd'.format(
  534. self.testvm2.name)))
  535. except subprocess.CalledProcessError as e:
  536. self.fail('qvm-copy-to-vm failed: {}'.format(e.stderr))
  537. # workaround for libvirt bug (domain ID isn't updated when is started
  538. # from other application) - details in
  539. # QubesOS/qubes-core-libvirt@63ede4dfb4485c4161dd6a2cc809e8fb45ca664f
  540. # XXX is it still true with qubesd? --woju 20170523
  541. self.testvm2._libvirt_domain = None
  542. self.assertTrue(self.testvm2.is_running())
  543. try:
  544. self.loop.run_until_complete(self.testvm2.run_for_stdio(
  545. 'diff /etc/passwd /home/user/QubesIncoming/{}/passwd'.format(
  546. self.testvm1.name)))
  547. except subprocess.CalledProcessError:
  548. self.fail('file differs')
  549. try:
  550. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  551. 'test -f /etc/passwd'))
  552. except subprocess.CalledProcessError:
  553. self.fail('source file got removed')
  554. def test_110_qrexec_filecopy_deny(self):
  555. self.loop.run_until_complete(asyncio.wait([
  556. self.testvm1.start(),
  557. self.testvm2.start()]))
  558. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2,
  559. allow=False):
  560. with self.assertRaises(subprocess.CalledProcessError):
  561. self.loop.run_until_complete(
  562. self.testvm1.run_for_stdio(
  563. 'qvm-copy-to-vm {} /etc/passwd'.format(
  564. self.testvm2.name)))
  565. with self.assertRaises(subprocess.CalledProcessError):
  566. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  567. 'test -d /home/user/QubesIncoming/{}'.format(
  568. self.testvm1.name)))
  569. def test_115_qrexec_filecopy_no_agent(self):
  570. # The operation should not hang when qrexec-agent is down on target
  571. # machine, see QubesOS/qubes-issues#5347.
  572. self.loop.run_until_complete(asyncio.wait([
  573. self.testvm1.start(),
  574. self.testvm2.start()]))
  575. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  576. try:
  577. self.loop.run_until_complete(
  578. self.testvm2.run_for_stdio(
  579. 'systemctl stop qubes-qrexec-agent.service', user='root'))
  580. except subprocess.CalledProcessError:
  581. # A failure is normal here, because we're killing the qrexec
  582. # process that is handling the command.
  583. pass
  584. with self.assertRaises(subprocess.CalledProcessError):
  585. self.loop.run_until_complete(
  586. asyncio.wait_for(
  587. self.testvm1.run_for_stdio(
  588. 'qvm-copy-to-vm {} /etc/passwd'.format(
  589. self.testvm2.name)),
  590. timeout=30))
  591. @unittest.skip("Xen gntalloc driver crashes when page is mapped in the "
  592. "same domain")
  593. def test_120_qrexec_filecopy_self(self):
  594. self.testvm1.start()
  595. self.qrexec_policy('qubes.Filecopy', self.testvm1.name,
  596. self.testvm1.name)
  597. p = self.testvm1.run("qvm-copy-to-vm %s /etc/passwd" %
  598. self.testvm1.name, passio_popen=True,
  599. passio_stderr=True)
  600. p.wait()
  601. self.assertEqual(p.returncode, 0, "qvm-copy-to-vm failed: %s" %
  602. p.stderr.read())
  603. retcode = self.testvm1.run(
  604. "diff /etc/passwd /home/user/QubesIncoming/{}/passwd".format(
  605. self.testvm1.name),
  606. wait=True)
  607. self.assertEqual(retcode, 0, "file differs")
  608. @unittest.skipUnless(spawn.find_executable('xdotool'),
  609. "xdotool not installed")
  610. def test_130_qrexec_filemove_disk_full(self):
  611. self.loop.run_until_complete(asyncio.wait([
  612. self.testvm1.start(),
  613. self.testvm2.start()]))
  614. self.loop.run_until_complete(self.wait_for_session(self.testvm1))
  615. # Prepare test file
  616. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  617. 'yes teststring | dd of=/tmp/testfile bs=1M count=50 '
  618. 'iflag=fullblock'))
  619. # Prepare target directory with limited size
  620. self.loop.run_until_complete(self.testvm2.run_for_stdio(
  621. 'mkdir -p /home/user/QubesIncoming && '
  622. 'chown user /home/user/QubesIncoming && '
  623. 'mount -t tmpfs none /home/user/QubesIncoming -o size=48M',
  624. user='root'))
  625. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  626. p = self.loop.run_until_complete(self.testvm1.run(
  627. 'qvm-move-to-vm {} /tmp/testfile'.format(
  628. self.testvm2.name)))
  629. # Close GUI error message
  630. try:
  631. self.enter_keys_in_window('Error', ['Return'])
  632. except subprocess.CalledProcessError:
  633. pass
  634. self.loop.run_until_complete(p.wait())
  635. self.assertNotEqual(p.returncode, 0)
  636. # the file shouldn't be removed in source vm
  637. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  638. 'test -f /tmp/testfile'))
  639. def test_200_timezone(self):
  640. """Test whether timezone setting is properly propagated to the VM"""
  641. if "whonix" in self.template:
  642. self.skipTest("Timezone propagation disabled on Whonix templates")
  643. self.loop.run_until_complete(self.testvm1.start())
  644. vm_tz, _ = self.loop.run_until_complete(self.testvm1.run_for_stdio(
  645. 'date +%Z'))
  646. dom0_tz = subprocess.check_output(['date', '+%Z'])
  647. self.assertEqual(vm_tz.strip(), dom0_tz.strip())
  648. # Check if reverting back to UTC works
  649. vm_tz, _ = self.loop.run_until_complete(self.testvm1.run_for_stdio(
  650. 'TZ=UTC date +%Z'))
  651. self.assertEqual(vm_tz.strip(), b'UTC')
  652. def test_210_time_sync(self):
  653. """Test time synchronization mechanism"""
  654. if self.template.startswith('whonix-'):
  655. self.skipTest('qvm-sync-clock disabled for Whonix VMs')
  656. self.loop.run_until_complete(asyncio.wait([
  657. self.testvm1.start(),
  658. self.testvm2.start(),]))
  659. start_time = subprocess.check_output(['date', '-u', '+%s'])
  660. try:
  661. self.app.clockvm = self.testvm1
  662. self.app.save()
  663. # break vm and dom0 time, to check if qvm-sync-clock would fix it
  664. subprocess.check_call(['sudo', 'date', '-s', '2001-01-01T12:34:56'],
  665. stdout=subprocess.DEVNULL)
  666. self.loop.run_until_complete(
  667. self.testvm2.run_for_stdio('date -s 2001-01-01T12:34:56',
  668. user='root'))
  669. self.loop.run_until_complete(
  670. self.testvm2.run_for_stdio('qvm-sync-clock',
  671. user='root'))
  672. p = self.loop.run_until_complete(
  673. asyncio.create_subprocess_exec('sudo', 'qvm-sync-clock',
  674. stdout=asyncio.subprocess.DEVNULL))
  675. self.loop.run_until_complete(p.wait())
  676. self.assertEqual(p.returncode, 0)
  677. vm_time, _ = self.loop.run_until_complete(
  678. self.testvm2.run_for_stdio('date -u +%s'))
  679. self.assertAlmostEquals(int(vm_time), int(start_time), delta=30)
  680. dom0_time = subprocess.check_output(['date', '-u', '+%s'])
  681. self.assertAlmostEquals(int(dom0_time), int(start_time), delta=30)
  682. except:
  683. # reset time to some approximation of the real time
  684. subprocess.Popen(
  685. ["sudo", "date", "-u", "-s", "@" + start_time.decode()])
  686. raise
  687. finally:
  688. self.app.clockvm = None
  689. def wait_for_pulseaudio_startup(self, vm):
  690. self.loop.run_until_complete(
  691. self.wait_for_session(self.testvm1))
  692. try:
  693. self.loop.run_until_complete(vm.run_for_stdio(
  694. "timeout 30s sh -c 'while ! pactl info; do sleep 1; done'"
  695. ))
  696. except subprocess.CalledProcessError as e:
  697. self.fail('Timeout waiting for pulseaudio start in {}: {}{}'.format(
  698. vm.name, e.stdout, e.stderr))
  699. # and some more...
  700. self.loop.run_until_complete(asyncio.sleep(1))
  701. @unittest.skipUnless(spawn.find_executable('parecord'),
  702. "pulseaudio-utils not installed in dom0")
  703. def test_220_audio_playback(self):
  704. if 'whonix-gw' in self.template:
  705. self.skipTest('whonix-gw have no audio')
  706. self.loop.run_until_complete(self.testvm1.start())
  707. try:
  708. self.loop.run_until_complete(
  709. self.testvm1.run_for_stdio('which parecord'))
  710. except subprocess.CalledProcessError:
  711. self.skipTest('pulseaudio-utils not installed in VM')
  712. self.wait_for_pulseaudio_startup(self.testvm1)
  713. # generate some "audio" data
  714. audio_in = b'\x20' * 44100
  715. self.loop.run_until_complete(
  716. self.testvm1.run_for_stdio('cat > audio_in.raw', input=audio_in))
  717. local_user = grp.getgrnam('qubes').gr_mem[0]
  718. with tempfile.NamedTemporaryFile() as recorded_audio:
  719. os.chmod(recorded_audio.name, 0o666)
  720. # FIXME: -d 0 assumes only one audio device
  721. p = subprocess.Popen(['sudo', '-E', '-u', local_user,
  722. 'parecord', '-d', '0', '--raw', recorded_audio.name],
  723. stdout=subprocess.PIPE)
  724. try:
  725. self.loop.run_until_complete(
  726. self.testvm1.run_for_stdio('paplay --raw audio_in.raw'))
  727. except subprocess.CalledProcessError as err:
  728. self.fail('{} stderr: {}'.format(str(err), err.stderr))
  729. # wait for possible parecord buffering
  730. self.loop.run_until_complete(asyncio.sleep(1))
  731. p.terminate()
  732. # for some reason sudo do not relay SIGTERM sent above
  733. subprocess.check_call(['pkill', 'parecord'])
  734. p.wait()
  735. # allow few bytes missing, don't use assertIn, to avoid printing
  736. # the whole data in error message
  737. recorded_audio = recorded_audio.file.read()
  738. if audio_in[:-8] not in recorded_audio:
  739. found_bytes = recorded_audio.count(audio_in[0])
  740. all_bytes = len(audio_in)
  741. self.fail('played sound not found in dom0, '
  742. 'missing {} bytes out of {}'.format(
  743. all_bytes-found_bytes, all_bytes))
  744. def _configure_audio_recording(self, vm):
  745. '''Connect VM's output-source to sink monitor instead of mic'''
  746. local_user = grp.getgrnam('qubes').gr_mem[0]
  747. sudo = ['sudo', '-E', '-u', local_user]
  748. source_outputs = subprocess.check_output(
  749. sudo + ['pacmd', 'list-source-outputs']).decode()
  750. last_index = None
  751. found = False
  752. for line in source_outputs.splitlines():
  753. if line.startswith(' index: '):
  754. last_index = line.split(':')[1].strip()
  755. elif line.startswith('\t\tapplication.name = '):
  756. app_name = line.split('=')[1].strip('" ')
  757. if vm.name == app_name:
  758. found = True
  759. break
  760. if not found:
  761. self.fail('source-output for VM {} not found'.format(vm.name))
  762. subprocess.check_call(sudo +
  763. ['pacmd', 'move-source-output', last_index, '0'])
  764. @unittest.skipUnless(spawn.find_executable('parecord'),
  765. "pulseaudio-utils not installed in dom0")
  766. def test_221_audio_record_muted(self):
  767. if 'whonix-gw' in self.template:
  768. self.skipTest('whonix-gw have no audio')
  769. self.loop.run_until_complete(self.testvm1.start())
  770. try:
  771. self.loop.run_until_complete(
  772. self.testvm1.run_for_stdio('which parecord'))
  773. except subprocess.CalledProcessError:
  774. self.skipTest('pulseaudio-utils not installed in VM')
  775. self.wait_for_pulseaudio_startup(self.testvm1)
  776. # connect VM's recording source output monitor (instead of mic)
  777. self._configure_audio_recording(self.testvm1)
  778. # generate some "audio" data
  779. audio_in = b'\x20' * 44100
  780. local_user = grp.getgrnam('qubes').gr_mem[0]
  781. record = self.loop.run_until_complete(
  782. self.testvm1.run('parecord --raw audio_rec.raw'))
  783. # give it time to start recording
  784. self.loop.run_until_complete(asyncio.sleep(0.5))
  785. p = subprocess.Popen(['sudo', '-E', '-u', local_user,
  786. 'paplay', '--raw'],
  787. stdin=subprocess.PIPE)
  788. p.communicate(audio_in)
  789. # wait for possible parecord buffering
  790. self.loop.run_until_complete(asyncio.sleep(1))
  791. self.loop.run_until_complete(
  792. self.testvm1.run_for_stdio('pkill parecord'))
  793. self.loop.run_until_complete(record.wait())
  794. recorded_audio, _ = self.loop.run_until_complete(
  795. self.testvm1.run_for_stdio('cat audio_rec.raw'))
  796. # should be empty or silence, so check just a little fragment
  797. if audio_in[:32] in recorded_audio:
  798. self.fail('VM recorded something, even though mic disabled')
  799. @unittest.skipUnless(spawn.find_executable('parecord'),
  800. "pulseaudio-utils not installed in dom0")
  801. def test_222_audio_record_unmuted(self):
  802. if 'whonix-gw' in self.template:
  803. self.skipTest('whonix-gw have no audio')
  804. self.loop.run_until_complete(self.testvm1.start())
  805. try:
  806. self.loop.run_until_complete(
  807. self.testvm1.run_for_stdio('which parecord'))
  808. except subprocess.CalledProcessError:
  809. self.skipTest('pulseaudio-utils not installed in VM')
  810. self.wait_for_pulseaudio_startup(self.testvm1)
  811. da = qubes.devices.DeviceAssignment(self.app.domains[0], 'mic')
  812. self.loop.run_until_complete(
  813. self.testvm1.devices['mic'].attach(da))
  814. # connect VM's recording source output monitor (instead of mic)
  815. self._configure_audio_recording(self.testvm1)
  816. # generate some "audio" data
  817. audio_in = b'\x20' * 44100
  818. local_user = grp.getgrnam('qubes').gr_mem[0]
  819. record = self.loop.run_until_complete(
  820. self.testvm1.run('parecord --raw audio_rec.raw'))
  821. # give it time to start recording
  822. self.loop.run_until_complete(asyncio.sleep(0.5))
  823. p = subprocess.Popen(['sudo', '-E', '-u', local_user,
  824. 'paplay', '--raw'],
  825. stdin=subprocess.PIPE)
  826. p.communicate(audio_in)
  827. # wait for possible parecord buffering
  828. self.loop.run_until_complete(asyncio.sleep(1))
  829. self.loop.run_until_complete(
  830. self.testvm1.run_for_stdio('pkill parecord'))
  831. self.loop.run_until_complete(record.wait())
  832. recorded_audio, _ = self.loop.run_until_complete(
  833. self.testvm1.run_for_stdio('cat audio_rec.raw'))
  834. # allow few bytes to be missing
  835. if audio_in[:-8] not in recorded_audio:
  836. found_bytes = recorded_audio.count(audio_in[0])
  837. all_bytes = len(audio_in)
  838. self.fail('VM not recorded expected data, '
  839. 'missing {} bytes out of {}'.format(
  840. all_bytes-found_bytes, all_bytes))
  841. def test_250_resize_private_img(self):
  842. """
  843. Test private.img resize, both offline and online
  844. :return:
  845. """
  846. # First offline test
  847. self.loop.run_until_complete(
  848. self.testvm1.storage.resize('private', 4*1024**3))
  849. self.loop.run_until_complete(self.testvm1.start())
  850. df_cmd = '( df --output=size /rw || df /rw | awk \'{print $2}\' )|' \
  851. 'tail -n 1'
  852. # new_size in 1k-blocks
  853. new_size, _ = self.loop.run_until_complete(
  854. self.testvm1.run_for_stdio(df_cmd))
  855. # some safety margin for FS metadata
  856. self.assertGreater(int(new_size.strip()), 3.8*1024**2)
  857. # Then online test
  858. self.loop.run_until_complete(
  859. self.testvm1.storage.resize('private', 6*1024**3))
  860. # new_size in 1k-blocks
  861. new_size, _ = self.loop.run_until_complete(
  862. self.testvm1.run_for_stdio(df_cmd))
  863. # some safety margin for FS metadata
  864. self.assertGreater(int(new_size.strip()), 5.7*1024**2)
  865. @unittest.skipUnless(spawn.find_executable('xdotool'),
  866. "xdotool not installed")
  867. def test_300_bug_1028_gui_memory_pinning(self):
  868. """
  869. If VM window composition buffers are relocated in memory, GUI will
  870. still use old pointers and will display old pages
  871. :return:
  872. """
  873. # this test does too much asynchronous operations,
  874. # so let's rewrite it as a coroutine and call it as such
  875. return self.loop.run_until_complete(
  876. self._test_300_bug_1028_gui_memory_pinning())
  877. @asyncio.coroutine
  878. def _test_300_bug_1028_gui_memory_pinning(self):
  879. self.testvm1.memory = 800
  880. self.testvm1.maxmem = 800
  881. # exclude from memory balancing
  882. self.testvm1.features['service.meminfo-writer'] = False
  883. yield from self.testvm1.start()
  884. yield from self.wait_for_session(self.testvm1)
  885. # and allow large map count
  886. yield from self.testvm1.run('echo 256000 > /proc/sys/vm/max_map_count',
  887. user="root")
  888. allocator_c = '''
  889. #include <sys/mman.h>
  890. #include <stdlib.h>
  891. #include <stdio.h>
  892. int main(int argc, char **argv) {
  893. int total_pages;
  894. char *addr, *iter;
  895. total_pages = atoi(argv[1]);
  896. addr = mmap(NULL, total_pages * 0x1000, PROT_READ | PROT_WRITE,
  897. MAP_ANONYMOUS | MAP_PRIVATE | MAP_POPULATE, -1, 0);
  898. if (addr == MAP_FAILED) {
  899. perror("mmap");
  900. exit(1);
  901. }
  902. printf("Stage1\\n");
  903. fflush(stdout);
  904. getchar();
  905. for (iter = addr; iter < addr + total_pages*0x1000; iter += 0x2000) {
  906. if (mlock(iter, 0x1000) == -1) {
  907. perror("mlock");
  908. fprintf(stderr, "%d of %d\\n", (iter-addr)/0x1000, total_pages);
  909. exit(1);
  910. }
  911. }
  912. printf("Stage2\\n");
  913. fflush(stdout);
  914. for (iter = addr+0x1000; iter < addr + total_pages*0x1000; iter += 0x2000) {
  915. if (munmap(iter, 0x1000) == -1) {
  916. perror(\"munmap\");
  917. exit(1);
  918. }
  919. }
  920. printf("Stage3\\n");
  921. fflush(stdout);
  922. fclose(stdout);
  923. getchar();
  924. return 0;
  925. }
  926. '''
  927. yield from self.testvm1.run_for_stdio('cat > allocator.c',
  928. input=allocator_c.encode())
  929. try:
  930. yield from self.testvm1.run_for_stdio(
  931. 'gcc allocator.c -o allocator')
  932. except subprocess.CalledProcessError as e:
  933. self.skipTest('allocator compile failed: {}'.format(e.stderr))
  934. # drop caches to have even more memory pressure
  935. yield from self.testvm1.run_for_stdio(
  936. 'echo 3 > /proc/sys/vm/drop_caches', user='root')
  937. # now fragment all free memory
  938. stdout, _ = yield from self.testvm1.run_for_stdio(
  939. "grep ^MemFree: /proc/meminfo|awk '{print $2}'")
  940. memory_pages = int(stdout) // 4 # 4k pages
  941. alloc1 = yield from self.testvm1.run(
  942. 'ulimit -l unlimited; exec /home/user/allocator {}'.format(
  943. memory_pages),
  944. user="root",
  945. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  946. stderr=subprocess.PIPE)
  947. # wait for memory being allocated; can't use just .read(), because EOF
  948. # passing is unreliable while the process is still running
  949. alloc1.stdin.write(b'\n')
  950. yield from alloc1.stdin.drain()
  951. try:
  952. alloc_out = yield from alloc1.stdout.readexactly(
  953. len('Stage1\nStage2\nStage3\n'))
  954. except asyncio.IncompleteReadError as e:
  955. alloc_out = e.partial
  956. if b'Stage3' not in alloc_out:
  957. # read stderr only in case of failed assert (), but still have nice
  958. # failure message (don't use self.fail() directly)
  959. #
  960. # stderr isn't always read, because on not-failed run, the process
  961. # is still running, so stderr.read() will wait (indefinitely).
  962. self.assertIn(b'Stage3', alloc_out,
  963. (yield from alloc1.stderr.read()))
  964. # now, launch some window - it should get fragmented composition buffer
  965. # it is important to have some changing content there, to generate
  966. # content update events (aka damage notify)
  967. proc = yield from self.testvm1.run(
  968. 'xterm -maximized -e top')
  969. if proc.returncode is not None:
  970. self.fail('xterm failed to start')
  971. # get window ID
  972. winid = yield from self.wait_for_window_coro(
  973. self.testvm1.name + ':xterm',
  974. search_class=True)
  975. xprop = yield from asyncio.get_event_loop().run_in_executor(None,
  976. subprocess.check_output,
  977. ['xprop', '-notype', '-id', winid, '_QUBES_VMWINDOWID'])
  978. vm_winid = xprop.decode().strip().split(' ')[4]
  979. # now free the fragmented memory and trigger compaction
  980. alloc1.stdin.write(b'\n')
  981. yield from alloc1.stdin.drain()
  982. yield from alloc1.wait()
  983. yield from self.testvm1.run_for_stdio(
  984. 'echo 1 > /proc/sys/vm/compact_memory', user='root')
  985. # now window may be already "broken"; to be sure, allocate (=zero)
  986. # some memory
  987. alloc2 = yield from self.testvm1.run(
  988. 'ulimit -l unlimited; /home/user/allocator {}'.format(memory_pages),
  989. user='root', stdout=subprocess.PIPE)
  990. yield from alloc2.stdout.read(len('Stage1\n'))
  991. # wait for damage notify - top updates every 3 sec by default
  992. yield from asyncio.sleep(6)
  993. # stop changing the window content
  994. subprocess.check_call(['xdotool', 'key', '--window', winid, 'd'])
  995. # now take screenshot of the window, from dom0 and VM
  996. # choose pnm format, as it doesn't have any useless metadata - easy
  997. # to compare
  998. vm_image, _ = yield from self.testvm1.run_for_stdio(
  999. 'import -window {} pnm:-'.format(vm_winid))
  1000. dom0_image = yield from asyncio.get_event_loop().run_in_executor(None,
  1001. subprocess.check_output, ['import', '-window', winid, 'pnm:-'])
  1002. if vm_image != dom0_image:
  1003. self.fail("Dom0 window doesn't match VM window content")
  1004. class TC_10_Generic(qubes.tests.SystemTestCase):
  1005. def setUp(self):
  1006. super(TC_10_Generic, self).setUp()
  1007. self.init_default_template()
  1008. self.vm = self.app.add_new_vm(
  1009. qubes.vm.appvm.AppVM,
  1010. name=self.make_vm_name('vm'),
  1011. label='red',
  1012. template=self.app.default_template)
  1013. self.loop.run_until_complete(self.vm.create_on_disk())
  1014. self.app.save()
  1015. self.vm = self.app.domains[self.vm.qid]
  1016. def test_000_anyvm_deny_dom0(self):
  1017. '''$anyvm in policy should not match dom0'''
  1018. policy = open("/etc/qubes-rpc/policy/test.AnyvmDeny", "w")
  1019. policy.write("%s $anyvm allow" % (self.vm.name,))
  1020. policy.close()
  1021. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.AnyvmDeny")
  1022. flagfile = '/tmp/test-anyvmdeny-flag'
  1023. if os.path.exists(flagfile):
  1024. os.remove(flagfile)
  1025. self.create_local_file('/etc/qubes-rpc/test.AnyvmDeny',
  1026. 'touch {}\necho service output\n'.format(flagfile))
  1027. self.loop.run_until_complete(self.vm.start())
  1028. with self.qrexec_policy('test.AnyvmDeny', self.vm, '$anyvm'):
  1029. with self.assertRaises(subprocess.CalledProcessError,
  1030. msg='$anyvm matched dom0') as e:
  1031. self.loop.run_until_complete(
  1032. self.vm.run_for_stdio(
  1033. '/usr/lib/qubes/qrexec-client-vm dom0 test.AnyvmDeny'))
  1034. stdout = e.exception.output
  1035. stderr = e.exception.stderr
  1036. self.assertFalse(os.path.exists(flagfile),
  1037. 'Flag file created (service was run) even though should be denied,'
  1038. ' qrexec-client-vm output: {} {}'.format(stdout, stderr))
  1039. def create_testcases_for_templates():
  1040. return qubes.tests.create_testcases_for_templates('TC_00_AppVM',
  1041. TC_00_AppVMMixin, qubes.tests.SystemTestCase,
  1042. module=sys.modules[__name__])
  1043. def load_tests(loader, tests, pattern):
  1044. tests.addTests(loader.loadTestsFromNames(
  1045. create_testcases_for_templates()))
  1046. return tests
  1047. qubes.tests.maybe_create_testcases_on_import(create_testcases_for_templates)