network.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2015
  5. # Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  6. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (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 along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. #
  22. from distutils import spawn
  23. import multiprocessing
  24. import os
  25. import subprocess
  26. import unittest
  27. import time
  28. import qubes.tests
  29. import qubes.vm.appvm
  30. class NcVersion:
  31. Trad = 1
  32. Nmap = 2
  33. # noinspection PyAttributeOutsideInit
  34. class VmNetworkingMixin(qubes.tests.SystemTestsMixin):
  35. test_ip = '192.168.123.45'
  36. test_name = 'test.example.com'
  37. ping_cmd = 'ping -W 1 -n -c 1 {target}'
  38. ping_ip = ping_cmd.format(target=test_ip)
  39. ping_name = ping_cmd.format(target=test_name)
  40. # filled by load_tests
  41. template = None
  42. def run_cmd(self, vm, cmd, user="root"):
  43. p = vm.run(cmd, user=user, passio_popen=True, ignore_stderr=True)
  44. p.stdin.close()
  45. p.stdout.read().decode()
  46. return p.wait()
  47. def setUp(self):
  48. super(VmNetworkingMixin, self).setUp()
  49. if self.template.startswith('whonix-gw'):
  50. self.skipTest("Test not supported here - Whonix uses its own "
  51. "firewall settings")
  52. self.init_default_template(self.template)
  53. self.testnetvm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  54. name=self.make_vm_name('netvm1'),
  55. label='red')
  56. self.testnetvm.create_on_disk()
  57. self.testnetvm.provides_network = True
  58. self.testvm1 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  59. name=self.make_vm_name('vm2'),
  60. label='red')
  61. self.testvm1.create_on_disk()
  62. self.testvm1.netvm = self.testnetvm
  63. self.app.save()
  64. self.configure_netvm()
  65. def configure_netvm(self):
  66. def run_netvm_cmd(cmd):
  67. if self.run_cmd(self.testnetvm, cmd) != 0:
  68. self.fail("Command '%s' failed" % cmd)
  69. if not self.testnetvm.is_running():
  70. self.testnetvm.start()
  71. # Ensure that dnsmasq is installed:
  72. p = self.testnetvm.run("dnsmasq --version", user="root",
  73. passio_popen=True)
  74. if p.wait() != 0:
  75. self.skipTest("dnsmasq not installed")
  76. run_netvm_cmd("ip link add test0 type dummy")
  77. run_netvm_cmd("ip link set test0 up")
  78. run_netvm_cmd("ip addr add {}/24 dev test0".format(self.test_ip))
  79. run_netvm_cmd("iptables -I INPUT -d {} -j ACCEPT".format(self.test_ip))
  80. # ignore failure
  81. self.run_cmd(self.testnetvm, "killall --wait dnsmasq")
  82. run_netvm_cmd("dnsmasq -a {ip} -A /{name}/{ip} -i test0 -z".format(
  83. ip=self.test_ip, name=self.test_name))
  84. run_netvm_cmd("echo nameserver {} > /etc/resolv.conf".format(
  85. self.test_ip))
  86. run_netvm_cmd("/usr/lib/qubes/qubes-setup-dnat-to-ns")
  87. def test_000_simple_networking(self):
  88. self.testvm1.start()
  89. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  90. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0)
  91. def test_010_simple_proxyvm(self):
  92. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  93. name=self.make_vm_name('proxy'),
  94. label='red')
  95. self.proxy.provides_network = True
  96. self.proxy.netvm = self.testnetvm
  97. self.proxy.create_on_disk()
  98. self.testvm1.netvm = self.proxy
  99. self.app.save()
  100. self.testvm1.start()
  101. self.assertTrue(self.proxy.is_running())
  102. self.assertEqual(self.run_cmd(self.proxy, self.ping_ip), 0,
  103. "Ping by IP from ProxyVM failed")
  104. self.assertEqual(self.run_cmd(self.proxy, self.ping_name), 0,
  105. "Ping by name from ProxyVM failed")
  106. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  107. "Ping by IP from AppVM failed")
  108. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  109. "Ping by IP from AppVM failed")
  110. @qubes.tests.expectedFailureIfTemplate('debian-7')
  111. @unittest.skipUnless(spawn.find_executable('xdotool'),
  112. "xdotool not installed")
  113. def test_020_simple_proxyvm_nm(self):
  114. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  115. name=self.make_vm_name('proxy'),
  116. label='red')
  117. self.proxy.provides_network = True
  118. self.proxy.create_on_disk()
  119. self.proxy.netvm = self.testnetvm
  120. self.proxy.features['network-manager'] = True
  121. self.testvm1.netvm = self.proxy
  122. self.app.save()
  123. self.testvm1.start()
  124. self.assertTrue(self.proxy.is_running())
  125. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  126. "Ping by IP failed")
  127. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  128. "Ping by name failed")
  129. # reconnect to make sure that device was configured by NM
  130. self.assertEqual(
  131. self.run_cmd(self.proxy, "nmcli device disconnect eth0",
  132. user="user"),
  133. 0, "Failed to disconnect eth0 using nmcli")
  134. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  135. "Network should be disabled, but apparently it isn't")
  136. self.assertEqual(
  137. self.run_cmd(self.proxy,
  138. 'nmcli connection up "VM uplink eth0" ifname eth0',
  139. user="user"),
  140. 0, "Failed to connect eth0 using nmcli")
  141. self.assertEqual(self.run_cmd(self.proxy, "nm-online", user="user"), 0,
  142. "Failed to wait for NM connection")
  143. # check for nm-applet presence
  144. self.assertEqual(subprocess.call([
  145. 'xdotool', 'search', '--class', '{}:nm-applet'.format(
  146. self.proxy.name)],
  147. stdout=open('/dev/null', 'w')), 0, "nm-applet window not found")
  148. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  149. "Ping by IP failed (after NM reconnection")
  150. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  151. "Ping by name failed (after NM reconnection)")
  152. def test_030_firewallvm_firewall(self):
  153. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  154. name=self.make_vm_name('proxy'),
  155. label='red')
  156. self.proxy.provides_network = True
  157. self.proxy.create_on_disk()
  158. self.proxy.netvm = self.testnetvm
  159. self.testvm1.netvm = self.proxy
  160. self.app.save()
  161. if self.run_cmd(self.testnetvm, 'nc -h 2>&1|grep -q nmap.org') == 0:
  162. nc_version = NcVersion.Nmap
  163. else:
  164. nc_version = NcVersion.Trad
  165. # block all for first
  166. self.testvm1.firewall.policy = 'drop'
  167. self.testvm1.firewall.save()
  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.firewall.rules = [(
  189. qubes.firewall.Rule(None, action='accept', proto='icmp')
  190. )]
  191. self.testvm1.firewall.save()
  192. # Ugly hack b/c there is no feedback when the rules are actually applied
  193. time.sleep(3)
  194. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  195. "Ping by IP failed (should be allowed now)")
  196. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  197. "Ping by name should be blocked")
  198. # all TCP still blocked
  199. self.testvm1.firewall.rules = [
  200. qubes.firewall.Rule(None, action='accept', proto='icmp'),
  201. qubes.firewall.Rule(None, action='accept', specialtarget='dns'),
  202. ]
  203. self.testvm1.firewall.save()
  204. # Ugly hack b/c there is no feedback when the rules are actually applied
  205. time.sleep(3)
  206. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  207. "Ping by name failed (should be allowed now)")
  208. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  209. "TCP connection should be blocked")
  210. # block all except target
  211. self.testvm1.firewall.policy = 'drop'
  212. self.testvm1.firewall.rules = [
  213. qubes.firewall.Rule(None, action='accept', dsthost=self.test_ip,
  214. proto='tcp', dstports=1234),
  215. ]
  216. self.testvm1.firewall.save()
  217. # Ugly hack b/c there is no feedback when the rules are actually applied
  218. time.sleep(3)
  219. self.assertEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  220. "TCP connection failed (should be allowed now)")
  221. # allow all except target
  222. self.testvm1.firewall.policy = 'accept'
  223. self.testvm1.firewall.rules = [
  224. qubes.firewall.Rule(None, action='drop', dsthost=self.test_ip,
  225. proto='tcp', dstports=1234),
  226. ]
  227. self.testvm1.firewall.save()
  228. # Ugly hack b/c there is no feedback when the rules are actually applied
  229. time.sleep(3)
  230. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  231. "TCP connection should be blocked")
  232. def test_040_inter_vm(self):
  233. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  234. name=self.make_vm_name('proxy'),
  235. label='red')
  236. self.proxy.create_on_disk()
  237. self.proxy.provides_network = True
  238. self.proxy.netvm = self.testnetvm
  239. self.testvm1.netvm = self.proxy
  240. self.testvm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  241. name=self.make_vm_name('vm3'),
  242. label='red')
  243. self.testvm2.create_on_disk()
  244. self.testvm2.netvm = self.proxy
  245. self.app.save()
  246. self.testvm1.start()
  247. self.testvm2.start()
  248. self.assertNotEqual(self.run_cmd(self.testvm1,
  249. self.ping_cmd.format(target=self.testvm2.ip)), 0)
  250. self.testvm2.netvm = self.testnetvm
  251. self.assertNotEqual(self.run_cmd(self.testvm1,
  252. self.ping_cmd.format(target=self.testvm2.ip)), 0)
  253. self.assertNotEqual(self.run_cmd(self.testvm2,
  254. self.ping_cmd.format(target=self.testvm1.ip)), 0)
  255. self.testvm1.netvm = self.testnetvm
  256. self.assertNotEqual(self.run_cmd(self.testvm1,
  257. self.ping_cmd.format(target=self.testvm2.ip)), 0)
  258. self.assertNotEqual(self.run_cmd(self.testvm2,
  259. self.ping_cmd.format(target=self.testvm1.ip)), 0)
  260. def test_050_spoof_ip(self):
  261. """Test if VM IP spoofing is blocked"""
  262. self.testvm1.start()
  263. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  264. self.testvm1.run("ip addr flush dev eth0", user="root", wait=True)
  265. self.testvm1.run("ip addr add 10.137.1.128/24 dev eth0", user="root",
  266. wait=True)
  267. self.testvm1.run("ip route add default dev eth0", user="root",
  268. wait=True)
  269. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  270. "Spoofed ping should be blocked")
  271. def test_100_late_xldevd_startup(self):
  272. """Regression test for #1990"""
  273. # Simulater late xl devd startup
  274. cmd = "systemctl stop xendriverdomain"
  275. if self.run_cmd(self.testnetvm, cmd) != 0:
  276. self.fail("Command '%s' failed" % cmd)
  277. self.testvm1.start()
  278. cmd = "systemctl start xendriverdomain"
  279. if self.run_cmd(self.testnetvm, cmd) != 0:
  280. self.fail("Command '%s' failed" % cmd)
  281. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  282. def test_200_fake_ip_simple(self):
  283. '''Test hiding VM real IP'''
  284. self.testvm1.features['net/fake-ip'] = '192.168.1.128'
  285. self.testvm1.features['net/fake-gateway'] = '192.168.1.1'
  286. self.testvm1.features['net/fake-netmask'] = '255.255.255.0'
  287. self.app.save()
  288. self.testvm1.start()
  289. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  290. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0)
  291. p = self.testvm1.run('ip addr show dev eth0', user='root',
  292. passio_popen=True,
  293. ignore_stderr=True)
  294. p.stdin.close()
  295. output = p.stdout.read().decode()
  296. self.assertEqual(p.wait(), 0, 'ip addr show dev eth0 failed')
  297. self.assertIn('192.168.1.128', output)
  298. self.assertNotIn(self.testvm1.ip, output)
  299. p = self.testvm1.run('ip route show', user='root',
  300. passio_popen=True,
  301. ignore_stderr=True)
  302. p.stdin.close()
  303. output = p.stdout.read().decode()
  304. self.assertEqual(p.wait(), 0, 'ip route show failed')
  305. self.assertIn('192.168.1.1', output)
  306. self.assertNotIn(self.testvm1.netvm.ip, output)
  307. def test_201_fake_ip_without_gw(self):
  308. '''Test hiding VM real IP'''
  309. self.testvm1.features['net/fake-ip'] = '192.168.1.128'
  310. self.app.save()
  311. self.testvm1.start()
  312. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  313. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0)
  314. p = self.testvm1.run('ip addr show dev eth0', user='root',
  315. passio_popen=True,
  316. ignore_stderr=True)
  317. p.stdin.close()
  318. output = p.stdout.read().decode()
  319. self.assertEqual(p.wait(), 0, 'ip addr show dev eth0 failed')
  320. self.assertIn('192.168.1.128', output)
  321. self.assertNotIn(self.testvm1.ip, output)
  322. def test_202_fake_ip_firewall(self):
  323. '''Test hiding VM real IP, firewall'''
  324. self.testvm1.features['net/fake-ip'] = '192.168.1.128'
  325. self.testvm1.features['net/fake-gateway'] = '192.168.1.1'
  326. self.testvm1.features['net/fake-netmask'] = '255.255.255.0'
  327. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  328. name=self.make_vm_name('proxy'),
  329. label='red')
  330. self.proxy.provides_network = True
  331. self.proxy.create_on_disk()
  332. self.proxy.netvm = self.testnetvm
  333. self.testvm1.netvm = self.proxy
  334. self.app.save()
  335. if self.run_cmd(self.testnetvm, 'nc -h 2>&1|grep -q nmap.org') == 0:
  336. nc_version = NcVersion.Nmap
  337. else:
  338. nc_version = NcVersion.Trad
  339. # block all but ICMP and DNS
  340. self.testvm1.firewall.policy = 'drop'
  341. self.testvm1.firewall.rules = [
  342. qubes.firewall.Rule(None, action='accept', proto='icmp'),
  343. qubes.firewall.Rule(None, action='accept', specialtarget='dns'),
  344. ]
  345. self.testvm1.firewall.save()
  346. self.testvm1.start()
  347. self.assertTrue(self.proxy.is_running())
  348. if nc_version == NcVersion.Nmap:
  349. self.testnetvm.run("nc -l --send-only -e /bin/hostname -k 1234")
  350. else:
  351. self.testnetvm.run("while nc -l -e /bin/hostname -p 1234; do "
  352. "true; done")
  353. self.assertEqual(self.run_cmd(self.proxy, self.ping_ip), 0,
  354. "Ping by IP from ProxyVM failed")
  355. self.assertEqual(self.run_cmd(self.proxy, self.ping_name), 0,
  356. "Ping by name from ProxyVM failed")
  357. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  358. "Ping by IP should be allowed")
  359. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  360. "Ping by name should be allowed")
  361. if nc_version == NcVersion.Nmap:
  362. nc_cmd = "nc -w 1 --recv-only {} 1234".format(self.test_ip)
  363. else:
  364. nc_cmd = "nc -w 1 {} 1234".format(self.test_ip)
  365. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  366. "TCP connection should be blocked")
  367. def test_203_fake_ip_inter_vm_allow(self):
  368. '''Access VM with "fake IP" from other VM (when firewall allows)'''
  369. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  370. name=self.make_vm_name('proxy'),
  371. label='red')
  372. self.proxy.create_on_disk()
  373. self.proxy.provides_network = True
  374. self.proxy.netvm = self.testnetvm
  375. self.testvm1.netvm = self.proxy
  376. self.testvm1.features['net/fake-ip'] = '192.168.1.128'
  377. self.testvm1.features['net/fake-gateway'] = '192.168.1.1'
  378. self.testvm1.features['net/fake-netmask'] = '255.255.255.0'
  379. self.testvm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  380. name=self.make_vm_name('vm3'),
  381. label='red')
  382. self.testvm2.create_on_disk()
  383. self.testvm2.netvm = self.proxy
  384. self.app.save()
  385. self.testvm1.start()
  386. self.testvm2.start()
  387. cmd = 'iptables -I FORWARD -s {} -d {} -j ACCEPT'.format(
  388. self.testvm2.ip, self.testvm1.ip)
  389. retcode = self.proxy.run(cmd, user='root', wait=True)
  390. self.assertEqual(retcode, 0, '{} failed with: {}'.format(cmd, retcode))
  391. cmd = 'iptables -I INPUT -s {} -j ACCEPT'.format(
  392. self.testvm2.ip)
  393. retcode = self.testvm1.run(cmd, user='root', wait=True)
  394. self.assertEqual(retcode, 0, '{} failed with: {}'.format(cmd, retcode))
  395. self.assertEqual(self.run_cmd(self.testvm2,
  396. self.ping_cmd.format(target=self.testvm1.ip)), 0)
  397. cmd = 'iptables -nvxL INPUT | grep {}'.format(self.testvm2.ip)
  398. p = self.testvm1.run(cmd, user='root', passio_popen=True)
  399. (stdout, _) = p.communicate()
  400. self.assertEqual(p.returncode, 0,
  401. '{} failed with {}'.format(cmd, p.returncode))
  402. self.assertNotEqual(stdout.decode().split()[0], '0',
  403. 'Packets didn\'t managed to the VM')
  404. def test_204_fake_ip_proxy(self):
  405. '''Test hiding VM real IP'''
  406. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  407. name=self.make_vm_name('proxy'),
  408. label='red')
  409. self.proxy.create_on_disk()
  410. self.proxy.provides_network = True
  411. self.proxy.netvm = self.testnetvm
  412. self.proxy.features['net/fake-ip'] = '192.168.1.128'
  413. self.proxy.features['net/fake-gateway'] = '192.168.1.1'
  414. self.proxy.features['net/fake-netmask'] = '255.255.255.0'
  415. self.testvm1.netvm = self.proxy
  416. self.app.save()
  417. self.testvm1.start()
  418. self.assertEqual(self.run_cmd(self.proxy, self.ping_ip), 0)
  419. self.assertEqual(self.run_cmd(self.proxy, self.ping_name), 0)
  420. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  421. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0)
  422. p = self.proxy.run('ip addr show dev eth0', user='root',
  423. passio_popen=True,
  424. ignore_stderr=True)
  425. p.stdin.close()
  426. output = p.stdout.read().decode()
  427. self.assertEqual(p.wait(), 0, 'ip addr show dev eth0 failed')
  428. self.assertIn('192.168.1.128', output)
  429. self.assertNotIn(self.testvm1.ip, output)
  430. p = self.proxy.run('ip route show', user='root',
  431. passio_popen=True,
  432. ignore_stderr=True)
  433. p.stdin.close()
  434. output = p.stdout.read().decode()
  435. self.assertEqual(p.wait(), 0, 'ip route show failed')
  436. self.assertIn('192.168.1.1', output)
  437. self.assertNotIn(self.testvm1.netvm.ip, output)
  438. p = self.testvm1.run('ip addr show dev eth0', user='root',
  439. passio_popen=True,
  440. ignore_stderr=True)
  441. p.stdin.close()
  442. output = p.stdout.read().decode()
  443. self.assertEqual(p.wait(), 0, 'ip addr show dev eth0 failed')
  444. self.assertNotIn('192.168.1.128', output)
  445. self.assertIn(self.testvm1.ip, output)
  446. p = self.testvm1.run('ip route show', user='root',
  447. passio_popen=True,
  448. ignore_stderr=True)
  449. p.stdin.close()
  450. output = p.stdout.read().decode()
  451. self.assertEqual(p.wait(), 0, 'ip route show failed')
  452. self.assertIn('192.168.1.128', output)
  453. self.assertNotIn(self.proxy.ip, output)
  454. def test_210_custom_ip_simple(self):
  455. '''Custom AppVM IP'''
  456. self.testvm1.ip = '192.168.1.1'
  457. self.app.save()
  458. self.testvm1.start()
  459. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  460. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0)
  461. def test_211_custom_ip_proxy(self):
  462. '''Custom ProxyVM IP'''
  463. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  464. name=self.make_vm_name('proxy'),
  465. label='red')
  466. self.proxy.create_on_disk()
  467. self.proxy.provides_network = True
  468. self.proxy.netvm = self.testnetvm
  469. self.proxy.ip = '192.168.1.1'
  470. self.testvm1.netvm = self.proxy
  471. self.app.save()
  472. self.testvm1.start()
  473. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  474. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0)
  475. def test_212_custom_ip_firewall(self):
  476. '''Custom VM IP and firewall'''
  477. self.testvm1.ip = '192.168.1.1'
  478. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  479. name=self.make_vm_name('proxy'),
  480. label='red')
  481. self.proxy.provides_network = True
  482. self.proxy.create_on_disk()
  483. self.proxy.netvm = self.testnetvm
  484. self.testvm1.netvm = self.proxy
  485. self.app.save()
  486. if self.run_cmd(self.testnetvm, 'nc -h 2>&1|grep -q nmap.org') == 0:
  487. nc_version = NcVersion.Nmap
  488. else:
  489. nc_version = NcVersion.Trad
  490. # block all but ICMP and DNS
  491. self.testvm1.firewall.policy = 'drop'
  492. self.testvm1.firewall.rules = [
  493. qubes.firewall.Rule(None, action='accept', proto='icmp'),
  494. qubes.firewall.Rule(None, action='accept', specialtarget='dns'),
  495. ]
  496. self.testvm1.firewall.save()
  497. self.testvm1.start()
  498. self.assertTrue(self.proxy.is_running())
  499. if nc_version == NcVersion.Nmap:
  500. self.testnetvm.run("nc -l --send-only -e /bin/hostname -k 1234")
  501. else:
  502. self.testnetvm.run("while nc -l -e /bin/hostname -p 1234; do "
  503. "true; done")
  504. self.assertEqual(self.run_cmd(self.proxy, self.ping_ip), 0,
  505. "Ping by IP from ProxyVM failed")
  506. self.assertEqual(self.run_cmd(self.proxy, self.ping_name), 0,
  507. "Ping by name from ProxyVM failed")
  508. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  509. "Ping by IP should be allowed")
  510. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  511. "Ping by name should be allowed")
  512. if nc_version == NcVersion.Nmap:
  513. nc_cmd = "nc -w 1 --recv-only {} 1234".format(self.test_ip)
  514. else:
  515. nc_cmd = "nc -w 1 {} 1234".format(self.test_ip)
  516. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  517. "TCP connection should be blocked")
  518. # noinspection PyAttributeOutsideInit
  519. class VmUpdatesMixin(qubes.tests.SystemTestsMixin):
  520. """
  521. Tests for VM updates
  522. """
  523. # filled by load_tests
  524. template = None
  525. # made this way to work also when no package build tools are installed
  526. """
  527. $ cat test-pkg.spec:
  528. Name: test-pkg
  529. Version: 1.0
  530. Release: 1%{?dist}
  531. Summary: Test package
  532. Group: System
  533. License: GPL
  534. URL: http://example.com/
  535. %description
  536. Test package
  537. %files
  538. %changelog
  539. $ rpmbuild -bb test-pkg.spec
  540. $ cat test-pkg-1.0-1.fc21.x86_64.rpm | gzip | base64
  541. """
  542. RPM_PACKAGE_GZIP_BASE64 = (
  543. b"H4sIAPzRLlYAA+2Y728URRjHn7ueUCkERKJVJDnTxLSxs7293o8WOER6ljYYrtKCLUSa3"
  544. b"bnZ64bd22VmTq8nr4wJbwxvjNHIG0x8oTHGGCHB8AcYE1/0lS80GgmQFCJU3wgB4ZjdfZ"
  545. b"q2xDe8NNlvMjfzmeeZH7tPbl98b35169cOUEpIJiTxT9SIrmVUs2hWh8dUAp54dOrM14s"
  546. b"JHK4D2DKl+j2qrVfjsuq3qEWbohjuAB2Lqk+p1o/8Z5QPmSi/YwnjezH+F8bLQZjqllW0"
  547. b"hvODRmFIL5hFk9JMXi/mi5ZuDleNwSEzP5wtmLnouNQnm3/6fndz7FLt9M/Hruj37gav4"
  548. b"tTjPnasWLFixYoVK1asWLFixYoV63+p0KNot9vnIPQc1vgYOwCSgXfxCoS+QzKHOVXVOj"
  549. b"Fn2ccIfI0k8nXkLuQbyJthxed4UrVnkG8i9yDfgsj3yCAv4foc8t+w1hf5B+Nl5Du43xj"
  550. b"yvxivIN9HpsgPkO2IU9uQfeRn8Xk/iJ4x1Y3nfxH1qecwfhH5+YgT25F7o/0SRdxvOppP"
  551. b"7MX9ZjB/DNnE/OOYX404uRGZIT+FbCFvQ3aQ8f0+/WF0XjJ8nyOw7H+BrmUA/a8pNZf2D"
  552. b"XrCqLG1cERbWHI8ajhznpBY9P0Tr8PkvJDMhTkp/Z0DA6xpuL7DNOq5A+DY9UYTmkOF2U"
  553. b"IO/sNt0wSnGvfdlZssD3rVIlLI9UUX37C6qXzHNntHPNfnTAhWHbUddtBwmegDjAUzZbu"
  554. b"m9lqZmzDmHc8Ik8WY8Tab4Myym4+Gx8V0qw8GtYyWIzrktEJwV9UHv3ktG471rAqHTmFQ"
  555. b"685V5uGqIalk06SWJr7tszR503Ac9cs493jJ8rhrSCIYbXBbzqt5v5+UZ0crh6bGR2dmJ"
  556. b"yuHD428VlLLLdakzJe2VxcKhFSFID73JKPS40RI7tXVCcQ3uOGWhPCJ2bAspiJ2i5Vy6n"
  557. b"jOqMerpEYpEe/Yks4xkU4Tt6BirmzUWanG6ozbFKhve9BsQRaLRTirzqk7hgUktXojKnf"
  558. b"n8jeg3X4QepP3i63po6oml+9t/CwJLya2Bn/ei6f7/4B3Ycdb0L3pt5Q5mNz16rWJ9fLk"
  559. b"vvOff/nxS7//8O2P2gvt7nDDnoV9L1du9N4+ucjl9u/8+a7dC5Nnvjlv9Ox5r+v9Cy0NE"
  560. b"m+c6rv60S/dZw98Gn6MNswcfQiWUvg3wBUAAA=="
  561. )
  562. """
  563. Minimal package generated by running dh_make on empty directory
  564. Then cat test-pkg_1.0-1_amd64.deb | gzip | base64
  565. """
  566. DEB_PACKAGE_GZIP_BASE64 = (
  567. b"H4sIACTXLlYAA1O0SSxKzrDjSklNykzM003KzEssqlRQUDA0MTG1NDQwNDVTUDBQAAEIa"
  568. b"WhgYGZioqBgogADCVxGegZcyfl5JUX5OXoliUV66VVE6DcwheuX7+ZgAAEW5rdXHb0PG4"
  569. b"iwf5j3WfMT6zWzzMuZgoE3jjYraNzbbFKWGms0SaRw/r2SV23WZ4IdP8preM4yqf0jt95"
  570. b"3c8qnacfNxJUkf9/w+/3X9ph2GEdgQdixrz/niHKKTnYXizf4oSC7tHOz2Zzq+/6vn8/7"
  571. b"ezQ7c1tmi7xZ3SGJ4yzhT2dcr7V+W3zM5ZPu/56PSv4Zdok+7Yv/V/6buWaKVlFkkV58S"
  572. b"N3GmLgnqzRmeZ3V3ymmurS5fGa85/LNx1bpZMin3S6dvXKqydp3ubP1vmyarJZb/qSh62"
  573. b"C8oIdxqm/BtvkGDza+On/Vfv2py7/0LV7VH+qR6a+bkKUbHXt5/SG187d+nps1a5PJfMO"
  574. b"i11dWcUe1HjwaW3Q5RHXn9LmcHy+tW9YcKf0768XVB1t3R0bKrzs5t9P+6r7rZ99svH10"
  575. b"+Q6F/o8tf1fO/32y+fWa14eifd+WxUy0jcxYH7N9/tUvmnUZL74pW32qLeuRU+ZwYGASa"
  576. b"GBgUWBgxM90ayy3VdmykkGDgYErJbEkERydFVWQmCMQo8aWZvAY/WteFRHFwMCYqXTPjI"
  577. b"lBkVEMGLsl+k8XP1D/z+gXyyDOvUemlnHqAVkvu0rRQ2fUFodkN3mtU9uwhqk8V+TqPEE"
  578. b"Nc7fzoQ4n71lqRs/7kbbT0+qOZuKH4r8mjzsc1k/YkCHN8Pjg48fbpE+teHa96LNcfu0V"
  579. b"5n2/Z2xa2KDvaCOx8cqBFxc514uZ3TmadXS+6cpzU7wSzq5SWfapJOD9n6wLXSwtlgxZh"
  580. b"xITzWW7buhx/bb291RcVlEfeC9K5hlrqunSzIMSZT7/Nqgc/qMvMNW227WI8ezB8mVuZh"
  581. b"0hERJSvysfburr4Dx0I9BW57UwR4+e1gxu49PcEt8sbK18Xpvt//Hj5UYm+Zc25q+T4xl"
  582. b"rJvxfVnh80oadq57OZxPaU1bbztv1yF365W4t45Yr+XrFzov237GVY1Zgf7NvE4+W2SuR"
  583. b"lQtLauR1TQ/mbOiIONYya6tU1jPGpWfk/i1+ttiXe3ZO14n0YOWggndznjGlGLyfVbBC6"
  584. b"MRP5aMM7aCco/s7sZqB8RlTQwADw8rnuT/sDHi7mUASjJFRAAbWwNLiAwAA"
  585. )
  586. def run_cmd(self, vm, cmd, user="root"):
  587. p = vm.run(cmd, user=user, passio_popen=True, ignore_stderr=True)
  588. p.stdin.close()
  589. p.stdout.read().decode()
  590. return p.wait()
  591. def setUp(self):
  592. super(VmUpdatesMixin, self).setUp()
  593. self.update_cmd = None
  594. if self.template.count("debian"):
  595. self.update_cmd = "set -o pipefail; apt-get update 2>&1 | " \
  596. "{ ! grep '^W:\|^E:'; }"
  597. self.install_cmd = "apt-get install -y {}"
  598. self.install_test_cmd = "dpkg -l {}"
  599. self.exit_code_ok = [0]
  600. elif self.template.count("fedora"):
  601. cmd = "yum"
  602. try:
  603. # assume template name in form "fedora-XX-suffix"
  604. if int(self.template.split("-")[1]) > 21:
  605. cmd = "dnf"
  606. except ValueError:
  607. pass
  608. self.update_cmd = "{cmd} clean all; {cmd} check-update".format(
  609. cmd=cmd)
  610. self.install_cmd = cmd + " install -y {}"
  611. self.install_test_cmd = "rpm -q {}"
  612. self.exit_code_ok = [0, 100]
  613. else:
  614. self.skipTest("Template {} not supported by this test".format(
  615. self.template))
  616. self.init_default_template(self.template)
  617. self.init_networking()
  618. self.testvm1 = self.app.add_new_vm(
  619. qubes.vm.appvm.AppVM,
  620. name=self.make_vm_name('vm1'),
  621. label='red')
  622. self.testvm1.create_on_disk()
  623. def test_000_simple_update(self):
  624. self.save_and_reload_db()
  625. # reload the VM to have all the properties properly set (especially
  626. # default netvm)
  627. self.testvm1 = self.app.domains[self.testvm1.qid]
  628. self.testvm1.start()
  629. p = self.testvm1.run(self.update_cmd, wait=True, user="root",
  630. passio_popen=True, passio_stderr=True)
  631. (stdout, stderr) = p.communicate()
  632. self.assertIn(p.wait(), self.exit_code_ok,
  633. "{}: {}\n{}".format(self.update_cmd, stdout, stderr)
  634. )
  635. def create_repo_apt(self):
  636. pkg_file_name = "test-pkg_1.0-1_amd64.deb"
  637. p = self.netvm_repo.run("mkdir /tmp/apt-repo && cd /tmp/apt-repo &&"
  638. "base64 -d | zcat > {}".format(pkg_file_name),
  639. passio_popen=True)
  640. p.stdin.write(self.DEB_PACKAGE_GZIP_BASE64)
  641. p.stdin.close()
  642. if p.wait() != 0:
  643. raise RuntimeError("Failed to write {}".format(pkg_file_name))
  644. # do not assume dpkg-scanpackage installed
  645. packages_path = "dists/test/main/binary-amd64/Packages"
  646. p = self.netvm_repo.run(
  647. "mkdir -p /tmp/apt-repo/dists/test/main/binary-amd64 && "
  648. "cd /tmp/apt-repo && "
  649. "cat > {packages} && "
  650. "echo MD5sum: $(openssl md5 -r {pkg} | cut -f 1 -d ' ')"
  651. " >> {packages} && "
  652. "echo SHA1: $(openssl sha1 -r {pkg} | cut -f 1 -d ' ')"
  653. " >> {packages} && "
  654. "echo SHA256: $(openssl sha256 -r {pkg} | cut -f 1 -d ' ')"
  655. " >> {packages} && "
  656. "gzip < {packages} > {packages}.gz".format(pkg=pkg_file_name,
  657. packages=packages_path),
  658. passio_popen=True, passio_stderr=True)
  659. p.stdin.write(
  660. "Package: test-pkg\n"
  661. "Version: 1.0-1\n"
  662. "Architecture: amd64\n"
  663. "Maintainer: unknown <user@host>\n"
  664. "Installed-Size: 25\n"
  665. "Filename: {pkg}\n"
  666. "Size: 994\n"
  667. "Section: unknown\n"
  668. "Priority: optional\n"
  669. "Description: Test package\n".format(pkg=pkg_file_name)
  670. )
  671. p.stdin.close()
  672. if p.wait() != 0:
  673. raise RuntimeError("Failed to write Packages file: {}".format(
  674. p.stderr.read().decode()))
  675. p = self.netvm_repo.run(
  676. "mkdir -p /tmp/apt-repo/dists/test && "
  677. "cd /tmp/apt-repo/dists/test && "
  678. "cat > Release && "
  679. "echo '' $(sha256sum {p} | cut -f 1 -d ' ') $(stat -c %s {p}) {p}"
  680. " >> Release && "
  681. "echo '' $(sha256sum {z} | cut -f 1 -d ' ') $(stat -c %s {z}) {z}"
  682. " >> Release"
  683. .format(p="main/binary-amd64/Packages",
  684. z="main/binary-amd64/Packages.gz"),
  685. passio_popen=True, passio_stderr=True
  686. )
  687. p.stdin.write(
  688. "Label: Test repo\n"
  689. "Suite: test\n"
  690. "Codename: test\n"
  691. "Date: Tue, 27 Oct 2015 03:22:09 UTC\n"
  692. "Architectures: amd64\n"
  693. "Components: main\n"
  694. "SHA256:\n"
  695. )
  696. p.stdin.close()
  697. if p.wait() != 0:
  698. raise RuntimeError("Failed to write Release file: {}".format(
  699. p.stderr.read().decode()))
  700. def create_repo_yum(self):
  701. pkg_file_name = "test-pkg-1.0-1.fc21.x86_64.rpm"
  702. p = self.netvm_repo.run("mkdir /tmp/yum-repo && cd /tmp/yum-repo &&"
  703. "base64 -d | zcat > {}".format(pkg_file_name),
  704. passio_popen=True, passio_stderr=True)
  705. p.stdin.write(self.RPM_PACKAGE_GZIP_BASE64)
  706. p.stdin.close()
  707. if p.wait() != 0:
  708. raise RuntimeError("Failed to write {}: {}".format(pkg_file_name,
  709. p.stderr.read().decode()))
  710. # createrepo is installed by default in Fedora template
  711. p = self.netvm_repo.run("createrepo /tmp/yum-repo",
  712. passio_popen=True,
  713. passio_stderr=True)
  714. if p.wait() != 0:
  715. raise RuntimeError("Failed to create yum metadata: {}".format(
  716. p.stderr.read().decode()))
  717. def create_repo_and_serve(self):
  718. if self.template.count("debian") or self.template.count("whonix"):
  719. self.create_repo_apt()
  720. self.netvm_repo.run("cd /tmp/apt-repo &&"
  721. "python -m SimpleHTTPServer 8080")
  722. elif self.template.count("fedora"):
  723. self.create_repo_yum()
  724. self.netvm_repo.run("cd /tmp/yum-repo &&"
  725. "python -m SimpleHTTPServer 8080")
  726. else:
  727. # not reachable...
  728. self.skipTest("Template {} not supported by this test".format(
  729. self.template))
  730. def configure_test_repo(self):
  731. """
  732. Configure test repository in test-vm and disable rest of them.
  733. The critical part is to use "localhost" - this will work only when
  734. accessed through update proxy and this is exactly what we want to
  735. test here.
  736. """
  737. if self.template.count("debian") or self.template.count("whonix"):
  738. self.testvm1.run(
  739. "rm -f /etc/apt/sources.list.d/* &&"
  740. "echo 'deb [trusted=yes] http://localhost:8080 test main' "
  741. "> /etc/apt/sources.list",
  742. user="root")
  743. elif self.template.count("fedora"):
  744. self.testvm1.run(
  745. "rm -f /etc/yum.repos.d/*.repo &&"
  746. "echo '[test]' > /etc/yum.repos.d/test.repo &&"
  747. "echo 'name=Test repo' >> /etc/yum.repos.d/test.repo &&"
  748. "echo 'gpgcheck=0' >> /etc/yum.repos.d/test.repo &&"
  749. "echo 'baseurl=http://localhost:8080/'"
  750. " >> /etc/yum.repos.d/test.repo",
  751. user="root"
  752. )
  753. else:
  754. # not reachable...
  755. self.skipTest("Template {} not supported by this test".format(
  756. self.template))
  757. def test_010_update_via_proxy(self):
  758. """
  759. Test both whether updates proxy works and whether is actually used by the VM
  760. """
  761. if self.template.count("minimal"):
  762. self.skipTest("Template {} not supported by this test".format(
  763. self.template))
  764. self.netvm_repo = self.app.add_new_vm(
  765. qubes.vm.appvm.AppVM,
  766. name=self.make_vm_name('net'),
  767. label='red')
  768. self.netvm_repo.provides_network = True
  769. self.netvm_repo.create_on_disk()
  770. self.testvm1.netvm = self.netvm_repo
  771. # NetVM should have qubes-updates-proxy enabled by default
  772. #self.netvm_repo.features['qubes-updates-proxy'] = True
  773. # TODO: consider also adding a test for the template itself
  774. self.testvm1.features['updates-proxy-setup'] = True
  775. self.app.save()
  776. # Setup test repo
  777. self.netvm_repo.start()
  778. self.create_repo_and_serve()
  779. # Configure local repo
  780. self.testvm1.start()
  781. self.configure_test_repo()
  782. # update repository metadata
  783. p = self.testvm1.run(self.update_cmd, wait=True, user="root",
  784. passio_popen=True, passio_stderr=True)
  785. (stdout, stderr) = p.communicate()
  786. self.assertIn(p.wait(), self.exit_code_ok,
  787. "{}: {}\n{}".format(self.update_cmd, stdout, stderr)
  788. )
  789. # install test package
  790. p = self.testvm1.run(self.install_cmd.format('test-pkg'),
  791. wait=True, user="root",
  792. passio_popen=True, passio_stderr=True)
  793. (stdout, stderr) = p.communicate()
  794. self.assertIn(p.wait(), self.exit_code_ok,
  795. "{}: {}\n{}".format(self.update_cmd, stdout, stderr)
  796. )
  797. # verify if it was really installed
  798. p = self.testvm1.run(self.install_test_cmd.format('test-pkg'),
  799. wait=True, user="root",
  800. passio_popen=True, passio_stderr=True)
  801. (stdout, stderr) = p.communicate()
  802. self.assertIn(p.wait(), self.exit_code_ok,
  803. "{}: {}\n{}".format(self.update_cmd, stdout, stderr)
  804. )
  805. def load_tests(loader, tests, pattern):
  806. try:
  807. app = qubes.Qubes()
  808. templates = [vm.name for vm in app.domains if
  809. isinstance(vm, qubes.vm.templatevm.TemplateVM)]
  810. except OSError:
  811. templates = []
  812. for template in templates:
  813. tests.addTests(loader.loadTestsFromTestCase(
  814. type(
  815. 'VmNetworking_' + template,
  816. (VmNetworkingMixin, qubes.tests.QubesTestCase),
  817. {'template': template})))
  818. tests.addTests(loader.loadTestsFromTestCase(
  819. type(
  820. 'VmUpdates_' + template,
  821. (VmUpdatesMixin, qubes.tests.QubesTestCase),
  822. {'template': template})))
  823. return tests