dom0_update.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. 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 = http://localhost:8080/
  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. if self.template.startswith('whonix-'):
  91. # Whonix redirect all the traffic through tor, so repository
  92. # on http://localhost:8080/ is unavailable
  93. self.skipTest("Test not supported for this template")
  94. self.updatevm = self.qc.add_new_vm(
  95. "QubesProxyVm",
  96. name=self.make_vm_name("updatevm"),
  97. template=self.qc.get_vm_by_name(self.template))
  98. self.updatevm.create_on_disk(verbose=False)
  99. self.saved_updatevm = self.qc.get_updatevm_vm()
  100. self.qc.set_updatevm_vm(self.updatevm)
  101. self.qc.save()
  102. self.qc.unlock_db()
  103. subprocess.call(['sudo', 'rpm', '-e', self.pkg_name],
  104. stderr=open(os.devnull, 'w'))
  105. subprocess.check_call(['sudo', 'rpm', '--import',
  106. os.path.join(self.tmpdir, 'pubkey.asc')])
  107. self.updatevm.start()
  108. self.repo_running = False
  109. def tearDown(self):
  110. self.qc.lock_db_for_writing()
  111. self.qc.load()
  112. self.qc.set_updatevm_vm(self.qc[self.saved_updatevm.qid])
  113. self.qc.save()
  114. super(TC_00_Dom0UpgradeMixin, self).tearDown()
  115. subprocess.call(['sudo', 'rpm', '-e', self.pkg_name], stderr=open(
  116. os.devnull, 'w'))
  117. subprocess.call(['sudo', 'rpm', '-e', 'gpg-pubkey-{}'.format(
  118. self.keyid)], stderr=open(os.devnull, 'w'))
  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=open(os.devnull),
  153. stdout=open(os.devnull, 'w'),
  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. p = self.updatevm.run('mkdir -p /tmp/repo; cat > /tmp/repo/{}'.format(
  159. os.path.basename(
  160. filename)), passio_popen=True)
  161. p.stdin.write(open(filename).read())
  162. p.stdin.close()
  163. p.wait()
  164. retcode = self.updatevm.run('cd /tmp/repo; createrepo .', wait=True)
  165. if retcode == 127:
  166. self.skipTest("createrepo not installed in template {}".format(
  167. self.template))
  168. elif retcode != 0:
  169. self.skipTest("createrepo failed with code {}, cannot perform the "
  170. "test".format(retcode))
  171. self.start_repo()
  172. def start_repo(self):
  173. if not self.repo_running:
  174. self.updatevm.run("cd /tmp/repo &&"
  175. "python -m SimpleHTTPServer 8080")
  176. self.repo_running = True
  177. def test_000_update(self):
  178. """Dom0 update tests
  179. Check if package update is:
  180. - detected
  181. - installed
  182. - "updates pending" flag is cleared
  183. """
  184. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  185. subprocess.check_call(['sudo', 'rpm', '-i', filename])
  186. filename = self.create_pkg(self.tmpdir, self.pkg_name, '2.0')
  187. self.send_pkg(filename)
  188. open(self.update_flag_path, 'a').close()
  189. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  190. try:
  191. subprocess.check_call(['sudo', 'qubes-dom0-update', '-y'] +
  192. self.dom0_update_common_opts,
  193. stdout=open(logpath, 'w'),
  194. stderr=subprocess.STDOUT)
  195. except subprocess.CalledProcessError:
  196. self.fail("qubes-dom0-update failed: " + open(
  197. logpath).read())
  198. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  199. self.pkg_name)], stdout=open(os.devnull, 'w'))
  200. self.assertEqual(retcode, 1, 'Package {}-1.0 still installed after '
  201. 'update'.format(self.pkg_name))
  202. retcode = subprocess.call(['rpm', '-q', '{}-2.0'.format(
  203. self.pkg_name)], stdout=open(os.devnull, 'w'))
  204. self.assertEqual(retcode, 0, 'Package {}-2.0 not installed after '
  205. 'update'.format(self.pkg_name))
  206. self.assertFalse(os.path.exists(self.update_flag_path),
  207. "'updates pending' flag not cleared")
  208. def test_005_update_flag_clear(self):
  209. """Check if 'updates pending' flag is creared"""
  210. # create any pkg (but not install it) to initialize repo in the VM
  211. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  212. self.send_pkg(filename)
  213. open(self.update_flag_path, 'a').close()
  214. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  215. try:
  216. subprocess.check_call(['sudo', 'qubes-dom0-update', '-y'] +
  217. self.dom0_update_common_opts,
  218. stdout=open(logpath, 'w'),
  219. stderr=subprocess.STDOUT)
  220. except subprocess.CalledProcessError:
  221. self.fail("qubes-dom0-update failed: " + open(
  222. logpath).read())
  223. with open(logpath) as f:
  224. dom0_update_output = f.read()
  225. self.assertFalse('Errno' in dom0_update_output or
  226. 'Couldn\'t' in dom0_update_output,
  227. "qubes-dom0-update reported an error: {}".
  228. format(dom0_update_output))
  229. self.assertFalse(os.path.exists(self.update_flag_path),
  230. "'updates pending' flag not cleared")
  231. def test_006_update_flag_clear(self):
  232. """Check if 'updates pending' flag is creared, using --clean"""
  233. # create any pkg (but not install it) to initialize repo in the VM
  234. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  235. self.send_pkg(filename)
  236. open(self.update_flag_path, 'a').close()
  237. # remove also repodata to test #1685
  238. if os.path.exists('/var/lib/qubes/updates/repodata'):
  239. shutil.rmtree('/var/lib/qubes/updates/repodata')
  240. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  241. try:
  242. subprocess.check_call(['sudo', 'qubes-dom0-update', '-y',
  243. '--clean'] +
  244. self.dom0_update_common_opts,
  245. stdout=open(logpath, 'w'),
  246. stderr=subprocess.STDOUT)
  247. except subprocess.CalledProcessError:
  248. self.fail("qubes-dom0-update failed: " + open(
  249. logpath).read())
  250. with open(logpath) as f:
  251. dom0_update_output = f.read()
  252. self.assertFalse('Errno' in dom0_update_output or
  253. 'Couldn\'t' in dom0_update_output,
  254. "qubes-dom0-update reported an error: {}".
  255. format(dom0_update_output))
  256. self.assertFalse(os.path.exists(self.update_flag_path),
  257. "'updates pending' flag not cleared")
  258. def test_010_instal(self):
  259. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  260. self.send_pkg(filename)
  261. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  262. try:
  263. subprocess.check_call(['sudo', 'qubes-dom0-update', '-y'] +
  264. self.dom0_update_common_opts + [
  265. self.pkg_name],
  266. stdout=open(logpath, 'w'),
  267. stderr=subprocess.STDOUT)
  268. except subprocess.CalledProcessError:
  269. self.fail("qubes-dom0-update failed: " + open(
  270. logpath).read())
  271. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  272. self.pkg_name)], stdout=open('/dev/null', 'w'))
  273. self.assertEqual(retcode, 0, 'Package {}-1.0 not installed'.format(
  274. self.pkg_name))
  275. def test_020_install_wrong_sign(self):
  276. subprocess.call(['sudo', 'rpm', '-e', 'gpg-pubkey-{}'.format(
  277. self.keyid)])
  278. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  279. self.send_pkg(filename)
  280. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  281. try:
  282. subprocess.check_call(['sudo', 'qubes-dom0-update', '-y'] +
  283. self.dom0_update_common_opts + [
  284. self.pkg_name],
  285. stdout=open(logpath, 'w'),
  286. stderr=subprocess.STDOUT)
  287. self.fail("qubes-dom0-update unexpectedly succeeded: " + open(
  288. logpath).read())
  289. except subprocess.CalledProcessError:
  290. pass
  291. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  292. self.pkg_name)], stdout=open('/dev/null', 'w'))
  293. self.assertEqual(retcode, 1,
  294. 'Package {}-1.0 installed although '
  295. 'signature is invalid'.format(self.pkg_name))
  296. def test_030_install_unsigned(self):
  297. filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0')
  298. subprocess.check_call(['rpm', '--delsign', filename],
  299. stdout=open(os.devnull, 'w'),
  300. stderr=subprocess.STDOUT)
  301. self.send_pkg(filename)
  302. logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt')
  303. try:
  304. subprocess.check_call(['sudo', 'qubes-dom0-update', '-y'] +
  305. self.dom0_update_common_opts +
  306. [self.pkg_name],
  307. stdout=open(logpath, 'w'),
  308. stderr=subprocess.STDOUT
  309. )
  310. self.fail("qubes-dom0-update unexpectedly succeeded: " + open(
  311. logpath).read())
  312. except subprocess.CalledProcessError:
  313. pass
  314. retcode = subprocess.call(['rpm', '-q', '{}-1.0'.format(
  315. self.pkg_name)], stdout=open('/dev/null', 'w'))
  316. self.assertEqual(retcode, 1,
  317. 'UNSIGNED package {}-1.0 installed'.format(self.pkg_name))
  318. def load_tests(loader, tests, pattern):
  319. try:
  320. qc = qubes.qubes.QubesVmCollection()
  321. qc.lock_db_for_reading()
  322. qc.load()
  323. qc.unlock_db()
  324. templates = [vm.name for vm in qc.values() if
  325. isinstance(vm, qubes.qubes.QubesTemplateVm)]
  326. except OSError:
  327. templates = []
  328. for template in templates:
  329. tests.addTests(loader.loadTestsFromTestCase(
  330. type(
  331. 'TC_00_Dom0Upgrade_' + template,
  332. (TC_00_Dom0UpgradeMixin, qubes.tests.QubesTestCase),
  333. {'template': template})))
  334. return tests