vm_qrexec_gui.py 42 KB

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