vm_qrexec_gui.py 42 KB

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