dom0_update.py 15 KB

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