network.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342
  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 library is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU Lesser General Public
  10. # License as published by the Free Software Foundation; either
  11. # version 2.1 of the License, or (at your option) any later version.
  12. #
  13. # This library 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 GNU
  16. # Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public
  19. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  20. #
  21. from distutils import spawn
  22. import asyncio
  23. import multiprocessing
  24. import os
  25. import subprocess
  26. import unittest
  27. import time
  28. import qubes.tests
  29. import qubes.firewall
  30. import qubes.vm.appvm
  31. class NcVersion:
  32. Trad = 1
  33. Nmap = 2
  34. # noinspection PyAttributeOutsideInit
  35. class VmNetworkingMixin(object):
  36. test_ip = '192.168.123.45'
  37. test_name = 'test.example.com'
  38. ping_cmd = 'ping -W 1 -n -c 1 {target}'
  39. ping_ip = ping_cmd.format(target=test_ip)
  40. ping_name = ping_cmd.format(target=test_name)
  41. # filled by load_tests
  42. template = None
  43. def run_cmd(self, vm, cmd, user="root"):
  44. try:
  45. self.loop.run_until_complete(vm.run_for_stdio(cmd, user=user))
  46. except subprocess.CalledProcessError as e:
  47. return e.returncode
  48. return 0
  49. def setUp(self):
  50. super(VmNetworkingMixin, self).setUp()
  51. if self.template.startswith('whonix-'):
  52. self.skipTest("Test not supported here - Whonix uses its own "
  53. "firewall settings")
  54. self.init_default_template(self.template)
  55. self.testnetvm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  56. name=self.make_vm_name('netvm1'),
  57. label='red')
  58. self.loop.run_until_complete(self.testnetvm.create_on_disk())
  59. self.testnetvm.provides_network = True
  60. self.testvm1 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  61. name=self.make_vm_name('vm1'),
  62. label='red')
  63. self.loop.run_until_complete(self.testvm1.create_on_disk())
  64. self.testvm1.netvm = self.testnetvm
  65. self.app.save()
  66. self.configure_netvm()
  67. def configure_netvm(self):
  68. def run_netvm_cmd(cmd):
  69. if self.run_cmd(self.testnetvm, cmd) != 0:
  70. self.fail("Command '%s' failed" % cmd)
  71. if not self.testnetvm.is_running():
  72. self.loop.run_until_complete(self.testnetvm.start())
  73. # Ensure that dnsmasq is installed:
  74. try:
  75. self.loop.run_until_complete(self.testnetvm.run_for_stdio(
  76. 'dnsmasq --version', user='root'))
  77. except subprocess.CalledProcessError:
  78. self.skipTest("dnsmasq not installed")
  79. run_netvm_cmd("ip link add test0 type dummy")
  80. run_netvm_cmd("ip link set test0 up")
  81. run_netvm_cmd("ip addr add {}/24 dev test0".format(self.test_ip))
  82. run_netvm_cmd("iptables -I INPUT -d {} -j ACCEPT".format(self.test_ip))
  83. # ignore failure
  84. self.run_cmd(self.testnetvm, "killall --wait dnsmasq")
  85. run_netvm_cmd("dnsmasq -a {ip} -A /{name}/{ip} -i test0 -z".format(
  86. ip=self.test_ip, name=self.test_name))
  87. run_netvm_cmd("echo nameserver {} > /etc/resolv.conf".format(
  88. self.test_ip))
  89. run_netvm_cmd("/usr/lib/qubes/qubes-setup-dnat-to-ns")
  90. def test_000_simple_networking(self):
  91. self.loop.run_until_complete(self.testvm1.start())
  92. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  93. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0)
  94. def test_010_simple_proxyvm(self):
  95. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  96. name=self.make_vm_name('proxy'),
  97. label='red')
  98. self.proxy.provides_network = True
  99. self.proxy.netvm = self.testnetvm
  100. self.loop.run_until_complete(self.proxy.create_on_disk())
  101. self.testvm1.netvm = self.proxy
  102. self.app.save()
  103. self.loop.run_until_complete(self.testvm1.start())
  104. self.assertTrue(self.proxy.is_running())
  105. self.assertEqual(self.run_cmd(self.proxy, self.ping_ip), 0,
  106. "Ping by IP from ProxyVM failed")
  107. self.assertEqual(self.run_cmd(self.proxy, self.ping_name), 0,
  108. "Ping by name from ProxyVM failed")
  109. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  110. "Ping by IP from AppVM failed")
  111. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  112. "Ping by IP from AppVM failed")
  113. @qubes.tests.expectedFailureIfTemplate('debian-7')
  114. @unittest.skipUnless(spawn.find_executable('xdotool'),
  115. "xdotool not installed")
  116. def test_020_simple_proxyvm_nm(self):
  117. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  118. name=self.make_vm_name('proxy'),
  119. label='red')
  120. self.proxy.provides_network = True
  121. self.loop.run_until_complete(self.proxy.create_on_disk())
  122. self.proxy.netvm = self.testnetvm
  123. self.proxy.features['service.network-manager'] = True
  124. self.testvm1.netvm = self.proxy
  125. self.app.save()
  126. self.loop.run_until_complete(self.testvm1.start())
  127. self.assertTrue(self.proxy.is_running())
  128. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  129. "Ping by IP failed")
  130. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  131. "Ping by name failed")
  132. # reconnect to make sure that device was configured by NM
  133. self.assertEqual(
  134. self.run_cmd(self.proxy, "nmcli device disconnect eth0",
  135. user="user"),
  136. 0, "Failed to disconnect eth0 using nmcli")
  137. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  138. "Network should be disabled, but apparently it isn't")
  139. self.assertEqual(
  140. self.run_cmd(self.proxy,
  141. 'nmcli connection up "VM uplink eth0" ifname eth0',
  142. user="user"),
  143. 0, "Failed to connect eth0 using nmcli")
  144. self.assertEqual(self.run_cmd(self.proxy, "nm-online", user="user"), 0,
  145. "Failed to wait for NM connection")
  146. # check for nm-applet presence
  147. self.assertEqual(subprocess.call([
  148. 'xdotool', 'search', '--class', '{}:nm-applet'.format(
  149. self.proxy.name)],
  150. stdout=subprocess.DEVNULL), 0, "nm-applet window not found")
  151. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  152. "Ping by IP failed (after NM reconnection")
  153. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  154. "Ping by name failed (after NM reconnection)")
  155. def test_030_firewallvm_firewall(self):
  156. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  157. name=self.make_vm_name('proxy'),
  158. label='red')
  159. self.proxy.provides_network = True
  160. self.loop.run_until_complete(self.proxy.create_on_disk())
  161. self.proxy.netvm = self.testnetvm
  162. self.testvm1.netvm = self.proxy
  163. self.app.save()
  164. if self.run_cmd(self.testnetvm, 'nc -h 2>&1|grep -q nmap.org') == 0:
  165. nc_version = NcVersion.Nmap
  166. else:
  167. nc_version = NcVersion.Trad
  168. # block all for first
  169. self.testvm1.firewall.rules = [qubes.firewall.Rule(action='drop')]
  170. self.testvm1.firewall.save()
  171. self.loop.run_until_complete(self.testvm1.start())
  172. self.assertTrue(self.proxy.is_running())
  173. nc = self.loop.run_until_complete(self.testnetvm.run(
  174. 'nc -l --send-only -e /bin/hostname -k 1234'
  175. if nc_version == NcVersion.Nmap
  176. else 'while nc -l -e /bin/hostname -p 1234; do true; done'))
  177. try:
  178. self.assertEqual(self.run_cmd(self.proxy, self.ping_ip), 0,
  179. "Ping by IP from ProxyVM failed")
  180. self.assertEqual(self.run_cmd(self.proxy, self.ping_name), 0,
  181. "Ping by name from ProxyVM failed")
  182. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  183. "Ping by IP should be blocked")
  184. if nc_version == NcVersion.Nmap:
  185. nc_cmd = "nc -w 1 --recv-only {} 1234".format(self.test_ip)
  186. else:
  187. nc_cmd = "nc -w 1 {} 1234".format(self.test_ip)
  188. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  189. "TCP connection should be blocked")
  190. # block all except ICMP
  191. self.testvm1.firewall.rules = [(
  192. qubes.firewall.Rule(None, action='accept', proto='icmp')
  193. )]
  194. self.testvm1.firewall.save()
  195. # Ugly hack b/c there is no feedback when the rules are actually
  196. # applied
  197. time.sleep(3)
  198. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  199. "Ping by IP failed (should be allowed now)")
  200. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  201. "Ping by name should be blocked")
  202. # all TCP still blocked
  203. self.testvm1.firewall.rules = [
  204. qubes.firewall.Rule(None, action='accept', proto='icmp'),
  205. qubes.firewall.Rule(None, action='accept', specialtarget='dns'),
  206. ]
  207. self.testvm1.firewall.save()
  208. # Ugly hack b/c there is no feedback when the rules are actually
  209. # applied
  210. time.sleep(3)
  211. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  212. "Ping by name failed (should be allowed now)")
  213. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  214. "TCP connection should be blocked")
  215. # block all except target
  216. self.testvm1.firewall.rules = [
  217. qubes.firewall.Rule(None, action='accept', dsthost=self.test_ip,
  218. proto='tcp', dstports=1234),
  219. ]
  220. self.testvm1.firewall.save()
  221. # Ugly hack b/c there is no feedback when the rules are actually
  222. # applied
  223. time.sleep(3)
  224. self.assertEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  225. "TCP connection failed (should be allowed now)")
  226. # allow all except target
  227. self.testvm1.firewall.rules = [
  228. qubes.firewall.Rule(None, action='drop', dsthost=self.test_ip,
  229. proto='tcp', dstports=1234),
  230. qubes.firewall.Rule(action='accept'),
  231. ]
  232. self.testvm1.firewall.save()
  233. # Ugly hack b/c there is no feedback when the rules are actually
  234. # applied
  235. time.sleep(3)
  236. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  237. "TCP connection should be blocked")
  238. finally:
  239. nc.terminate()
  240. self.loop.run_until_complete(nc.wait())
  241. def test_040_inter_vm(self):
  242. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  243. name=self.make_vm_name('proxy'),
  244. label='red')
  245. self.loop.run_until_complete(self.proxy.create_on_disk())
  246. self.proxy.provides_network = True
  247. self.proxy.netvm = self.testnetvm
  248. self.testvm1.netvm = self.proxy
  249. self.testvm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  250. name=self.make_vm_name('vm2'),
  251. label='red')
  252. self.loop.run_until_complete(self.testvm2.create_on_disk())
  253. self.testvm2.netvm = self.proxy
  254. self.app.save()
  255. self.loop.run_until_complete(asyncio.wait([
  256. self.testvm1.start(),
  257. self.testvm2.start()]))
  258. self.assertNotEqual(self.run_cmd(self.testvm1,
  259. self.ping_cmd.format(target=self.testvm2.ip)), 0)
  260. self.testvm2.netvm = self.testnetvm
  261. self.assertNotEqual(self.run_cmd(self.testvm1,
  262. self.ping_cmd.format(target=self.testvm2.ip)), 0)
  263. self.assertNotEqual(self.run_cmd(self.testvm2,
  264. self.ping_cmd.format(target=self.testvm1.ip)), 0)
  265. self.testvm1.netvm = self.testnetvm
  266. self.assertNotEqual(self.run_cmd(self.testvm1,
  267. self.ping_cmd.format(target=self.testvm2.ip)), 0)
  268. self.assertNotEqual(self.run_cmd(self.testvm2,
  269. self.ping_cmd.format(target=self.testvm1.ip)), 0)
  270. def test_050_spoof_ip(self):
  271. """Test if VM IP spoofing is blocked"""
  272. self.loop.run_until_complete(self.testvm1.start())
  273. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  274. self.assertEqual(self.run_cmd(self.testnetvm,
  275. 'iptables -I INPUT -i vif+ ! -s {} -p icmp -j LOG'.format(
  276. self.testvm1.ip)), 0)
  277. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  278. 'ip addr flush dev eth0 && '
  279. 'ip addr add 10.137.1.128/24 dev eth0 && '
  280. 'ip route add default dev eth0',
  281. user='root'))
  282. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  283. "Spoofed ping should be blocked")
  284. try:
  285. (output, _) = self.loop.run_until_complete(
  286. self.testnetvm.run_for_stdio('iptables -nxvL INPUT',
  287. user='root'))
  288. except subprocess.CalledProcessError:
  289. self.fail('iptables -nxvL INPUT failed')
  290. output = output.decode().splitlines()
  291. packets = output[2].lstrip().split()[0]
  292. self.assertEquals(packets, '0', 'Some packet hit the INPUT rule')
  293. def test_100_late_xldevd_startup(self):
  294. """Regression test for #1990"""
  295. # Simulater late xl devd startup
  296. cmd = "systemctl stop xendriverdomain"
  297. if self.run_cmd(self.testnetvm, cmd) != 0:
  298. self.fail("Command '%s' failed" % cmd)
  299. self.loop.run_until_complete(self.testvm1.start())
  300. cmd = "systemctl start xendriverdomain"
  301. if self.run_cmd(self.testnetvm, cmd) != 0:
  302. self.fail("Command '%s' failed" % cmd)
  303. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  304. def test_200_fake_ip_simple(self):
  305. '''Test hiding VM real IP'''
  306. self.testvm1.features['net.fake-ip'] = '192.168.1.128'
  307. self.testvm1.features['net.fake-gateway'] = '192.168.1.1'
  308. self.testvm1.features['net.fake-netmask'] = '255.255.255.0'
  309. self.app.save()
  310. self.loop.run_until_complete(self.testvm1.start())
  311. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  312. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0)
  313. try:
  314. (output, _) = self.loop.run_until_complete(
  315. self.testvm1.run_for_stdio(
  316. 'ip addr show dev eth0', user='root'))
  317. except subprocess.CalledProcessError:
  318. self.fail('ip addr show dev eth0 failed')
  319. output = output.decode()
  320. self.assertIn('192.168.1.128', output)
  321. self.assertNotIn(self.testvm1.ip, output)
  322. try:
  323. (output, _) = self.loop.run_until_complete(
  324. self.testvm1.run_for_stdio('ip route show', user='root'))
  325. except subprocess.CalledProcessError:
  326. self.fail('ip route show failed')
  327. output = output.decode()
  328. self.assertIn('192.168.1.1', output)
  329. self.assertNotIn(self.testvm1.netvm.ip, output)
  330. def test_201_fake_ip_without_gw(self):
  331. '''Test hiding VM real IP'''
  332. self.testvm1.features['net.fake-ip'] = '192.168.1.128'
  333. self.app.save()
  334. self.loop.run_until_complete(self.testvm1.start())
  335. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  336. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0)
  337. try:
  338. (output, _) = self.loop.run_until_complete(
  339. self.testvm1.run_for_stdio('ip addr show dev eth0',
  340. user='root'))
  341. except subprocess.CalledProcessError:
  342. self.fail('ip addr show dev eth0 failed')
  343. output = output.decode()
  344. self.assertIn('192.168.1.128', output)
  345. self.assertNotIn(self.testvm1.ip, output)
  346. def test_202_fake_ip_firewall(self):
  347. '''Test hiding VM real IP, firewall'''
  348. self.testvm1.features['net.fake-ip'] = '192.168.1.128'
  349. self.testvm1.features['net.fake-gateway'] = '192.168.1.1'
  350. self.testvm1.features['net.fake-netmask'] = '255.255.255.0'
  351. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  352. name=self.make_vm_name('proxy'),
  353. label='red')
  354. self.proxy.provides_network = True
  355. self.loop.run_until_complete(self.proxy.create_on_disk())
  356. self.proxy.netvm = self.testnetvm
  357. self.testvm1.netvm = self.proxy
  358. self.app.save()
  359. if self.run_cmd(self.testnetvm, 'nc -h 2>&1|grep -q nmap.org') == 0:
  360. nc_version = NcVersion.Nmap
  361. else:
  362. nc_version = NcVersion.Trad
  363. # block all but ICMP and DNS
  364. self.testvm1.firewall.rules = [
  365. qubes.firewall.Rule(None, action='accept', proto='icmp'),
  366. qubes.firewall.Rule(None, action='accept', specialtarget='dns'),
  367. ]
  368. self.testvm1.firewall.save()
  369. self.loop.run_until_complete(self.testvm1.start())
  370. self.assertTrue(self.proxy.is_running())
  371. nc = self.loop.run_until_complete(self.testnetvm.run(
  372. 'nc -l --send-only -e /bin/hostname -k 1234'
  373. if nc_version == NcVersion.Nmap
  374. else 'while nc -l -e /bin/hostname -p 1234; do true; done'))
  375. try:
  376. self.assertEqual(self.run_cmd(self.proxy, self.ping_ip), 0,
  377. "Ping by IP from ProxyVM failed")
  378. self.assertEqual(self.run_cmd(self.proxy, self.ping_name), 0,
  379. "Ping by name from ProxyVM failed")
  380. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  381. "Ping by IP should be allowed")
  382. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  383. "Ping by name should be allowed")
  384. if nc_version == NcVersion.Nmap:
  385. nc_cmd = "nc -w 1 --recv-only {} 1234".format(self.test_ip)
  386. else:
  387. nc_cmd = "nc -w 1 {} 1234".format(self.test_ip)
  388. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  389. "TCP connection should be blocked")
  390. finally:
  391. nc.terminate()
  392. self.loop.run_until_complete(nc.wait())
  393. def test_203_fake_ip_inter_vm_allow(self):
  394. '''Access VM with "fake IP" from other VM (when firewall allows)'''
  395. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  396. name=self.make_vm_name('proxy'),
  397. label='red')
  398. self.loop.run_until_complete(self.proxy.create_on_disk())
  399. self.proxy.provides_network = True
  400. self.proxy.netvm = self.testnetvm
  401. self.testvm1.netvm = self.proxy
  402. self.testvm1.features['net.fake-ip'] = '192.168.1.128'
  403. self.testvm1.features['net.fake-gateway'] = '192.168.1.1'
  404. self.testvm1.features['net.fake-netmask'] = '255.255.255.0'
  405. self.testvm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  406. name=self.make_vm_name('vm2'),
  407. label='red')
  408. self.loop.run_until_complete(self.testvm2.create_on_disk())
  409. self.testvm2.netvm = self.proxy
  410. self.app.save()
  411. self.loop.run_until_complete(self.testvm1.start())
  412. self.loop.run_until_complete(self.testvm2.start())
  413. try:
  414. cmd = 'iptables -I FORWARD -s {} -d {} -j ACCEPT'.format(
  415. self.testvm2.ip, self.testvm1.ip)
  416. self.loop.run_until_complete(self.proxy.run_for_stdio(
  417. cmd, user='root'))
  418. except subprocess.CalledProcessError as e:
  419. raise AssertionError(
  420. '{} failed with: {}'.format(cmd, e.returncode)) from None
  421. try:
  422. cmd = 'iptables -I INPUT -s {} -j ACCEPT'.format(self.testvm2.ip)
  423. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  424. cmd, user='root'))
  425. except subprocess.CalledProcessError as e:
  426. raise AssertionError(
  427. '{} failed with: {}'.format(cmd, e.returncode)) from None
  428. self.assertEqual(self.run_cmd(self.testvm2,
  429. self.ping_cmd.format(target=self.testvm1.ip)), 0)
  430. try:
  431. cmd = 'iptables -nvxL INPUT | grep {}'.format(self.testvm2.ip)
  432. (stdout, _) = self.loop.run_until_complete(
  433. self.testvm1.run_for_stdio(cmd, user='root'))
  434. except subprocess.CalledProcessError as e:
  435. raise AssertionError(
  436. '{} failed with {}'.format(cmd, e.returncode)) from None
  437. self.assertNotEqual(stdout.decode().split()[0], '0',
  438. 'Packets didn\'t managed to the VM')
  439. def test_204_fake_ip_proxy(self):
  440. '''Test hiding VM real IP'''
  441. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  442. name=self.make_vm_name('proxy'),
  443. label='red')
  444. self.loop.run_until_complete(self.proxy.create_on_disk())
  445. self.proxy.provides_network = True
  446. self.proxy.netvm = self.testnetvm
  447. self.proxy.features['net.fake-ip'] = '192.168.1.128'
  448. self.proxy.features['net.fake-gateway'] = '192.168.1.1'
  449. self.proxy.features['net.fake-netmask'] = '255.255.255.0'
  450. self.testvm1.netvm = self.proxy
  451. self.app.save()
  452. self.loop.run_until_complete(self.testvm1.start())
  453. self.assertEqual(self.run_cmd(self.proxy, self.ping_ip), 0)
  454. self.assertEqual(self.run_cmd(self.proxy, self.ping_name), 0)
  455. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  456. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0)
  457. try:
  458. (output, _) = self.loop.run_until_complete(
  459. self.proxy.run_for_stdio(
  460. 'ip addr show dev eth0', user='root'))
  461. except subprocess.CalledProcessError as e:
  462. self.fail('ip addr show dev eth0 failed')
  463. output = output.decode()
  464. self.assertIn('192.168.1.128', output)
  465. self.assertNotIn(self.testvm1.ip, output)
  466. try:
  467. (output, _) = self.loop.run_until_complete(
  468. self.proxy.run_for_stdio(
  469. 'ip route show', user='root'))
  470. except subprocess.CalledProcessError as e:
  471. self.fail('ip route show failed')
  472. output = output.decode()
  473. self.assertIn('192.168.1.1', output)
  474. self.assertNotIn(self.testvm1.netvm.ip, output)
  475. try:
  476. (output, _) = self.loop.run_until_complete(
  477. self.testvm1.run_for_stdio(
  478. 'ip addr show dev eth0', user='root'))
  479. except subprocess.CalledProcessError as e:
  480. self.fail('ip addr show dev eth0 failed')
  481. output = output.decode()
  482. self.assertNotIn('192.168.1.128', output)
  483. self.assertIn(self.testvm1.ip, output)
  484. try:
  485. (output, _) = self.loop.run_until_complete(
  486. self.testvm1.run_for_stdio(
  487. 'ip route show', user='root'))
  488. except subprocess.CalledProcessError as e:
  489. self.fail('ip route show failed')
  490. output = output.decode()
  491. self.assertIn('192.168.1.128', output)
  492. self.assertNotIn(self.proxy.ip, output)
  493. def test_210_custom_ip_simple(self):
  494. '''Custom AppVM IP'''
  495. self.testvm1.ip = '192.168.1.1'
  496. self.app.save()
  497. self.loop.run_until_complete(self.testvm1.start())
  498. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  499. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0)
  500. def test_211_custom_ip_proxy(self):
  501. '''Custom ProxyVM IP'''
  502. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  503. name=self.make_vm_name('proxy'),
  504. label='red')
  505. self.loop.run_until_complete(self.proxy.create_on_disk())
  506. self.proxy.provides_network = True
  507. self.proxy.netvm = self.testnetvm
  508. self.proxy.ip = '192.168.1.1'
  509. self.testvm1.netvm = self.proxy
  510. self.app.save()
  511. self.loop.run_until_complete(self.testvm1.start())
  512. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0)
  513. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0)
  514. def test_212_custom_ip_firewall(self):
  515. '''Custom VM IP and firewall'''
  516. self.testvm1.ip = '192.168.1.1'
  517. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  518. name=self.make_vm_name('proxy'),
  519. label='red')
  520. self.proxy.provides_network = True
  521. self.loop.run_until_complete(self.proxy.create_on_disk())
  522. self.proxy.netvm = self.testnetvm
  523. self.testvm1.netvm = self.proxy
  524. self.app.save()
  525. if self.run_cmd(self.testnetvm, 'nc -h 2>&1|grep -q nmap.org') == 0:
  526. nc_version = NcVersion.Nmap
  527. else:
  528. nc_version = NcVersion.Trad
  529. # block all but ICMP and DNS
  530. self.testvm1.firewall.rules = [
  531. qubes.firewall.Rule(None, action='accept', proto='icmp'),
  532. qubes.firewall.Rule(None, action='accept', specialtarget='dns'),
  533. ]
  534. self.testvm1.firewall.save()
  535. self.loop.run_until_complete(self.testvm1.start())
  536. self.assertTrue(self.proxy.is_running())
  537. nc = self.loop.run_until_complete(self.testnetvm.run(
  538. 'nc -l --send-only -e /bin/hostname -k 1234'
  539. if nc_version == NcVersion.Nmap
  540. else 'while nc -l -e /bin/hostname -p 1234; do true; done'))
  541. try:
  542. self.assertEqual(self.run_cmd(self.proxy, self.ping_ip), 0,
  543. "Ping by IP from ProxyVM failed")
  544. self.assertEqual(self.run_cmd(self.proxy, self.ping_name), 0,
  545. "Ping by name from ProxyVM failed")
  546. self.assertEqual(self.run_cmd(self.testvm1, self.ping_ip), 0,
  547. "Ping by IP should be allowed")
  548. self.assertEqual(self.run_cmd(self.testvm1, self.ping_name), 0,
  549. "Ping by name should be allowed")
  550. if nc_version == NcVersion.Nmap:
  551. nc_cmd = "nc -w 1 --recv-only {} 1234".format(self.test_ip)
  552. else:
  553. nc_cmd = "nc -w 1 {} 1234".format(self.test_ip)
  554. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  555. "TCP connection should be blocked")
  556. finally:
  557. nc.terminate()
  558. self.loop.run_until_complete(nc.wait())
  559. class VmIPv6NetworkingMixin(VmNetworkingMixin):
  560. test_ip6 = '2000:abcd::1'
  561. ping6_cmd = 'ping6 -W 1 -n -c 1 {target}'
  562. def setUp(self):
  563. super(VmIPv6NetworkingMixin, self).setUp()
  564. self.ping6_ip = self.ping6_cmd.format(target=self.test_ip6)
  565. self.ping6_name = self.ping6_cmd.format(target=self.test_name)
  566. def configure_netvm(self):
  567. self.testnetvm.features['ipv6'] = True
  568. super(VmIPv6NetworkingMixin, self).configure_netvm()
  569. def run_netvm_cmd(cmd):
  570. if self.run_cmd(self.testnetvm, cmd) != 0:
  571. self.fail("Command '%s' failed" % cmd)
  572. run_netvm_cmd("ip addr add {}/128 dev test0".format(self.test_ip6))
  573. run_netvm_cmd(
  574. "ip6tables -I INPUT -d {} -j ACCEPT".format(self.test_ip6))
  575. # ignore failure
  576. self.run_cmd(self.testnetvm, "killall --wait dnsmasq")
  577. run_netvm_cmd(
  578. "dnsmasq -a {ip} -A /{name}/{ip} -A /{name}/{ip6} -i test0 -z".
  579. format(ip=self.test_ip, ip6=self.test_ip6, name=self.test_name))
  580. def test_500_ipv6_simple_networking(self):
  581. self.loop.run_until_complete(self.testvm1.start())
  582. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_ip), 0)
  583. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_name), 0)
  584. def test_510_ipv6_simple_proxyvm(self):
  585. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  586. name=self.make_vm_name('proxy'),
  587. label='red')
  588. self.proxy.provides_network = True
  589. self.proxy.netvm = self.testnetvm
  590. self.loop.run_until_complete(self.proxy.create_on_disk())
  591. self.testvm1.netvm = self.proxy
  592. self.app.save()
  593. self.loop.run_until_complete(self.testvm1.start())
  594. self.assertTrue(self.proxy.is_running())
  595. self.assertEqual(self.run_cmd(self.proxy, self.ping6_ip), 0,
  596. "Ping by IP from ProxyVM failed")
  597. self.assertEqual(self.run_cmd(self.proxy, self.ping6_name), 0,
  598. "Ping by name from ProxyVM failed")
  599. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_ip), 0,
  600. "Ping by IP from AppVM failed")
  601. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_name), 0,
  602. "Ping by IP from AppVM failed")
  603. @qubes.tests.expectedFailureIfTemplate('debian-7')
  604. @unittest.skipUnless(spawn.find_executable('xdotool'),
  605. "xdotool not installed")
  606. def test_520_ipv6_simple_proxyvm_nm(self):
  607. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  608. name=self.make_vm_name('proxy'),
  609. label='red')
  610. self.proxy.provides_network = True
  611. self.loop.run_until_complete(self.proxy.create_on_disk())
  612. self.proxy.netvm = self.testnetvm
  613. self.proxy.features['service.network-manager'] = True
  614. self.testvm1.netvm = self.proxy
  615. self.app.save()
  616. self.loop.run_until_complete(self.testvm1.start())
  617. self.assertTrue(self.proxy.is_running())
  618. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_ip), 0,
  619. "Ping by IP failed")
  620. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_name), 0,
  621. "Ping by name failed")
  622. # reconnect to make sure that device was configured by NM
  623. self.assertEqual(
  624. self.run_cmd(self.proxy, "nmcli device disconnect eth0",
  625. user="user"),
  626. 0, "Failed to disconnect eth0 using nmcli")
  627. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping6_ip), 0,
  628. "Network should be disabled, but apparently it isn't")
  629. self.assertEqual(
  630. self.run_cmd(self.proxy,
  631. 'nmcli connection up "VM uplink eth0" ifname eth0',
  632. user="user"),
  633. 0, "Failed to connect eth0 using nmcli")
  634. self.assertEqual(self.run_cmd(self.proxy, "nm-online",
  635. user="user"), 0,
  636. "Failed to wait for NM connection")
  637. # wait for duplicate-address-detection to complete - by default it has
  638. # 1s timeout
  639. time.sleep(2)
  640. # check for nm-applet presence
  641. self.assertEqual(subprocess.call([
  642. 'xdotool', 'search', '--class', '{}:nm-applet'.format(
  643. self.proxy.name)],
  644. stdout=subprocess.DEVNULL), 0, "nm-applet window not found")
  645. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_ip), 0,
  646. "Ping by IP failed (after NM reconnection")
  647. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_name), 0,
  648. "Ping by name failed (after NM reconnection)")
  649. def test_530_ipv6_firewallvm_firewall(self):
  650. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  651. name=self.make_vm_name('proxy'),
  652. label='red')
  653. self.proxy.provides_network = True
  654. self.loop.run_until_complete(self.proxy.create_on_disk())
  655. self.proxy.netvm = self.testnetvm
  656. self.testvm1.netvm = self.proxy
  657. self.app.save()
  658. if self.run_cmd(self.testnetvm, 'ncat -h') != 0:
  659. self.skipTest('nmap ncat not installer')
  660. # block all for first
  661. self.testvm1.firewall.rules = [qubes.firewall.Rule(action='drop')]
  662. self.testvm1.firewall.save()
  663. self.loop.run_until_complete(self.testvm1.start())
  664. self.assertTrue(self.proxy.is_running())
  665. nc = self.loop.run_until_complete(self.testnetvm.run(
  666. 'ncat -l --send-only -e /bin/hostname -k 1234'))
  667. try:
  668. self.assertEqual(self.run_cmd(self.proxy, self.ping6_ip), 0,
  669. "Ping by IP from ProxyVM failed")
  670. self.assertEqual(self.run_cmd(self.proxy, self.ping6_name), 0,
  671. "Ping by name from ProxyVM failed")
  672. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping6_ip), 0,
  673. "Ping by IP should be blocked")
  674. nc_cmd = "ncat -w 1 --recv-only {} 1234".format(self.test_ip6)
  675. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  676. "TCP connection should be blocked")
  677. # block all except ICMP
  678. self.testvm1.firewall.rules = [(
  679. qubes.firewall.Rule(None, action='accept', proto='icmp')
  680. )]
  681. self.testvm1.firewall.save()
  682. # Ugly hack b/c there is no feedback when the rules are actually
  683. # applied
  684. time.sleep(3)
  685. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_ip), 0,
  686. "Ping by IP failed (should be allowed now)")
  687. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping6_name), 0,
  688. "Ping by name should be blocked")
  689. # all TCP still blocked
  690. self.testvm1.firewall.rules = [
  691. qubes.firewall.Rule(None, action='accept', proto='icmp'),
  692. qubes.firewall.Rule(None, action='accept', specialtarget='dns'),
  693. ]
  694. self.testvm1.firewall.save()
  695. # Ugly hack b/c there is no feedback when the rules are actually
  696. # applied
  697. time.sleep(3)
  698. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_name), 0,
  699. "Ping by name failed (should be allowed now)")
  700. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  701. "TCP connection should be blocked")
  702. # block all except target
  703. self.testvm1.firewall.rules = [
  704. qubes.firewall.Rule(None, action='accept', dsthost=self.test_ip6,
  705. proto='tcp', dstports=1234),
  706. ]
  707. self.testvm1.firewall.save()
  708. # Ugly hack b/c there is no feedback when the rules are actually
  709. # applied
  710. time.sleep(3)
  711. self.assertEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  712. "TCP connection failed (should be allowed now)")
  713. # block all except target - by name
  714. self.testvm1.firewall.rules = [
  715. qubes.firewall.Rule(None, action='accept',
  716. dsthost=self.test_name,
  717. proto='tcp', dstports=1234),
  718. ]
  719. self.testvm1.firewall.save()
  720. # Ugly hack b/c there is no feedback when the rules are actually
  721. # applied
  722. time.sleep(3)
  723. self.assertEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  724. "TCP (IPv6) connection failed (should be allowed now)")
  725. self.assertEqual(self.run_cmd(self.testvm1,
  726. nc_cmd.replace(self.test_ip6, self.test_ip)),
  727. 0,
  728. "TCP (IPv4) connection failed (should be allowed now)")
  729. # allow all except target
  730. self.testvm1.firewall.rules = [
  731. qubes.firewall.Rule(None, action='drop', dsthost=self.test_ip6,
  732. proto='tcp', dstports=1234),
  733. qubes.firewall.Rule(action='accept'),
  734. ]
  735. self.testvm1.firewall.save()
  736. # Ugly hack b/c there is no feedback when the rules are actually
  737. # applied
  738. time.sleep(3)
  739. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  740. "TCP connection should be blocked")
  741. finally:
  742. nc.terminate()
  743. self.loop.run_until_complete(nc.wait())
  744. def test_540_ipv6_inter_vm(self):
  745. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  746. name=self.make_vm_name('proxy'),
  747. label='red')
  748. self.loop.run_until_complete(self.proxy.create_on_disk())
  749. self.proxy.provides_network = True
  750. self.proxy.netvm = self.testnetvm
  751. self.testvm1.netvm = self.proxy
  752. self.testvm2 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  753. name=self.make_vm_name('vm2'),
  754. label='red')
  755. self.loop.run_until_complete(self.testvm2.create_on_disk())
  756. self.testvm2.netvm = self.proxy
  757. self.app.save()
  758. self.loop.run_until_complete(asyncio.wait([
  759. self.testvm1.start(),
  760. self.testvm2.start()]))
  761. self.assertNotEqual(self.run_cmd(self.testvm1,
  762. self.ping_cmd.format(target=self.testvm2.ip6)), 0)
  763. self.testvm2.netvm = self.testnetvm
  764. self.assertNotEqual(self.run_cmd(self.testvm1,
  765. self.ping_cmd.format(target=self.testvm2.ip6)), 0)
  766. self.assertNotEqual(self.run_cmd(self.testvm2,
  767. self.ping_cmd.format(target=self.testvm1.ip6)), 0)
  768. self.testvm1.netvm = self.testnetvm
  769. self.assertNotEqual(self.run_cmd(self.testvm1,
  770. self.ping_cmd.format(target=self.testvm2.ip6)), 0)
  771. self.assertNotEqual(self.run_cmd(self.testvm2,
  772. self.ping_cmd.format(target=self.testvm1.ip6)), 0)
  773. def test_550_ipv6_spoof_ip(self):
  774. """Test if VM IP spoofing is blocked"""
  775. self.loop.run_until_complete(self.testvm1.start())
  776. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_ip), 0)
  777. # add a simple rule counting packets
  778. self.assertEqual(self.run_cmd(self.testnetvm,
  779. 'ip6tables -I INPUT -i vif+ ! -s {} -p icmpv6 -j LOG'.format(
  780. self.testvm1.ip6)), 0)
  781. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  782. 'ip -6 addr flush dev eth0 && '
  783. 'ip -6 addr add {}/128 dev eth0 && '
  784. 'ip -6 route add default via {} dev eth0'.format(
  785. self.testvm1.visible_ip6 + '1',
  786. self.testvm1.visible_gateway6),
  787. user='root'))
  788. self.assertNotEqual(self.run_cmd(self.testvm1, self.ping6_ip), 0,
  789. "Spoofed ping should be blocked")
  790. try:
  791. (output, _) = self.loop.run_until_complete(
  792. self.testnetvm.run_for_stdio('ip6tables -nxvL INPUT',
  793. user='root'))
  794. except subprocess.CalledProcessError:
  795. self.fail('ip6tables -nxvL INPUT failed')
  796. output = output.decode().splitlines()
  797. packets = output[2].lstrip().split()[0]
  798. self.assertEquals(packets, '0', 'Some packet hit the INPUT rule')
  799. def test_710_ipv6_custom_ip_simple(self):
  800. '''Custom AppVM IP'''
  801. self.testvm1.ip6 = '2000:aaaa:bbbb::1'
  802. self.app.save()
  803. self.loop.run_until_complete(self.testvm1.start())
  804. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_ip), 0)
  805. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_name), 0)
  806. def test_711_ipv6_custom_ip_proxy(self):
  807. '''Custom ProxyVM IP'''
  808. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  809. name=self.make_vm_name('proxy'),
  810. label='red')
  811. self.loop.run_until_complete(self.proxy.create_on_disk())
  812. self.proxy.provides_network = True
  813. self.proxy.netvm = self.testnetvm
  814. self.testvm1.ip6 = '2000:aaaa:bbbb::1'
  815. self.testvm1.netvm = self.proxy
  816. self.app.save()
  817. self.loop.run_until_complete(self.testvm1.start())
  818. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_ip), 0)
  819. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_name), 0)
  820. def test_712_ipv6_custom_ip_firewall(self):
  821. '''Custom VM IP and firewall'''
  822. self.testvm1.ip6 = '2000:aaaa:bbbb::1'
  823. self.proxy = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  824. name=self.make_vm_name('proxy'),
  825. label='red')
  826. self.proxy.provides_network = True
  827. self.loop.run_until_complete(self.proxy.create_on_disk())
  828. self.proxy.netvm = self.testnetvm
  829. self.testvm1.netvm = self.proxy
  830. self.app.save()
  831. if self.run_cmd(self.testnetvm, 'nc -h 2>&1|grep -q nmap.org') == 0:
  832. nc_version = NcVersion.Nmap
  833. else:
  834. nc_version = NcVersion.Trad
  835. # block all but ICMP and DNS
  836. self.testvm1.firewall.rules = [
  837. qubes.firewall.Rule(None, action='accept', proto='icmp'),
  838. qubes.firewall.Rule(None, action='accept', specialtarget='dns'),
  839. ]
  840. self.testvm1.firewall.save()
  841. self.loop.run_until_complete(self.testvm1.start())
  842. self.assertTrue(self.proxy.is_running())
  843. nc = self.loop.run_until_complete(self.testnetvm.run(
  844. 'nc -l --send-only -e /bin/hostname -k 1234'
  845. if nc_version == NcVersion.Nmap
  846. else 'while nc -l -e /bin/hostname -p 1234; do true; done'))
  847. try:
  848. self.assertEqual(self.run_cmd(self.proxy, self.ping6_ip), 0,
  849. "Ping by IP from ProxyVM failed")
  850. self.assertEqual(self.run_cmd(self.proxy, self.ping6_name), 0,
  851. "Ping by name from ProxyVM failed")
  852. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_ip), 0,
  853. "Ping by IP should be allowed")
  854. self.assertEqual(self.run_cmd(self.testvm1, self.ping6_name), 0,
  855. "Ping by name should be allowed")
  856. if nc_version == NcVersion.Nmap:
  857. nc_cmd = "nc -w 1 --recv-only {} 1234".format(self.test_ip6)
  858. else:
  859. nc_cmd = "nc -w 1 {} 1234".format(self.test_ip6)
  860. self.assertNotEqual(self.run_cmd(self.testvm1, nc_cmd), 0,
  861. "TCP connection should be blocked")
  862. finally:
  863. nc.terminate()
  864. self.loop.run_until_complete(nc.wait())
  865. # noinspection PyAttributeOutsideInit
  866. class VmUpdatesMixin(object):
  867. """
  868. Tests for VM updates
  869. """
  870. # filled by load_tests
  871. template = None
  872. # made this way to work also when no package build tools are installed
  873. """
  874. $ cat test-pkg.spec:
  875. Name: test-pkg
  876. Version: 1.0
  877. Release: 1%{?dist}
  878. Summary: Test package
  879. Group: System
  880. License: GPL
  881. URL: http://example.com/
  882. %description
  883. Test package
  884. %files
  885. %changelog
  886. $ rpmbuild -bb test-pkg.spec
  887. $ cat test-pkg-1.0-1.fc21.x86_64.rpm | gzip | base64
  888. """
  889. RPM_PACKAGE_GZIP_BASE64 = (
  890. b"H4sIAPzRLlYAA+2Y728URRjHn7ueUCkERKJVJDnTxLSxs7293o8WOER6ljYYrtKCLUSa3"
  891. b"bnZ64bd22VmTq8nr4wJbwxvjNHIG0x8oTHGGCHB8AcYE1/0lS80GgmQFCJU3wgB4ZjdfZ"
  892. b"q2xDe8NNlvMjfzmeeZH7tPbl98b35169cOUEpIJiTxT9SIrmVUs2hWh8dUAp54dOrM14s"
  893. b"JHK4D2DKl+j2qrVfjsuq3qEWbohjuAB2Lqk+p1o/8Z5QPmSi/YwnjezH+F8bLQZjqllW0"
  894. b"hvODRmFIL5hFk9JMXi/mi5ZuDleNwSEzP5wtmLnouNQnm3/6fndz7FLt9M/Hruj37gav4"
  895. b"tTjPnasWLFixYoVK1asWLFixYoV63+p0KNot9vnIPQc1vgYOwCSgXfxCoS+QzKHOVXVOj"
  896. b"Fn2ccIfI0k8nXkLuQbyJthxed4UrVnkG8i9yDfgsj3yCAv4foc8t+w1hf5B+Nl5Du43xj"
  897. b"yvxivIN9HpsgPkO2IU9uQfeRn8Xk/iJ4x1Y3nfxH1qecwfhH5+YgT25F7o/0SRdxvOppP"
  898. b"7MX9ZjB/DNnE/OOYX404uRGZIT+FbCFvQ3aQ8f0+/WF0XjJ8nyOw7H+BrmUA/a8pNZf2D"
  899. b"XrCqLG1cERbWHI8ajhznpBY9P0Tr8PkvJDMhTkp/Z0DA6xpuL7DNOq5A+DY9UYTmkOF2U"
  900. b"IO/sNt0wSnGvfdlZssD3rVIlLI9UUX37C6qXzHNntHPNfnTAhWHbUddtBwmegDjAUzZbu"
  901. b"m9lqZmzDmHc8Ik8WY8Tab4Myym4+Gx8V0qw8GtYyWIzrktEJwV9UHv3ktG471rAqHTmFQ"
  902. b"685V5uGqIalk06SWJr7tszR503Ac9cs493jJ8rhrSCIYbXBbzqt5v5+UZ0crh6bGR2dmJ"
  903. b"yuHD428VlLLLdakzJe2VxcKhFSFID73JKPS40RI7tXVCcQ3uOGWhPCJ2bAspiJ2i5Vy6n"
  904. b"jOqMerpEYpEe/Yks4xkU4Tt6BirmzUWanG6ozbFKhve9BsQRaLRTirzqk7hgUktXojKnf"
  905. b"n8jeg3X4QepP3i63po6oml+9t/CwJLya2Bn/ei6f7/4B3Ycdb0L3pt5Q5mNz16rWJ9fLk"
  906. b"vvOff/nxS7//8O2P2gvt7nDDnoV9L1du9N4+ucjl9u/8+a7dC5Nnvjlv9Ox5r+v9Cy0NE"
  907. b"m+c6rv60S/dZw98Gn6MNswcfQiWUvg3wBUAAA=="
  908. )
  909. """
  910. Minimal package generated by running dh_make on empty directory
  911. Then cat test-pkg_1.0-1_amd64.deb | gzip | base64
  912. """
  913. DEB_PACKAGE_GZIP_BASE64 = (
  914. b"H4sIACTXLlYAA1O0SSxKzrDjSklNykzM003KzEssqlRQUDA0MTG1NDQwNDVTUDBQAAEIa"
  915. b"WhgYGZioqBgogADCVxGegZcyfl5JUX5OXoliUV66VVE6DcwheuX7+ZgAAEW5rdXHb0PG4"
  916. b"iwf5j3WfMT6zWzzMuZgoE3jjYraNzbbFKWGms0SaRw/r2SV23WZ4IdP8preM4yqf0jt95"
  917. b"3c8qnacfNxJUkf9/w+/3X9ph2GEdgQdixrz/niHKKTnYXizf4oSC7tHOz2Zzq+/6vn8/7"
  918. b"ezQ7c1tmi7xZ3SGJ4yzhT2dcr7V+W3zM5ZPu/56PSv4Zdok+7Yv/V/6buWaKVlFkkV58S"
  919. b"N3GmLgnqzRmeZ3V3ymmurS5fGa85/LNx1bpZMin3S6dvXKqydp3ubP1vmyarJZb/qSh62"
  920. b"C8oIdxqm/BtvkGDza+On/Vfv2py7/0LV7VH+qR6a+bkKUbHXt5/SG187d+nps1a5PJfMO"
  921. b"i11dWcUe1HjwaW3Q5RHXn9LmcHy+tW9YcKf0768XVB1t3R0bKrzs5t9P+6r7rZ99svH10"
  922. b"+Q6F/o8tf1fO/32y+fWa14eifd+WxUy0jcxYH7N9/tUvmnUZL74pW32qLeuRU+ZwYGASa"
  923. b"GBgUWBgxM90ayy3VdmykkGDgYErJbEkERydFVWQmCMQo8aWZvAY/WteFRHFwMCYqXTPjI"
  924. b"lBkVEMGLsl+k8XP1D/z+gXyyDOvUemlnHqAVkvu0rRQ2fUFodkN3mtU9uwhqk8V+TqPEE"
  925. b"Nc7fzoQ4n71lqRs/7kbbT0+qOZuKH4r8mjzsc1k/YkCHN8Pjg48fbpE+teHa96LNcfu0V"
  926. b"5n2/Z2xa2KDvaCOx8cqBFxc514uZ3TmadXS+6cpzU7wSzq5SWfapJOD9n6wLXSwtlgxZh"
  927. b"xITzWW7buhx/bb291RcVlEfeC9K5hlrqunSzIMSZT7/Nqgc/qMvMNW227WI8ezB8mVuZh"
  928. b"0hERJSvysfburr4Dx0I9BW57UwR4+e1gxu49PcEt8sbK18Xpvt//Hj5UYm+Zc25q+T4xl"
  929. b"rJvxfVnh80oadq57OZxPaU1bbztv1yF365W4t45Yr+XrFzov237GVY1Zgf7NvE4+W2SuR"
  930. b"lQtLauR1TQ/mbOiIONYya6tU1jPGpWfk/i1+ttiXe3ZO14n0YOWggndznjGlGLyfVbBC6"
  931. b"MRP5aMM7aCco/s7sZqB8RlTQwADw8rnuT/sDHi7mUASjJFRAAbWwNLiAwAA"
  932. )
  933. def run_cmd(self, vm, cmd, user="root"):
  934. try:
  935. self.loop.run_until_complete(vm.run_for_stdio(cmd))
  936. except subprocess.CalledProcessError as e:
  937. return e.returncode
  938. return 0
  939. def setUp(self):
  940. if not self.template.count('debian') and \
  941. not self.template.count('fedora'):
  942. self.skipTest("Template {} not supported by this test".format(
  943. self.template))
  944. super(VmUpdatesMixin, self).setUp()
  945. self.update_cmd = None
  946. if self.template.count("debian"):
  947. self.update_cmd = "set -o pipefail; apt-get update 2>&1 | " \
  948. "{ ! grep '^W:\|^E:'; }"
  949. self.install_cmd = "apt-get install -y {}"
  950. self.install_test_cmd = "dpkg -l {}"
  951. self.exit_code_ok = [0]
  952. elif self.template.count("fedora"):
  953. cmd = "yum"
  954. try:
  955. # assume template name in form "fedora-XX-suffix"
  956. if int(self.template.split("-")[1]) > 21:
  957. cmd = "dnf"
  958. except ValueError:
  959. pass
  960. self.update_cmd = "{cmd} clean all; {cmd} check-update".format(
  961. cmd=cmd)
  962. self.install_cmd = cmd + " install -y {}"
  963. self.install_test_cmd = "rpm -q {}"
  964. self.exit_code_ok = [0, 100]
  965. self.init_default_template(self.template)
  966. self.init_networking()
  967. self.testvm1 = self.app.add_new_vm(
  968. qubes.vm.appvm.AppVM,
  969. name=self.make_vm_name('vm1'),
  970. label='red')
  971. self.loop.run_until_complete(self.testvm1.create_on_disk())
  972. def test_000_simple_update(self):
  973. self.app.save()
  974. # reload the VM to have all the properties properly set (especially
  975. # default netvm)
  976. self.testvm1 = self.app.domains[self.testvm1.qid]
  977. self.loop.run_until_complete(self.testvm1.start())
  978. p = self.loop.run_until_complete(
  979. self.testvm1.run(self.update_cmd, user='root',
  980. stdout=subprocess.PIPE, stderr=subprocess.PIPE))
  981. (stdout, stderr) = self.loop.run_until_complete(p.communicate())
  982. self.assertIn(p.returncode, self.exit_code_ok,
  983. '{}: {}\n{}'.format(self.update_cmd, stdout, stderr))
  984. def create_repo_apt(self):
  985. pkg_file_name = "test-pkg_1.0-1_amd64.deb"
  986. self.loop.run_until_complete(self.netvm_repo.run_for_stdio('''
  987. mkdir /tmp/apt-repo \
  988. && cd /tmp/apt-repo \
  989. && base64 -d | zcat > {}
  990. '''.format(pkg_file_name),
  991. input=self.DEB_PACKAGE_GZIP_BASE64))
  992. # do not assume dpkg-scanpackage installed
  993. packages_path = "dists/test/main/binary-amd64/Packages"
  994. self.loop.run_until_complete(self.netvm_repo.run_for_stdio('''
  995. mkdir -p /tmp/apt-repo/dists/test/main/binary-amd64 \
  996. && cd /tmp/apt-repo \
  997. && cat > {packages} \
  998. && echo MD5sum: $(openssl md5 -r {pkg} | cut -f 1 -d ' ') \
  999. >> {packages} \
  1000. && echo SHA1: $(openssl sha1 -r {pkg} | cut -f 1 -d ' ') \
  1001. >> {packages} \
  1002. && echo SHA256: $(openssl sha256 -r {pkg} | cut -f 1 -d ' ') \
  1003. >> {packages} \
  1004. && gzip < {packages} > {packages}.gz
  1005. '''.format(pkg=pkg_file_name, packages=packages_path),
  1006. input='''\
  1007. Package: test-pkg
  1008. Version: 1.0-1
  1009. Architecture: amd64
  1010. Maintainer: unknown <user@host>
  1011. Installed-Size: 25
  1012. Filename: {pkg}
  1013. Size: 994
  1014. Section: unknown
  1015. Priority: optional
  1016. Description: Test package'''.format(pkg=pkg_file_name).encode('utf-8')))
  1017. self.loop.run_until_complete(self.netvm_repo.run_for_stdio('''
  1018. mkdir -p /tmp/apt-repo/dists/test \
  1019. && cd /tmp/apt-repo/dists/test \
  1020. && cat > Release \
  1021. && echo '' $(sha256sum {p} | cut -f 1 -d ' ') $(stat -c %s {p}) {p}\
  1022. >> Release \
  1023. && echo '' $(sha256sum {z} | cut -f 1 -d ' ') $(stat -c %s {z}) {z}\
  1024. >> Release
  1025. '''.format(p='main/binary-amd64/Packages',
  1026. z='main/binary-amd64/Packages.gz'),
  1027. input=b'''\
  1028. Label: Test repo
  1029. Suite: test
  1030. Codename: test
  1031. Date: Tue, 27 Oct 2015 03:22:09 UTC
  1032. Architectures: amd64
  1033. Components: main
  1034. SHA256:
  1035. '''))
  1036. def create_repo_yum(self):
  1037. pkg_file_name = "test-pkg-1.0-1.fc21.x86_64.rpm"
  1038. self.loop.run_until_complete(self.netvm_repo.run_for_stdio('''
  1039. mkdir /tmp/yum-repo \
  1040. && cd /tmp/yum-repo \
  1041. && base64 -d | zcat > {}
  1042. '''.format(pkg_file_name), input=self.RPM_PACKAGE_GZIP_BASE64))
  1043. # createrepo is installed by default in Fedora template
  1044. self.loop.run_until_complete(self.netvm_repo.run_for_stdio(
  1045. 'createrepo /tmp/yum-repo'))
  1046. def create_repo_and_serve(self):
  1047. if self.template.count("debian") or self.template.count("whonix"):
  1048. self.create_repo_apt()
  1049. self.loop.run_until_complete(self.netvm_repo.run(
  1050. 'cd /tmp/apt-repo && python -m SimpleHTTPServer 8080',
  1051. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
  1052. elif self.template.count("fedora"):
  1053. self.create_repo_yum()
  1054. self.loop.run_until_complete(self.netvm_repo.run(
  1055. 'cd /tmp/yum-repo && python -m SimpleHTTPServer 8080',
  1056. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
  1057. else:
  1058. # not reachable...
  1059. self.skipTest("Template {} not supported by this test".format(
  1060. self.template))
  1061. def configure_test_repo(self):
  1062. """
  1063. Configure test repository in test-vm and disable rest of them.
  1064. The critical part is to use "localhost" - this will work only when
  1065. accessed through update proxy and this is exactly what we want to
  1066. test here.
  1067. """
  1068. if self.template.count("debian") or self.template.count("whonix"):
  1069. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  1070. "rm -f /etc/apt/sources.list.d/* &&"
  1071. "echo 'deb [trusted=yes] http://localhost:8080 test main' "
  1072. "> /etc/apt/sources.list",
  1073. user="root"))
  1074. elif self.template.count("fedora"):
  1075. self.loop.run_until_complete(self.testvm1.run_for_stdio(
  1076. "rm -f /etc/yum.repos.d/*.repo &&"
  1077. "echo '[test]' > /etc/yum.repos.d/test.repo &&"
  1078. "echo 'name=Test repo' >> /etc/yum.repos.d/test.repo &&"
  1079. "echo 'gpgcheck=0' >> /etc/yum.repos.d/test.repo &&"
  1080. "echo 'baseurl=http://localhost:8080/'"
  1081. " >> /etc/yum.repos.d/test.repo",
  1082. user="root"
  1083. ))
  1084. else:
  1085. # not reachable...
  1086. self.skipTest("Template {} not supported by this test".format(
  1087. self.template))
  1088. def test_010_update_via_proxy(self):
  1089. """
  1090. Test both whether updates proxy works and whether is actually used by the VM
  1091. """
  1092. if self.template.count("minimal"):
  1093. self.skipTest("Template {} not supported by this test".format(
  1094. self.template))
  1095. self.netvm_repo = self.app.add_new_vm(
  1096. qubes.vm.appvm.AppVM,
  1097. name=self.make_vm_name('net'),
  1098. label='red')
  1099. self.netvm_repo.provides_network = True
  1100. self.loop.run_until_complete(self.netvm_repo.create_on_disk())
  1101. self.testvm1.netvm = self.netvm_repo
  1102. self.netvm_repo.features['service.qubes-updates-proxy'] = True
  1103. # TODO: consider also adding a test for the template itself
  1104. self.testvm1.features['service.updates-proxy-setup'] = True
  1105. self.app.save()
  1106. # Setup test repo
  1107. self.loop.run_until_complete(self.netvm_repo.start())
  1108. self.create_repo_and_serve()
  1109. # Configure local repo
  1110. self.loop.run_until_complete(self.testvm1.start())
  1111. self.configure_test_repo()
  1112. with self.qrexec_policy('qubes.UpdatesProxy', self.testvm1,
  1113. '$default', action='allow,target=' + self.netvm_repo.name):
  1114. # update repository metadata
  1115. p = self.loop.run_until_complete(self.testvm1.run(
  1116. self.update_cmd, user='root', stdout=subprocess.PIPE,
  1117. stderr=subprocess.PIPE))
  1118. (stdout, stderr) = self.loop.run_until_complete(p.communicate())
  1119. self.assertIn(self.loop.run_until_complete(p.wait()), self.exit_code_ok,
  1120. '{}: {}\n{}'.format(self.update_cmd, stdout, stderr))
  1121. # install test package
  1122. p = self.loop.run_until_complete(self.testvm1.run(
  1123. self.install_cmd.format('test-pkg'), user='root',
  1124. stdout=subprocess.PIPE, stderr=subprocess.PIPE))
  1125. (stdout, stderr) = self.loop.run_until_complete(p.communicate())
  1126. self.assertIn(self.loop.run_until_complete(p.wait()), self.exit_code_ok,
  1127. '{}: {}\n{}'.format(self.update_cmd, stdout, stderr))
  1128. # verify if it was really installed
  1129. p = self.loop.run_until_complete(self.testvm1.run(
  1130. self.install_test_cmd.format('test-pkg'), user='root',
  1131. stdout=subprocess.PIPE, stderr=subprocess.PIPE))
  1132. (stdout, stderr) = self.loop.run_until_complete(p.communicate())
  1133. self.assertIn(self.loop.run_until_complete(p.wait()), self.exit_code_ok,
  1134. '{}: {}\n{}'.format(self.update_cmd, stdout, stderr))
  1135. def load_tests(loader, tests, pattern):
  1136. for template in qubes.tests.list_templates():
  1137. tests.addTests(loader.loadTestsFromTestCase(
  1138. type(
  1139. 'VmNetworking_' + template,
  1140. (VmNetworkingMixin, qubes.tests.SystemTestCase),
  1141. {'template': template})))
  1142. tests.addTests(loader.loadTestsFromTestCase(
  1143. type(
  1144. 'VmIPv6Networking_' + template,
  1145. (VmIPv6NetworkingMixin, qubes.tests.SystemTestCase),
  1146. {'template': template})))
  1147. tests.addTests(loader.loadTestsFromTestCase(
  1148. type(
  1149. 'VmUpdates_' + template,
  1150. (VmUpdatesMixin, qubes.tests.SystemTestCase),
  1151. {'template': template})))
  1152. return tests