vm_qrexec_gui.py 42 KB

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