vm_qrexec_gui.py 48 KB

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