vm_qrexec_gui.py 35 KB

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