dom0_update.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2015 Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; either version 2
  11. # of the License, or (at your option) any later version.
  12. #
  13. # This program 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
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
  21. # USA.
  22. #
  23. import os
  24. import shutil
  25. import subprocess
  26. import tempfile
  27. import unittest
  28. import qubes
  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(qubes.tests.SystemTestsMixin):
  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. '--setopt=test.copy_local=1']
  40. update_flag_path = '/var/lib/qubes/updates/dom0-updates-available'
  41. @classmethod
  42. def generate_key(cls, keydir):
  43. gpg_opts = ['gpg', '--quiet', '--no-default-keyring',
  44. '--homedir', keydir]
  45. p = subprocess.Popen(gpg_opts + ['--gen-key', '--batch'],
  46. stdin=subprocess.PIPE,
  47. stderr=open(os.devnull, 'w'))
  48. p.stdin.write('''
  49. Key-Type: RSA
  50. Key-Length: 1024
  51. Key-Usage: sign
  52. Name-Real: Qubes test
  53. Expire-Date: 0
  54. %commit
  55. '''.format(keydir=keydir))
  56. p.stdin.close()
  57. p.wait()
  58. subprocess.check_call(gpg_opts + ['-a', '--export',
  59. '--output', os.path.join(keydir, 'pubkey.asc')])
  60. p = subprocess.Popen(gpg_opts + ['--with-colons', '--list-keys'],
  61. stdout=subprocess.PIPE)
  62. for line in p.stdout.readlines():
  63. fields = line.split(':')
  64. if fields[0] == 'pub':
  65. return fields[4][-8:].lower()
  66. raise RuntimeError
  67. @classmethod
  68. def setUpClass(cls):
  69. super(TC_00_Dom0UpgradeMixin, cls).setUpClass()
  70. cls.tmpdir = tempfile.mkdtemp()
  71. cls.keyid = cls.generate_key(cls.tmpdir)
  72. p = subprocess.Popen(['sudo', 'dd',
  73. 'status=none', 'of=/etc/yum.repos.d/test.repo'],
  74. stdin=subprocess.PIPE)
  75. p.stdin.write('''
  76. [test]
  77. name = Test
  78. baseurl = file:///tmp/repo
  79. enabled = 1
  80. ''')
  81. p.stdin.close()
  82. p.wait()
  83. @classmethod
  84. def tearDownClass(cls):
  85. subprocess.check_call(['sudo', 'rm', '-f',
  86. '/etc/yum.repos.d/test.repo'])
  87. shutil.rmtree(cls.tmpdir)
  88. def setUp(self):
  89. super(TC_00_Dom0UpgradeMixin, self).setUp()
  90. self.init_default_template(self.template)
  91. self.updatevm = self.app.add_new_vm(
  92. qubes.vm.appvm.AppVM,
  93. name=self.make_vm_name("updatevm"),
  94. label='red'
  95. )
  96. self.updatevm.create_on_disk()
  97. self.app.updatevm = self.updatevm
  98. self.app.save()
  99. subprocess.call(['sudo', 'rpm', '-e', self.pkg_name],
  100. stderr=open(os.devnull, 'w'))
  101. subprocess.check_call(['sudo', 'rpm', '--import',
  102. os.path.join(self.tmpdir, 'pubkey.asc')])
  103. self.updatevm.start()
  104. def tearDown(self):
  105. super(TC_00_Dom0UpgradeMixin, self).tearDown()
  106. subprocess.call(['sudo', 'rpm', '-e', self.pkg_name], stderr=open(
  107. os.devnull, 'w'))
  108. subprocess.call(['sudo', 'rpm', '-e', 'gpg-pubkey-{}'.format(
  109. self.keyid)], stderr=open(os.devnull, 'w'))
  110. for pkg in os.listdir(self.tmpdir):
  111. if pkg.endswith('.rpm'):
  112. os.unlink(pkg)
  113. def create_pkg(self, dir, name, version):
  114. spec_path = os.path.join(dir, name+'.spec')
  115. spec = open(spec_path, 'w')
  116. spec.write(
  117. '''
  118. Name: {name}
  119. Summary: Test Package
  120. Version: {version}
  121. Release: 1
  122. Vendor: Invisible Things Lab
  123. License: GPL
  124. Group: Qubes
  125. URL: http://www.qubes-os.org
  126. %description
  127. Test package
  128. %install
  129. %files
  130. '''.format(name=name, version=version)
  131. )
  132. spec.close()
  133. subprocess.check_call(
  134. ['rpmbuild', '--quiet', '-bb', '--define', '_rpmdir {}'.format(dir),
  135. spec_path])
  136. pkg_path = os.path.join(dir, 'x86_64',
  137. '{}-{}-1.x86_64.rpm'.format(name, version))
  138. subprocess.check_call(['sudo', 'chmod', 'go-rw', '/dev/tty'])
  139. subprocess.check_call(
  140. ['rpm', '--quiet', '--define=_gpg_path {}'.format(dir),
  141. '--define=_gpg_name {}'.format("Qubes test"),
  142. '--addsign', pkg_path],
  143. stdin=open(os.devnull),
  144. stdout=open(os.devnull, 'w'),
  145. stderr=subprocess.STDOUT)
  146. subprocess.check_call(['sudo', 'chmod', 'go+rw', '/dev/tty'])
  147. return pkg_path
  148. def send_pkg(self, filename):
  149. p = self.updatevm.run('mkdir -p /tmp/repo; cat > /tmp/repo/{}'.format(
  150. os.path.basename(
  151. filename)), passio_popen=True)
  152. p.stdin.write(open(filename).read())
  153. p.stdin.close()
  154. p.wait()
  155. retcode = self.updatevm.run('cd /tmp/repo; createrepo .', wait=True)
  156. if retcode == 127:
  157. self.skipTest("createrepo not installed in template {}".format(
  158. self.template))
  159. elif retcode != 0:
  160. self.skipTest("createrepo failed with code {}, cannot perform the "
  161. "test".format(retcode))
  162. def test_000_update(self):
  163. """Dom0 update tests
  164. Check if package update is:
  165. - detected
  166. - installed
  167. - "updates pending" flag is cleared
  168. """
  169. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  170. subprocess.check_call(['sudo', 'rpm', '-i', filename])
  171. filename = self.create_pkg(self.tmpdir, self.pkg_name, '2.0')
  172. self.send_pkg(filename)
  173. open(self.update_flag_path, 'a').close()
  174. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  175. try:
  176. subprocess.check_call(['sudo', '-E', 'qubes-dom0-update', '-y'] +
  177. self.dom0_update_common_opts,
  178. stdout=open(logpath, 'w'),
  179. stderr=subprocess.STDOUT)
  180. except subprocess.CalledProcessError:
  181. self.fail("qubes-dom0-update failed: " + open(
  182. logpath).read())
  183. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  184. self.pkg_name)], stdout=open(os.devnull, 'w'))
  185. self.assertEqual(retcode, 1, 'Package {}-1.0 still installed after '
  186. 'update'.format(self.pkg_name))
  187. retcode = subprocess.call(['rpm', '-q', '{}-2.0'.format(
  188. self.pkg_name)], stdout=open(os.devnull, 'w'))
  189. self.assertEqual(retcode, 0, 'Package {}-2.0 not installed after '
  190. 'update'.format(self.pkg_name))
  191. self.assertFalse(os.path.exists(self.update_flag_path),
  192. "'updates pending' flag not cleared")
  193. def test_005_update_flag_clear(self):
  194. """Check if 'updates pending' flag is creared"""
  195. # create any pkg (but not install it) to initialize repo in the VM
  196. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  197. self.send_pkg(filename)
  198. open(self.update_flag_path, 'a').close()
  199. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  200. try:
  201. subprocess.check_call(['sudo', 'qubes-dom0-update', '-y'] +
  202. self.dom0_update_common_opts,
  203. stdout=open(logpath, 'w'),
  204. stderr=subprocess.STDOUT)
  205. except subprocess.CalledProcessError:
  206. self.fail("qubes-dom0-update failed: " + open(
  207. logpath).read())
  208. with open(logpath) as f:
  209. dom0_update_output = f.read()
  210. self.assertFalse('Errno' in dom0_update_output or
  211. 'Couldn\'t' in dom0_update_output,
  212. "qubes-dom0-update reported an error: {}".
  213. format(dom0_update_output))
  214. self.assertFalse(os.path.exists(self.update_flag_path),
  215. "'updates pending' flag not cleared")
  216. def test_006_update_flag_clear(self):
  217. """Check if 'updates pending' flag is creared, using --clean"""
  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. # remove also repodata to test #1685
  223. shutil.rmtree('/var/lib/qubes/updates/repodata')
  224. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  225. try:
  226. subprocess.check_call(['sudo', 'qubes-dom0-update', '-y',
  227. '--clean'] +
  228. self.dom0_update_common_opts,
  229. stdout=open(logpath, 'w'),
  230. stderr=subprocess.STDOUT)
  231. except subprocess.CalledProcessError:
  232. self.fail("qubes-dom0-update failed: " + open(
  233. logpath).read())
  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_010_instal(self):
  243. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  244. self.send_pkg(filename)
  245. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  246. try:
  247. subprocess.check_call(['sudo', '-E', 'qubes-dom0-update', '-y'] +
  248. self.dom0_update_common_opts + [
  249. self.pkg_name],
  250. stdout=open(logpath, 'w'),
  251. stderr=subprocess.STDOUT)
  252. except subprocess.CalledProcessError:
  253. self.fail("qubes-dom0-update failed: " + open(
  254. logpath).read())
  255. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  256. self.pkg_name)], stdout=open('/dev/null', 'w'))
  257. self.assertEqual(retcode, 0, 'Package {}-1.0 not installed'.format(
  258. self.pkg_name))
  259. def test_020_install_wrong_sign(self):
  260. subprocess.call(['sudo', 'rpm', '-e', 'gpg-pubkey-{}'.format(
  261. self.keyid)])
  262. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  263. self.send_pkg(filename)
  264. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  265. try:
  266. subprocess.check_call(['sudo', '-E', 'qubes-dom0-update', '-y'] +
  267. self.dom0_update_common_opts + [
  268. self.pkg_name],
  269. stdout=open(logpath, 'w'),
  270. stderr=subprocess.STDOUT)
  271. self.fail("qubes-dom0-update unexpectedly succeeded: " + open(
  272. logpath).read())
  273. except subprocess.CalledProcessError:
  274. pass
  275. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  276. self.pkg_name)], stdout=open('/dev/null', 'w'))
  277. self.assertEqual(retcode, 1,
  278. 'Package {}-1.0 installed although '
  279. 'signature is invalid'.format(self.pkg_name))
  280. def test_030_install_unsigned(self):
  281. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  282. subprocess.check_call(['rpm', '--delsign', filename],
  283. stdout=open(os.devnull, 'w'),
  284. stderr=subprocess.STDOUT)
  285. self.send_pkg(filename)
  286. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  287. try:
  288. subprocess.check_call(['sudo', '-E', 'qubes-dom0-update', '-y'] +
  289. self.dom0_update_common_opts +
  290. [self.pkg_name],
  291. stdout=open(logpath, 'w'),
  292. stderr=subprocess.STDOUT
  293. )
  294. self.fail("qubes-dom0-update unexpectedly succeeded: " + open(
  295. logpath).read())
  296. except subprocess.CalledProcessError:
  297. pass
  298. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  299. self.pkg_name)], stdout=open('/dev/null', 'w'))
  300. self.assertEqual(retcode, 1,
  301. 'UNSIGNED package {}-1.0 installed'.format(self.pkg_name))
  302. def load_tests(loader, tests, pattern):
  303. try:
  304. app = qubes.Qubes()
  305. templates = [vm.name for vm in app.domains if
  306. isinstance(vm, qubes.vm.templatevm.TemplateVM)]
  307. except OSError:
  308. templates = []
  309. for template in templates:
  310. tests.addTests(loader.loadTestsFromTestCase(
  311. type(
  312. 'TC_00_Dom0Upgrade_' + template,
  313. (TC_00_Dom0UpgradeMixin, qubes.tests.QubesTestCase),
  314. {'template': template})))
  315. return tests