vm_qrexec_gui.py 48 KB

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