vm_qrexec_gui.py 48 KB

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