dom0_update.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. #
  2. # The Qubes OS Project, http://www.qubes-os.org
  3. #
  4. # Copyright (C) 2015 Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  5. #
  6. # This library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  18. # USA.
  19. #
  20. import asyncio
  21. import os
  22. import shutil
  23. import subprocess
  24. import sys
  25. import tempfile
  26. import unittest
  27. import qubes
  28. import qubes.tests
  29. VM_PREFIX = "test-"
  30. @unittest.skipUnless(os.path.exists('/usr/bin/rpmsign') and
  31. os.path.exists('/usr/bin/rpmbuild'),
  32. 'rpm-sign and/or rpm-build not installed')
  33. class TC_00_Dom0UpgradeMixin(object):
  34. """
  35. Tests for downloading dom0 updates using VMs based on different templates
  36. """
  37. pkg_name = 'qubes-test-pkg'
  38. dom0_update_common_opts = ['--disablerepo=*', '--enablerepo=test']
  39. update_flag_path = '/var/lib/qubes/updates/dom0-updates-available'
  40. @classmethod
  41. def generate_key(cls, keydir):
  42. gpg_opts = ['gpg', '--quiet', '--no-default-keyring',
  43. '--homedir', keydir]
  44. p = subprocess.Popen(gpg_opts + ['--gen-key', '--batch'],
  45. stdin=subprocess.PIPE,
  46. stderr=open(os.devnull, 'w'))
  47. p.stdin.write('''
  48. Key-Type: RSA
  49. Key-Length: 1024
  50. Key-Usage: sign
  51. Name-Real: Qubes test
  52. Expire-Date: 0
  53. %commit
  54. '''.format(keydir=keydir).encode())
  55. p.stdin.close()
  56. p.wait()
  57. subprocess.check_call(gpg_opts + ['-a', '--export',
  58. '--output', os.path.join(keydir, 'pubkey.asc')])
  59. p = subprocess.Popen(gpg_opts + ['--with-colons', '--list-keys'],
  60. stdout=subprocess.PIPE)
  61. for line in p.stdout.readlines():
  62. fields = line.decode().split(':')
  63. if fields[0] == 'pub':
  64. return fields[4][-8:].lower()
  65. raise RuntimeError
  66. @classmethod
  67. def setUpClass(cls):
  68. super(TC_00_Dom0UpgradeMixin, cls).setUpClass()
  69. cls.tmpdir = tempfile.mkdtemp()
  70. cls.keyid = cls.generate_key(cls.tmpdir)
  71. p = subprocess.Popen(['sudo', 'dd',
  72. 'status=none', 'of=/etc/yum.repos.d/test.repo'],
  73. stdin=subprocess.PIPE)
  74. p.stdin.write(b'''
  75. [test]
  76. name = Test
  77. baseurl = http://localhost:8080/
  78. enabled = 1
  79. ''')
  80. p.stdin.close()
  81. p.wait()
  82. @classmethod
  83. def tearDownClass(cls):
  84. subprocess.check_call(['sudo', 'rm', '-f',
  85. '/etc/yum.repos.d/test.repo'])
  86. shutil.rmtree(cls.tmpdir)
  87. def setUp(self):
  88. super(TC_00_Dom0UpgradeMixin, self).setUp()
  89. if self.template.startswith('whonix-'):
  90. # Whonix redirect all the traffic through tor, so repository
  91. # on http://localhost:8080/ is unavailable
  92. self.skipTest("Test not supported for this template")
  93. self.init_default_template(self.template)
  94. self.updatevm = self.app.add_new_vm(
  95. qubes.vm.appvm.AppVM,
  96. name=self.make_vm_name("updatevm"),
  97. label='red'
  98. )
  99. self.loop.run_until_complete(self.updatevm.create_on_disk())
  100. self.app.updatevm = self.updatevm
  101. self.app.save()
  102. subprocess.call(['sudo', 'rpm', '-e', self.pkg_name],
  103. stderr=subprocess.DEVNULL)
  104. subprocess.check_call(['sudo', 'rpm', '--import',
  105. os.path.join(self.tmpdir, 'pubkey.asc')])
  106. self.loop.run_until_complete(self.updatevm.start())
  107. self.repo_running = False
  108. self.repo_proc = None
  109. def tearDown(self):
  110. if self.repo_proc:
  111. self.repo_proc.terminate()
  112. self.loop.run_until_complete(self.repo_proc.wait())
  113. del self.repo_proc
  114. super(TC_00_Dom0UpgradeMixin, self).tearDown()
  115. subprocess.call(['sudo', 'rpm', '-e', self.pkg_name],
  116. stderr=subprocess.DEVNULL)
  117. subprocess.call(['sudo', 'rpm', '-e', 'gpg-pubkey-{}'.format(
  118. self.keyid)], stderr=subprocess.DEVNULL)
  119. for pkg in os.listdir(self.tmpdir):
  120. if pkg.endswith('.rpm'):
  121. os.unlink(pkg)
  122. def create_pkg(self, dir, name, version):
  123. spec_path = os.path.join(dir, name+'.spec')
  124. spec = open(spec_path, 'w')
  125. spec.write(
  126. '''
  127. Name: {name}
  128. Summary: Test Package
  129. Version: {version}
  130. Release: 1
  131. Vendor: Invisible Things Lab
  132. License: GPL
  133. Group: Qubes
  134. URL: http://www.qubes-os.org
  135. %description
  136. Test package
  137. %install
  138. %files
  139. '''.format(name=name, version=version)
  140. )
  141. spec.close()
  142. subprocess.check_call(
  143. ['rpmbuild', '--quiet', '-bb', '--define', '_rpmdir {}'.format(dir),
  144. spec_path])
  145. pkg_path = os.path.join(dir, 'x86_64',
  146. '{}-{}-1.x86_64.rpm'.format(name, version))
  147. subprocess.check_call(['sudo', 'chmod', 'go-rw', '/dev/tty'])
  148. subprocess.check_call(
  149. ['rpm', '--quiet', '--define=_gpg_path {}'.format(dir),
  150. '--define=_gpg_name {}'.format("Qubes test"),
  151. '--addsign', pkg_path],
  152. stdin=subprocess.DEVNULL,
  153. stdout=subprocess.DEVNULL,
  154. stderr=subprocess.STDOUT)
  155. subprocess.check_call(['sudo', 'chmod', 'go+rw', '/dev/tty'])
  156. return pkg_path
  157. def send_pkg(self, filename):
  158. with open(filename, 'rb') as f_pkg:
  159. self.loop.run_until_complete(self.updatevm.run_for_stdio(
  160. 'mkdir -p /tmp/repo; cat > /tmp/repo/{}'.format(
  161. os.path.basename(filename)),
  162. input=f_pkg.read()))
  163. try:
  164. self.loop.run_until_complete(
  165. self.updatevm.run_for_stdio('cd /tmp/repo; createrepo .'))
  166. except subprocess.CalledProcessError as e:
  167. if e.returncode == 127:
  168. self.skipTest('createrepo not installed in template {}'.format(
  169. self.template))
  170. else:
  171. self.skipTest('createrepo failed with code {}, '
  172. 'cannot perform the test'.format(e.returncode))
  173. self.start_repo()
  174. def start_repo(self):
  175. if self.repo_running:
  176. return
  177. self.repo_proc = self.loop.run_until_complete(self.updatevm.run(
  178. 'cd /tmp/repo && python -m SimpleHTTPServer 8080',
  179. stdout=subprocess.DEVNULL,
  180. stderr=subprocess.STDOUT))
  181. self.repo_running = True
  182. def test_000_update(self):
  183. """Dom0 update tests
  184. Check if package update is:
  185. - detected
  186. - installed
  187. - "updates pending" flag is cleared
  188. """
  189. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  190. subprocess.check_call(['sudo', 'rpm', '-i', filename])
  191. filename = self.create_pkg(self.tmpdir, self.pkg_name, '2.0')
  192. self.send_pkg(filename)
  193. open(self.update_flag_path, 'a').close()
  194. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  195. with open(logpath, 'w') as f_log:
  196. proc = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  197. 'qubes-dom0-update', '-y', *self.dom0_update_common_opts,
  198. stdout=f_log,
  199. stderr=subprocess.STDOUT))
  200. self.loop.run_until_complete(proc.wait())
  201. if proc.returncode:
  202. del proc
  203. with open(logpath) as f_log:
  204. self.fail("qubes-dom0-update failed: " + f_log.read())
  205. del proc
  206. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  207. self.pkg_name)], stdout=subprocess.DEVNULL)
  208. self.assertEqual(retcode, 1, 'Package {}-1.0 still installed after '
  209. 'update'.format(self.pkg_name))
  210. retcode = subprocess.call(['rpm', '-q', '{}-2.0'.format(
  211. self.pkg_name)], stdout=subprocess.DEVNULL)
  212. self.assertEqual(retcode, 0, 'Package {}-2.0 not installed after '
  213. 'update'.format(self.pkg_name))
  214. self.assertFalse(os.path.exists(self.update_flag_path),
  215. "'updates pending' flag not cleared")
  216. def test_005_update_flag_clear(self):
  217. """Check if 'updates pending' flag is creared"""
  218. # create any pkg (but not install it) to initialize repo in the VM
  219. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  220. self.send_pkg(filename)
  221. open(self.update_flag_path, 'a').close()
  222. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  223. with open(logpath, 'w') as f_log:
  224. proc = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  225. 'qubes-dom0-update', '-y', *self.dom0_update_common_opts,
  226. stdout=f_log,
  227. stderr=subprocess.STDOUT))
  228. self.loop.run_until_complete(proc.wait())
  229. if proc.returncode:
  230. del proc
  231. with open(logpath) as f_log:
  232. self.fail("qubes-dom0-update failed: " + f_log.read())
  233. del proc
  234. with open(logpath) as f:
  235. dom0_update_output = f.read()
  236. self.assertFalse('Errno' in dom0_update_output or
  237. 'Couldn\'t' in dom0_update_output,
  238. "qubes-dom0-update reported an error: {}".
  239. format(dom0_update_output))
  240. self.assertFalse(os.path.exists(self.update_flag_path),
  241. "'updates pending' flag not cleared")
  242. def test_006_update_flag_clear(self):
  243. """Check if 'updates pending' flag is creared, using --clean"""
  244. # create any pkg (but not install it) to initialize repo in the VM
  245. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  246. self.send_pkg(filename)
  247. open(self.update_flag_path, 'a').close()
  248. # remove also repodata to test #1685
  249. if os.path.exists('/var/lib/qubes/updates/repodata'):
  250. shutil.rmtree('/var/lib/qubes/updates/repodata')
  251. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  252. with open(logpath, 'w') as f_log:
  253. proc = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  254. 'qubes-dom0-update', '-y', '--clean',
  255. *self.dom0_update_common_opts,
  256. stdout=f_log,
  257. stderr=subprocess.STDOUT))
  258. self.loop.run_until_complete(proc.wait())
  259. if proc.returncode:
  260. del proc
  261. with open(logpath) as f_log:
  262. self.fail("qubes-dom0-update failed: " + f_log.read())
  263. del proc
  264. with open(logpath) as f:
  265. dom0_update_output = f.read()
  266. self.assertFalse('Errno' in dom0_update_output or
  267. 'Couldn\'t' in dom0_update_output,
  268. "qubes-dom0-update reported an error: {}".
  269. format(dom0_update_output))
  270. self.assertFalse(os.path.exists(self.update_flag_path),
  271. "'updates pending' flag not cleared")
  272. def test_010_instal(self):
  273. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  274. self.send_pkg(filename)
  275. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  276. with open(logpath, 'w') as f_log:
  277. proc = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  278. 'qubes-dom0-update', '-y', *self.dom0_update_common_opts,
  279. self.pkg_name,
  280. stdout=f_log,
  281. stderr=subprocess.STDOUT))
  282. self.loop.run_until_complete(proc.wait())
  283. if proc.returncode:
  284. del proc
  285. with open(logpath) as f_log:
  286. self.fail("qubes-dom0-update failed: " + f_log.read())
  287. del proc
  288. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  289. self.pkg_name)], stdout=open('/dev/null', 'w'))
  290. self.assertEqual(retcode, 0, 'Package {}-1.0 not installed'.format(
  291. self.pkg_name))
  292. def test_020_install_wrong_sign(self):
  293. subprocess.call(['sudo', 'rpm', '-e', 'gpg-pubkey-{}'.format(
  294. self.keyid)])
  295. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  296. self.send_pkg(filename)
  297. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  298. with open(logpath, 'w') as f_log:
  299. proc = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  300. 'qubes-dom0-update', '-y', *self.dom0_update_common_opts,
  301. self.pkg_name,
  302. stdout=f_log,
  303. stderr=subprocess.STDOUT))
  304. self.loop.run_until_complete(proc.wait())
  305. if not proc.returncode:
  306. del proc
  307. with open(logpath) as f_log:
  308. self.fail("qubes-dom0-update unexpectedly succeeded: " +
  309. f_log.read())
  310. del proc
  311. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  312. self.pkg_name)], stdout=subprocess.DEVNULL)
  313. self.assertEqual(retcode, 1,
  314. 'Package {}-1.0 installed although '
  315. 'signature is invalid'.format(self.pkg_name))
  316. def test_030_install_unsigned(self):
  317. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  318. subprocess.check_call(['rpm', '--delsign', filename],
  319. stdout=subprocess.DEVNULL,
  320. stderr=subprocess.STDOUT)
  321. self.send_pkg(filename)
  322. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  323. with open(logpath, 'w') as f_log:
  324. proc = self.loop.run_until_complete(asyncio.create_subprocess_exec(
  325. 'qubes-dom0-update', '-y', *self.dom0_update_common_opts,
  326. self.pkg_name,
  327. stdout=f_log,
  328. stderr=subprocess.STDOUT))
  329. self.loop.run_until_complete(proc.wait())
  330. if not proc.returncode:
  331. del proc
  332. with open(logpath) as f_log:
  333. self.fail("qubes-dom0-update unexpectedly succeeded: " +
  334. f_log.read())
  335. del proc
  336. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  337. self.pkg_name)], stdout=subprocess.DEVNULL)
  338. self.assertEqual(retcode, 1,
  339. 'UNSIGNED package {}-1.0 installed'.format(self.pkg_name))
  340. def load_tests(loader, tests, pattern):
  341. tests.addTests(loader.loadTestsFromNames(
  342. qubes.tests.create_testcases_for_templates('TC_00_Dom0Upgrade',
  343. TC_00_Dom0UpgradeMixin, qubes.tests.SystemTestCase,
  344. module=sys.modules[__name__])))
  345. return tests