vm_qrexec_gui.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  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 os
  23. import subprocess
  24. import sys
  25. import tempfile
  26. import unittest
  27. from distutils import spawn
  28. import grp
  29. import qubes.config
  30. import qubes.devices
  31. import qubes.tests
  32. import qubes.vm.appvm
  33. import qubes.vm.templatevm
  34. import numpy as np
  35. class TC_00_AppVMMixin(object):
  36. def setUp(self):
  37. super(TC_00_AppVMMixin, self).setUp()
  38. self.init_default_template(self.template)
  39. if self._testMethodName == 'test_210_time_sync':
  40. self.init_networking()
  41. self.testvm1 = self.app.add_new_vm(
  42. qubes.vm.appvm.AppVM,
  43. label='red',
  44. name=self.make_vm_name('vm1'),
  45. template=self.app.domains[self.template])
  46. self.loop.run_until_complete(self.testvm1.create_on_disk())
  47. self.testvm2 = self.app.add_new_vm(
  48. qubes.vm.appvm.AppVM,
  49. label='red',
  50. name=self.make_vm_name('vm2'),
  51. template=self.app.domains[self.template])
  52. self.loop.run_until_complete(self.testvm2.create_on_disk())
  53. if self.template.startswith('whonix-gw'):
  54. # Whonix Gateway loudly complains if the VM doesn't provide network,
  55. # which spams the screen with error messages that interfere with
  56. # other tests
  57. self.testvm1.provides_network = True
  58. self.testvm2.provides_network = True
  59. self.app.save()
  60. def test_000_start_shutdown(self):
  61. # TODO: wait_for, timeout
  62. self.loop.run_until_complete(self.testvm1.start())
  63. self.assertEqual(self.testvm1.get_power_state(), "Running")
  64. self.loop.run_until_complete(self.wait_for_session(self.testvm1))
  65. self.loop.run_until_complete(self.testvm1.shutdown(wait=True))
  66. self.assertEqual(self.testvm1.get_power_state(), "Halted")
  67. @unittest.skipUnless(spawn.find_executable('xdotool'),
  68. "xdotool not installed")
  69. def test_010_run_xterm(self):
  70. self.loop.run_until_complete(self.testvm1.start())
  71. self.assertEqual(self.testvm1.get_power_state(), "Running")
  72. self.loop.run_until_complete(self.wait_for_session(self.testvm1))
  73. p = self.loop.run_until_complete(self.testvm1.run('xterm'))
  74. try:
  75. title = 'user@{}'.format(self.testvm1.name)
  76. if self.template.count("whonix"):
  77. title = 'user@host'
  78. self.wait_for_window(title)
  79. self.loop.run_until_complete(asyncio.sleep(0.5))
  80. subprocess.check_call(
  81. ['xdotool', 'search', '--name', title,
  82. 'windowactivate', 'type', 'exit\n'])
  83. self.wait_for_window(title, show=False)
  84. finally:
  85. try:
  86. p.terminate()
  87. self.loop.run_until_complete(p.wait())
  88. except ProcessLookupError: # already dead
  89. pass
  90. @unittest.skipUnless(spawn.find_executable('xdotool'),
  91. "xdotool not installed")
  92. def test_011_run_gnome_terminal(self):
  93. if "minimal" in self.template:
  94. self.skipTest("Minimal template doesn't have 'gnome-terminal'")
  95. if 'whonix' in self.template:
  96. self.skipTest("Whonix template doesn't have 'gnome-terminal'")
  97. if 'xfce' in self.template:
  98. self.skipTest("Xfce template doesn't have 'gnome-terminal'")
  99. self.loop.run_until_complete(self.testvm1.start())
  100. self.assertEqual(self.testvm1.get_power_state(), "Running")
  101. self.loop.run_until_complete(self.wait_for_session(self.testvm1))
  102. p = self.loop.run_until_complete(self.testvm1.run('gnome-terminal'))
  103. try:
  104. title = 'user@{}'.format(self.testvm1.name)
  105. if self.template.count("whonix"):
  106. title = 'user@host'
  107. self.wait_for_window(title)
  108. self.loop.run_until_complete(asyncio.sleep(0.5))
  109. subprocess.check_call(
  110. ['xdotool', 'search', '--name', title,
  111. 'windowactivate', '--sync', 'type', 'exit\n'])
  112. wait_count = 0
  113. while subprocess.call(['xdotool', 'search', '--name', title],
  114. stdout=open(os.path.devnull, 'w'),
  115. stderr=subprocess.STDOUT) == 0:
  116. wait_count += 1
  117. if wait_count > 100:
  118. self.fail("Timeout while waiting for gnome-terminal "
  119. "termination")
  120. self.loop.run_until_complete(asyncio.sleep(0.1))
  121. finally:
  122. try:
  123. p.terminate()
  124. self.loop.run_until_complete(p.wait())
  125. except ProcessLookupError: # already dead
  126. pass
  127. @unittest.skipUnless(spawn.find_executable('xdotool'),
  128. "xdotool not installed")
  129. def test_012_qubes_desktop_run(self):
  130. self.loop.run_until_complete(self.testvm1.start())
  131. self.assertEqual(self.testvm1.get_power_state(), "Running")
  132. xterm_desktop_path = "/usr/share/applications/xterm.desktop"
  133. # Debian has it different...
  134. xterm_desktop_path_debian = \
  135. "/usr/share/applications/debian-xterm.desktop"
  136. try:
  137. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  138. 'test -r {}'.format(xterm_desktop_path_debian)))
  139. except subprocess.CalledProcessError:
  140. pass
  141. else:
  142. xterm_desktop_path = xterm_desktop_path_debian
  143. self.loop.run_until_complete(self.wait_for_session(self.testvm1))
  144. self.loop.run_until_complete(
  145. self.testvm1.run('qubes-desktop-run {}'.format(xterm_desktop_path)))
  146. title = 'user@{}'.format(self.testvm1.name)
  147. if self.template.count("whonix"):
  148. title = 'user@host'
  149. self.wait_for_window(title)
  150. self.loop.run_until_complete(asyncio.sleep(0.5))
  151. subprocess.check_call(
  152. ['xdotool', 'search', '--name', title,
  153. 'windowactivate', '--sync', 'type', 'exit\n'])
  154. self.wait_for_window(title, show=False)
  155. def test_100_qrexec_filecopy(self):
  156. self.loop.run_until_complete(asyncio.gather(
  157. self.testvm1.start(),
  158. self.testvm2.start()))
  159. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  160. 'cp /etc/passwd /tmp/passwd'))
  161. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  162. try:
  163. self.loop.run_until_complete(
  164. self.testvm1.run_for_stdio(
  165. 'qvm-copy-to-vm {} /tmp/passwd'.format(
  166. self.testvm2.name)))
  167. except subprocess.CalledProcessError as e:
  168. self.fail('qvm-copy-to-vm failed: {}'.format(e.stderr))
  169. try:
  170. self.loop.run_until_complete(self.testvm2.run_for_stdio(
  171. 'diff /etc/passwd /home/user/QubesIncoming/{}/passwd'.format(
  172. self.testvm1.name)))
  173. except subprocess.CalledProcessError:
  174. self.fail('file differs')
  175. try:
  176. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  177. 'test -f /tmp/passwd'))
  178. except subprocess.CalledProcessError:
  179. self.fail('source file got removed')
  180. def test_105_qrexec_filemove(self):
  181. self.loop.run_until_complete(asyncio.gather(
  182. self.testvm1.start(),
  183. self.testvm2.start()))
  184. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  185. 'cp /etc/passwd /tmp/passwd'))
  186. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  187. try:
  188. self.loop.run_until_complete(
  189. self.testvm1.run_for_stdio(
  190. 'qvm-move-to-vm {} /tmp/passwd'.format(
  191. self.testvm2.name)))
  192. except subprocess.CalledProcessError as e:
  193. self.fail('qvm-move-to-vm failed: {}'.format(e.stderr))
  194. try:
  195. self.loop.run_until_complete(self.testvm2.run_for_stdio(
  196. 'diff /etc/passwd /home/user/QubesIncoming/{}/passwd'.format(
  197. self.testvm1.name)))
  198. except subprocess.CalledProcessError:
  199. self.fail('file differs')
  200. with self.assertRaises(subprocess.CalledProcessError):
  201. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  202. 'test -f /tmp/passwd'))
  203. def test_101_qrexec_filecopy_with_autostart(self):
  204. self.loop.run_until_complete(self.testvm1.start())
  205. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  206. try:
  207. self.loop.run_until_complete(
  208. self.testvm1.run_for_stdio(
  209. 'qvm-copy-to-vm {} /etc/passwd'.format(
  210. self.testvm2.name)))
  211. except subprocess.CalledProcessError as e:
  212. self.fail('qvm-copy-to-vm failed: {}'.format(e.stderr))
  213. # workaround for libvirt bug (domain ID isn't updated when is started
  214. # from other application) - details in
  215. # QubesOS/qubes-core-libvirt@63ede4dfb4485c4161dd6a2cc809e8fb45ca664f
  216. # XXX is it still true with qubesd? --woju 20170523
  217. self.testvm2._libvirt_domain = None
  218. self.assertTrue(self.testvm2.is_running())
  219. try:
  220. self.loop.run_until_complete(self.testvm2.run_for_stdio(
  221. 'diff /etc/passwd /home/user/QubesIncoming/{}/passwd'.format(
  222. self.testvm1.name)))
  223. except subprocess.CalledProcessError:
  224. self.fail('file differs')
  225. try:
  226. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  227. 'test -f /etc/passwd'))
  228. except subprocess.CalledProcessError:
  229. self.fail('source file got removed')
  230. def test_110_qrexec_filecopy_deny(self):
  231. self.loop.run_until_complete(asyncio.gather(
  232. self.testvm1.start(),
  233. self.testvm2.start()))
  234. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2,
  235. allow=False):
  236. with self.assertRaises(subprocess.CalledProcessError):
  237. self.loop.run_until_complete(
  238. self.testvm1.run_for_stdio(
  239. 'qvm-copy-to-vm {} /etc/passwd'.format(
  240. self.testvm2.name)))
  241. with self.assertRaises(subprocess.CalledProcessError):
  242. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  243. 'test -d /home/user/QubesIncoming/{}'.format(
  244. self.testvm1.name)))
  245. def test_115_qrexec_filecopy_no_agent(self):
  246. # The operation should not hang when qrexec-agent is down on target
  247. # machine, see QubesOS/qubes-issues#5347.
  248. self.loop.run_until_complete(asyncio.gather(
  249. self.testvm1.start(),
  250. self.testvm2.start()))
  251. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  252. try:
  253. self.loop.run_until_complete(
  254. self.testvm2.run_for_stdio(
  255. 'systemctl stop qubes-qrexec-agent.service', user='root'))
  256. except subprocess.CalledProcessError:
  257. # A failure is normal here, because we're killing the qrexec
  258. # process that is handling the command.
  259. pass
  260. with self.assertRaises(subprocess.CalledProcessError):
  261. self.loop.run_until_complete(
  262. asyncio.wait_for(
  263. self.testvm1.run_for_stdio(
  264. 'qvm-copy-to-vm {} /etc/passwd'.format(
  265. self.testvm2.name)),
  266. timeout=30))
  267. @unittest.skip("Xen gntalloc driver crashes when page is mapped in the "
  268. "same domain")
  269. def test_120_qrexec_filecopy_self(self):
  270. self.testvm1.start()
  271. self.qrexec_policy('qubes.Filecopy', self.testvm1.name,
  272. self.testvm1.name)
  273. p = self.testvm1.run("qvm-copy-to-vm %s /etc/passwd" %
  274. self.testvm1.name, passio_popen=True,
  275. passio_stderr=True)
  276. p.wait()
  277. self.assertEqual(p.returncode, 0, "qvm-copy-to-vm failed: %s" %
  278. p.stderr.read())
  279. retcode = self.testvm1.run(
  280. "diff /etc/passwd /home/user/QubesIncoming/{}/passwd".format(
  281. self.testvm1.name),
  282. wait=True)
  283. self.assertEqual(retcode, 0, "file differs")
  284. @unittest.skipUnless(spawn.find_executable('xdotool'),
  285. "xdotool not installed")
  286. def test_130_qrexec_filemove_disk_full(self):
  287. self.loop.run_until_complete(asyncio.gather(
  288. self.testvm1.start(),
  289. self.testvm2.start()))
  290. self.loop.run_until_complete(self.wait_for_session(self.testvm1))
  291. # Prepare test file
  292. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  293. 'yes teststring | dd of=/tmp/testfile bs=1M count=50 '
  294. 'iflag=fullblock'))
  295. # Prepare target directory with limited size
  296. self.loop.run_until_complete(self.testvm2.run_for_stdio(
  297. 'mkdir -p /home/user/QubesIncoming && '
  298. 'chown user /home/user/QubesIncoming && '
  299. 'mount -t tmpfs none /home/user/QubesIncoming -o size=48M',
  300. user='root'))
  301. with self.qrexec_policy('qubes.Filecopy', self.testvm1, self.testvm2):
  302. p = self.loop.run_until_complete(self.testvm1.run(
  303. 'qvm-move-to-vm {} /tmp/testfile'.format(
  304. self.testvm2.name)))
  305. # Close GUI error message
  306. try:
  307. self.enter_keys_in_window('Error', ['Return'])
  308. except subprocess.CalledProcessError:
  309. pass
  310. self.loop.run_until_complete(p.wait())
  311. self.assertNotEqual(p.returncode, 0)
  312. # the file shouldn't be removed in source vm
  313. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  314. 'test -f /tmp/testfile'))
  315. def test_200_timezone(self):
  316. """Test whether timezone setting is properly propagated to the VM"""
  317. if "whonix" in self.template:
  318. self.skipTest("Timezone propagation disabled on Whonix templates")
  319. self.loop.run_until_complete(self.testvm1.start())
  320. vm_tz, _ = self.loop.run_until_complete(self.testvm1.run_for_stdio(
  321. 'date +%Z'))
  322. dom0_tz = subprocess.check_output(['date', '+%Z'])
  323. self.assertEqual(vm_tz.strip(), dom0_tz.strip())
  324. # Check if reverting back to UTC works
  325. vm_tz, _ = self.loop.run_until_complete(self.testvm1.run_for_stdio(
  326. 'TZ=UTC date +%Z'))
  327. self.assertEqual(vm_tz.strip(), b'UTC')
  328. def test_210_time_sync(self):
  329. """Test time synchronization mechanism"""
  330. if self.template.startswith('whonix-'):
  331. self.skipTest('qvm-sync-clock disabled for Whonix VMs')
  332. self.loop.run_until_complete(asyncio.gather(
  333. self.testvm1.start(),
  334. self.testvm2.start()))
  335. start_time = subprocess.check_output(['date', '-u', '+%s'])
  336. try:
  337. self.app.clockvm = self.testvm1
  338. self.app.save()
  339. # break vm and dom0 time, to check if qvm-sync-clock would fix it
  340. subprocess.check_call(['sudo', 'date', '-s', '2001-01-01T12:34:56'],
  341. stdout=subprocess.DEVNULL)
  342. self.loop.run_until_complete(
  343. self.testvm2.run_for_stdio('date -s 2001-01-01T12:34:56',
  344. user='root'))
  345. self.loop.run_until_complete(
  346. self.testvm2.run_for_stdio('qvm-sync-clock',
  347. user='root'))
  348. p = self.loop.run_until_complete(
  349. asyncio.create_subprocess_exec('sudo', 'qvm-sync-clock',
  350. stdout=asyncio.subprocess.DEVNULL))
  351. self.loop.run_until_complete(p.wait())
  352. self.assertEqual(p.returncode, 0)
  353. vm_time, _ = self.loop.run_until_complete(
  354. self.testvm2.run_for_stdio('date -u +%s'))
  355. # get current time
  356. current_time, _ = self.loop.run_until_complete(
  357. self.testvm1.run_for_stdio('date -u +%s'))
  358. self.assertAlmostEquals(int(vm_time), int(current_time), delta=30)
  359. dom0_time = subprocess.check_output(['date', '-u', '+%s'])
  360. self.assertAlmostEquals(int(dom0_time), int(current_time), delta=30)
  361. except:
  362. # reset time to some approximation of the real time
  363. subprocess.Popen(
  364. ["sudo", "date", "-u", "-s", "@" + start_time.decode()])
  365. raise
  366. finally:
  367. self.app.clockvm = None
  368. def wait_for_pulseaudio_startup(self, vm):
  369. self.loop.run_until_complete(
  370. self.wait_for_session(self.testvm1))
  371. try:
  372. self.loop.run_until_complete(vm.run_for_stdio(
  373. "timeout 30s sh -c 'while ! pactl info; do sleep 1; done'"
  374. ))
  375. except subprocess.CalledProcessError as e:
  376. self.fail('Timeout waiting for pulseaudio start in {}: {}{}'.format(
  377. vm.name, e.stdout, e.stderr))
  378. # then wait for the stream to appear in dom0
  379. local_user = grp.getgrnam('qubes').gr_mem[0]
  380. p = self.loop.run_until_complete(asyncio.create_subprocess_shell(
  381. "sudo -E -u {} timeout 60s sh -c '"
  382. "while ! pactl list sink-inputs | grep -q :{}; do sleep 1; done'"
  383. .format(local_user, vm.name)))
  384. self.loop.run_until_complete(p.wait())
  385. # and some more...
  386. self.loop.run_until_complete(asyncio.sleep(1))
  387. def prepare_audio_vm(self):
  388. if 'whonix-gw' in self.template:
  389. self.skipTest('whonix-gw have no audio')
  390. self.loop.run_until_complete(self.testvm1.start())
  391. try:
  392. self.loop.run_until_complete(
  393. self.testvm1.run_for_stdio('which parecord'))
  394. except subprocess.CalledProcessError:
  395. self.skipTest('pulseaudio-utils not installed in VM')
  396. self.wait_for_pulseaudio_startup(self.testvm1)
  397. def check_audio_sample(self, sample, sfreq):
  398. rec = np.fromstring(sample, dtype=np.float32)
  399. # determine sample size using silence threshold
  400. threshold = 10**-3
  401. rec_size = np.count_nonzero((rec > threshold) | (rec < -threshold))
  402. if not rec_size:
  403. self.fail('only silence detected, no useful audio data')
  404. # find zero crossings
  405. crossings = np.nonzero((rec[1:] > threshold) &
  406. (rec[:-1] < -threshold))[0]
  407. np.seterr('raise')
  408. # compare against sine wave frequency
  409. rec_freq = 44100/np.mean(np.diff(crossings))
  410. if not sfreq*0.8 < rec_freq < sfreq*1.2:
  411. self.fail('frequency {} not in specified range'
  412. .format(rec_freq))
  413. def common_audio_playback(self):
  414. # sine frequency
  415. sfreq = 4400
  416. # generate signal
  417. audio_in = np.sin(2*np.pi*np.arange(44100)*sfreq/44100)
  418. self.loop.run_until_complete(
  419. self.testvm1.run_for_stdio('cat > audio_in.raw',
  420. input=audio_in.astype(np.float32).tobytes()))
  421. local_user = grp.getgrnam('qubes').gr_mem[0]
  422. with tempfile.NamedTemporaryFile() as recorded_audio:
  423. os.chmod(recorded_audio.name, 0o666)
  424. # FIXME: -d 0 assumes only one audio device
  425. p = subprocess.Popen(['sudo', '-E', '-u', local_user,
  426. 'parecord', '-d', '0', '--raw',
  427. '--format=float32le', '--rate=44100', '--channels=1',
  428. recorded_audio.name], stdout=subprocess.PIPE)
  429. try:
  430. self.loop.run_until_complete(
  431. self.testvm1.run_for_stdio(
  432. 'paplay --format=float32le --rate=44100 \
  433. --channels=1 --raw audio_in.raw'))
  434. except subprocess.CalledProcessError as err:
  435. self.fail('{} stderr: {}'.format(str(err), err.stderr))
  436. # wait for possible parecord buffering
  437. self.loop.run_until_complete(asyncio.sleep(1))
  438. p.terminate()
  439. # for some reason sudo do not relay SIGTERM sent above
  440. subprocess.check_call(['pkill', 'parecord'])
  441. p.wait()
  442. self.check_audio_sample(recorded_audio.file.read(), sfreq)
  443. def _configure_audio_recording(self, vm):
  444. '''Connect VM's output-source to sink monitor instead of mic'''
  445. local_user = grp.getgrnam('qubes').gr_mem[0]
  446. sudo = ['sudo', '-E', '-u', local_user]
  447. source_outputs = subprocess.check_output(
  448. sudo + ['pacmd', 'list-source-outputs']).decode()
  449. last_index = None
  450. found = False
  451. for line in source_outputs.splitlines():
  452. if line.startswith(' index: '):
  453. last_index = line.split(':')[1].strip()
  454. elif line.startswith('\t\tapplication.name = '):
  455. app_name = line.split('=')[1].strip('" ')
  456. if vm.name == app_name:
  457. found = True
  458. break
  459. if not found:
  460. self.fail('source-output for VM {} not found'.format(vm.name))
  461. subprocess.check_call(sudo +
  462. ['pacmd', 'move-source-output', last_index, '0'])
  463. def common_audio_record_muted(self):
  464. # connect VM's recording source output monitor (instead of mic)
  465. self._configure_audio_recording(self.testvm1)
  466. # generate some "audio" data
  467. audio_in = b'\x20' * 44100
  468. local_user = grp.getgrnam('qubes').gr_mem[0]
  469. record = self.loop.run_until_complete(
  470. self.testvm1.run('parecord --raw audio_rec.raw'))
  471. # give it time to start recording
  472. self.loop.run_until_complete(asyncio.sleep(0.5))
  473. p = subprocess.Popen(['sudo', '-E', '-u', local_user,
  474. 'paplay', '--raw'],
  475. stdin=subprocess.PIPE)
  476. p.communicate(audio_in)
  477. # wait for possible parecord buffering
  478. self.loop.run_until_complete(asyncio.sleep(1))
  479. self.loop.run_until_complete(
  480. self.testvm1.run_for_stdio('pkill parecord'))
  481. self.loop.run_until_complete(record.wait())
  482. recorded_audio, _ = self.loop.run_until_complete(
  483. self.testvm1.run_for_stdio('cat audio_rec.raw'))
  484. # should be empty or silence, so check just a little fragment
  485. if audio_in[:32] in recorded_audio:
  486. self.fail('VM recorded something, even though mic disabled')
  487. def common_audio_record_unmuted(self):
  488. deva = qubes.devices.DeviceAssignment(self.app.domains[0], 'mic')
  489. self.loop.run_until_complete(
  490. self.testvm1.devices['mic'].attach(deva))
  491. # connect VM's recording source output monitor (instead of mic)
  492. self._configure_audio_recording(self.testvm1)
  493. sfreq = 4400
  494. audio_in = np.sin(2*np.pi*np.arange(44100)*sfreq/44100)
  495. local_user = grp.getgrnam('qubes').gr_mem[0]
  496. record = self.loop.run_until_complete(self.testvm1.run(
  497. 'parecord --raw --format=float32le --rate=44100 \
  498. --channels=1 audio_rec.raw'))
  499. # give it time to start recording
  500. self.loop.run_until_complete(asyncio.sleep(0.5))
  501. p = subprocess.Popen(['sudo', '-E', '-u', local_user,
  502. 'paplay', '--raw', '--format=float32le',
  503. '--rate=44100', '--channels=1'],
  504. stdin=subprocess.PIPE)
  505. p.communicate(audio_in.astype(np.float32).tobytes())
  506. # wait for possible parecord buffering
  507. self.loop.run_until_complete(asyncio.sleep(1))
  508. self.loop.run_until_complete(
  509. self.testvm1.run_for_stdio('pkill parecord || :'))
  510. _, record_stderr = self.loop.run_until_complete(record.communicate())
  511. if record_stderr:
  512. self.fail('parecord printed something on stderr: {}'.format(
  513. record_stderr))
  514. recorded_audio, _ = self.loop.run_until_complete(
  515. self.testvm1.run_for_stdio('cat audio_rec.raw'))
  516. self.check_audio_sample(recorded_audio, sfreq)
  517. @unittest.skipUnless(spawn.find_executable('parecord'),
  518. "pulseaudio-utils not installed in dom0")
  519. def test_220_audio_play(self):
  520. self.prepare_audio_vm()
  521. self.common_audio_playback()
  522. @unittest.skipUnless(spawn.find_executable('parecord'),
  523. "pulseaudio-utils not installed in dom0")
  524. def test_221_audio_rec_muted(self):
  525. self.prepare_audio_vm()
  526. self.common_audio_record_muted()
  527. @unittest.skipUnless(spawn.find_executable('parecord'),
  528. "pulseaudio-utils not installed in dom0")
  529. def test_222_audio_rec_unmuted(self):
  530. self.prepare_audio_vm()
  531. self.common_audio_record_unmuted()
  532. @unittest.skipUnless(spawn.find_executable('parecord'),
  533. "pulseaudio-utils not installed in dom0")
  534. def test_223_audio_play_hvm(self):
  535. self.testvm1.virt_mode = 'hvm'
  536. self.testvm1.features['audio-model'] = 'ich6'
  537. self.prepare_audio_vm()
  538. self.loop.run_until_complete(
  539. self.testvm1.run_for_stdio('pacmd unload-module module-vchan-sink'))
  540. self.common_audio_playback()
  541. @unittest.skipUnless(spawn.find_executable('parecord'),
  542. "pulseaudio-utils not installed in dom0")
  543. def test_224_audio_rec_muted_hvm(self):
  544. self.testvm1.virt_mode = 'hvm'
  545. self.testvm1.features['audio-model'] = 'ich6'
  546. self.prepare_audio_vm()
  547. self.loop.run_until_complete(
  548. self.testvm1.run_for_stdio('pacmd unload-module module-vchan-sink'))
  549. self.common_audio_record_muted()
  550. @unittest.skipUnless(spawn.find_executable('parecord'),
  551. "pulseaudio-utils not installed in dom0")
  552. def test_225_audio_rec_unmuted_hvm(self):
  553. self.testvm1.virt_mode = 'hvm'
  554. self.testvm1.features['audio-model'] = 'ich6'
  555. self.prepare_audio_vm()
  556. self.loop.run_until_complete(
  557. self.testvm1.run_for_stdio('pacmd set-sink-volume 1 0x10000'))
  558. self.loop.run_until_complete(
  559. self.testvm1.run_for_stdio('pacmd unload-module module-vchan-sink'))
  560. self.common_audio_record_unmuted()
  561. def test_250_resize_private_img(self):
  562. """
  563. Test private.img resize, both offline and online
  564. :return:
  565. """
  566. # First offline test
  567. self.loop.run_until_complete(
  568. self.testvm1.storage.resize('private', 4*1024**3))
  569. self.loop.run_until_complete(self.testvm1.start())
  570. df_cmd = '( df --output=size /rw || df /rw | awk \'{print $2}\' )|' \
  571. 'tail -n 1'
  572. # new_size in 1k-blocks
  573. new_size, _ = self.loop.run_until_complete(
  574. self.testvm1.run_for_stdio(df_cmd))
  575. # some safety margin for FS metadata
  576. self.assertGreater(int(new_size.strip()), 3.8*1024**2)
  577. # Then online test
  578. self.loop.run_until_complete(
  579. self.testvm1.storage.resize('private', 6*1024**3))
  580. # new_size in 1k-blocks
  581. new_size, _ = self.loop.run_until_complete(
  582. self.testvm1.run_for_stdio(df_cmd))
  583. # some safety margin for FS metadata
  584. self.assertGreater(int(new_size.strip()), 5.7*1024**2)
  585. @unittest.skipUnless(spawn.find_executable('xdotool'),
  586. "xdotool not installed")
  587. def test_300_bug_1028_gui_memory_pinning(self):
  588. """
  589. If VM window composition buffers are relocated in memory, GUI will
  590. still use old pointers and will display old pages
  591. :return:
  592. """
  593. # this test does too much asynchronous operations,
  594. # so let's rewrite it as a coroutine and call it as such
  595. return self.loop.run_until_complete(
  596. self._test_300_bug_1028_gui_memory_pinning())
  597. @asyncio.coroutine
  598. def _test_300_bug_1028_gui_memory_pinning(self):
  599. self.testvm1.memory = 800
  600. self.testvm1.maxmem = 800
  601. # exclude from memory balancing
  602. self.testvm1.features['service.meminfo-writer'] = False
  603. yield from self.testvm1.start()
  604. yield from self.wait_for_session(self.testvm1)
  605. # and allow large map count
  606. yield from self.testvm1.run('echo 256000 > /proc/sys/vm/max_map_count',
  607. user="root")
  608. allocator_c = '''
  609. #include <sys/mman.h>
  610. #include <stdlib.h>
  611. #include <stdio.h>
  612. int main(int argc, char **argv) {
  613. int total_pages;
  614. char *addr, *iter;
  615. total_pages = atoi(argv[1]);
  616. addr = mmap(NULL, total_pages * 0x1000, PROT_READ | PROT_WRITE,
  617. MAP_ANONYMOUS | MAP_PRIVATE | MAP_POPULATE, -1, 0);
  618. if (addr == MAP_FAILED) {
  619. perror("mmap");
  620. exit(1);
  621. }
  622. printf("Stage1\\n");
  623. fflush(stdout);
  624. getchar();
  625. for (iter = addr; iter < addr + total_pages*0x1000; iter += 0x2000) {
  626. if (mlock(iter, 0x1000) == -1) {
  627. perror("mlock");
  628. fprintf(stderr, "%d of %d\\n", (iter-addr)/0x1000, total_pages);
  629. exit(1);
  630. }
  631. }
  632. printf("Stage2\\n");
  633. fflush(stdout);
  634. for (iter = addr+0x1000; iter < addr + total_pages*0x1000; iter += 0x2000) {
  635. if (munmap(iter, 0x1000) == -1) {
  636. perror(\"munmap\");
  637. exit(1);
  638. }
  639. }
  640. printf("Stage3\\n");
  641. fflush(stdout);
  642. fclose(stdout);
  643. getchar();
  644. return 0;
  645. }
  646. '''
  647. yield from self.testvm1.run_for_stdio('cat > allocator.c',
  648. input=allocator_c.encode())
  649. try:
  650. yield from self.testvm1.run_for_stdio(
  651. 'gcc allocator.c -o allocator')
  652. except subprocess.CalledProcessError as e:
  653. self.skipTest('allocator compile failed: {}'.format(e.stderr))
  654. # drop caches to have even more memory pressure
  655. yield from self.testvm1.run_for_stdio(
  656. 'echo 3 > /proc/sys/vm/drop_caches', user='root')
  657. # now fragment all free memory
  658. stdout, _ = yield from self.testvm1.run_for_stdio(
  659. "grep ^MemFree: /proc/meminfo|awk '{print $2}'")
  660. memory_pages = int(stdout) // 4 # 4k pages
  661. alloc1 = yield from self.testvm1.run(
  662. 'ulimit -l unlimited; exec /home/user/allocator {}'.format(
  663. memory_pages),
  664. user="root",
  665. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  666. stderr=subprocess.PIPE)
  667. # wait for memory being allocated; can't use just .read(), because EOF
  668. # passing is unreliable while the process is still running
  669. alloc1.stdin.write(b'\n')
  670. yield from alloc1.stdin.drain()
  671. try:
  672. alloc_out = yield from alloc1.stdout.readexactly(
  673. len('Stage1\nStage2\nStage3\n'))
  674. except asyncio.IncompleteReadError as e:
  675. alloc_out = e.partial
  676. if b'Stage3' not in alloc_out:
  677. # read stderr only in case of failed assert (), but still have nice
  678. # failure message (don't use self.fail() directly)
  679. #
  680. # stderr isn't always read, because on not-failed run, the process
  681. # is still running, so stderr.read() will wait (indefinitely).
  682. self.assertIn(b'Stage3', alloc_out,
  683. (yield from alloc1.stderr.read()))
  684. # now, launch some window - it should get fragmented composition buffer
  685. # it is important to have some changing content there, to generate
  686. # content update events (aka damage notify)
  687. proc = yield from self.testvm1.run(
  688. 'xterm -maximized -e top')
  689. if proc.returncode is not None:
  690. self.fail('xterm failed to start')
  691. # get window ID
  692. winid = yield from self.wait_for_window_coro(
  693. self.testvm1.name + ':xterm',
  694. search_class=True)
  695. xprop = yield from asyncio.get_event_loop().run_in_executor(None,
  696. subprocess.check_output,
  697. ['xprop', '-notype', '-id', winid, '_QUBES_VMWINDOWID'])
  698. vm_winid = xprop.decode().strip().split(' ')[4]
  699. # now free the fragmented memory and trigger compaction
  700. alloc1.stdin.write(b'\n')
  701. yield from alloc1.stdin.drain()
  702. yield from alloc1.wait()
  703. yield from self.testvm1.run_for_stdio(
  704. 'echo 1 > /proc/sys/vm/compact_memory', user='root')
  705. # now window may be already "broken"; to be sure, allocate (=zero)
  706. # some memory
  707. alloc2 = yield from self.testvm1.run(
  708. 'ulimit -l unlimited; /home/user/allocator {}'.format(memory_pages),
  709. user='root', stdout=subprocess.PIPE)
  710. yield from alloc2.stdout.read(len('Stage1\n'))
  711. # wait for damage notify - top updates every 3 sec by default
  712. yield from asyncio.sleep(6)
  713. # stop changing the window content
  714. subprocess.check_call(['xdotool', 'key', '--window', winid, 'd'])
  715. # now take screenshot of the window, from dom0 and VM
  716. # choose pnm format, as it doesn't have any useless metadata - easy
  717. # to compare
  718. vm_image, _ = yield from self.testvm1.run_for_stdio(
  719. 'import -window {} pnm:-'.format(vm_winid))
  720. dom0_image = yield from asyncio.get_event_loop().run_in_executor(None,
  721. subprocess.check_output, ['import', '-window', winid, 'pnm:-'])
  722. if vm_image != dom0_image:
  723. self.fail("Dom0 window doesn't match VM window content")
  724. class TC_10_Generic(qubes.tests.SystemTestCase):
  725. def setUp(self):
  726. super(TC_10_Generic, self).setUp()
  727. self.init_default_template()
  728. self.vm = self.app.add_new_vm(
  729. qubes.vm.appvm.AppVM,
  730. name=self.make_vm_name('vm'),
  731. label='red',
  732. template=self.app.default_template)
  733. self.loop.run_until_complete(self.vm.create_on_disk())
  734. self.app.save()
  735. self.vm = self.app.domains[self.vm.qid]
  736. def test_000_anyvm_deny_dom0(self):
  737. '''$anyvm in policy should not match dom0'''
  738. policy = open("/etc/qubes-rpc/policy/test.AnyvmDeny", "w")
  739. policy.write("%s $anyvm allow" % (self.vm.name,))
  740. policy.close()
  741. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.AnyvmDeny")
  742. flagfile = '/tmp/test-anyvmdeny-flag'
  743. if os.path.exists(flagfile):
  744. os.remove(flagfile)
  745. self.create_local_file('/etc/qubes-rpc/test.AnyvmDeny',
  746. 'touch {}\necho service output\n'.format(flagfile))
  747. self.loop.run_until_complete(self.vm.start())
  748. with self.qrexec_policy('test.AnyvmDeny', self.vm, '$anyvm'):
  749. with self.assertRaises(subprocess.CalledProcessError,
  750. msg='$anyvm matched dom0') as e:
  751. self.loop.run_until_complete(
  752. self.vm.run_for_stdio(
  753. '/usr/lib/qubes/qrexec-client-vm dom0 test.AnyvmDeny'))
  754. stdout = e.exception.output
  755. stderr = e.exception.stderr
  756. self.assertFalse(os.path.exists(flagfile),
  757. 'Flag file created (service was run) even though should be denied,'
  758. ' qrexec-client-vm output: {} {}'.format(stdout, stderr))
  759. def create_testcases_for_templates():
  760. return qubes.tests.create_testcases_for_templates('TC_00_AppVM',
  761. TC_00_AppVMMixin, qubes.tests.SystemTestCase,
  762. module=sys.modules[__name__])
  763. def load_tests(loader, tests, pattern):
  764. tests.addTests(loader.loadTestsFromNames(
  765. create_testcases_for_templates()))
  766. return tests
  767. qubes.tests.maybe_create_testcases_on_import(create_testcases_for_templates)