vm_qrexec_gui.py 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565
  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 tearDown(self):
  56. # socket-based qrexec tests:
  57. if os.path.exists('/etc/qubes-rpc/test.Socket'):
  58. os.unlink('/etc/qubes-rpc/test.Socket')
  59. if hasattr(self, 'service_proc'):
  60. try:
  61. self.service_proc.terminate()
  62. self.loop.run_until_complete(self.service_proc.communicate())
  63. except ProcessLookupError:
  64. pass
  65. super(TC_00_AppVMMixin, self).tearDown()
  66. def test_000_start_shutdown(self):
  67. # TODO: wait_for, timeout
  68. self.loop.run_until_complete(self.testvm1.start())
  69. self.assertEqual(self.testvm1.get_power_state(), "Running")
  70. self.loop.run_until_complete(self.wait_for_session(self.testvm1))
  71. self.loop.run_until_complete(self.testvm1.shutdown(wait=True))
  72. self.assertEqual(self.testvm1.get_power_state(), "Halted")
  73. @unittest.skipUnless(spawn.find_executable('xdotool'),
  74. "xdotool not installed")
  75. def test_010_run_xterm(self):
  76. self.loop.run_until_complete(self.testvm1.start())
  77. self.assertEqual(self.testvm1.get_power_state(), "Running")
  78. self.loop.run_until_complete(self.wait_for_session(self.testvm1))
  79. p = self.loop.run_until_complete(self.testvm1.run('xterm'))
  80. try:
  81. title = 'user@{}'.format(self.testvm1.name)
  82. if self.template.count("whonix"):
  83. title = 'user@host'
  84. self.wait_for_window(title)
  85. self.loop.run_until_complete(asyncio.sleep(0.5))
  86. subprocess.check_call(
  87. ['xdotool', 'search', '--name', title,
  88. 'windowactivate', 'type', 'exit\n'])
  89. self.wait_for_window(title, show=False)
  90. finally:
  91. try:
  92. p.terminate()
  93. self.loop.run_until_complete(p.wait())
  94. except ProcessLookupError: # already dead
  95. pass
  96. @unittest.skipUnless(spawn.find_executable('xdotool'),
  97. "xdotool not installed")
  98. def test_011_run_gnome_terminal(self):
  99. if "minimal" in self.template:
  100. self.skipTest("Minimal template doesn't have 'gnome-terminal'")
  101. if 'whonix' in self.template:
  102. self.skipTest("Whonix template doesn't have 'gnome-terminal'")
  103. self.loop.run_until_complete(self.testvm1.start())
  104. self.assertEqual(self.testvm1.get_power_state(), "Running")
  105. self.loop.run_until_complete(self.wait_for_session(self.testvm1))
  106. p = self.loop.run_until_complete(self.testvm1.run('gnome-terminal'))
  107. try:
  108. title = 'user@{}'.format(self.testvm1.name)
  109. if self.template.count("whonix"):
  110. title = 'user@host'
  111. self.wait_for_window(title)
  112. self.loop.run_until_complete(asyncio.sleep(0.5))
  113. subprocess.check_call(
  114. ['xdotool', 'search', '--name', title,
  115. 'windowactivate', '--sync', 'type', 'exit\n'])
  116. wait_count = 0
  117. while subprocess.call(['xdotool', 'search', '--name', title],
  118. stdout=open(os.path.devnull, 'w'),
  119. stderr=subprocess.STDOUT) == 0:
  120. wait_count += 1
  121. if wait_count > 100:
  122. self.fail("Timeout while waiting for gnome-terminal "
  123. "termination")
  124. self.loop.run_until_complete(asyncio.sleep(0.1))
  125. finally:
  126. try:
  127. p.terminate()
  128. self.loop.run_until_complete(p.wait())
  129. except ProcessLookupError: # already dead
  130. pass
  131. @unittest.skipUnless(spawn.find_executable('xdotool'),
  132. "xdotool not installed")
  133. def test_012_qubes_desktop_run(self):
  134. self.loop.run_until_complete(self.testvm1.start())
  135. self.assertEqual(self.testvm1.get_power_state(), "Running")
  136. xterm_desktop_path = "/usr/share/applications/xterm.desktop"
  137. # Debian has it different...
  138. xterm_desktop_path_debian = \
  139. "/usr/share/applications/debian-xterm.desktop"
  140. try:
  141. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  142. 'test -r {}'.format(xterm_desktop_path_debian)))
  143. except subprocess.CalledProcessError:
  144. pass
  145. else:
  146. xterm_desktop_path = xterm_desktop_path_debian
  147. self.loop.run_until_complete(self.wait_for_session(self.testvm1))
  148. self.loop.run_until_complete(
  149. self.testvm1.run('qubes-desktop-run {}'.format(xterm_desktop_path)))
  150. title = 'user@{}'.format(self.testvm1.name)
  151. if self.template.count("whonix"):
  152. title = 'user@host'
  153. self.wait_for_window(title)
  154. self.loop.run_until_complete(asyncio.sleep(0.5))
  155. subprocess.check_call(
  156. ['xdotool', 'search', '--name', title,
  157. 'windowactivate', '--sync', 'type', 'exit\n'])
  158. self.wait_for_window(title, show=False)
  159. def test_050_qrexec_simple_eof(self):
  160. """Test for data and EOF transmission dom0->VM"""
  161. # XXX is this still correct? this is no longer simple qrexec,
  162. # but qubes.VMShell
  163. self.loop.run_until_complete(self.testvm1.start())
  164. try:
  165. (stdout, stderr) = self.loop.run_until_complete(asyncio.wait_for(
  166. self.testvm1.run_for_stdio('cat', input=TEST_DATA),
  167. timeout=10))
  168. except asyncio.TimeoutError:
  169. self.fail(
  170. "Timeout, probably EOF wasn't transferred to the VM process")
  171. self.assertEqual(stdout, TEST_DATA,
  172. 'Received data differs from what was sent')
  173. self.assertFalse(stderr,
  174. 'Some data was printed to stderr')
  175. def test_051_qrexec_simple_eof_reverse(self):
  176. """Test for EOF transmission VM->dom0"""
  177. @asyncio.coroutine
  178. def run(self):
  179. p = yield from self.testvm1.run(
  180. 'echo test; exec >&-; cat > /dev/null',
  181. stdin=subprocess.PIPE,
  182. stdout=subprocess.PIPE,
  183. stderr=subprocess.PIPE)
  184. # this will hang on test failure
  185. stdout = yield from asyncio.wait_for(p.stdout.read(), timeout=10)
  186. p.stdin.write(TEST_DATA)
  187. yield from p.stdin.drain()
  188. p.stdin.close()
  189. self.assertEqual(stdout.strip(), b'test',
  190. 'Received data differs from what was expected')
  191. # this may hang in some buggy cases
  192. self.assertFalse((yield from p.stderr.read()),
  193. 'Some data was printed to stderr')
  194. try:
  195. yield from asyncio.wait_for(p.wait(), timeout=1)
  196. except asyncio.TimeoutError:
  197. self.fail("Timeout, "
  198. "probably EOF wasn't transferred from the VM process")
  199. self.loop.run_until_complete(self.testvm1.start())
  200. self.loop.run_until_complete(self.wait_for_session(self.testvm1))
  201. self.loop.run_until_complete(run(self))
  202. def test_052_qrexec_vm_service_eof(self):
  203. """Test for EOF transmission VM(src)->VM(dst)"""
  204. self.loop.run_until_complete(asyncio.wait([
  205. self.testvm1.start(),
  206. self.testvm2.start()]))
  207. self.loop.run_until_complete(asyncio.wait([
  208. self.wait_for_session(self.testvm1),
  209. self.wait_for_session(self.testvm2)]))
  210. self.loop.run_until_complete(self.testvm2.run_for_stdio(
  211. 'cat > /etc/qubes-rpc/test.EOF',
  212. user='root',
  213. input=b'/bin/cat'))
  214. with self.qrexec_policy('test.EOF', self.testvm1, self.testvm2):
  215. try:
  216. stdout, _ = self.loop.run_until_complete(asyncio.wait_for(
  217. self.testvm1.run_for_stdio('''\
  218. /usr/lib/qubes/qrexec-client-vm {} test.EOF \
  219. /bin/sh -c 'echo test; exec >&-; cat >&$SAVED_FD_1'
  220. '''.format(self.testvm2.name)),
  221. timeout=10))
  222. except asyncio.TimeoutError:
  223. self.fail("Timeout, probably EOF wasn't transferred")
  224. self.assertEqual(stdout, b'test\n',
  225. 'Received data differs from what was expected')
  226. @unittest.expectedFailure
  227. def test_053_qrexec_vm_service_eof_reverse(self):
  228. """Test for EOF transmission VM(src)<-VM(dst)"""
  229. self.loop.run_until_complete(asyncio.wait([
  230. self.testvm1.start(),
  231. self.testvm2.start()]))
  232. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.EOF',
  233. 'echo test; exec >&-; cat >/dev/null')
  234. with self.qrexec_policy('test.EOF', self.testvm1, self.testvm2):
  235. try:
  236. stdout, _ = self.loop.run_until_complete(asyncio.wait_for(
  237. self.testvm1.run_for_stdio('''\
  238. /usr/lib/qubes/qrexec-client-vm {} test.EOF \
  239. /bin/sh -c 'cat >&$SAVED_FD_1'
  240. '''.format(self.testvm2.name)),
  241. timeout=10))
  242. except asyncio.TimeoutError:
  243. self.fail("Timeout, probably EOF wasn't transferred")
  244. self.assertEqual(stdout, b'test',
  245. 'Received data differs from what was expected')
  246. def test_055_qrexec_dom0_service_abort(self):
  247. """
  248. Test if service abort (by dom0) is properly handled by source VM.
  249. If "remote" part of the service terminates, the source part should
  250. properly be notified. This includes closing its stdin (which is
  251. already checked by test_053_qrexec_vm_service_eof_reverse), but also
  252. its stdout - otherwise such service might hang on write(2) call.
  253. """
  254. self.loop.run_until_complete(self.testvm1.start())
  255. self.create_local_file('/etc/qubes-rpc/test.Abort',
  256. 'sleep 1')
  257. with self.qrexec_policy('test.Abort', self.testvm1, 'dom0'):
  258. try:
  259. # two possible exit codes, depending on when exactly dom0
  260. # service terminates:
  261. # exit code 141: EPIPE (no buffered data)
  262. # exit code 1: ECONNRESET (some buffered data remains)
  263. stdout, _ = self.loop.run_until_complete(asyncio.wait_for(
  264. self.testvm1.run_for_stdio('''\
  265. /usr/lib/qubes/qrexec-client-vm dom0 test.Abort \
  266. /bin/cat /dev/zero; test $? -eq 141 -o $? -eq 1'''),
  267. timeout=10))
  268. except asyncio.TimeoutError:
  269. self.fail("Timeout, probably stdout wasn't closed")
  270. def test_060_qrexec_exit_code_dom0(self):
  271. self.loop.run_until_complete(self.testvm1.start())
  272. self.loop.run_until_complete(self.testvm1.run_for_stdio('exit 0'))
  273. with self.assertRaises(subprocess.CalledProcessError) as e:
  274. self.loop.run_until_complete(self.testvm1.run_for_stdio('exit 3'))
  275. self.assertEqual(e.exception.returncode, 3)
  276. def test_065_qrexec_exit_code_vm(self):
  277. self.loop.run_until_complete(asyncio.wait([
  278. self.testvm1.start(),
  279. self.testvm2.start()]))
  280. with self.qrexec_policy('test.Retcode', self.testvm1, self.testvm2):
  281. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.Retcode',
  282. 'exit 0')
  283. (stdout, stderr) = self.loop.run_until_complete(
  284. self.testvm1.run_for_stdio('''\
  285. /usr/lib/qubes/qrexec-client-vm {} test.Retcode;
  286. echo $?'''.format(self.testvm2.name)))
  287. self.assertEqual(stdout, b'0\n')
  288. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.Retcode',
  289. 'exit 3')
  290. (stdout, stderr) = self.loop.run_until_complete(
  291. self.testvm1.run_for_stdio('''\
  292. /usr/lib/qubes/qrexec-client-vm {} test.Retcode;
  293. echo $?'''.format(self.testvm2.name)))
  294. self.assertEqual(stdout, b'3\n')
  295. def test_070_qrexec_vm_simultaneous_write(self):
  296. """Test for simultaneous write in VM(src)->VM(dst) connection
  297. This is regression test for #1347
  298. Check for deadlock when initially both sides writes a lot of data
  299. (and not read anything). When one side starts reading, it should
  300. get the data and the remote side should be possible to write then more.
  301. There was a bug where remote side was waiting on write(2) and not
  302. handling anything else.
  303. """
  304. self.loop.run_until_complete(asyncio.wait([
  305. self.testvm1.start(),
  306. self.testvm2.start()]))
  307. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.write', '''\
  308. # first write a lot of data
  309. dd if=/dev/zero bs=993 count=10000 iflag=fullblock
  310. # and only then read something
  311. dd of=/dev/null bs=993 count=10000 iflag=fullblock
  312. ''')
  313. with self.qrexec_policy('test.write', self.testvm1, self.testvm2):
  314. try:
  315. self.loop.run_until_complete(asyncio.wait_for(
  316. # first write a lot of data to fill all the buffers
  317. # then after some time start reading
  318. self.testvm1.run_for_stdio('''\
  319. /usr/lib/qubes/qrexec-client-vm {} test.write \
  320. /bin/sh -c '
  321. dd if=/dev/zero bs=993 count=10000 iflag=fullblock &
  322. sleep 1;
  323. dd of=/dev/null bs=993 count=10000 iflag=fullblock;
  324. wait'
  325. '''.format(self.testvm2.name)), timeout=10))
  326. except subprocess.CalledProcessError:
  327. self.fail('Service call failed')
  328. except asyncio.TimeoutError:
  329. self.fail('Timeout, probably deadlock')
  330. def test_071_qrexec_dom0_simultaneous_write(self):
  331. """Test for simultaneous write in dom0(src)->VM(dst) connection
  332. Similar to test_070_qrexec_vm_simultaneous_write, but with dom0
  333. as a source.
  334. """
  335. self.loop.run_until_complete(self.testvm2.start())
  336. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.write', '''\
  337. # first write a lot of data
  338. dd if=/dev/zero bs=993 count=10000 iflag=fullblock
  339. # and only then read something
  340. dd of=/dev/null bs=993 count=10000 iflag=fullblock
  341. ''')
  342. # can't use subprocess.PIPE, because asyncio will claim those FDs
  343. pipe1_r, pipe1_w = os.pipe()
  344. pipe2_r, pipe2_w = os.pipe()
  345. try:
  346. local_proc = self.loop.run_until_complete(
  347. asyncio.create_subprocess_shell(
  348. # first write a lot of data to fill all the buffers
  349. "dd if=/dev/zero bs=993 count=10000 iflag=fullblock & "
  350. # then after some time start reading
  351. "sleep 1; "
  352. "dd of=/dev/null bs=993 count=10000 iflag=fullblock; "
  353. "wait", stdin=pipe1_r, stdout=pipe2_w))
  354. service_proc = self.loop.run_until_complete(self.testvm2.run_service(
  355. "test.write", stdin=pipe2_r, stdout=pipe1_w))
  356. finally:
  357. os.close(pipe1_r)
  358. os.close(pipe1_w)
  359. os.close(pipe2_r)
  360. os.close(pipe2_w)
  361. try:
  362. self.loop.run_until_complete(
  363. asyncio.wait_for(service_proc.wait(), timeout=10))
  364. except asyncio.TimeoutError:
  365. self.fail("Timeout, probably deadlock")
  366. else:
  367. self.assertEqual(service_proc.returncode, 0,
  368. "Service call failed")
  369. finally:
  370. try:
  371. service_proc.terminate()
  372. except ProcessLookupError:
  373. pass
  374. def test_072_qrexec_to_dom0_simultaneous_write(self):
  375. """Test for simultaneous write in dom0(src)<-VM(dst) connection
  376. Similar to test_071_qrexec_dom0_simultaneous_write, but with dom0
  377. as a "hanging" side.
  378. """
  379. self.loop.run_until_complete(self.testvm2.start())
  380. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.write', '''\
  381. # first write a lot of data
  382. dd if=/dev/zero bs=993 count=10000 iflag=fullblock &
  383. # and only then read something
  384. dd of=/dev/null bs=993 count=10000 iflag=fullblock
  385. sleep 1;
  386. wait
  387. ''')
  388. # can't use subprocess.PIPE, because asyncio will claim those FDs
  389. pipe1_r, pipe1_w = os.pipe()
  390. pipe2_r, pipe2_w = os.pipe()
  391. try:
  392. local_proc = self.loop.run_until_complete(
  393. asyncio.create_subprocess_shell(
  394. # first write a lot of data to fill all the buffers
  395. "dd if=/dev/zero bs=993 count=10000 iflag=fullblock & "
  396. # then, only when all written, read something
  397. "dd of=/dev/null bs=993 count=10000 iflag=fullblock; ",
  398. stdin=pipe1_r, stdout=pipe2_w))
  399. service_proc = self.loop.run_until_complete(self.testvm2.run_service(
  400. "test.write", stdin=pipe2_r, stdout=pipe1_w))
  401. finally:
  402. os.close(pipe1_r)
  403. os.close(pipe1_w)
  404. os.close(pipe2_r)
  405. os.close(pipe2_w)
  406. try:
  407. self.loop.run_until_complete(
  408. asyncio.wait_for(service_proc.wait(), timeout=10))
  409. except asyncio.TimeoutError:
  410. self.fail("Timeout, probably deadlock")
  411. else:
  412. self.assertEqual(service_proc.returncode, 0,
  413. "Service call failed")
  414. finally:
  415. try:
  416. service_proc.terminate()
  417. except ProcessLookupError:
  418. pass
  419. def test_080_qrexec_service_argument_allow_default(self):
  420. """Qrexec service call with argument"""
  421. self.loop.run_until_complete(asyncio.wait([
  422. self.testvm1.start(),
  423. self.testvm2.start()]))
  424. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.Argument',
  425. '/usr/bin/printf %s "$1"')
  426. with self.qrexec_policy('test.Argument', self.testvm1, self.testvm2):
  427. stdout, stderr = self.loop.run_until_complete(
  428. self.testvm1.run_for_stdio('/usr/lib/qubes/qrexec-client-vm '
  429. '{} test.Argument+argument'.format(self.testvm2.name)))
  430. self.assertEqual(stdout, b'argument')
  431. def test_081_qrexec_service_argument_allow_specific(self):
  432. """Qrexec service call with argument - allow only specific value"""
  433. self.loop.run_until_complete(asyncio.wait([
  434. self.testvm1.start(),
  435. self.testvm2.start()]))
  436. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.Argument',
  437. '/usr/bin/printf %s "$1"')
  438. with self.qrexec_policy('test.Argument', '$anyvm', '$anyvm', False):
  439. with self.qrexec_policy('test.Argument+argument',
  440. self.testvm1.name, self.testvm2.name):
  441. stdout, stderr = self.loop.run_until_complete(
  442. self.testvm1.run_for_stdio(
  443. '/usr/lib/qubes/qrexec-client-vm '
  444. '{} test.Argument+argument'.format(self.testvm2.name)))
  445. self.assertEqual(stdout, b'argument')
  446. def test_082_qrexec_service_argument_deny_specific(self):
  447. """Qrexec service call with argument - deny specific value"""
  448. self.loop.run_until_complete(asyncio.wait([
  449. self.testvm1.start(),
  450. self.testvm2.start()]))
  451. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.Argument',
  452. '/usr/bin/printf %s "$1"')
  453. with self.qrexec_policy('test.Argument', '$anyvm', '$anyvm'):
  454. with self.qrexec_policy('test.Argument+argument',
  455. self.testvm1, self.testvm2, allow=False):
  456. with self.assertRaises(subprocess.CalledProcessError,
  457. msg='Service request should be denied'):
  458. self.loop.run_until_complete(
  459. self.testvm1.run_for_stdio(
  460. '/usr/lib/qubes/qrexec-client-vm {} '
  461. 'test.Argument+argument'.format(self.testvm2.name)))
  462. def test_083_qrexec_service_argument_specific_implementation(self):
  463. """Qrexec service call with argument - argument specific
  464. implementatation"""
  465. self.loop.run_until_complete(asyncio.wait([
  466. self.testvm1.start(),
  467. self.testvm2.start()]))
  468. self.create_remote_file(self.testvm2,
  469. '/etc/qubes-rpc/test.Argument',
  470. '/usr/bin/printf %s "$1"')
  471. self.create_remote_file(self.testvm2,
  472. '/etc/qubes-rpc/test.Argument+argument',
  473. '/usr/bin/printf "specific: %s" "$1"')
  474. with self.qrexec_policy('test.Argument', self.testvm1, self.testvm2):
  475. stdout, stderr = self.loop.run_until_complete(
  476. self.testvm1.run_for_stdio('/usr/lib/qubes/qrexec-client-vm '
  477. '{} test.Argument+argument'.format(self.testvm2.name)))
  478. self.assertEqual(stdout, b'specific: argument')
  479. def test_084_qrexec_service_argument_extra_env(self):
  480. """Qrexec service call with argument - extra env variables"""
  481. self.loop.run_until_complete(asyncio.wait([
  482. self.testvm1.start(),
  483. self.testvm2.start()]))
  484. self.create_remote_file(self.testvm2, '/etc/qubes-rpc/test.Argument',
  485. '/usr/bin/printf "%s %s" '
  486. '"$QREXEC_SERVICE_FULL_NAME" "$QREXEC_SERVICE_ARGUMENT"')
  487. with self.qrexec_policy('test.Argument', self.testvm1, self.testvm2):
  488. stdout, stderr = self.loop.run_until_complete(
  489. self.testvm1.run_for_stdio('/usr/lib/qubes/qrexec-client-vm '
  490. '{} test.Argument+argument'.format(self.testvm2.name)))
  491. self.assertEqual(stdout, b'test.Argument+argument argument')
  492. def test_090_qrexec_service_socket_dom0(self):
  493. """Basic test socket services (dom0) - data receive"""
  494. self.loop.run_until_complete(self.testvm1.start())
  495. service_proc = self.loop.run_until_complete(
  496. asyncio.create_subprocess_shell(
  497. 'socat -u UNIX-LISTEN:/etc/qubes-rpc/test.Socket,mode=666 -',
  498. stdout=subprocess.PIPE, stdin=subprocess.PIPE))
  499. try:
  500. with self.qrexec_policy('test.Socket', self.testvm1, '@adminvm'):
  501. (stdout, stderr) = self.loop.run_until_complete(asyncio.wait_for(
  502. self.testvm1.run_for_stdio(
  503. 'qrexec-client-vm @adminvm test.Socket', input=TEST_DATA),
  504. timeout=10))
  505. except asyncio.TimeoutError:
  506. self.fail(
  507. "service timeout, probably EOF wasn't transferred to the VM process")
  508. try:
  509. (service_stdout, service_stderr) = self.loop.run_until_complete(
  510. asyncio.wait_for(
  511. service_proc.communicate(),
  512. timeout=10))
  513. except asyncio.TimeoutError:
  514. self.fail(
  515. "socat timeout, probably EOF wasn't transferred to the VM process")
  516. service_descriptor = b'test.Socket+ test-inst-vm1 keyword adminvm\0'
  517. self.assertEqual(service_stdout, service_descriptor + TEST_DATA,
  518. 'Received data differs from what was sent')
  519. self.assertFalse(stderr,
  520. 'Some data was printed to stderr')
  521. self.assertFalse(service_stderr,
  522. 'Some data was printed to stderr')
  523. def test_091_qrexec_service_socket_dom0_send(self):
  524. """Basic test socket services (dom0) - data send"""
  525. self.loop.run_until_complete(self.testvm1.start())
  526. self.create_local_file('/tmp/service-input', TEST_DATA.decode())
  527. service_proc = self.loop.run_until_complete(asyncio.create_subprocess_shell(
  528. 'socat -u OPEN:/tmp/service-input UNIX-LISTEN:/etc/qubes-rpc/test.Socket,mode=666'))
  529. try:
  530. with self.qrexec_policy('test.Socket', self.testvm1, '@adminvm'):
  531. stdout, stderr = self.loop.run_until_complete(asyncio.wait_for(
  532. self.testvm1.run_for_stdio(
  533. 'qrexec-client-vm @adminvm test.Socket'),
  534. timeout=10))
  535. except asyncio.TimeoutError:
  536. self.fail(
  537. "service timeout, probably EOF wasn't transferred to the VM process")
  538. try:
  539. (service_stdout, service_stderr) = self.loop.run_until_complete(
  540. asyncio.wait_for(
  541. service_proc.communicate(),
  542. timeout=10))
  543. except asyncio.TimeoutError:
  544. self.fail(
  545. "socat timeout, probably EOF wasn't transferred to the VM process")
  546. self.assertEqual(stdout, TEST_DATA,
  547. 'Received data differs from what was sent')
  548. self.assertFalse(stderr,
  549. 'Some data was printed to stderr')
  550. self.assertFalse(service_stderr,
  551. 'Some data was printed to stderr')
  552. def test_092_qrexec_service_socket_dom0_eof_reverse(self):
  553. """Test for EOF transmission dom0(socket)->VM"""
  554. self.loop.run_until_complete(self.testvm1.start())
  555. self.create_local_file(
  556. '/tmp/service_script',
  557. '#!/usr/bin/python3\n'
  558. 'import socket, os, sys, time\n'
  559. 's = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n'
  560. 'os.umask(0)\n'
  561. 's.bind("/etc/qubes-rpc/test.Socket")\n'
  562. 's.listen(1)\n'
  563. 'conn, addr = s.accept()\n'
  564. 'conn.send(b"test\\n")\n'
  565. 'conn.shutdown(socket.SHUT_WR)\n'
  566. # wait longer than the timeout below
  567. 'time.sleep(15)\n'
  568. )
  569. self.service_proc = self.loop.run_until_complete(
  570. asyncio.create_subprocess_shell('python3 /tmp/service_script',
  571. stdout=subprocess.PIPE, stdin=subprocess.PIPE))
  572. try:
  573. with self.qrexec_policy('test.Socket', self.testvm1, '@adminvm'):
  574. p = self.loop.run_until_complete(self.testvm1.run(
  575. 'qrexec-client-vm @adminvm test.Socket',
  576. stdout=subprocess.PIPE, stdin=subprocess.PIPE))
  577. stdout = self.loop.run_until_complete(asyncio.wait_for(
  578. p.stdout.read(),
  579. timeout=10))
  580. except asyncio.TimeoutError:
  581. self.fail(
  582. "service timeout, probably EOF wasn't transferred from the VM process")
  583. self.assertEqual(stdout, b'test\n',
  584. 'Received data differs from what was expected')
  585. def test_093_qrexec_service_socket_dom0_eof(self):
  586. """Test for EOF transmission VM->dom0(socket)"""
  587. self.loop.run_until_complete(self.testvm1.start())
  588. self.create_local_file(
  589. '/tmp/service_script',
  590. '#!/usr/bin/python3\n'
  591. 'import socket, os, sys, time\n'
  592. 's = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n'
  593. 'os.umask(0)\n'
  594. 's.bind("/etc/qubes-rpc/test.Socket")\n'
  595. 's.listen(1)\n'
  596. 'conn, addr = s.accept()\n'
  597. 'buf = conn.recv(100)\n'
  598. 'sys.stdout.buffer.write(buf)\n'
  599. 'buf = conn.recv(10)\n'
  600. 'sys.stdout.buffer.write(buf)\n'
  601. 'sys.stdout.buffer.flush()\n'
  602. 'os.close(1)\n'
  603. # wait longer than the timeout below
  604. 'time.sleep(15)\n'
  605. )
  606. self.service_proc = self.loop.run_until_complete(
  607. asyncio.create_subprocess_shell('python3 /tmp/service_script',
  608. stdout=subprocess.PIPE, stdin=subprocess.PIPE))
  609. try:
  610. with self.qrexec_policy('test.Socket', self.testvm1, '@adminvm'):
  611. p = self.loop.run_until_complete(self.testvm1.run(
  612. 'qrexec-client-vm @adminvm test.Socket',
  613. stdin=subprocess.PIPE))
  614. p.stdin.write(b'test1test2')
  615. p.stdin.write_eof()
  616. service_stdout = self.loop.run_until_complete(asyncio.wait_for(
  617. self.service_proc.stdout.read(),
  618. timeout=10))
  619. except asyncio.TimeoutError:
  620. self.fail(
  621. "service timeout, probably EOF wasn't transferred from the VM process")
  622. service_descriptor = b'test.Socket+ test-inst-vm1 keyword adminvm\0'
  623. self.assertEqual(service_stdout, service_descriptor + b'test1test2',
  624. 'Received data differs from what was expected')
  625. def _wait_for_socket_setup(self):
  626. try:
  627. self.loop.run_until_complete(asyncio.wait_for(
  628. self.testvm1.run_for_stdio(
  629. 'while ! test -e /etc/qubes-rpc/test.Socket; do sleep 0.1; done'),
  630. timeout=10))
  631. except asyncio.TimeoutError:
  632. self.fail(
  633. "waiting for /etc/qubes-rpc/test.Socket in VM timed out")
  634. def test_095_qrexec_service_socket_vm(self):
  635. """Basic test socket services (VM) - receive"""
  636. self.loop.run_until_complete(self.testvm1.start())
  637. self.service_proc = self.loop.run_until_complete(self.testvm1.run(
  638. 'socat -u UNIX-LISTEN:/etc/qubes-rpc/test.Socket,mode=666 -',
  639. stdout=subprocess.PIPE, stdin=subprocess.PIPE,
  640. user='root'))
  641. self._wait_for_socket_setup()
  642. try:
  643. (stdout, stderr) = self.loop.run_until_complete(asyncio.wait_for(
  644. self.testvm1.run_service_for_stdio('test.Socket+', input=TEST_DATA),
  645. timeout=10))
  646. except asyncio.TimeoutError:
  647. self.fail(
  648. "service timeout, probably EOF wasn't transferred to the VM process")
  649. try:
  650. (service_stdout, service_stderr) = self.loop.run_until_complete(
  651. asyncio.wait_for(
  652. self.service_proc.communicate(),
  653. timeout=10))
  654. except asyncio.TimeoutError:
  655. self.fail(
  656. "socat timeout, probably EOF wasn't transferred to the VM process")
  657. service_descriptor = b'test.Socket+ dom0\0'
  658. self.assertEqual(service_stdout, service_descriptor + TEST_DATA,
  659. 'Received data differs from what was sent')
  660. self.assertFalse(stderr,
  661. 'Some data was printed to stderr')
  662. self.assertFalse(service_stderr,
  663. 'Some data was printed to stderr')
  664. def test_096_qrexec_service_socket_vm_send(self):
  665. """Basic test socket services (VM) - send"""
  666. self.loop.run_until_complete(self.testvm1.start())
  667. self.create_remote_file(self.testvm1,
  668. '/tmp/service-input',
  669. TEST_DATA.decode())
  670. service_proc = self.loop.run_until_complete(self.testvm1.run(
  671. 'socat -u OPEN:/tmp/service-input UNIX-LISTEN:/etc/qubes-rpc/test.Socket,mode=666',
  672. user='root'))
  673. self._wait_for_socket_setup()
  674. try:
  675. (stdout, stderr) = self.loop.run_until_complete(asyncio.wait_for(
  676. self.testvm1.run_service_for_stdio('test.Socket+'),
  677. timeout=10))
  678. except asyncio.TimeoutError:
  679. self.fail(
  680. "service timeout, probably EOF wasn't transferred to the VM process")
  681. try:
  682. (service_stdout, service_stderr) = self.loop.run_until_complete(
  683. asyncio.wait_for(
  684. service_proc.communicate(),
  685. timeout=10))
  686. except asyncio.TimeoutError:
  687. self.fail(
  688. "socat timeout, probably EOF wasn't transferred to the VM process")
  689. self.assertEqual(stdout, TEST_DATA,
  690. 'Received data differs from what was sent')
  691. self.assertFalse(stderr,
  692. 'Some data was printed to stderr')
  693. self.assertFalse(service_stderr,
  694. 'Some data was printed to stderr')
  695. def test_097_qrexec_service_socket_vm_eof_reverse(self):
  696. """Test for EOF transmission VM(socket)->dom0"""
  697. self.loop.run_until_complete(self.testvm1.start())
  698. self.create_remote_file(self.testvm1,
  699. '/tmp/service_script',
  700. '#!/usr/bin/python3\n'
  701. 'import socket, os, sys, time\n'
  702. 's = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n'
  703. 'os.umask(0)\n'
  704. 's.bind("/etc/qubes-rpc/test.Socket")\n'
  705. 's.listen(1)\n'
  706. 'conn, addr = s.accept()\n'
  707. 'conn.send(b"test\\n")\n'
  708. 'conn.shutdown(socket.SHUT_WR)\n'
  709. # wait longer than the timeout below
  710. 'time.sleep(15)\n'
  711. )
  712. service_proc = self.loop.run_until_complete(self.testvm1.run(
  713. 'python3 /tmp/service_script',
  714. stdout=subprocess.PIPE, stdin=subprocess.PIPE,
  715. user='root'))
  716. self._wait_for_socket_setup()
  717. try:
  718. p = self.loop.run_until_complete(
  719. self.testvm1.run_service('test.Socket+',
  720. stdin=subprocess.PIPE, stdout=subprocess.PIPE))
  721. stdout = self.loop.run_until_complete(asyncio.wait_for(p.stdout.read(),
  722. timeout=10))
  723. except asyncio.TimeoutError:
  724. self.fail(
  725. "service timeout, probably EOF wasn't transferred from the VM process")
  726. self.assertEqual(stdout,
  727. b'test\n',
  728. 'Received data differs from what was expected')
  729. def test_098_qrexec_service_socket_vm_eof(self):
  730. """Test for EOF transmission dom0->VM(socket)"""
  731. self.loop.run_until_complete(self.testvm1.start())
  732. self.create_remote_file(
  733. self.testvm1,
  734. '/tmp/service_script',
  735. '#!/usr/bin/python3\n'
  736. 'import socket, os, sys, time\n'
  737. 's = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n'
  738. 'os.umask(0)\n'
  739. 's.bind("/etc/qubes-rpc/test.Socket")\n'
  740. 's.listen(1)\n'
  741. 'conn, addr = s.accept()\n'
  742. 'buf = conn.recv(100)\n'
  743. 'sys.stdout.buffer.write(buf)\n'
  744. 'buf = conn.recv(10)\n'
  745. 'sys.stdout.buffer.write(buf)\n'
  746. 'sys.stdout.buffer.flush()\n'
  747. 'os.close(1)\n'
  748. # wait longer than the timeout below
  749. 'time.sleep(15)\n'
  750. )
  751. self.service_proc = self.loop.run_until_complete(self.testvm1.run(
  752. 'python3 /tmp/service_script',
  753. stdout=subprocess.PIPE, stdin=subprocess.PIPE,
  754. user='root'))
  755. self._wait_for_socket_setup()
  756. try:
  757. p = self.loop.run_until_complete(
  758. self.testvm1.run_service('test.Socket+',
  759. stdin=subprocess.PIPE, stdout=subprocess.PIPE))
  760. p.stdin.write(b'test1test2')
  761. self.loop.run_until_complete(
  762. asyncio.wait_for(p.stdin.drain(), timeout=10))
  763. p.stdin.close()
  764. service_stdout = self.loop.run_until_complete(asyncio.wait_for(
  765. self.service_proc.stdout.read(),
  766. timeout=10))
  767. except asyncio.TimeoutError:
  768. self.fail(
  769. "service timeout, probably EOF wasn't transferred to the VM process")
  770. service_descriptor = b'test.Socket+ dom0\0'
  771. self.assertEqual(service_stdout, service_descriptor + b'test1test2',
  772. 'Received data differs from what was expected')
  773. def test_100_qrexec_filecopy(self):
  774. self.loop.run_until_complete(asyncio.wait([
  775. self.testvm1.start(),
  776. self.testvm2.start()]))
  777. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  778. try:
  779. self.loop.run_until_complete(
  780. self.testvm1.run_for_stdio(
  781. 'qvm-copy-to-vm {} /etc/passwd'.format(
  782. self.testvm2.name)))
  783. except subprocess.CalledProcessError as e:
  784. self.fail('qvm-copy-to-vm failed: {}'.format(e.stderr))
  785. try:
  786. self.loop.run_until_complete(self.testvm2.run_for_stdio(
  787. 'diff /etc/passwd /home/user/QubesIncoming/{}/passwd'.format(
  788. self.testvm1.name)))
  789. except subprocess.CalledProcessError:
  790. self.fail('file differs')
  791. try:
  792. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  793. 'test -f /etc/passwd'))
  794. except subprocess.CalledProcessError:
  795. self.fail('source file got removed')
  796. def test_105_qrexec_filemove(self):
  797. self.loop.run_until_complete(asyncio.wait([
  798. self.testvm1.start(),
  799. self.testvm2.start()]))
  800. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  801. 'cp /etc/passwd /tmp/passwd'))
  802. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  803. try:
  804. self.loop.run_until_complete(
  805. self.testvm1.run_for_stdio(
  806. 'qvm-move-to-vm {} /tmp/passwd'.format(
  807. self.testvm2.name)))
  808. except subprocess.CalledProcessError as e:
  809. self.fail('qvm-move-to-vm failed: {}'.format(e.stderr))
  810. try:
  811. self.loop.run_until_complete(self.testvm2.run_for_stdio(
  812. 'diff /etc/passwd /home/user/QubesIncoming/{}/passwd'.format(
  813. self.testvm1.name)))
  814. except subprocess.CalledProcessError:
  815. self.fail('file differs')
  816. with self.assertRaises(subprocess.CalledProcessError):
  817. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  818. 'test -f /tmp/passwd'))
  819. def test_101_qrexec_filecopy_with_autostart(self):
  820. self.loop.run_until_complete(self.testvm1.start())
  821. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  822. try:
  823. self.loop.run_until_complete(
  824. self.testvm1.run_for_stdio(
  825. 'qvm-copy-to-vm {} /etc/passwd'.format(
  826. self.testvm2.name)))
  827. except subprocess.CalledProcessError as e:
  828. self.fail('qvm-copy-to-vm failed: {}'.format(e.stderr))
  829. # workaround for libvirt bug (domain ID isn't updated when is started
  830. # from other application) - details in
  831. # QubesOS/qubes-core-libvirt@63ede4dfb4485c4161dd6a2cc809e8fb45ca664f
  832. # XXX is it still true with qubesd? --woju 20170523
  833. self.testvm2._libvirt_domain = None
  834. self.assertTrue(self.testvm2.is_running())
  835. try:
  836. self.loop.run_until_complete(self.testvm2.run_for_stdio(
  837. 'diff /etc/passwd /home/user/QubesIncoming/{}/passwd'.format(
  838. self.testvm1.name)))
  839. except subprocess.CalledProcessError:
  840. self.fail('file differs')
  841. try:
  842. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  843. 'test -f /etc/passwd'))
  844. except subprocess.CalledProcessError:
  845. self.fail('source file got removed')
  846. def test_110_qrexec_filecopy_deny(self):
  847. self.loop.run_until_complete(asyncio.wait([
  848. self.testvm1.start(),
  849. self.testvm2.start()]))
  850. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2,
  851. allow=False):
  852. with self.assertRaises(subprocess.CalledProcessError):
  853. self.loop.run_until_complete(
  854. self.testvm1.run_for_stdio(
  855. 'qvm-copy-to-vm {} /etc/passwd'.format(
  856. self.testvm2.name)))
  857. with self.assertRaises(subprocess.CalledProcessError):
  858. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  859. 'test -d /home/user/QubesIncoming/{}'.format(
  860. self.testvm1.name)))
  861. def test_115_qrexec_filecopy_no_agent(self):
  862. # The operation should not hang when qrexec-agent is down on target
  863. # machine, see QubesOS/qubes-issues#5347.
  864. self.loop.run_until_complete(asyncio.wait([
  865. self.testvm1.start(),
  866. self.testvm2.start()]))
  867. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  868. try:
  869. self.loop.run_until_complete(
  870. self.testvm2.run_for_stdio(
  871. 'systemctl stop qubes-qrexec-agent.service', user='root'))
  872. except subprocess.CalledProcessError:
  873. # A failure is normal here, because we're killing the qrexec
  874. # process that is handling the command.
  875. pass
  876. with self.assertRaises(subprocess.CalledProcessError):
  877. self.loop.run_until_complete(
  878. asyncio.wait_for(
  879. self.testvm1.run_for_stdio(
  880. 'qvm-copy-to-vm {} /etc/passwd'.format(
  881. self.testvm2.name)),
  882. timeout=30))
  883. @unittest.skip("Xen gntalloc driver crashes when page is mapped in the "
  884. "same domain")
  885. def test_120_qrexec_filecopy_self(self):
  886. self.testvm1.start()
  887. self.qrexec_policy('qubes.Filecopy', self.testvm1.name,
  888. self.testvm1.name)
  889. p = self.testvm1.run("qvm-copy-to-vm %s /etc/passwd" %
  890. self.testvm1.name, passio_popen=True,
  891. passio_stderr=True)
  892. p.wait()
  893. self.assertEqual(p.returncode, 0, "qvm-copy-to-vm failed: %s" %
  894. p.stderr.read())
  895. retcode = self.testvm1.run(
  896. "diff /etc/passwd /home/user/QubesIncoming/{}/passwd".format(
  897. self.testvm1.name),
  898. wait=True)
  899. self.assertEqual(retcode, 0, "file differs")
  900. @unittest.skipUnless(spawn.find_executable('xdotool'),
  901. "xdotool not installed")
  902. def test_130_qrexec_filemove_disk_full(self):
  903. self.loop.run_until_complete(asyncio.wait([
  904. self.testvm1.start(),
  905. self.testvm2.start()]))
  906. self.loop.run_until_complete(self.wait_for_session(self.testvm1))
  907. # Prepare test file
  908. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  909. 'yes teststring | dd of=/tmp/testfile bs=1M count=50 '
  910. 'iflag=fullblock'))
  911. # Prepare target directory with limited size
  912. self.loop.run_until_complete(self.testvm2.run_for_stdio(
  913. 'mkdir -p /home/user/QubesIncoming && '
  914. 'chown user /home/user/QubesIncoming && '
  915. 'mount -t tmpfs none /home/user/QubesIncoming -o size=48M',
  916. user='root'))
  917. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  918. p = self.loop.run_until_complete(self.testvm1.run(
  919. 'qvm-move-to-vm {} /tmp/testfile'.format(
  920. self.testvm2.name)))
  921. # Close GUI error message
  922. try:
  923. self.enter_keys_in_window('Error', ['Return'])
  924. except subprocess.CalledProcessError:
  925. pass
  926. self.loop.run_until_complete(p.wait())
  927. self.assertNotEqual(p.returncode, 0)
  928. # the file shouldn't be removed in source vm
  929. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  930. 'test -f /tmp/testfile'))
  931. def test_200_timezone(self):
  932. """Test whether timezone setting is properly propagated to the VM"""
  933. if "whonix" in self.template:
  934. self.skipTest("Timezone propagation disabled on Whonix templates")
  935. self.loop.run_until_complete(self.testvm1.start())
  936. vm_tz, _ = self.loop.run_until_complete(self.testvm1.run_for_stdio(
  937. 'date +%Z'))
  938. dom0_tz = subprocess.check_output(['date', '+%Z'])
  939. self.assertEqual(vm_tz.strip(), dom0_tz.strip())
  940. # Check if reverting back to UTC works
  941. vm_tz, _ = self.loop.run_until_complete(self.testvm1.run_for_stdio(
  942. 'TZ=UTC date +%Z'))
  943. self.assertEqual(vm_tz.strip(), b'UTC')
  944. def test_210_time_sync(self):
  945. """Test time synchronization mechanism"""
  946. if self.template.startswith('whonix-'):
  947. self.skipTest('qvm-sync-clock disabled for Whonix VMs')
  948. self.loop.run_until_complete(asyncio.wait([
  949. self.testvm1.start(),
  950. self.testvm2.start(),]))
  951. start_time = subprocess.check_output(['date', '-u', '+%s'])
  952. try:
  953. self.app.clockvm = self.testvm1
  954. self.app.save()
  955. # break vm and dom0 time, to check if qvm-sync-clock would fix it
  956. subprocess.check_call(['sudo', 'date', '-s', '2001-01-01T12:34:56'],
  957. stdout=subprocess.DEVNULL)
  958. self.loop.run_until_complete(
  959. self.testvm2.run_for_stdio('date -s 2001-01-01T12:34:56',
  960. user='root'))
  961. self.loop.run_until_complete(
  962. self.testvm2.run_for_stdio('qvm-sync-clock',
  963. user='root'))
  964. p = self.loop.run_until_complete(
  965. asyncio.create_subprocess_exec('sudo', 'qvm-sync-clock',
  966. stdout=asyncio.subprocess.DEVNULL))
  967. self.loop.run_until_complete(p.wait())
  968. self.assertEqual(p.returncode, 0)
  969. vm_time, _ = self.loop.run_until_complete(
  970. self.testvm2.run_for_stdio('date -u +%s'))
  971. self.assertAlmostEquals(int(vm_time), int(start_time), delta=30)
  972. dom0_time = subprocess.check_output(['date', '-u', '+%s'])
  973. self.assertAlmostEquals(int(dom0_time), int(start_time), delta=30)
  974. except:
  975. # reset time to some approximation of the real time
  976. subprocess.Popen(
  977. ["sudo", "date", "-u", "-s", "@" + start_time.decode()])
  978. raise
  979. finally:
  980. self.app.clockvm = None
  981. def wait_for_pulseaudio_startup(self, vm):
  982. self.loop.run_until_complete(
  983. self.wait_for_session(self.testvm1))
  984. try:
  985. self.loop.run_until_complete(vm.run_for_stdio(
  986. "timeout 30s sh -c 'while ! pactl info; do sleep 1; done'"
  987. ))
  988. except subprocess.CalledProcessError as e:
  989. self.fail('Timeout waiting for pulseaudio start in {}: {}{}'.format(
  990. vm.name, e.stdout, e.stderr))
  991. # and some more...
  992. self.loop.run_until_complete(asyncio.sleep(1))
  993. @unittest.skipUnless(spawn.find_executable('parecord'),
  994. "pulseaudio-utils not installed in dom0")
  995. def test_220_audio_playback(self):
  996. if 'whonix-gw' in self.template:
  997. self.skipTest('whonix-gw have no audio')
  998. self.loop.run_until_complete(self.testvm1.start())
  999. try:
  1000. self.loop.run_until_complete(
  1001. self.testvm1.run_for_stdio('which parecord'))
  1002. except subprocess.CalledProcessError:
  1003. self.skipTest('pulseaudio-utils not installed in VM')
  1004. self.wait_for_pulseaudio_startup(self.testvm1)
  1005. # generate some "audio" data
  1006. audio_in = b'\x20' * 44100
  1007. self.loop.run_until_complete(
  1008. self.testvm1.run_for_stdio('cat > audio_in.raw', input=audio_in))
  1009. local_user = grp.getgrnam('qubes').gr_mem[0]
  1010. with tempfile.NamedTemporaryFile() as recorded_audio:
  1011. os.chmod(recorded_audio.name, 0o666)
  1012. # FIXME: -d 0 assumes only one audio device
  1013. p = subprocess.Popen(['sudo', '-E', '-u', local_user,
  1014. 'parecord', '-d', '0', '--raw', recorded_audio.name],
  1015. stdout=subprocess.PIPE)
  1016. try:
  1017. self.loop.run_until_complete(
  1018. self.testvm1.run_for_stdio('paplay --raw audio_in.raw'))
  1019. except subprocess.CalledProcessError as err:
  1020. self.fail('{} stderr: {}'.format(str(err), err.stderr))
  1021. # wait for possible parecord buffering
  1022. self.loop.run_until_complete(asyncio.sleep(1))
  1023. p.terminate()
  1024. # for some reason sudo do not relay SIGTERM sent above
  1025. subprocess.check_call(['pkill', 'parecord'])
  1026. p.wait()
  1027. # allow few bytes missing, don't use assertIn, to avoid printing
  1028. # the whole data in error message
  1029. recorded_audio = recorded_audio.file.read()
  1030. if audio_in[:-8] not in recorded_audio:
  1031. found_bytes = recorded_audio.count(audio_in[0])
  1032. all_bytes = len(audio_in)
  1033. self.fail('played sound not found in dom0, '
  1034. 'missing {} bytes out of {}'.format(
  1035. all_bytes-found_bytes, all_bytes))
  1036. def _configure_audio_recording(self, vm):
  1037. '''Connect VM's output-source to sink monitor instead of mic'''
  1038. local_user = grp.getgrnam('qubes').gr_mem[0]
  1039. sudo = ['sudo', '-E', '-u', local_user]
  1040. source_outputs = subprocess.check_output(
  1041. sudo + ['pacmd', 'list-source-outputs']).decode()
  1042. last_index = None
  1043. found = False
  1044. for line in source_outputs.splitlines():
  1045. if line.startswith(' index: '):
  1046. last_index = line.split(':')[1].strip()
  1047. elif line.startswith('\t\tapplication.name = '):
  1048. app_name = line.split('=')[1].strip('" ')
  1049. if vm.name == app_name:
  1050. found = True
  1051. break
  1052. if not found:
  1053. self.fail('source-output for VM {} not found'.format(vm.name))
  1054. subprocess.check_call(sudo +
  1055. ['pacmd', 'move-source-output', last_index, '0'])
  1056. @unittest.skipUnless(spawn.find_executable('parecord'),
  1057. "pulseaudio-utils not installed in dom0")
  1058. def test_221_audio_record_muted(self):
  1059. if 'whonix-gw' in self.template:
  1060. self.skipTest('whonix-gw have no audio')
  1061. self.loop.run_until_complete(self.testvm1.start())
  1062. try:
  1063. self.loop.run_until_complete(
  1064. self.testvm1.run_for_stdio('which parecord'))
  1065. except subprocess.CalledProcessError:
  1066. self.skipTest('pulseaudio-utils not installed in VM')
  1067. self.wait_for_pulseaudio_startup(self.testvm1)
  1068. # connect VM's recording source output monitor (instead of mic)
  1069. self._configure_audio_recording(self.testvm1)
  1070. # generate some "audio" data
  1071. audio_in = b'\x20' * 44100
  1072. local_user = grp.getgrnam('qubes').gr_mem[0]
  1073. record = self.loop.run_until_complete(
  1074. self.testvm1.run('parecord --raw audio_rec.raw'))
  1075. # give it time to start recording
  1076. self.loop.run_until_complete(asyncio.sleep(0.5))
  1077. p = subprocess.Popen(['sudo', '-E', '-u', local_user,
  1078. 'paplay', '--raw'],
  1079. stdin=subprocess.PIPE)
  1080. p.communicate(audio_in)
  1081. # wait for possible parecord buffering
  1082. self.loop.run_until_complete(asyncio.sleep(1))
  1083. self.loop.run_until_complete(
  1084. self.testvm1.run_for_stdio('pkill parecord'))
  1085. self.loop.run_until_complete(record.wait())
  1086. recorded_audio, _ = self.loop.run_until_complete(
  1087. self.testvm1.run_for_stdio('cat audio_rec.raw'))
  1088. # should be empty or silence, so check just a little fragment
  1089. if audio_in[:32] in recorded_audio:
  1090. self.fail('VM recorded something, even though mic disabled')
  1091. @unittest.skipUnless(spawn.find_executable('parecord'),
  1092. "pulseaudio-utils not installed in dom0")
  1093. def test_222_audio_record_unmuted(self):
  1094. if 'whonix-gw' in self.template:
  1095. self.skipTest('whonix-gw have no audio')
  1096. self.loop.run_until_complete(self.testvm1.start())
  1097. try:
  1098. self.loop.run_until_complete(
  1099. self.testvm1.run_for_stdio('which parecord'))
  1100. except subprocess.CalledProcessError:
  1101. self.skipTest('pulseaudio-utils not installed in VM')
  1102. self.wait_for_pulseaudio_startup(self.testvm1)
  1103. da = qubes.devices.DeviceAssignment(self.app.domains[0], 'mic')
  1104. self.loop.run_until_complete(
  1105. self.testvm1.devices['mic'].attach(da))
  1106. # connect VM's recording source output monitor (instead of mic)
  1107. self._configure_audio_recording(self.testvm1)
  1108. # generate some "audio" data
  1109. audio_in = b'\x20' * 44100
  1110. local_user = grp.getgrnam('qubes').gr_mem[0]
  1111. record = self.loop.run_until_complete(
  1112. self.testvm1.run('parecord --raw audio_rec.raw'))
  1113. # give it time to start recording
  1114. self.loop.run_until_complete(asyncio.sleep(0.5))
  1115. p = subprocess.Popen(['sudo', '-E', '-u', local_user,
  1116. 'paplay', '--raw'],
  1117. stdin=subprocess.PIPE)
  1118. p.communicate(audio_in)
  1119. # wait for possible parecord buffering
  1120. self.loop.run_until_complete(asyncio.sleep(1))
  1121. self.loop.run_until_complete(
  1122. self.testvm1.run_for_stdio('pkill parecord'))
  1123. self.loop.run_until_complete(record.wait())
  1124. recorded_audio, _ = self.loop.run_until_complete(
  1125. self.testvm1.run_for_stdio('cat audio_rec.raw'))
  1126. # allow few bytes to be missing
  1127. if audio_in[:-8] not in recorded_audio:
  1128. found_bytes = recorded_audio.count(audio_in[0])
  1129. all_bytes = len(audio_in)
  1130. self.fail('VM not recorded expected data, '
  1131. 'missing {} bytes out of {}'.format(
  1132. all_bytes-found_bytes, all_bytes))
  1133. def test_250_resize_private_img(self):
  1134. """
  1135. Test private.img resize, both offline and online
  1136. :return:
  1137. """
  1138. # First offline test
  1139. self.loop.run_until_complete(
  1140. self.testvm1.storage.resize('private', 4*1024**3))
  1141. self.loop.run_until_complete(self.testvm1.start())
  1142. df_cmd = '( df --output=size /rw || df /rw | awk \'{print $2}\' )|' \
  1143. 'tail -n 1'
  1144. # new_size in 1k-blocks
  1145. new_size, _ = self.loop.run_until_complete(
  1146. self.testvm1.run_for_stdio(df_cmd))
  1147. # some safety margin for FS metadata
  1148. self.assertGreater(int(new_size.strip()), 3.8*1024**2)
  1149. # Then online test
  1150. self.loop.run_until_complete(
  1151. self.testvm1.storage.resize('private', 6*1024**3))
  1152. # new_size in 1k-blocks
  1153. new_size, _ = self.loop.run_until_complete(
  1154. self.testvm1.run_for_stdio(df_cmd))
  1155. # some safety margin for FS metadata
  1156. self.assertGreater(int(new_size.strip()), 5.7*1024**2)
  1157. @unittest.skipUnless(spawn.find_executable('xdotool'),
  1158. "xdotool not installed")
  1159. def test_300_bug_1028_gui_memory_pinning(self):
  1160. """
  1161. If VM window composition buffers are relocated in memory, GUI will
  1162. still use old pointers and will display old pages
  1163. :return:
  1164. """
  1165. # this test does too much asynchronous operations,
  1166. # so let's rewrite it as a coroutine and call it as such
  1167. return self.loop.run_until_complete(
  1168. self._test_300_bug_1028_gui_memory_pinning())
  1169. @asyncio.coroutine
  1170. def _test_300_bug_1028_gui_memory_pinning(self):
  1171. self.testvm1.memory = 800
  1172. self.testvm1.maxmem = 800
  1173. # exclude from memory balancing
  1174. self.testvm1.features['service.meminfo-writer'] = False
  1175. yield from self.testvm1.start()
  1176. yield from self.wait_for_session(self.testvm1)
  1177. # and allow large map count
  1178. yield from self.testvm1.run('echo 256000 > /proc/sys/vm/max_map_count',
  1179. user="root")
  1180. allocator_c = '''
  1181. #include <sys/mman.h>
  1182. #include <stdlib.h>
  1183. #include <stdio.h>
  1184. int main(int argc, char **argv) {
  1185. int total_pages;
  1186. char *addr, *iter;
  1187. total_pages = atoi(argv[1]);
  1188. addr = mmap(NULL, total_pages * 0x1000, PROT_READ | PROT_WRITE,
  1189. MAP_ANONYMOUS | MAP_PRIVATE | MAP_POPULATE, -1, 0);
  1190. if (addr == MAP_FAILED) {
  1191. perror("mmap");
  1192. exit(1);
  1193. }
  1194. printf("Stage1\\n");
  1195. fflush(stdout);
  1196. getchar();
  1197. for (iter = addr; iter < addr + total_pages*0x1000; iter += 0x2000) {
  1198. if (mlock(iter, 0x1000) == -1) {
  1199. perror("mlock");
  1200. fprintf(stderr, "%d of %d\\n", (iter-addr)/0x1000, total_pages);
  1201. exit(1);
  1202. }
  1203. }
  1204. printf("Stage2\\n");
  1205. fflush(stdout);
  1206. for (iter = addr+0x1000; iter < addr + total_pages*0x1000; iter += 0x2000) {
  1207. if (munmap(iter, 0x1000) == -1) {
  1208. perror(\"munmap\");
  1209. exit(1);
  1210. }
  1211. }
  1212. printf("Stage3\\n");
  1213. fflush(stdout);
  1214. fclose(stdout);
  1215. getchar();
  1216. return 0;
  1217. }
  1218. '''
  1219. yield from self.testvm1.run_for_stdio('cat > allocator.c',
  1220. input=allocator_c.encode())
  1221. try:
  1222. yield from self.testvm1.run_for_stdio(
  1223. 'gcc allocator.c -o allocator')
  1224. except subprocess.CalledProcessError as e:
  1225. self.skipTest('allocator compile failed: {}'.format(e.stderr))
  1226. # drop caches to have even more memory pressure
  1227. yield from self.testvm1.run_for_stdio(
  1228. 'echo 3 > /proc/sys/vm/drop_caches', user='root')
  1229. # now fragment all free memory
  1230. stdout, _ = yield from self.testvm1.run_for_stdio(
  1231. "grep ^MemFree: /proc/meminfo|awk '{print $2}'")
  1232. memory_pages = int(stdout) // 4 # 4k pages
  1233. alloc1 = yield from self.testvm1.run(
  1234. 'ulimit -l unlimited; exec /home/user/allocator {}'.format(
  1235. memory_pages),
  1236. user="root",
  1237. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  1238. stderr=subprocess.PIPE)
  1239. # wait for memory being allocated; can't use just .read(), because EOF
  1240. # passing is unreliable while the process is still running
  1241. alloc1.stdin.write(b'\n')
  1242. yield from alloc1.stdin.drain()
  1243. try:
  1244. alloc_out = yield from alloc1.stdout.readexactly(
  1245. len('Stage1\nStage2\nStage3\n'))
  1246. except asyncio.IncompleteReadError as e:
  1247. alloc_out = e.partial
  1248. if b'Stage3' not in alloc_out:
  1249. # read stderr only in case of failed assert (), but still have nice
  1250. # failure message (don't use self.fail() directly)
  1251. #
  1252. # stderr isn't always read, because on not-failed run, the process
  1253. # is still running, so stderr.read() will wait (indefinitely).
  1254. self.assertIn(b'Stage3', alloc_out,
  1255. (yield from alloc1.stderr.read()))
  1256. # now, launch some window - it should get fragmented composition buffer
  1257. # it is important to have some changing content there, to generate
  1258. # content update events (aka damage notify)
  1259. proc = yield from self.testvm1.run(
  1260. 'xterm -maximized -e top')
  1261. if proc.returncode is not None:
  1262. self.fail('xterm failed to start')
  1263. # get window ID
  1264. winid = yield from self.wait_for_window_coro(
  1265. self.testvm1.name + ':xterm',
  1266. search_class=True)
  1267. xprop = yield from asyncio.get_event_loop().run_in_executor(None,
  1268. subprocess.check_output,
  1269. ['xprop', '-notype', '-id', winid, '_QUBES_VMWINDOWID'])
  1270. vm_winid = xprop.decode().strip().split(' ')[4]
  1271. # now free the fragmented memory and trigger compaction
  1272. alloc1.stdin.write(b'\n')
  1273. yield from alloc1.stdin.drain()
  1274. yield from alloc1.wait()
  1275. yield from self.testvm1.run_for_stdio(
  1276. 'echo 1 > /proc/sys/vm/compact_memory', user='root')
  1277. # now window may be already "broken"; to be sure, allocate (=zero)
  1278. # some memory
  1279. alloc2 = yield from self.testvm1.run(
  1280. 'ulimit -l unlimited; /home/user/allocator {}'.format(memory_pages),
  1281. user='root', stdout=subprocess.PIPE)
  1282. yield from alloc2.stdout.read(len('Stage1\n'))
  1283. # wait for damage notify - top updates every 3 sec by default
  1284. yield from asyncio.sleep(6)
  1285. # stop changing the window content
  1286. subprocess.check_call(['xdotool', 'key', '--window', winid, 'd'])
  1287. # now take screenshot of the window, from dom0 and VM
  1288. # choose pnm format, as it doesn't have any useless metadata - easy
  1289. # to compare
  1290. vm_image, _ = yield from self.testvm1.run_for_stdio(
  1291. 'import -window {} pnm:-'.format(vm_winid))
  1292. dom0_image = yield from asyncio.get_event_loop().run_in_executor(None,
  1293. subprocess.check_output, ['import', '-window', winid, 'pnm:-'])
  1294. if vm_image != dom0_image:
  1295. self.fail("Dom0 window doesn't match VM window content")
  1296. class TC_10_Generic(qubes.tests.SystemTestCase):
  1297. def setUp(self):
  1298. super(TC_10_Generic, self).setUp()
  1299. self.init_default_template()
  1300. self.vm = self.app.add_new_vm(
  1301. qubes.vm.appvm.AppVM,
  1302. name=self.make_vm_name('vm'),
  1303. label='red',
  1304. template=self.app.default_template)
  1305. self.loop.run_until_complete(self.vm.create_on_disk())
  1306. self.app.save()
  1307. self.vm = self.app.domains[self.vm.qid]
  1308. def test_000_anyvm_deny_dom0(self):
  1309. '''$anyvm in policy should not match dom0'''
  1310. policy = open("/etc/qubes-rpc/policy/test.AnyvmDeny", "w")
  1311. policy.write("%s $anyvm allow" % (self.vm.name,))
  1312. policy.close()
  1313. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.AnyvmDeny")
  1314. flagfile = '/tmp/test-anyvmdeny-flag'
  1315. if os.path.exists(flagfile):
  1316. os.remove(flagfile)
  1317. self.create_local_file('/etc/qubes-rpc/test.AnyvmDeny',
  1318. 'touch {}\necho service output\n'.format(flagfile))
  1319. self.loop.run_until_complete(self.vm.start())
  1320. with self.qrexec_policy('test.AnyvmDeny', self.vm, '$anyvm'):
  1321. with self.assertRaises(subprocess.CalledProcessError,
  1322. msg='$anyvm matched dom0') as e:
  1323. self.loop.run_until_complete(
  1324. self.vm.run_for_stdio(
  1325. '/usr/lib/qubes/qrexec-client-vm dom0 test.AnyvmDeny'))
  1326. stdout = e.exception.output
  1327. stderr = e.exception.stderr
  1328. self.assertFalse(os.path.exists(flagfile),
  1329. 'Flag file created (service was run) even though should be denied,'
  1330. ' qrexec-client-vm output: {} {}'.format(stdout, stderr))
  1331. def create_testcases_for_templates():
  1332. return qubes.tests.create_testcases_for_templates('TC_00_AppVM',
  1333. TC_00_AppVMMixin, qubes.tests.SystemTestCase,
  1334. module=sys.modules[__name__])
  1335. def load_tests(loader, tests, pattern):
  1336. tests.addTests(loader.loadTestsFromNames(
  1337. create_testcases_for_templates()))
  1338. return tests
  1339. qubes.tests.maybe_create_testcases_on_import(create_testcases_for_templates)