dom0_update.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. from qubes.qubes import QubesVmCollection
  29. import qubes.qubes
  30. VM_PREFIX = "test-"
  31. @unittest.skipUnless(os.path.exists('/usr/bin/rpmsign') and
  32. os.path.exists('/usr/bin/rpmbuild'),
  33. 'rpm-sign and/or rpm-build not installed')
  34. class TC_00_Dom0UpgradeMixin(qubes.tests.SystemTestsMixin):
  35. """
  36. Tests for downloading dom0 updates using VMs based on different templates
  37. """
  38. pkg_name = 'qubes-test-pkg'
  39. dom0_update_common_opts = ['--disablerepo=*', '--enablerepo=test',
  40. '--setopt=test.copy_local=1']
  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.updatevm = self.qc.add_new_vm(
  91. "QubesProxyVm",
  92. name=self.make_vm_name("updatevm"),
  93. template=self.qc.get_vm_by_name(self.template))
  94. self.updatevm.create_on_disk(verbose=False)
  95. self.saved_updatevm = self.qc.get_updatevm_vm()
  96. self.qc.set_updatevm_vm(self.updatevm)
  97. self.qc.save()
  98. self.qc.unlock_db()
  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. self.qc.lock_db_for_writing()
  106. self.qc.load()
  107. self.qc.set_updatevm_vm(self.qc[self.saved_updatevm.qid])
  108. self.qc.save()
  109. super(TC_00_Dom0UpgradeMixin, self).tearDown()
  110. subprocess.call(['sudo', 'rpm', '-e', self.pkg_name], stderr=open(
  111. os.devnull, 'w'))
  112. subprocess.call(['sudo', 'rpm', '-e', 'gpg-pubkey-{}'.format(
  113. self.keyid)], stderr=open(os.devnull, 'w'))
  114. for pkg in os.listdir(self.tmpdir):
  115. if pkg.endswith('.rpm'):
  116. os.unlink(pkg)
  117. def create_pkg(self, dir, name, version):
  118. spec_path = os.path.join(dir, name+'.spec')
  119. spec = open(spec_path, 'w')
  120. spec.write(
  121. '''
  122. Name: {name}
  123. Summary: Test Package
  124. Version: {version}
  125. Release: 1
  126. Vendor: Invisible Things Lab
  127. License: GPL
  128. Group: Qubes
  129. URL: http://www.qubes-os.org
  130. %description
  131. Test package
  132. %install
  133. %files
  134. '''.format(name=name, version=version)
  135. )
  136. spec.close()
  137. subprocess.check_call(
  138. ['rpmbuild', '--quiet', '-bb', '--define', '_rpmdir {}'.format(dir),
  139. spec_path])
  140. pkg_path = os.path.join(dir, 'x86_64',
  141. '{}-{}-1.x86_64.rpm'.format(name, version))
  142. subprocess.check_call(['sudo', 'chmod', 'go-rw', '/dev/tty'])
  143. subprocess.check_call(
  144. ['rpm', '--quiet', '--define=_gpg_path {}'.format(dir),
  145. '--define=_gpg_name {}'.format("Qubes test"),
  146. '--addsign', pkg_path],
  147. stdin=open(os.devnull),
  148. stdout=open(os.devnull, 'w'),
  149. stderr=subprocess.STDOUT)
  150. subprocess.check_call(['sudo', 'chmod', 'go+rw', '/dev/tty'])
  151. return pkg_path
  152. def send_pkg(self, filename):
  153. p = self.updatevm.run('mkdir -p /tmp/repo; cat > /tmp/repo/{}'.format(
  154. os.path.basename(
  155. filename)), passio_popen=True)
  156. p.stdin.write(open(filename).read())
  157. p.stdin.close()
  158. p.wait()
  159. retcode = self.updatevm.run('cd /tmp/repo; createrepo .', wait=True)
  160. if retcode == 127:
  161. self.skipTest("createrepo not installed in template {}".format(
  162. self.template))
  163. elif retcode != 0:
  164. self.skipTest("createrepo failed with code {}, cannot perform the "
  165. "test".format(retcode))
  166. def test_000_update(self):
  167. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  168. subprocess.check_call(['sudo', 'rpm', '-i', filename])
  169. filename = self.create_pkg(self.tmpdir, self.pkg_name, '2.0')
  170. self.send_pkg(filename)
  171. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  172. try:
  173. subprocess.check_call(['sudo', 'qubes-dom0-update', '-y'] +
  174. self.dom0_update_common_opts,
  175. stdout=open(logpath, 'w'),
  176. stderr=subprocess.STDOUT)
  177. except subprocess.CalledProcessError:
  178. self.fail("qubes-dom0-update failed: " + open(
  179. logpath).read())
  180. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  181. self.pkg_name)], stdout=open(os.devnull, 'w'))
  182. self.assertEqual(retcode, 1, 'Package {}-1.0 still installed after '
  183. 'update'.format(self.pkg_name))
  184. retcode = subprocess.call(['rpm', '-q', '{}-2.0'.format(
  185. self.pkg_name)], stdout=open(os.devnull, 'w'))
  186. self.assertEqual(retcode, 0, 'Package {}-2.0 not installed after '
  187. 'update'.format(self.pkg_name))
  188. def test_010_instal(self):
  189. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  190. self.send_pkg(filename)
  191. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  192. try:
  193. subprocess.check_call(['sudo', 'qubes-dom0-update', '-y'] +
  194. self.dom0_update_common_opts + [
  195. self.pkg_name],
  196. stdout=open(logpath, 'w'),
  197. stderr=subprocess.STDOUT)
  198. except subprocess.CalledProcessError:
  199. self.fail("qubes-dom0-update failed: " + open(
  200. logpath).read())
  201. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  202. self.pkg_name)], stdout=open('/dev/null', 'w'))
  203. self.assertEqual(retcode, 0, 'Package {}-1.0 not installed'.format(
  204. self.pkg_name))
  205. def test_020_install_wrong_sign(self):
  206. subprocess.call(['sudo', 'rpm', '-e', 'gpg-pubkey-{}'.format(
  207. self.keyid)])
  208. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  209. self.send_pkg(filename)
  210. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  211. try:
  212. subprocess.check_call(['sudo', 'qubes-dom0-update', '-y'] +
  213. self.dom0_update_common_opts + [
  214. self.pkg_name],
  215. stdout=open(logpath, 'w'),
  216. stderr=subprocess.STDOUT)
  217. self.fail("qubes-dom0-update unexpectedly succeeded: " + open(
  218. logpath).read())
  219. except subprocess.CalledProcessError:
  220. pass
  221. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  222. self.pkg_name)], stdout=open('/dev/null', 'w'))
  223. self.assertEqual(retcode, 1,
  224. 'Package {}-1.0 installed although '
  225. 'signature is invalid'.format(self.pkg_name))
  226. def test_030_install_unsigned(self):
  227. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  228. subprocess.check_call(['rpm', '--delsign', filename],
  229. stdout=open(os.devnull, 'w'),
  230. stderr=subprocess.STDOUT)
  231. self.send_pkg(filename)
  232. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  233. try:
  234. subprocess.check_call(['sudo', 'qubes-dom0-update', '-y'] +
  235. self.dom0_update_common_opts +
  236. [self.pkg_name],
  237. stdout=open(logpath, 'w'),
  238. stderr=subprocess.STDOUT
  239. )
  240. self.fail("qubes-dom0-update unexpectedly succeeded: " + open(
  241. logpath).read())
  242. except subprocess.CalledProcessError:
  243. pass
  244. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  245. self.pkg_name)], stdout=open('/dev/null', 'w'))
  246. self.assertEqual(retcode, 1,
  247. 'UNSIGNED package {}-1.0 installed'.format(self.pkg_name))
  248. def load_tests(loader, tests, pattern):
  249. try:
  250. qc = qubes.qubes.QubesVmCollection()
  251. qc.lock_db_for_reading()
  252. qc.load()
  253. qc.unlock_db()
  254. templates = [vm.name for vm in qc.values() if
  255. isinstance(vm, qubes.qubes.QubesTemplateVm)]
  256. except OSError:
  257. templates = []
  258. for template in templates:
  259. tests.addTests(loader.loadTestsFromTestCase(
  260. type(
  261. 'TC_00_Dom0Upgrade_' + template,
  262. (TC_00_Dom0UpgradeMixin, qubes.tests.QubesTestCase),
  263. {'template': template})))
  264. return tests