network.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. #!/usr/bin/python
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2015
  7. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  8. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  9. #
  10. # This program is free software; you can redistribute it and/or modify
  11. # it under the terms of the GNU General Public License as published by
  12. # the Free Software Foundation; either version 2 of the License, or
  13. # (at your option) any later version.
  14. #
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU General Public License along
  21. # with this program; if not, write to the Free Software Foundation, Inc.,
  22. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  23. #
  24. from distutils import spawn
  25. import multiprocessing
  26. import os
  27. import subprocess
  28. import unittest
  29. import time
  30. import qubes.tests
  31. import qubes.vm.appvm
  32. class NcVersion:
  33. Trad = 1
  34. Nmap = 2
  35. # noinspection PyAttributeOutsideInit
  36. class VmNetworkingMixin(qubes.tests.SystemTestsMixin):
  37. test_ip = '192.168.123.45'
  38. test_name = 'test.example.com'
  39. ping_cmd = 'ping -W 1 -n -c 1 {target}'
  40. ping_ip = ping_cmd.format(target=test_ip)
  41. ping_name = ping_cmd.format(target=test_name)
  42. # filled by load_tests
  43. template = None
  44. def run_cmd(self, vm, cmd, user="root"):
  45. p = vm.run(cmd, user=user, passio_popen=True, ignore_stderr=True)
  46. p.stdin.close()
  47. p.stdout.read()
  48. return p.wait()
  49. def setUp(self):
  50. super(VmNetworkingMixin, self).setUp()
  51. self.init_default_template(self.template)
  52. self.testnetvm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  53. name=self.make_vm_name('netvm1'),
  54. label='red')
  55. self.testnetvm.create_on_disk()
  56. self.testnetvm.provides_network = True
  57. self.testvm1 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  58. name=self.make_vm_name('vm2'),
  59. label='red')
  60. self.testvm1.create_on_disk()
  61. self.testvm1.netvm = self.testnetvm
  62. self.app.save()
  63. self.configure_netvm()
  64. def configure_netvm(self):
  65. def run_netvm_cmd(cmd):
  66. if self.run_cmd(self.testnetvm, cmd) != 0:
  67. self.fail("Command '%s' failed" % cmd)
  68. if not self.testnetvm.is_running():
  69. self.testnetvm.start()
  70. # Ensure that dnsmasq is installed:
  71. p = self.testnetvm.run("dnsmasq --version", user="root",
  72. passio_popen=True)
  73. if p.wait() != 0:
  74. self.skipTest("dnsmasq not installed")
  75. run_netvm_cmd("ip link add test0 type dummy")
  76. run_netvm_cmd("ip link set test0 up")
  77. run_netvm_cmd("ip addr add {}/24 dev test0".format(self.test_ip))
  78. run_netvm_cmd("iptables -I INPUT -d {} -j ACCEPT".format(self.test_ip))
  79. run_netvm_cmd("dnsmasq -a {ip} -A /{name}/{ip} -i test0 -z".format(
  80. ip=self.test_ip, name=self.test_name))
  81. run_netvm_cmd("echo nameserver {} > /etc/resolv.conf".format(
  82. self.test_ip))
  83. run_netvm_cmd("/usr/lib/qubes/qubes-setup-dnat-to-ns")
  84. def test_000_simple_networking(self):
  85. self.testvm1.start()
  86. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  87. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0)
  88. def test_010_simple_proxyvm(self):
  89. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  90. name=self.make_vm_name('proxy'),
  91. label='red')
  92. self.proxy.provides_network = True
  93. self.proxy.netvm = self.testnetvm
  94. self.proxy.create_on_disk()
  95. self.testvm1.netvm = self.proxy
  96. self.app.save()
  97. self.testvm1.start()
  98. self.assertTrue(self.proxy.is_running())
  99. self.assertEqual(self.run_cmd(self.proxy, self.ping_ip), 0,
  100. "Ping by IP from ProxyVM failed")
  101. self.assertEqual(self.run_cmd(self.proxy, self.ping_name), 0,
  102. "Ping by name from ProxyVM failed")
  103. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  104. "Ping by IP from AppVM failed")
  105. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  106. "Ping by IP from AppVM failed")
  107. @qubes.tests.expectedFailureIfTemplate('debian-7')
  108. @unittest.skipUnless(spawn.find_executable('xdotool'),
  109. "xdotool not installed")
  110. def test_020_simple_proxyvm_nm(self):
  111. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  112. name=self.make_vm_name('proxy'),
  113. label='red')
  114. self.proxy.provides_network = True
  115. self.proxy.create_on_disk()
  116. self.proxy.netvm = self.testnetvm
  117. self.proxy.features['network-manager'] = True
  118. self.testvm1.netvm = self.proxy
  119. self.app.save()
  120. self.testvm1.start()
  121. self.assertTrue(self.proxy.is_running())
  122. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  123. "Ping by IP failed")
  124. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  125. "Ping by name failed")
  126. # reconnect to make sure that device was configured by NM
  127. self.assertEqual(
  128. self.run_cmd(self.proxy, "nmcli device disconnect eth0",
  129. user="user"),
  130. 0, "Failed to disconnect eth0 using nmcli")
  131. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  132. "Network should be disabled, but apparently it isn't")
  133. self.assertEqual(
  134. self.run_cmd(self.proxy,
  135. 'nmcli connection up "VM uplink eth0" ifname eth0',
  136. user="user"),
  137. 0, "Failed to connect eth0 using nmcli")
  138. self.assertEqual(self.run_cmd(self.proxy, "nm-online", user="user"), 0,
  139. "Failed to wait for NM connection")
  140. # check for nm-applet presence
  141. self.assertEqual(subprocess.call([
  142. 'xdotool', 'search', '--all', '--name',
  143. '--class', '^(NetworkManager Applet|{})$'.format(self.proxy.name)],
  144. stdout=open('/dev/null', 'w')), 0, "nm-applet window not found")
  145. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  146. "Ping by IP failed (after NM reconnection")
  147. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  148. "Ping by name failed (after NM reconnection)")
  149. def test_030_firewallvm_firewall(self):
  150. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  151. name=self.make_vm_name('proxy'),
  152. label='red')
  153. self.proxy.provides_network = True
  154. self.proxy.create_on_disk()
  155. self.proxy.netvm = self.testnetvm
  156. self.testvm1.netvm = self.proxy
  157. self.app.save()
  158. if self.run_cmd(self.testnetvm, 'nc -h 2>&1|grep -q nmap.org') == 0:
  159. nc_version = NcVersion.Nmap
  160. else:
  161. nc_version = NcVersion.Trad
  162. # block all for first
  163. self.testvm1.write_firewall_conf({
  164. 'allow': False,
  165. 'allowDns': False,
  166. 'allowIcmp': False,
  167. })
  168. self.testvm1.start()
  169. self.assertTrue(self.proxy.is_running())
  170. if nc_version == NcVersion.Nmap:
  171. self.testnetvm.run("nc -l --send-only -e /bin/hostname -k 1234")
  172. else:
  173. self.testnetvm.run("while nc -l -e /bin/hostname -p 1234; do "
  174. "true; done")
  175. self.assertEqual(self.run_cmd(self.proxy, self.ping_ip), 0,
  176. "Ping by IP from ProxyVM failed")
  177. self.assertEqual(self.run_cmd(self.proxy, self.ping_name), 0,
  178. "Ping by name from ProxyVM failed")
  179. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  180. "Ping by IP should be blocked")
  181. if nc_version == NcVersion.Nmap:
  182. nc_cmd = "nc -w 1 --recv-only {} 1234".format(self.test_ip)
  183. else:
  184. nc_cmd = "nc -w 1 {} 1234".format(self.test_ip)
  185. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  186. "TCP connection should be blocked")
  187. # block all except ICMP
  188. self.testvm1.write_firewall_conf({
  189. 'allow': False,
  190. 'allowDns': False,
  191. 'allowIcmp': True,
  192. })
  193. # Ugly hack b/c there is no feedback when the rules are actually applied
  194. time.sleep(3)
  195. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  196. "Ping by IP failed (should be allowed now)")
  197. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  198. "Ping by name should be blocked")
  199. # all TCP still blocked
  200. self.testvm1.write_firewall_conf({
  201. 'allow': False,
  202. 'allowDns': True,
  203. 'allowIcmp': True,
  204. })
  205. # Ugly hack b/c there is no feedback when the rules are actually applied
  206. time.sleep(3)
  207. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  208. "Ping by name failed (should be allowed now)")
  209. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  210. "TCP connection should be blocked")
  211. # block all except target
  212. self.testvm1.write_firewall_conf({
  213. 'allow': False,
  214. 'allowDns': True,
  215. 'allowIcmp': True,
  216. 'rules': [{'address': self.test_ip,
  217. 'netmask': 32,
  218. 'proto': 'tcp',
  219. 'portBegin': 1234
  220. }] })
  221. # Ugly hack b/c there is no feedback when the rules are actually applied
  222. time.sleep(3)
  223. self.assertEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  224. "TCP connection failed (should be allowed now)")
  225. # allow all except target
  226. self.testvm1.write_firewall_conf({
  227. 'allow': True,
  228. 'allowDns': True,
  229. 'allowIcmp': True,
  230. 'rules': [{'address': self.test_ip,
  231. 'netmask': 32,
  232. 'proto': 'tcp',
  233. 'portBegin': 1234
  234. }]
  235. })
  236. # Ugly hack b/c there is no feedback when the rules are actually applied
  237. time.sleep(3)
  238. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  239. "TCP connection should be blocked")
  240. def test_040_inter_vm(self):
  241. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  242. name=self.make_vm_name('proxy'),
  243. label='red')
  244. self.proxy.create_on_disk()
  245. self.proxy.provides_network = True
  246. self.proxy.netvm = self.testnetvm
  247. self.testvm1.netvm = self.proxy
  248. self.testvm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  249. name=self.make_vm_name('vm3'),
  250. label='red')
  251. self.testvm2.create_on_disk()
  252. self.testvm2.netvm = self.proxy
  253. self.app.save()
  254. self.testvm1.start()
  255. self.testvm2.start()
  256. self.assertNotEqual(self.run_cmd(self.testvm1,
  257. self.ping_cmd.format(target=self.testvm2.ip)), 0)
  258. self.testvm2.netvm = self.testnetvm
  259. self.assertNotEqual(self.run_cmd(self.testvm1,
  260. self.ping_cmd.format(target=self.testvm2.ip)), 0)
  261. self.assertNotEqual(self.run_cmd(self.testvm2,
  262. self.ping_cmd.format(target=self.testvm1.ip)), 0)
  263. self.testvm1.netvm = self.testnetvm
  264. self.assertNotEqual(self.run_cmd(self.testvm1,
  265. self.ping_cmd.format(target=self.testvm2.ip)), 0)
  266. self.assertNotEqual(self.run_cmd(self.testvm2,
  267. self.ping_cmd.format(target=self.testvm1.ip)), 0)
  268. def test_050_spoof_ip(self):
  269. """Test if VM IP spoofing is blocked"""
  270. self.testvm1.start()
  271. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  272. self.testvm1.run("ip addr flush dev eth0", user="root", wait=True)
  273. self.testvm1.run("ip addr add 10.137.1.128/24 dev eth0", user="root",
  274. wait=True)
  275. self.testvm1.run("ip route add default dev eth0", user="root",
  276. wait=True)
  277. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  278. "Spoofed ping should be blocked")
  279. # noinspection PyAttributeOutsideInit
  280. class VmUpdatesMixin(qubes.tests.SystemTestsMixin):
  281. """
  282. Tests for VM updates
  283. """
  284. # filled by load_tests
  285. template = None
  286. # made this way to work also when no package build tools are installed
  287. """
  288. $ cat test-pkg.spec:
  289. Name: test-pkg
  290. Version: 1.0
  291. Release: 1%{?dist}
  292. Summary: Test package
  293. Group: System
  294. License: GPL
  295. URL: http://example.com/
  296. %description
  297. Test package
  298. %files
  299. %changelog
  300. $ rpmbuild -bb test-pkg.spec
  301. $ cat test-pkg-1.0-1.fc21.x86_64.rpm | gzip | base64
  302. """
  303. RPM_PACKAGE_GZIP_BASE64 = (
  304. "H4sIAPzRLlYAA+2Y728URRjHn7ueUCkERKJVJDnTxLSxs7293o8WOER6ljYYrtKCLUSa3"
  305. "bnZ64bd22VmTq8nr4wJbwxvjNHIG0x8oTHGGCHB8AcYE1/0lS80GgmQFCJU3wgB4ZjdfZ"
  306. "q2xDe8NNlvMjfzmeeZH7tPbl98b35169cOUEpIJiTxT9SIrmVUs2hWh8dUAp54dOrM14s"
  307. "JHK4D2DKl+j2qrVfjsuq3qEWbohjuAB2Lqk+p1o/8Z5QPmSi/YwnjezH+F8bLQZjqllW0"
  308. "hvODRmFIL5hFk9JMXi/mi5ZuDleNwSEzP5wtmLnouNQnm3/6fndz7FLt9M/Hruj37gav4"
  309. "tTjPnasWLFixYoVK1asWLFixYoV63+p0KNot9vnIPQc1vgYOwCSgXfxCoS+QzKHOVXVOj"
  310. "Fn2ccIfI0k8nXkLuQbyJthxed4UrVnkG8i9yDfgsj3yCAv4foc8t+w1hf5B+Nl5Du43xj"
  311. "yvxivIN9HpsgPkO2IU9uQfeRn8Xk/iJ4x1Y3nfxH1qecwfhH5+YgT25F7o/0SRdxvOppP"
  312. "7MX9ZjB/DNnE/OOYX404uRGZIT+FbCFvQ3aQ8f0+/WF0XjJ8nyOw7H+BrmUA/a8pNZf2D"
  313. "XrCqLG1cERbWHI8ajhznpBY9P0Tr8PkvJDMhTkp/Z0DA6xpuL7DNOq5A+DY9UYTmkOF2U"
  314. "IO/sNt0wSnGvfdlZssD3rVIlLI9UUX37C6qXzHNntHPNfnTAhWHbUddtBwmegDjAUzZbu"
  315. "m9lqZmzDmHc8Ik8WY8Tab4Myym4+Gx8V0qw8GtYyWIzrktEJwV9UHv3ktG471rAqHTmFQ"
  316. "685V5uGqIalk06SWJr7tszR503Ac9cs493jJ8rhrSCIYbXBbzqt5v5+UZ0crh6bGR2dmJ"
  317. "yuHD428VlLLLdakzJe2VxcKhFSFID73JKPS40RI7tXVCcQ3uOGWhPCJ2bAspiJ2i5Vy6n"
  318. "jOqMerpEYpEe/Yks4xkU4Tt6BirmzUWanG6ozbFKhve9BsQRaLRTirzqk7hgUktXojKnf"
  319. "n8jeg3X4QepP3i63po6oml+9t/CwJLya2Bn/ei6f7/4B3Ycdb0L3pt5Q5mNz16rWJ9fLk"
  320. "vvOff/nxS7//8O2P2gvt7nDDnoV9L1du9N4+ucjl9u/8+a7dC5Nnvjlv9Ox5r+v9Cy0NE"
  321. "m+c6rv60S/dZw98Gn6MNswcfQiWUvg3wBUAAA=="
  322. )
  323. """
  324. Minimal package generated by running dh_make on empty directory
  325. Then cat test-pkg_1.0-1_amd64.deb | gzip | base64
  326. """
  327. DEB_PACKAGE_GZIP_BASE64 = (
  328. "H4sIACTXLlYAA1O0SSxKzrDjSklNykzM003KzEssqlRQUDA0MTG1NDQwNDVTUDBQAAEIa"
  329. "WhgYGZioqBgogADCVxGegZcyfl5JUX5OXoliUV66VVE6DcwheuX7+ZgAAEW5rdXHb0PG4"
  330. "iwf5j3WfMT6zWzzMuZgoE3jjYraNzbbFKWGms0SaRw/r2SV23WZ4IdP8preM4yqf0jt95"
  331. "3c8qnacfNxJUkf9/w+/3X9ph2GEdgQdixrz/niHKKTnYXizf4oSC7tHOz2Zzq+/6vn8/7"
  332. "ezQ7c1tmi7xZ3SGJ4yzhT2dcr7V+W3zM5ZPu/56PSv4Zdok+7Yv/V/6buWaKVlFkkV58S"
  333. "N3GmLgnqzRmeZ3V3ymmurS5fGa85/LNx1bpZMin3S6dvXKqydp3ubP1vmyarJZb/qSh62"
  334. "C8oIdxqm/BtvkGDza+On/Vfv2py7/0LV7VH+qR6a+bkKUbHXt5/SG187d+nps1a5PJfMO"
  335. "i11dWcUe1HjwaW3Q5RHXn9LmcHy+tW9YcKf0768XVB1t3R0bKrzs5t9P+6r7rZ99svH10"
  336. "+Q6F/o8tf1fO/32y+fWa14eifd+WxUy0jcxYH7N9/tUvmnUZL74pW32qLeuRU+ZwYGASa"
  337. "GBgUWBgxM90ayy3VdmykkGDgYErJbEkERydFVWQmCMQo8aWZvAY/WteFRHFwMCYqXTPjI"
  338. "lBkVEMGLsl+k8XP1D/z+gXyyDOvUemlnHqAVkvu0rRQ2fUFodkN3mtU9uwhqk8V+TqPEE"
  339. "Nc7fzoQ4n71lqRs/7kbbT0+qOZuKH4r8mjzsc1k/YkCHN8Pjg48fbpE+teHa96LNcfu0V"
  340. "5n2/Z2xa2KDvaCOx8cqBFxc514uZ3TmadXS+6cpzU7wSzq5SWfapJOD9n6wLXSwtlgxZh"
  341. "xITzWW7buhx/bb291RcVlEfeC9K5hlrqunSzIMSZT7/Nqgc/qMvMNW227WI8ezB8mVuZh"
  342. "0hERJSvysfburr4Dx0I9BW57UwR4+e1gxu49PcEt8sbK18Xpvt//Hj5UYm+Zc25q+T4xl"
  343. "rJvxfVnh80oadq57OZxPaU1bbztv1yF365W4t45Yr+XrFzov237GVY1Zgf7NvE4+W2SuR"
  344. "lQtLauR1TQ/mbOiIONYya6tU1jPGpWfk/i1+ttiXe3ZO14n0YOWggndznjGlGLyfVbBC6"
  345. "MRP5aMM7aCco/s7sZqB8RlTQwADw8rnuT/sDHi7mUASjJFRAAbWwNLiAwAA"
  346. )
  347. def run_cmd(self, vm, cmd, user="root"):
  348. p = vm.run(cmd, user=user, passio_popen=True, ignore_stderr=True)
  349. p.stdin.close()
  350. p.stdout.read()
  351. return p.wait()
  352. def setUp(self):
  353. super(VmUpdatesMixin, self).setUp()
  354. self.update_cmd = None
  355. if self.template.count("debian"):
  356. self.update_cmd = "set -o pipefail; apt-get update 2>&1 | " \
  357. "{ ! grep '^W:\|^E:'; }"
  358. self.install_cmd = "apt-get install -y {}"
  359. self.install_test_cmd = "dpkg -l {}"
  360. self.exit_code_ok = [0]
  361. elif self.template.count("fedora"):
  362. cmd = "yum"
  363. try:
  364. # assume template name in form "fedora-XX-suffix"
  365. if int(self.template.split("-")[1]) > 21:
  366. cmd = "dnf"
  367. except ValueError:
  368. pass
  369. self.update_cmd = "{cmd} clean all; {cmd} check-update".format(
  370. cmd=cmd)
  371. self.install_cmd = cmd + " install -y {}"
  372. self.install_test_cmd = "rpm -q {}"
  373. self.exit_code_ok = [0, 100]
  374. else:
  375. self.skipTest("Template {} not supported by this test".format(
  376. self.template))
  377. self.init_default_template(self.template)
  378. self.init_networking()
  379. self.testvm1 = self.app.add_new_vm(
  380. qubes.vm.appvm.AppVM,
  381. name=self.make_vm_name('vm1'),
  382. label='red')
  383. self.testvm1.create_on_disk()
  384. def test_000_simple_update(self):
  385. self.save_and_reload_db()
  386. # reload the VM to have all the properties properly set (especially
  387. # default netvm)
  388. self.testvm1 = self.app.domains[self.testvm1.qid]
  389. self.testvm1.start()
  390. p = self.testvm1.run(self.update_cmd, wait=True, user="root",
  391. passio_popen=True, passio_stderr=True)
  392. (stdout, stderr) = p.communicate()
  393. self.assertIn(p.wait(), self.exit_code_ok,
  394. "{}: {}\n{}".format(self.update_cmd, stdout, stderr)
  395. )
  396. def create_repo_apt(self):
  397. pkg_file_name = "test-pkg_1.0-1_amd64.deb"
  398. p = self.netvm_repo.run("mkdir /tmp/apt-repo && cd /tmp/apt-repo &&"
  399. "base64 -d | zcat > {}".format(pkg_file_name),
  400. passio_popen=True)
  401. p.stdin.write(self.DEB_PACKAGE_GZIP_BASE64)
  402. p.stdin.close()
  403. if p.wait() != 0:
  404. raise RuntimeError("Failed to write {}".format(pkg_file_name))
  405. # do not assume dpkg-scanpackage installed
  406. packages_path = "dists/test/main/binary-amd64/Packages"
  407. p = self.netvm_repo.run(
  408. "mkdir -p /tmp/apt-repo/dists/test/main/binary-amd64 && "
  409. "cd /tmp/apt-repo && "
  410. "cat > {packages} && "
  411. "echo MD5sum: $(openssl md5 -r {pkg} | cut -f 1 -d ' ')"
  412. " >> {packages} && "
  413. "echo SHA1: $(openssl sha1 -r {pkg} | cut -f 1 -d ' ')"
  414. " >> {packages} && "
  415. "echo SHA256: $(openssl sha256 -r {pkg} | cut -f 1 -d ' ')"
  416. " >> {packages} && "
  417. "gzip < {packages} > {packages}.gz".format(pkg=pkg_file_name,
  418. packages=packages_path),
  419. passio_popen=True, passio_stderr=True)
  420. p.stdin.write(
  421. "Package: test-pkg\n"
  422. "Version: 1.0-1\n"
  423. "Architecture: amd64\n"
  424. "Maintainer: unknown <user@host>\n"
  425. "Installed-Size: 25\n"
  426. "Filename: {pkg}\n"
  427. "Size: 994\n"
  428. "Section: unknown\n"
  429. "Priority: optional\n"
  430. "Description: Test package\n".format(pkg=pkg_file_name)
  431. )
  432. p.stdin.close()
  433. if p.wait() != 0:
  434. raise RuntimeError("Failed to write Packages file: {}".format(
  435. p.stderr.read()))
  436. p = self.netvm_repo.run(
  437. "mkdir -p /tmp/apt-repo/dists/test && "
  438. "cd /tmp/apt-repo/dists/test && "
  439. "cat > Release <<EOF && "
  440. "echo '' $(sha1sum {p} | cut -f 1 -d ' ') $(stat -c %s {p}) {p}"
  441. " >> Release && "
  442. "echo '' $(sha1sum {z} | cut -f 1 -d ' ') $(stat -c %s {z}) {z}"
  443. " >> Release"
  444. .format(p="main/binary-amd64/Packages",
  445. z="main/binary-amd64/Packages.gz"),
  446. passio_popen=True, passio_stderr=True
  447. )
  448. p.stdin.write(
  449. "Label: Test repo\n"
  450. "Suite: test\n"
  451. "Codename: test\n"
  452. "Date: Tue, 27 Oct 2015 03:22:09 +0100\n"
  453. "Architectures: amd64\n"
  454. "Components: main\n"
  455. "SHA1:\n"
  456. "EOF\n"
  457. )
  458. p.stdin.close()
  459. if p.wait() != 0:
  460. raise RuntimeError("Failed to write Release file: {}".format(
  461. p.stderr.read()))
  462. def create_repo_yum(self):
  463. pkg_file_name = "test-pkg-1.0-1.fc21.x86_64.rpm"
  464. p = self.netvm_repo.run("mkdir /tmp/yum-repo && cd /tmp/yum-repo &&"
  465. "base64 -d | zcat > {}".format(pkg_file_name),
  466. passio_popen=True, passio_stderr=True)
  467. p.stdin.write(self.RPM_PACKAGE_GZIP_BASE64)
  468. p.stdin.close()
  469. if p.wait() != 0:
  470. raise RuntimeError("Failed to write {}: {}".format(pkg_file_name,
  471. p.stderr.read()))
  472. # createrepo is installed by default in Fedora template
  473. p = self.netvm_repo.run("createrepo /tmp/yum-repo",
  474. passio_popen=True,
  475. passio_stderr=True)
  476. if p.wait() != 0:
  477. raise RuntimeError("Failed to create yum metadata: {}".format(
  478. p.stderr.read()))
  479. def create_repo_and_serve(self):
  480. if self.template.count("debian") or self.template.count("whonix"):
  481. self.create_repo_apt()
  482. self.netvm_repo.run("cd /tmp/apt-repo &&"
  483. "python -m SimpleHTTPServer 8080")
  484. elif self.template.count("fedora"):
  485. self.create_repo_yum()
  486. self.netvm_repo.run("cd /tmp/yum-repo &&"
  487. "python -m SimpleHTTPServer 8080")
  488. else:
  489. # not reachable...
  490. self.skipTest("Template {} not supported by this test".format(
  491. self.template))
  492. def configure_test_repo(self):
  493. """
  494. Configure test repository in test-vm and disable rest of them.
  495. The critical part is to use "localhost" - this will work only when
  496. accessed through update proxy and this is exactly what we want to
  497. test here.
  498. """
  499. if self.template.count("debian") or self.template.count("whonix"):
  500. self.testvm1.run(
  501. "rm -f /etc/apt/sources.list.d/* &&"
  502. "echo 'deb [trusted=yes] http://localhost:8080 test main' "
  503. "> /etc/apt/sources.list",
  504. user="root")
  505. elif self.template.count("fedora"):
  506. self.testvm1.run(
  507. "rm -f /etc/yum.repos.d/*.repo &&"
  508. "echo '[test]' > /etc/yum.repos.d/test.repo &&"
  509. "echo 'name=Test repo' >> /etc/yum.repos.d/test.repo &&"
  510. "echo 'gpgcheck=0' >> /etc/yum.repos.d/test.repo &&"
  511. "echo 'baseurl=http://localhost:8080/'"
  512. " >> /etc/yum.repos.d/test.repo",
  513. user="root"
  514. )
  515. else:
  516. # not reachable...
  517. self.skipTest("Template {} not supported by this test".format(
  518. self.template))
  519. def test_010_update_via_proxy(self):
  520. """
  521. Test both whether updates proxy works and whether is actually used by the VM
  522. """
  523. if self.template.count("minimal"):
  524. self.skipTest("Template {} not supported by this test".format(
  525. self.template))
  526. self.netvm_repo = self.app.add_new_vm(
  527. qubes.vm.appvm.AppVM,
  528. name=self.make_vm_name('net'),
  529. label='red')
  530. self.netvm_repo.provides_network = True
  531. self.netvm_repo.create_on_disk()
  532. self.testvm1.netvm = self.netvm_repo
  533. # NetVM should have qubes-updates-proxy enabled by default
  534. #self.netvm_repo.features['qubes-updates-proxy'] = True
  535. # TODO: consider also adding a test for the template itself
  536. self.testvm1.features['updates-proxy-setup'] = True
  537. self.app.save()
  538. # Setup test repo
  539. self.netvm_repo.start()
  540. self.create_repo_and_serve()
  541. # Configure local repo
  542. self.testvm1.start()
  543. self.configure_test_repo()
  544. # update repository metadata
  545. p = self.testvm1.run(self.update_cmd, wait=True, user="root",
  546. passio_popen=True, passio_stderr=True)
  547. (stdout, stderr) = p.communicate()
  548. self.assertIn(p.wait(), self.exit_code_ok,
  549. "{}: {}\n{}".format(self.update_cmd, stdout, stderr)
  550. )
  551. # install test package
  552. p = self.testvm1.run(self.install_cmd.format('test-pkg'),
  553. wait=True, user="root",
  554. passio_popen=True, passio_stderr=True)
  555. (stdout, stderr) = p.communicate()
  556. self.assertIn(p.wait(), self.exit_code_ok,
  557. "{}: {}\n{}".format(self.update_cmd, stdout, stderr)
  558. )
  559. # verify if it was really installed
  560. p = self.testvm1.run(self.install_test_cmd.format('test-pkg'),
  561. wait=True, user="root",
  562. passio_popen=True, passio_stderr=True)
  563. (stdout, stderr) = p.communicate()
  564. self.assertIn(p.wait(), self.exit_code_ok,
  565. "{}: {}\n{}".format(self.update_cmd, stdout, stderr)
  566. )
  567. def load_tests(loader, tests, pattern):
  568. try:
  569. app = qubes.Qubes()
  570. templates = [vm.name for vm in app.domains if
  571. isinstance(vm, qubes.vm.templatevm.TemplateVM)]
  572. except OSError:
  573. templates = []
  574. for template in templates:
  575. tests.addTests(loader.loadTestsFromTestCase(
  576. type(
  577. 'VmNetworking_' + template,
  578. (VmNetworkingMixin, qubes.tests.QubesTestCase),
  579. {'template': template})))
  580. tests.addTests(loader.loadTestsFromTestCase(
  581. type(
  582. 'VmUpdates_' + template,
  583. (VmUpdatesMixin, qubes.tests.QubesTestCase),
  584. {'template': template})))
  585. return tests