vm_qrexec_gui.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  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.gather(
  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.gather(
  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.gather(
  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.gather(
  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.gather(
  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.gather(
  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. # get current time
  350. current_time, _ = self.loop.run_until_complete(
  351. self.testvm1.run_for_stdio('date -u +%s'))
  352. self.assertAlmostEquals(int(vm_time), int(current_time), delta=30)
  353. dom0_time = subprocess.check_output(['date', '-u', '+%s'])
  354. self.assertAlmostEquals(int(dom0_time), int(current_time), delta=30)
  355. except:
  356. # reset time to some approximation of the real time
  357. subprocess.Popen(
  358. ["sudo", "date", "-u", "-s", "@" + start_time.decode()])
  359. raise
  360. finally:
  361. self.app.clockvm = None
  362. def wait_for_pulseaudio_startup(self, vm):
  363. self.loop.run_until_complete(
  364. self.wait_for_session(self.testvm1))
  365. try:
  366. self.loop.run_until_complete(vm.run_for_stdio(
  367. "timeout 30s sh -c 'while ! pactl info; do sleep 1; done'"
  368. ))
  369. except subprocess.CalledProcessError as e:
  370. self.fail('Timeout waiting for pulseaudio start in {}: {}{}'.format(
  371. vm.name, e.stdout, e.stderr))
  372. # then wait for the stream to appear in dom0
  373. local_user = grp.getgrnam('qubes').gr_mem[0]
  374. p = self.loop.run_until_complete(asyncio.create_subprocess_shell(
  375. "sudo -E -u {} timeout 60s sh -c '"
  376. "while ! pactl list sink-inputs | grep -q :{}; do sleep 1; done'"
  377. .format(local_user, vm.name)))
  378. self.loop.run_until_complete(p.wait())
  379. # and some more...
  380. self.loop.run_until_complete(asyncio.sleep(1))
  381. def prepare_audio_vm(self):
  382. if 'whonix-gw' in self.template:
  383. self.skipTest('whonix-gw have no audio')
  384. self.loop.run_until_complete(self.testvm1.start())
  385. try:
  386. self.loop.run_until_complete(
  387. self.testvm1.run_for_stdio('which parecord'))
  388. except subprocess.CalledProcessError:
  389. self.skipTest('pulseaudio-utils not installed in VM')
  390. self.wait_for_pulseaudio_startup(self.testvm1)
  391. def check_audio_sample(self, sample, sfreq):
  392. rec = np.fromstring(sample, dtype=np.float32)
  393. # determine sample size using silence threshold
  394. threshold = 10**-3
  395. rec_size = np.count_nonzero((rec > threshold) | (rec < -threshold))
  396. if not rec_size:
  397. self.fail('only silence detected, no useful audio data')
  398. # find zero crossings
  399. crossings = np.nonzero((rec[1:] > threshold) &
  400. (rec[:-1] < -threshold))[0]
  401. np.seterr('raise')
  402. # compare against sine wave frequency
  403. rec_freq = 44100/np.mean(np.diff(crossings))
  404. if not sfreq*0.8 < rec_freq < sfreq*1.2:
  405. self.fail('frequency {} not in specified range'
  406. .format(rec_freq))
  407. def common_audio_playback(self):
  408. # sine frequency
  409. sfreq = 4400
  410. # generate signal
  411. audio_in = np.sin(2*np.pi*np.arange(44100)*sfreq/44100)
  412. self.loop.run_until_complete(
  413. self.testvm1.run_for_stdio('cat > audio_in.raw',
  414. input=audio_in.astype(np.float32).tobytes()))
  415. local_user = grp.getgrnam('qubes').gr_mem[0]
  416. with tempfile.NamedTemporaryFile() as recorded_audio:
  417. os.chmod(recorded_audio.name, 0o666)
  418. # FIXME: -d 0 assumes only one audio device
  419. p = subprocess.Popen(['sudo', '-E', '-u', local_user,
  420. 'parecord', '-d', '0', '--raw',
  421. '--format=float32le', '--rate=44100', '--channels=1',
  422. recorded_audio.name], stdout=subprocess.PIPE)
  423. try:
  424. self.loop.run_until_complete(
  425. self.testvm1.run_for_stdio(
  426. 'paplay --format=float32le --rate=44100 \
  427. --channels=1 --raw audio_in.raw'))
  428. except subprocess.CalledProcessError as err:
  429. self.fail('{} stderr: {}'.format(str(err), err.stderr))
  430. # wait for possible parecord buffering
  431. self.loop.run_until_complete(asyncio.sleep(1))
  432. p.terminate()
  433. # for some reason sudo do not relay SIGTERM sent above
  434. subprocess.check_call(['pkill', 'parecord'])
  435. p.wait()
  436. self.check_audio_sample(recorded_audio.file.read(), sfreq)
  437. def _configure_audio_recording(self, vm):
  438. '''Connect VM's output-source to sink monitor instead of mic'''
  439. local_user = grp.getgrnam('qubes').gr_mem[0]
  440. sudo = ['sudo', '-E', '-u', local_user]
  441. source_outputs = subprocess.check_output(
  442. sudo + ['pacmd', 'list-source-outputs']).decode()
  443. last_index = None
  444. found = False
  445. for line in source_outputs.splitlines():
  446. if line.startswith(' index: '):
  447. last_index = line.split(':')[1].strip()
  448. elif line.startswith('\t\tapplication.name = '):
  449. app_name = line.split('=')[1].strip('" ')
  450. if vm.name == app_name:
  451. found = True
  452. break
  453. if not found:
  454. self.fail('source-output for VM {} not found'.format(vm.name))
  455. subprocess.check_call(sudo +
  456. ['pacmd', 'move-source-output', last_index, '0'])
  457. def common_audio_record_muted(self):
  458. # connect VM's recording source output monitor (instead of mic)
  459. self._configure_audio_recording(self.testvm1)
  460. # generate some "audio" data
  461. audio_in = b'\x20' * 44100
  462. local_user = grp.getgrnam('qubes').gr_mem[0]
  463. record = self.loop.run_until_complete(
  464. self.testvm1.run('parecord --raw audio_rec.raw'))
  465. # give it time to start recording
  466. self.loop.run_until_complete(asyncio.sleep(0.5))
  467. p = subprocess.Popen(['sudo', '-E', '-u', local_user,
  468. 'paplay', '--raw'],
  469. stdin=subprocess.PIPE)
  470. p.communicate(audio_in)
  471. # wait for possible parecord buffering
  472. self.loop.run_until_complete(asyncio.sleep(1))
  473. self.loop.run_until_complete(
  474. self.testvm1.run_for_stdio('pkill parecord'))
  475. self.loop.run_until_complete(record.wait())
  476. recorded_audio, _ = self.loop.run_until_complete(
  477. self.testvm1.run_for_stdio('cat audio_rec.raw'))
  478. # should be empty or silence, so check just a little fragment
  479. if audio_in[:32] in recorded_audio:
  480. self.fail('VM recorded something, even though mic disabled')
  481. def common_audio_record_unmuted(self):
  482. deva = qubes.devices.DeviceAssignment(self.app.domains[0], 'mic')
  483. self.loop.run_until_complete(
  484. self.testvm1.devices['mic'].attach(deva))
  485. # connect VM's recording source output monitor (instead of mic)
  486. self._configure_audio_recording(self.testvm1)
  487. sfreq = 4400
  488. audio_in = np.sin(2*np.pi*np.arange(44100)*sfreq/44100)
  489. local_user = grp.getgrnam('qubes').gr_mem[0]
  490. record = self.loop.run_until_complete(self.testvm1.run(
  491. 'parecord --raw --format=float32le --rate=44100 \
  492. --channels=1 audio_rec.raw'))
  493. # give it time to start recording
  494. self.loop.run_until_complete(asyncio.sleep(0.5))
  495. p = subprocess.Popen(['sudo', '-E', '-u', local_user,
  496. 'paplay', '--raw', '--format=float32le',
  497. '--rate=44100', '--channels=1'],
  498. stdin=subprocess.PIPE)
  499. p.communicate(audio_in.astype(np.float32).tobytes())
  500. # wait for possible parecord buffering
  501. self.loop.run_until_complete(asyncio.sleep(1))
  502. self.loop.run_until_complete(
  503. self.testvm1.run_for_stdio('pkill parecord || :'))
  504. _, record_stderr = self.loop.run_until_complete(record.communicate())
  505. if record_stderr:
  506. self.fail('parecord printed something on stderr: {}'.format(
  507. record_stderr))
  508. recorded_audio, _ = self.loop.run_until_complete(
  509. self.testvm1.run_for_stdio('cat audio_rec.raw'))
  510. self.check_audio_sample(recorded_audio, sfreq)
  511. @unittest.skipUnless(spawn.find_executable('parecord'),
  512. "pulseaudio-utils not installed in dom0")
  513. def test_220_audio_play(self):
  514. self.prepare_audio_vm()
  515. self.common_audio_playback()
  516. @unittest.skipUnless(spawn.find_executable('parecord'),
  517. "pulseaudio-utils not installed in dom0")
  518. def test_221_audio_rec_muted(self):
  519. self.prepare_audio_vm()
  520. self.common_audio_record_muted()
  521. @unittest.skipUnless(spawn.find_executable('parecord'),
  522. "pulseaudio-utils not installed in dom0")
  523. def test_222_audio_rec_unmuted(self):
  524. self.prepare_audio_vm()
  525. self.common_audio_record_unmuted()
  526. @unittest.skipUnless(spawn.find_executable('parecord'),
  527. "pulseaudio-utils not installed in dom0")
  528. def test_223_audio_play_hvm(self):
  529. self.testvm1.virt_mode = 'hvm'
  530. self.testvm1.features['audio-model'] = 'ich6'
  531. self.prepare_audio_vm()
  532. self.loop.run_until_complete(
  533. self.testvm1.run_for_stdio('pacmd unload-module module-vchan-sink'))
  534. self.common_audio_playback()
  535. @unittest.skipUnless(spawn.find_executable('parecord'),
  536. "pulseaudio-utils not installed in dom0")
  537. def test_224_audio_rec_muted_hvm(self):
  538. self.testvm1.virt_mode = 'hvm'
  539. self.testvm1.features['audio-model'] = 'ich6'
  540. self.prepare_audio_vm()
  541. self.loop.run_until_complete(
  542. self.testvm1.run_for_stdio('pacmd unload-module module-vchan-sink'))
  543. self.common_audio_record_muted()
  544. @unittest.skipUnless(spawn.find_executable('parecord'),
  545. "pulseaudio-utils not installed in dom0")
  546. def test_225_audio_rec_unmuted_hvm(self):
  547. self.testvm1.virt_mode = 'hvm'
  548. self.testvm1.features['audio-model'] = 'ich6'
  549. self.prepare_audio_vm()
  550. self.loop.run_until_complete(
  551. self.testvm1.run_for_stdio('pacmd set-sink-volume 1 0x10000'))
  552. self.loop.run_until_complete(
  553. self.testvm1.run_for_stdio('pacmd unload-module module-vchan-sink'))
  554. self.common_audio_record_unmuted()
  555. def test_250_resize_private_img(self):
  556. """
  557. Test private.img resize, both offline and online
  558. :return:
  559. """
  560. # First offline test
  561. self.loop.run_until_complete(
  562. self.testvm1.storage.resize('private', 4*1024**3))
  563. self.loop.run_until_complete(self.testvm1.start())
  564. df_cmd = '( df --output=size /rw || df /rw | awk \'{print $2}\' )|' \
  565. 'tail -n 1'
  566. # new_size in 1k-blocks
  567. new_size, _ = self.loop.run_until_complete(
  568. self.testvm1.run_for_stdio(df_cmd))
  569. # some safety margin for FS metadata
  570. self.assertGreater(int(new_size.strip()), 3.8*1024**2)
  571. # Then online test
  572. self.loop.run_until_complete(
  573. self.testvm1.storage.resize('private', 6*1024**3))
  574. # new_size in 1k-blocks
  575. new_size, _ = self.loop.run_until_complete(
  576. self.testvm1.run_for_stdio(df_cmd))
  577. # some safety margin for FS metadata
  578. self.assertGreater(int(new_size.strip()), 5.7*1024**2)
  579. @unittest.skipUnless(spawn.find_executable('xdotool'),
  580. "xdotool not installed")
  581. def test_300_bug_1028_gui_memory_pinning(self):
  582. """
  583. If VM window composition buffers are relocated in memory, GUI will
  584. still use old pointers and will display old pages
  585. :return:
  586. """
  587. # this test does too much asynchronous operations,
  588. # so let's rewrite it as a coroutine and call it as such
  589. return self.loop.run_until_complete(
  590. self._test_300_bug_1028_gui_memory_pinning())
  591. @asyncio.coroutine
  592. def _test_300_bug_1028_gui_memory_pinning(self):
  593. self.testvm1.memory = 800
  594. self.testvm1.maxmem = 800
  595. # exclude from memory balancing
  596. self.testvm1.features['service.meminfo-writer'] = False
  597. yield from self.testvm1.start()
  598. yield from self.wait_for_session(self.testvm1)
  599. # and allow large map count
  600. yield from self.testvm1.run('echo 256000 > /proc/sys/vm/max_map_count',
  601. user="root")
  602. allocator_c = '''
  603. #include <sys/mman.h>
  604. #include <stdlib.h>
  605. #include <stdio.h>
  606. int main(int argc, char **argv) {
  607. int total_pages;
  608. char *addr, *iter;
  609. total_pages = atoi(argv[1]);
  610. addr = mmap(NULL, total_pages * 0x1000, PROT_READ | PROT_WRITE,
  611. MAP_ANONYMOUS | MAP_PRIVATE | MAP_POPULATE, -1, 0);
  612. if (addr == MAP_FAILED) {
  613. perror("mmap");
  614. exit(1);
  615. }
  616. printf("Stage1\\n");
  617. fflush(stdout);
  618. getchar();
  619. for (iter = addr; iter < addr + total_pages*0x1000; iter += 0x2000) {
  620. if (mlock(iter, 0x1000) == -1) {
  621. perror("mlock");
  622. fprintf(stderr, "%d of %d\\n", (iter-addr)/0x1000, total_pages);
  623. exit(1);
  624. }
  625. }
  626. printf("Stage2\\n");
  627. fflush(stdout);
  628. for (iter = addr+0x1000; iter < addr + total_pages*0x1000; iter += 0x2000) {
  629. if (munmap(iter, 0x1000) == -1) {
  630. perror(\"munmap\");
  631. exit(1);
  632. }
  633. }
  634. printf("Stage3\\n");
  635. fflush(stdout);
  636. fclose(stdout);
  637. getchar();
  638. return 0;
  639. }
  640. '''
  641. yield from self.testvm1.run_for_stdio('cat > allocator.c',
  642. input=allocator_c.encode())
  643. try:
  644. yield from self.testvm1.run_for_stdio(
  645. 'gcc allocator.c -o allocator')
  646. except subprocess.CalledProcessError as e:
  647. self.skipTest('allocator compile failed: {}'.format(e.stderr))
  648. # drop caches to have even more memory pressure
  649. yield from self.testvm1.run_for_stdio(
  650. 'echo 3 > /proc/sys/vm/drop_caches', user='root')
  651. # now fragment all free memory
  652. stdout, _ = yield from self.testvm1.run_for_stdio(
  653. "grep ^MemFree: /proc/meminfo|awk '{print $2}'")
  654. memory_pages = int(stdout) // 4 # 4k pages
  655. alloc1 = yield from self.testvm1.run(
  656. 'ulimit -l unlimited; exec /home/user/allocator {}'.format(
  657. memory_pages),
  658. user="root",
  659. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  660. stderr=subprocess.PIPE)
  661. # wait for memory being allocated; can't use just .read(), because EOF
  662. # passing is unreliable while the process is still running
  663. alloc1.stdin.write(b'\n')
  664. yield from alloc1.stdin.drain()
  665. try:
  666. alloc_out = yield from alloc1.stdout.readexactly(
  667. len('Stage1\nStage2\nStage3\n'))
  668. except asyncio.IncompleteReadError as e:
  669. alloc_out = e.partial
  670. if b'Stage3' not in alloc_out:
  671. # read stderr only in case of failed assert (), but still have nice
  672. # failure message (don't use self.fail() directly)
  673. #
  674. # stderr isn't always read, because on not-failed run, the process
  675. # is still running, so stderr.read() will wait (indefinitely).
  676. self.assertIn(b'Stage3', alloc_out,
  677. (yield from alloc1.stderr.read()))
  678. # now, launch some window - it should get fragmented composition buffer
  679. # it is important to have some changing content there, to generate
  680. # content update events (aka damage notify)
  681. proc = yield from self.testvm1.run(
  682. 'xterm -maximized -e top')
  683. if proc.returncode is not None:
  684. self.fail('xterm failed to start')
  685. # get window ID
  686. winid = yield from self.wait_for_window_coro(
  687. self.testvm1.name + ':xterm',
  688. search_class=True)
  689. xprop = yield from asyncio.get_event_loop().run_in_executor(None,
  690. subprocess.check_output,
  691. ['xprop', '-notype', '-id', winid, '_QUBES_VMWINDOWID'])
  692. vm_winid = xprop.decode().strip().split(' ')[4]
  693. # now free the fragmented memory and trigger compaction
  694. alloc1.stdin.write(b'\n')
  695. yield from alloc1.stdin.drain()
  696. yield from alloc1.wait()
  697. yield from self.testvm1.run_for_stdio(
  698. 'echo 1 > /proc/sys/vm/compact_memory', user='root')
  699. # now window may be already "broken"; to be sure, allocate (=zero)
  700. # some memory
  701. alloc2 = yield from self.testvm1.run(
  702. 'ulimit -l unlimited; /home/user/allocator {}'.format(memory_pages),
  703. user='root', stdout=subprocess.PIPE)
  704. yield from alloc2.stdout.read(len('Stage1\n'))
  705. # wait for damage notify - top updates every 3 sec by default
  706. yield from asyncio.sleep(6)
  707. # stop changing the window content
  708. subprocess.check_call(['xdotool', 'key', '--window', winid, 'd'])
  709. # now take screenshot of the window, from dom0 and VM
  710. # choose pnm format, as it doesn't have any useless metadata - easy
  711. # to compare
  712. vm_image, _ = yield from self.testvm1.run_for_stdio(
  713. 'import -window {} pnm:-'.format(vm_winid))
  714. dom0_image = yield from asyncio.get_event_loop().run_in_executor(None,
  715. subprocess.check_output, ['import', '-window', winid, 'pnm:-'])
  716. if vm_image != dom0_image:
  717. self.fail("Dom0 window doesn't match VM window content")
  718. class TC_10_Generic(qubes.tests.SystemTestCase):
  719. def setUp(self):
  720. super(TC_10_Generic, self).setUp()
  721. self.init_default_template()
  722. self.vm = self.app.add_new_vm(
  723. qubes.vm.appvm.AppVM,
  724. name=self.make_vm_name('vm'),
  725. label='red',
  726. template=self.app.default_template)
  727. self.loop.run_until_complete(self.vm.create_on_disk())
  728. self.app.save()
  729. self.vm = self.app.domains[self.vm.qid]
  730. def test_000_anyvm_deny_dom0(self):
  731. '''$anyvm in policy should not match dom0'''
  732. policy = open("/etc/qubes-rpc/policy/test.AnyvmDeny", "w")
  733. policy.write("%s $anyvm allow" % (self.vm.name,))
  734. policy.close()
  735. self.addCleanup(os.unlink, "/etc/qubes-rpc/policy/test.AnyvmDeny")
  736. flagfile = '/tmp/test-anyvmdeny-flag'
  737. if os.path.exists(flagfile):
  738. os.remove(flagfile)
  739. self.create_local_file('/etc/qubes-rpc/test.AnyvmDeny',
  740. 'touch {}\necho service output\n'.format(flagfile))
  741. self.loop.run_until_complete(self.vm.start())
  742. with self.qrexec_policy('test.AnyvmDeny', self.vm, '$anyvm'):
  743. with self.assertRaises(subprocess.CalledProcessError,
  744. msg='$anyvm matched dom0') as e:
  745. self.loop.run_until_complete(
  746. self.vm.run_for_stdio(
  747. '/usr/lib/qubes/qrexec-client-vm dom0 test.AnyvmDeny'))
  748. stdout = e.exception.output
  749. stderr = e.exception.stderr
  750. self.assertFalse(os.path.exists(flagfile),
  751. 'Flag file created (service was run) even though should be denied,'
  752. ' qrexec-client-vm output: {} {}'.format(stdout, stderr))
  753. def create_testcases_for_templates():
  754. return qubes.tests.create_testcases_for_templates('TC_00_AppVM',
  755. TC_00_AppVMMixin, qubes.tests.SystemTestCase,
  756. module=sys.modules[__name__])
  757. def load_tests(loader, tests, pattern):
  758. tests.addTests(loader.loadTestsFromNames(
  759. create_testcases_for_templates()))
  760. return tests
  761. qubes.tests.maybe_create_testcases_on_import(create_testcases_for_templates)