qubesvm.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. # pylint: disable=protected-access
  2. #
  3. # The Qubes OS Project, https://www.qubes-os.org/
  4. #
  5. # Copyright (C) 2014-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  6. # Copyright (C) 2014-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. import base64
  22. import os
  23. import unittest
  24. import uuid
  25. import datetime
  26. import lxml.etree
  27. import unittest.mock
  28. import shutil
  29. import qubes
  30. import qubes.exc
  31. import qubes.config
  32. import qubes.vm
  33. import qubes.vm.qubesvm
  34. import qubes.tests
  35. import qubes.tests.vm
  36. class TestApp(object):
  37. labels = {1: qubes.Label(1, '0xcc0000', 'red')}
  38. def __init__(self):
  39. self.domains = {}
  40. class TestProp(object):
  41. # pylint: disable=too-few-public-methods
  42. __name__ = 'testprop'
  43. class TestDeviceCollection(object):
  44. def __init__(self):
  45. self._list = []
  46. def persistent(self):
  47. return self._list
  48. class TestQubesDB(object):
  49. def __init__(self):
  50. self.data = {}
  51. def write(self, path, value):
  52. self.data[path] = value
  53. def rm(self, path):
  54. if path.endswith('/'):
  55. for key in [x for x in self.data if x.startswith(path)]:
  56. del self.data[key]
  57. else:
  58. self.data.pop(path, None)
  59. class TestVM(object):
  60. # pylint: disable=too-few-public-methods
  61. app = TestApp()
  62. def __init__(self, **kwargs):
  63. self.running = False
  64. self.installed_by_rpm = False
  65. for k, v in kwargs.items():
  66. setattr(self, k, v)
  67. self.devices = {'pci': TestDeviceCollection()}
  68. def is_running(self):
  69. return self.running
  70. class TC_00_setters(qubes.tests.QubesTestCase):
  71. def setUp(self):
  72. super().setUp()
  73. self.vm = TestVM()
  74. self.prop = TestProp()
  75. def test_000_setter_qid(self):
  76. self.assertEqual(
  77. qubes.vm._setter_qid(self.vm, self.prop, 5), 5)
  78. def test_001_setter_qid_lt_0(self):
  79. with self.assertRaises(ValueError):
  80. qubes.vm._setter_qid(self.vm, self.prop, -1)
  81. def test_002_setter_qid_gt_max(self):
  82. with self.assertRaises(ValueError):
  83. qubes.vm._setter_qid(self.vm,
  84. self.prop, qubes.config.max_qid + 5)
  85. @unittest.skip('test not implemented')
  86. def test_020_setter_kernel(self):
  87. pass
  88. def test_030_setter_label_object(self):
  89. label = TestApp.labels[1]
  90. self.assertIs(label,
  91. qubes.vm.setter_label(self.vm, self.prop, label))
  92. def test_031_setter_label_getitem(self):
  93. label = TestApp.labels[1]
  94. self.assertIs(label,
  95. qubes.vm.setter_label(self.vm, self.prop, 'label-1'))
  96. # there is no check for self.app.get_label()
  97. def test_040_setter_virt_mode(self):
  98. self.assertEqual(
  99. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'hvm'),
  100. 'hvm')
  101. self.assertEqual(
  102. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'HVM'),
  103. 'hvm')
  104. self.assertEqual(
  105. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'PV'),
  106. 'pv')
  107. self.assertEqual(
  108. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'pvh'),
  109. 'pvh')
  110. self.vm.devices['pci']._list.append(object())
  111. with self.assertRaises(ValueError):
  112. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'pvh')
  113. with self.assertRaises(ValueError):
  114. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'True')
  115. class TC_10_default(qubes.tests.QubesTestCase):
  116. def setUp(self):
  117. super().setUp()
  118. self.app = TestApp()
  119. self.vm = TestVM(app=self.app)
  120. self.prop = TestProp()
  121. def test_000_default_with_template_simple(self):
  122. default_getter = qubes.vm.qubesvm._default_with_template('kernel',
  123. 'dfl-kernel')
  124. self.assertEqual(default_getter(self.vm), 'dfl-kernel')
  125. self.vm.template = None
  126. self.assertEqual(default_getter(self.vm), 'dfl-kernel')
  127. self.vm.template = unittest.mock.Mock()
  128. self.vm.template.kernel = 'template-kernel'
  129. self.assertEqual(default_getter(self.vm), 'template-kernel')
  130. def test_001_default_with_template_callable(self):
  131. default_getter = qubes.vm.qubesvm._default_with_template('kernel',
  132. lambda x: x.app.default_kernel)
  133. self.app.default_kernel = 'global-dfl-kernel'
  134. self.assertEqual(default_getter(self.vm), 'global-dfl-kernel')
  135. self.vm.template = None
  136. self.assertEqual(default_getter(self.vm), 'global-dfl-kernel')
  137. self.vm.template = unittest.mock.Mock()
  138. self.vm.template.kernel = 'template-kernel'
  139. self.assertEqual(default_getter(self.vm), 'template-kernel')
  140. def test_010_default_virt_mode(self):
  141. default_getter = qubes.vm.qubesvm._default_with_template('kernel',
  142. lambda x: x.app.default_kernel)
  143. self.assertEqual(qubes.vm.qubesvm._default_virt_mode(self.vm),
  144. 'pvh')
  145. self.vm.template = unittest.mock.Mock()
  146. self.vm.template.virt_mode = 'hvm'
  147. self.assertEqual(qubes.vm.qubesvm._default_virt_mode(self.vm),
  148. 'hvm')
  149. self.vm.template = None
  150. self.assertEqual(qubes.vm.qubesvm._default_virt_mode(self.vm),
  151. 'pvh')
  152. self.vm.devices['pci'].persistent().append('some-dev')
  153. self.assertEqual(qubes.vm.qubesvm._default_virt_mode(self.vm),
  154. 'hvm')
  155. class QubesVMTestsMixin(object):
  156. property_no_default = object()
  157. def setUp(self):
  158. super(QubesVMTestsMixin, self).setUp()
  159. self.app = qubes.tests.vm.TestApp()
  160. self.app.vmm.offline_mode = True
  161. self.app.default_kernel = None
  162. # when full test run is called, extensions are loaded by earlier
  163. # tests, but if just this test class is run, load them manually here,
  164. # to have the same behaviour
  165. qubes.ext.get_extensions()
  166. def tearDown(self):
  167. try:
  168. self.app.domains.close()
  169. except AttributeError:
  170. pass
  171. super(QubesVMTestsMixin, self).tearDown()
  172. def get_vm(self, name='test', cls=qubes.vm.qubesvm.QubesVM, **kwargs):
  173. vm = cls(self.app, None,
  174. qid=kwargs.pop('qid', 1), name=qubes.tests.VMPREFIX + name,
  175. **kwargs)
  176. self.app.domains[vm.qid] = vm
  177. self.app.domains[vm.uuid] = vm
  178. self.app.domains[vm] = vm
  179. self.addCleanup(vm.close)
  180. return vm
  181. def assertPropertyValue(self, vm, prop_name, set_value, expected_value,
  182. expected_xml_content=None):
  183. # FIXME: any better exception list? or maybe all of that should be a
  184. # single exception?
  185. with self.assertNotRaises((ValueError, TypeError, KeyError)):
  186. setattr(vm, prop_name, set_value)
  187. self.assertEqual(getattr(vm, prop_name), expected_value)
  188. if expected_xml_content is not None:
  189. xml = vm.__xml__()
  190. prop_xml = xml.xpath(
  191. './properties/property[@name=\'{}\']'.format(prop_name))
  192. self.assertEqual(len(prop_xml), 1, "Property not found in XML")
  193. self.assertEqual(prop_xml[0].text, expected_xml_content)
  194. def assertPropertyInvalidValue(self, vm, prop_name, set_value):
  195. orig_value_set = True
  196. orig_value = None
  197. try:
  198. orig_value = getattr(vm, prop_name)
  199. except AttributeError:
  200. orig_value_set = False
  201. # FIXME: any better exception list? or maybe all of that should be a
  202. # single exception?
  203. with self.assertRaises((ValueError, TypeError, KeyError)):
  204. setattr(vm, prop_name, set_value)
  205. if orig_value_set:
  206. self.assertEqual(getattr(vm, prop_name), orig_value)
  207. else:
  208. with self.assertRaises(AttributeError):
  209. getattr(vm, prop_name)
  210. def assertPropertyDefaultValue(self, vm, prop_name,
  211. expected_default=property_no_default):
  212. if expected_default is self.property_no_default:
  213. with self.assertRaises(AttributeError):
  214. getattr(vm, prop_name)
  215. else:
  216. with self.assertNotRaises(AttributeError):
  217. self.assertEqual(getattr(vm, prop_name), expected_default)
  218. xml = vm.__xml__()
  219. prop_xml = xml.xpath(
  220. './properties/property[@name=\'{}\']'.format(prop_name))
  221. self.assertEqual(len(prop_xml), 0, "Property still found in XML")
  222. def _test_generic_bool_property(self, vm, prop_name, default=False):
  223. self.assertPropertyDefaultValue(vm, prop_name, default)
  224. self.assertPropertyValue(vm, prop_name, False, False, 'False')
  225. self.assertPropertyValue(vm, prop_name, True, True, 'True')
  226. delattr(vm, prop_name)
  227. self.assertPropertyDefaultValue(vm, prop_name, default)
  228. self.assertPropertyValue(vm, prop_name, 'True', True, 'True')
  229. self.assertPropertyValue(vm, prop_name, 'False', False, 'False')
  230. self.assertPropertyInvalidValue(vm, prop_name, 'xxx')
  231. self.assertPropertyValue(vm, prop_name, 123, True)
  232. self.assertPropertyInvalidValue(vm, prop_name, '')
  233. class TC_90_QubesVM(QubesVMTestsMixin, qubes.tests.QubesTestCase):
  234. def test_000_init(self):
  235. self.get_vm()
  236. def test_001_init_no_qid_or_name(self):
  237. with self.assertRaises(AssertionError):
  238. qubes.vm.qubesvm.QubesVM(self.app, None,
  239. name=qubes.tests.VMPREFIX + 'test')
  240. with self.assertRaises(AssertionError):
  241. qubes.vm.qubesvm.QubesVM(self.app, None,
  242. qid=1)
  243. def test_003_init_fire_domain_init(self):
  244. class TestVM2(qubes.vm.qubesvm.QubesVM):
  245. event_fired = False
  246. @qubes.events.handler('domain-init')
  247. def on_domain_init(self, event): # pylint: disable=unused-argument
  248. self.__class__.event_fired = True
  249. TestVM2(self.app, None, qid=1, name=qubes.tests.VMPREFIX + 'test')
  250. self.assertTrue(TestVM2.event_fired)
  251. def test_004_uuid_autogen(self):
  252. vm = self.get_vm()
  253. self.assertTrue(hasattr(vm, 'uuid'))
  254. def test_100_qid(self):
  255. vm = self.get_vm()
  256. self.assertIsInstance(vm.qid, int)
  257. with self.assertRaises(AttributeError):
  258. vm.qid = 2
  259. def test_110_name(self):
  260. vm = self.get_vm()
  261. self.assertIsInstance(vm.name, str)
  262. def test_120_uuid(self):
  263. my_uuid = uuid.uuid4()
  264. vm = self.get_vm(uuid=my_uuid)
  265. self.assertIsInstance(vm.uuid, uuid.UUID)
  266. self.assertIs(vm.uuid, my_uuid)
  267. with self.assertRaises(AttributeError):
  268. vm.uuid = uuid.uuid4()
  269. @unittest.skip('TODO: how to not fail on making an icon symlink here?')
  270. def test_130_label(self):
  271. vm = self.get_vm()
  272. self.assertPropertyDefaultValue(vm, 'label')
  273. self.assertPropertyValue(vm, 'label', self.app.labels[1],
  274. self.app.labels[1], 'label-1')
  275. del vm.label
  276. self.assertPropertyDefaultValue(vm, 'label')
  277. self.assertPropertyValue(vm, 'label', 'red',
  278. self.app.labels[1], 'label-1')
  279. self.assertPropertyValue(vm, 'label', 'label-1',
  280. self.app.labels[1], 'label-1')
  281. def test_131_label_invalid(self):
  282. vm = self.get_vm()
  283. self.assertPropertyInvalidValue(vm, 'label', 'invalid')
  284. self.assertPropertyInvalidValue(vm, 'label', 123)
  285. def test_160_memory(self):
  286. vm = self.get_vm()
  287. self.assertPropertyDefaultValue(vm, 'memory', 400)
  288. self.assertPropertyValue(vm, 'memory', 500, 500, '500')
  289. del vm.memory
  290. self.assertPropertyDefaultValue(vm, 'memory', 400)
  291. self.assertPropertyValue(vm, 'memory', '500', 500, '500')
  292. def test_161_memory_invalid(self):
  293. vm = self.get_vm()
  294. self.assertPropertyInvalidValue(vm, 'memory', -100)
  295. self.assertPropertyInvalidValue(vm, 'memory', '-100')
  296. self.assertPropertyInvalidValue(vm, 'memory', '')
  297. # TODO: higher than maxmem
  298. # TODO: human readable setter (500M, 4G)?
  299. def test_170_maxmem(self):
  300. vm = self.get_vm()
  301. self.assertPropertyDefaultValue(vm, 'maxmem',
  302. self.app.host.memory_total / 1024 / 2)
  303. self.assertPropertyValue(vm, 'maxmem', 500, 500, '500')
  304. del vm.maxmem
  305. self.assertPropertyDefaultValue(vm, 'maxmem',
  306. self.app.host.memory_total / 1024 / 2)
  307. self.assertPropertyValue(vm, 'maxmem', '500', 500, '500')
  308. def test_171_maxmem_invalid(self):
  309. vm = self.get_vm()
  310. self.assertPropertyInvalidValue(vm, 'maxmem', -100)
  311. self.assertPropertyInvalidValue(vm, 'maxmem', '-100')
  312. self.assertPropertyInvalidValue(vm, 'maxmem', '')
  313. # TODO: lower than memory
  314. # TODO: human readable setter (500M, 4G)?
  315. def test_190_vcpus(self):
  316. vm = self.get_vm()
  317. self.assertPropertyDefaultValue(vm, 'vcpus', 2)
  318. self.assertPropertyValue(vm, 'vcpus', 3, 3, '3')
  319. del vm.vcpus
  320. self.assertPropertyDefaultValue(vm, 'vcpus', 2)
  321. self.assertPropertyValue(vm, 'vcpus', '3', 3, '3')
  322. def test_191_vcpus_invalid(self):
  323. vm = self.get_vm()
  324. self.assertPropertyInvalidValue(vm, 'vcpus', 0)
  325. self.assertPropertyInvalidValue(vm, 'vcpus', -2)
  326. self.assertPropertyInvalidValue(vm, 'vcpus', '-2')
  327. self.assertPropertyInvalidValue(vm, 'vcpus', '')
  328. def test_200_debug(self):
  329. vm = self.get_vm()
  330. self._test_generic_bool_property(vm, 'debug', False)
  331. def test_210_installed_by_rpm(self):
  332. vm = self.get_vm()
  333. self._test_generic_bool_property(vm, 'installed_by_rpm', False)
  334. def test_220_include_in_backups(self):
  335. vm = self.get_vm()
  336. self._test_generic_bool_property(vm, 'include_in_backups', True)
  337. @qubes.tests.skipUnlessDom0
  338. def test_250_kernel(self):
  339. kernels = os.listdir(os.path.join(
  340. qubes.config.qubes_base_dir,
  341. qubes.config.system_path['qubes_kernels_base_dir']))
  342. if not len(kernels):
  343. self.skipTest('Needs at least one kernel installed')
  344. self.app.default_kernel = kernels[0]
  345. vm = self.get_vm()
  346. self.assertPropertyDefaultValue(vm, 'kernel', kernels[0])
  347. self.assertPropertyValue(vm, 'kernel', kernels[-1], kernels[-1],
  348. kernels[-1])
  349. del vm.kernel
  350. self.assertPropertyDefaultValue(vm, 'kernel', kernels[0])
  351. @qubes.tests.skipUnlessDom0
  352. def test_251_kernel_invalid(self):
  353. vm = self.get_vm()
  354. self.assertPropertyInvalidValue(vm, 'kernel', 123)
  355. self.assertPropertyInvalidValue(vm, 'kernel', 'invalid')
  356. def test_252_kernel_empty(self):
  357. vm = self.get_vm()
  358. self.assertPropertyValue(vm, 'kernel', '', '', '')
  359. self.assertPropertyValue(vm, 'kernel', None, '', '')
  360. def test_260_kernelopts(self):
  361. vm = self.get_vm()
  362. self.assertPropertyDefaultValue(vm, 'kernelopts',
  363. qubes.config.defaults['kernelopts'])
  364. self.assertPropertyValue(vm, 'kernelopts', 'some options',
  365. 'some options', 'some options')
  366. del vm.kernelopts
  367. self.assertPropertyDefaultValue(vm, 'kernelopts',
  368. qubes.config.defaults['kernelopts'])
  369. self.assertPropertyValue(vm, 'kernelopts', '',
  370. '', '')
  371. # TODO?
  372. # self.assertPropertyInvalidValue(vm, 'kernelopts', None),
  373. @unittest.skip('test not implemented')
  374. def test_261_kernelopts_pcidevs(self):
  375. vm = self.get_vm()
  376. # how to do that here? use dummy DeviceManager/DeviceCollection?
  377. # Disable events?
  378. vm.devices['pci'].attach('something')
  379. self.assertPropertyDefaultValue(vm, 'kernelopts',
  380. qubes.config.defaults['kernelopts_pcidevs'])
  381. def test_270_qrexec_timeout(self):
  382. vm = self.get_vm()
  383. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 60)
  384. self.assertPropertyValue(vm, 'qrexec_timeout', 3, 3, '3')
  385. del vm.qrexec_timeout
  386. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 60)
  387. self.assertPropertyValue(vm, 'qrexec_timeout', '3', 3, '3')
  388. def test_271_qrexec_timeout_invalid(self):
  389. vm = self.get_vm()
  390. self.assertPropertyInvalidValue(vm, 'qrexec_timeout', -2)
  391. self.assertPropertyInvalidValue(vm, 'qrexec_timeout', '-2')
  392. self.assertPropertyInvalidValue(vm, 'qrexec_timeout', '')
  393. def test_272_qrexec_timeout_global_changed(self):
  394. self.app.default_qrexec_timeout = 123
  395. vm = self.get_vm()
  396. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 123)
  397. self.assertPropertyValue(vm, 'qrexec_timeout', 3, 3, '3')
  398. del vm.qrexec_timeout
  399. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 123)
  400. self.assertPropertyValue(vm, 'qrexec_timeout', '3', 3, '3')
  401. def test_280_autostart(self):
  402. vm = self.get_vm()
  403. # FIXME any better idea to not involve systemctl call at this stage?
  404. vm.events_enabled = False
  405. self._test_generic_bool_property(vm, 'autostart', False)
  406. @qubes.tests.skipUnlessDom0
  407. def test_281_autostart_systemd(self):
  408. vm = self.get_vm()
  409. self.assertFalse(os.path.exists(
  410. '/etc/systemd/system/multi-user.target.wants/'
  411. 'qubes-vm@{}.service'.format(vm.name)),
  412. "systemd service enabled before setting autostart")
  413. vm.autostart = True
  414. self.assertTrue(os.path.exists(
  415. '/etc/systemd/system/multi-user.target.wants/'
  416. 'qubes-vm@{}.service'.format(vm.name)),
  417. "systemd service not enabled by autostart=True")
  418. vm.autostart = False
  419. self.assertFalse(os.path.exists(
  420. '/etc/systemd/system/multi-user.target.wants/'
  421. 'qubes-vm@{}.service'.format(vm.name)),
  422. "systemd service not disabled by autostart=False")
  423. vm.autostart = True
  424. del vm.autostart
  425. self.assertFalse(os.path.exists(
  426. '/etc/systemd/system/multi-user.target.wants/'
  427. 'qubes-vm@{}.service'.format(vm.name)),
  428. "systemd service not disabled by resetting autostart")
  429. @unittest.skip('TODO')
  430. def test_320_seamless_gui_mode(self):
  431. vm = self.get_vm()
  432. self._test_generic_bool_property(vm, 'seamless_gui_mode')
  433. # TODO: reject setting to True when guiagent_installed is false
  434. def test_330_mac(self):
  435. vm = self.get_vm()
  436. # TODO: calculate proper default here
  437. default_mac = vm.mac
  438. self.assertIsNotNone(default_mac)
  439. self.assertPropertyDefaultValue(vm, 'mac', default_mac)
  440. self.assertPropertyValue(vm, 'mac', '00:11:22:33:44:55',
  441. '00:11:22:33:44:55', '00:11:22:33:44:55')
  442. del vm.mac
  443. self.assertPropertyDefaultValue(vm, 'mac', default_mac)
  444. def test_331_mac_invalid(self):
  445. vm = self.get_vm()
  446. self.assertPropertyInvalidValue(vm, 'mac', 123)
  447. self.assertPropertyInvalidValue(vm, 'mac', 'invalid')
  448. self.assertPropertyInvalidValue(vm, 'mac', '00:11:22:33:44:55:66')
  449. def test_340_default_user(self):
  450. vm = self.get_vm()
  451. self.assertPropertyDefaultValue(vm, 'default_user', 'user')
  452. self.assertPropertyValue(vm, 'default_user', 'someuser', 'someuser',
  453. 'someuser')
  454. del vm.default_user
  455. self.assertPropertyDefaultValue(vm, 'default_user', 'user')
  456. self.assertPropertyValue(vm, 'default_user', 123, '123', '123')
  457. vm.default_user = 'user'
  458. # TODO: check propagation for template-based VMs
  459. @unittest.skip('TODO')
  460. def test_350_timezone(self):
  461. vm = self.get_vm()
  462. self.assertPropertyDefaultValue(vm, 'timezone', 'localtime')
  463. self.assertPropertyValue(vm, 'timezone', 0, 0, '0')
  464. del vm.timezone
  465. self.assertPropertyDefaultValue(vm, 'timezone', 'localtime')
  466. self.assertPropertyValue(vm, 'timezone', '0', 0, '0')
  467. self.assertPropertyValue(vm, 'timezone', -3600, -3600, '-3600')
  468. self.assertPropertyValue(vm, 'timezone', 7200, 7200, '7200')
  469. @unittest.skip('TODO')
  470. def test_350_timezone_invalid(self):
  471. vm = self.get_vm()
  472. self.assertPropertyInvalidValue(vm, 'timezone', 'xxx')
  473. @unittest.skip('TODO')
  474. def test_360_drive(self):
  475. vm = self.get_vm()
  476. self.assertPropertyDefaultValue(vm, 'drive', None)
  477. # self.execute_tests('drive', [
  478. # ('hd:dom0:/tmp/drive.img', 'hd:dom0:/tmp/drive.img', True),
  479. # ('hd:/tmp/drive.img', 'hd:dom0:/tmp/drive.img', True),
  480. # ('cdrom:dom0:/tmp/drive.img', 'cdrom:dom0:/tmp/drive.img', True),
  481. # ('cdrom:/tmp/drive.img', 'cdrom:dom0:/tmp/drive.img', True),
  482. # ('/tmp/drive.img', 'cdrom:dom0:/tmp/drive.img', True),
  483. # ('hd:drive.img', '', False),
  484. # ('drive.img', '', False),
  485. # ])
  486. def test_400_backup_timestamp(self):
  487. vm = self.get_vm()
  488. timestamp = datetime.datetime(2016, 1, 1, 12, 14, 2)
  489. timestamp_str = timestamp.strftime('%s')
  490. self.assertPropertyDefaultValue(vm, 'backup_timestamp', None)
  491. self.assertPropertyValue(vm, 'backup_timestamp', int(timestamp_str),
  492. int(timestamp_str), timestamp_str)
  493. del vm.backup_timestamp
  494. self.assertPropertyDefaultValue(vm, 'backup_timestamp', None)
  495. self.assertPropertyValue(vm, 'backup_timestamp', timestamp_str,
  496. int(timestamp_str))
  497. def test_401_backup_timestamp_invalid(self):
  498. vm = self.get_vm()
  499. self.assertPropertyInvalidValue(vm, 'backup_timestamp', 'xxx')
  500. self.assertPropertyInvalidValue(vm, 'backup_timestamp', None)
  501. def test_500_property_migrate_virt_mode(self):
  502. xml_template = '''
  503. <domain class="QubesVM" id="domain-1">
  504. <properties>
  505. <property name="qid">1</property>
  506. <property name="name">testvm</property>
  507. <property name="label" ref="label-1" />
  508. <property name="hvm">{hvm_value}</property>
  509. </properties>
  510. </domain>
  511. '''
  512. xml = lxml.etree.XML(xml_template.format(hvm_value='True'))
  513. vm = qubes.vm.qubesvm.QubesVM(self.app, xml)
  514. self.assertEqual(vm.virt_mode, 'hvm')
  515. with self.assertRaises(AttributeError):
  516. vm.hvm
  517. xml = lxml.etree.XML(xml_template.format(hvm_value='False'))
  518. vm = qubes.vm.qubesvm.QubesVM(self.app, xml)
  519. self.assertEqual(vm.virt_mode, 'pv')
  520. with self.assertRaises(AttributeError):
  521. vm.hvm
  522. def test_600_libvirt_xml_pv(self):
  523. expected = '''<domain type="xen">
  524. <name>test-inst-test</name>
  525. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  526. <memory unit="MiB">500</memory>
  527. <currentMemory unit="MiB">400</currentMemory>
  528. <vcpu placement="static">2</vcpu>
  529. <os>
  530. <type arch="x86_64" machine="xenpv">linux</type>
  531. <kernel>/tmp/kernel/vmlinuz</kernel>
  532. <initrd>/tmp/kernel/initramfs</initrd>
  533. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  534. </os>
  535. <features>
  536. </features>
  537. <clock offset='utc' adjustment='reset'>
  538. <timer name="tsc" mode="native"/>
  539. </clock>
  540. <on_poweroff>destroy</on_poweroff>
  541. <on_reboot>destroy</on_reboot>
  542. <on_crash>destroy</on_crash>
  543. <devices>
  544. <disk type="block" device="disk">
  545. <driver name="phy" />
  546. <source dev="/tmp/kernel/modules.img" />
  547. <target dev="xvdd" />
  548. <backenddomain name="dom0" />
  549. </disk>
  550. <console type="pty">
  551. <target type="xen" port="0"/>
  552. </console>
  553. </devices>
  554. </domain>
  555. '''
  556. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  557. vm = self.get_vm(uuid=my_uuid)
  558. vm.netvm = None
  559. vm.virt_mode = 'pv'
  560. with unittest.mock.patch('qubes.config.qubes_base_dir',
  561. '/tmp/qubes-test'):
  562. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  563. os.makedirs(kernel_dir, exist_ok=True)
  564. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  565. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  566. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  567. vm.kernel = 'dummy'
  568. # tests for storage are later
  569. vm.volumes['kernel'] = unittest.mock.Mock(**{
  570. 'kernels_dir': '/tmp/kernel',
  571. 'block_device.return_value.domain': 'dom0',
  572. 'block_device.return_value.script': None,
  573. 'block_device.return_value.path': '/tmp/kernel/modules.img',
  574. 'block_device.return_value.devtype': 'disk',
  575. 'block_device.return_value.name': 'kernel',
  576. })
  577. libvirt_xml = vm.create_config_file()
  578. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  579. lxml.etree.XML(expected))
  580. def test_600_libvirt_xml_hvm(self):
  581. expected = '''<domain type="xen">
  582. <name>test-inst-test</name>
  583. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  584. <memory unit="MiB">500</memory>
  585. <currentMemory unit="MiB">400</currentMemory>
  586. <vcpu placement="static">2</vcpu>
  587. <cpu mode='host-passthrough'>
  588. <!-- disable nested HVM -->
  589. <feature name='vmx' policy='disable'/>
  590. <feature name='svm' policy='disable'/>
  591. <!-- disable SMAP inside VM, because of Linux bug -->
  592. <feature name='smap' policy='disable'/>
  593. </cpu>
  594. <os>
  595. <type arch="x86_64" machine="xenfv">hvm</type>
  596. <!--
  597. For the libxl backend libvirt switches between OVMF (UEFI)
  598. and SeaBIOS based on the loader type. This has nothing to
  599. do with the hvmloader binary.
  600. -->
  601. <loader type="rom">hvmloader</loader>
  602. <boot dev="cdrom" />
  603. <boot dev="hd" />
  604. </os>
  605. <features>
  606. <pae/>
  607. <acpi/>
  608. <apic/>
  609. <viridian/>
  610. </features>
  611. <clock offset="variable" adjustment="0" basis="localtime" />
  612. <on_poweroff>destroy</on_poweroff>
  613. <on_reboot>destroy</on_reboot>
  614. <on_crash>destroy</on_crash>
  615. <devices>
  616. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  617. <emulator type="stubdom-linux" />
  618. <input type="tablet" bus="usb"/>
  619. <video>
  620. <model type="vga"/>
  621. </video>
  622. <graphics type="qubes"/>
  623. </devices>
  624. </domain>
  625. '''
  626. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  627. vm = self.get_vm(uuid=my_uuid)
  628. vm.netvm = None
  629. vm.virt_mode = 'hvm'
  630. libvirt_xml = vm.create_config_file()
  631. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  632. lxml.etree.XML(expected))
  633. def test_600_libvirt_xml_hvm_dom0_kernel(self):
  634. expected = '''<domain type="xen">
  635. <name>test-inst-test</name>
  636. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  637. <memory unit="MiB">500</memory>
  638. <currentMemory unit="MiB">400</currentMemory>
  639. <vcpu placement="static">2</vcpu>
  640. <cpu mode='host-passthrough'>
  641. <!-- disable nested HVM -->
  642. <feature name='vmx' policy='disable'/>
  643. <feature name='svm' policy='disable'/>
  644. <!-- disable SMAP inside VM, because of Linux bug -->
  645. <feature name='smap' policy='disable'/>
  646. </cpu>
  647. <os>
  648. <type arch="x86_64" machine="xenfv">hvm</type>
  649. <!--
  650. For the libxl backend libvirt switches between OVMF (UEFI)
  651. and SeaBIOS based on the loader type. This has nothing to
  652. do with the hvmloader binary.
  653. -->
  654. <loader type="rom">hvmloader</loader>
  655. <boot dev="cdrom" />
  656. <boot dev="hd" />
  657. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  658. </os>
  659. <features>
  660. <pae/>
  661. <acpi/>
  662. <apic/>
  663. <viridian/>
  664. </features>
  665. <clock offset="variable" adjustment="0" basis="localtime" />
  666. <on_poweroff>destroy</on_poweroff>
  667. <on_reboot>destroy</on_reboot>
  668. <on_crash>destroy</on_crash>
  669. <devices>
  670. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  671. <emulator type="stubdom-linux" />
  672. <input type="tablet" bus="usb"/>
  673. <video>
  674. <model type="vga"/>
  675. </video>
  676. <graphics type="qubes"/>
  677. </devices>
  678. </domain>
  679. '''
  680. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  681. vm = self.get_vm(uuid=my_uuid)
  682. vm.netvm = None
  683. vm.virt_mode = 'hvm'
  684. with unittest.mock.patch('qubes.config.qubes_base_dir',
  685. '/tmp/qubes-test'):
  686. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  687. os.makedirs(kernel_dir, exist_ok=True)
  688. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  689. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  690. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  691. vm.kernel = 'dummy'
  692. libvirt_xml = vm.create_config_file()
  693. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  694. lxml.etree.XML(expected))
  695. def test_600_libvirt_xml_pvh(self):
  696. expected = '''<domain type="xen">
  697. <name>test-inst-test</name>
  698. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  699. <memory unit="MiB">500</memory>
  700. <currentMemory unit="MiB">400</currentMemory>
  701. <vcpu placement="static">2</vcpu>
  702. <cpu mode='host-passthrough'>
  703. <!-- disable nested HVM -->
  704. <feature name='vmx' policy='disable'/>
  705. <feature name='svm' policy='disable'/>
  706. <!-- disable SMAP inside VM, because of Linux bug -->
  707. <feature name='smap' policy='disable'/>
  708. </cpu>
  709. <os>
  710. <type arch="x86_64" machine="xenfv">pvh</type>
  711. <kernel>/tmp/kernel/vmlinuz</kernel>
  712. <initrd>/tmp/kernel/initramfs</initrd>
  713. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  714. </os>
  715. <features>
  716. <pae/>
  717. <acpi/>
  718. <apic/>
  719. <viridian/>
  720. </features>
  721. <clock offset='utc' adjustment='reset'>
  722. <timer name="tsc" mode="native"/>
  723. </clock>
  724. <on_poweroff>destroy</on_poweroff>
  725. <on_reboot>destroy</on_reboot>
  726. <on_crash>destroy</on_crash>
  727. <devices>
  728. <disk type="block" device="disk">
  729. <driver name="phy" />
  730. <source dev="/tmp/kernel/modules.img" />
  731. <target dev="xvdd" />
  732. <backenddomain name="dom0" />
  733. </disk>
  734. <console type="pty">
  735. <target type="xen" port="0"/>
  736. </console>
  737. </devices>
  738. </domain>
  739. '''
  740. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  741. vm = self.get_vm(uuid=my_uuid)
  742. vm.netvm = None
  743. vm.virt_mode = 'pvh'
  744. with unittest.mock.patch('qubes.config.qubes_base_dir',
  745. '/tmp/qubes-test'):
  746. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  747. os.makedirs(kernel_dir, exist_ok=True)
  748. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  749. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  750. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  751. vm.kernel = 'dummy'
  752. # tests for storage are later
  753. vm.volumes['kernel'] = unittest.mock.Mock(**{
  754. 'kernels_dir': '/tmp/kernel',
  755. 'block_device.return_value.domain': 'dom0',
  756. 'block_device.return_value.script': None,
  757. 'block_device.return_value.path': '/tmp/kernel/modules.img',
  758. 'block_device.return_value.devtype': 'disk',
  759. 'block_device.return_value.name': 'kernel',
  760. })
  761. libvirt_xml = vm.create_config_file()
  762. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  763. lxml.etree.XML(expected))
  764. def test_610_libvirt_xml_network(self):
  765. expected = '''<domain type="xen">
  766. <name>test-inst-test</name>
  767. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  768. <memory unit="MiB">500</memory>
  769. <currentMemory unit="MiB">400</currentMemory>
  770. <vcpu placement="static">2</vcpu>
  771. <cpu mode='host-passthrough'>
  772. <!-- disable nested HVM -->
  773. <feature name='vmx' policy='disable'/>
  774. <feature name='svm' policy='disable'/>
  775. <!-- disable SMAP inside VM, because of Linux bug -->
  776. <feature name='smap' policy='disable'/>
  777. </cpu>
  778. <os>
  779. <type arch="x86_64" machine="xenfv">hvm</type>
  780. <!--
  781. For the libxl backend libvirt switches between OVMF (UEFI)
  782. and SeaBIOS based on the loader type. This has nothing to
  783. do with the hvmloader binary.
  784. -->
  785. <loader type="rom">hvmloader</loader>
  786. <boot dev="cdrom" />
  787. <boot dev="hd" />
  788. </os>
  789. <features>
  790. <pae/>
  791. <acpi/>
  792. <apic/>
  793. <viridian/>
  794. </features>
  795. <clock offset="variable" adjustment="0" basis="localtime" />
  796. <on_poweroff>destroy</on_poweroff>
  797. <on_reboot>destroy</on_reboot>
  798. <on_crash>destroy</on_crash>
  799. <devices>
  800. <interface type="ethernet">
  801. <mac address="00:16:3E:5E:6C:00" />
  802. <ip address="10.137.0.1" />
  803. {extra_ip}
  804. <backenddomain name="test-inst-netvm" />
  805. <script path="vif-route-qubes" />
  806. </interface>
  807. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  808. <emulator type="stubdom-linux" />
  809. <input type="tablet" bus="usb"/>
  810. <video>
  811. <model type="vga"/>
  812. </video>
  813. <graphics type="qubes"/>
  814. </devices>
  815. </domain>
  816. '''
  817. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  818. netvm = self.get_vm(qid=2, name='netvm', provides_network=True)
  819. vm = self.get_vm(uuid=my_uuid)
  820. vm.netvm = netvm
  821. vm.virt_mode = 'hvm'
  822. with self.subTest('ipv4_only'):
  823. libvirt_xml = vm.create_config_file()
  824. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  825. lxml.etree.XML(expected.format(extra_ip='')))
  826. with self.subTest('ipv6'):
  827. netvm.features['ipv6'] = True
  828. libvirt_xml = vm.create_config_file()
  829. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  830. lxml.etree.XML(expected.format(
  831. extra_ip='<ip address="{}::a89:1" family=\'ipv6\'/>'.format(
  832. qubes.config.qubes_ipv6_prefix.replace(':0000', '')))))
  833. @unittest.mock.patch('qubes.utils.get_timezone')
  834. @unittest.mock.patch('qubes.utils.urandom')
  835. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.untrusted_qdb')
  836. def test_620_qdb_standalone(self, mock_qubesdb, mock_urandom,
  837. mock_timezone):
  838. mock_urandom.return_value = b'A' * 64
  839. mock_timezone.return_value = 'UTC'
  840. vm = self.get_vm(cls=qubes.vm.standalonevm.StandaloneVM)
  841. vm.netvm = None
  842. vm.events_enabled = True
  843. test_qubesdb = TestQubesDB()
  844. mock_qubesdb.write.side_effect = test_qubesdb.write
  845. mock_qubesdb.rm.side_effect = test_qubesdb.rm
  846. vm.create_qdb_entries()
  847. self.maxDiff = None
  848. iptables_header = (
  849. '# Generated by Qubes Core on {}\n'
  850. '*filter\n'
  851. ':INPUT DROP [0:0]\n'
  852. ':FORWARD DROP [0:0]\n'
  853. ':OUTPUT ACCEPT [0:0]\n'
  854. '-A INPUT -i vif+ -p udp -m udp --dport 68 -j DROP\n'
  855. '-A INPUT -m conntrack --ctstate '
  856. 'RELATED,ESTABLISHED -j ACCEPT\n'
  857. '-A INPUT -p icmp -j ACCEPT\n'
  858. '-A INPUT -i lo -j ACCEPT\n'
  859. '-A INPUT -j REJECT --reject-with '
  860. 'icmp-host-prohibited\n'
  861. '-A FORWARD -m conntrack --ctstate '
  862. 'RELATED,ESTABLISHED -j ACCEPT\n'
  863. '-A FORWARD -i vif+ -o vif+ -j DROP\n'
  864. 'COMMIT\n'.format(datetime.datetime.now().ctime()))
  865. self.assertEqual(test_qubesdb.data, {
  866. '/name': 'test-inst-test',
  867. '/type': 'StandaloneVM',
  868. '/default-user': 'user',
  869. '/qubes-vm-type': 'AppVM',
  870. '/qubes-debug-mode': '0',
  871. '/qubes-base-template': '',
  872. '/qubes-timezone': 'UTC',
  873. '/qubes-random-seed': base64.b64encode(b'A' * 64),
  874. '/qubes-vm-persistence': 'full',
  875. '/qubes-vm-updateable': 'True',
  876. '/qubes-block-devices': '',
  877. '/qubes-usb-devices': '',
  878. '/qubes-iptables': 'reload',
  879. '/qubes-iptables-error': '',
  880. '/qubes-iptables-header': iptables_header,
  881. '/qubes-service/qubes-update-check': '0',
  882. })
  883. @unittest.mock.patch('qubes.utils.get_timezone')
  884. @unittest.mock.patch('qubes.utils.urandom')
  885. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.untrusted_qdb')
  886. def test_621_qdb_vm_with_network(self, mock_qubesdb, mock_urandom,
  887. mock_timezone):
  888. mock_urandom.return_value = b'A' * 64
  889. mock_timezone.return_value = 'UTC'
  890. template = self.get_vm(cls=qubes.vm.templatevm.TemplateVM, name='template')
  891. template.netvm = None
  892. netvm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  893. name='netvm', qid=2, provides_network=True)
  894. vm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  895. name='appvm', qid=3)
  896. vm.netvm = netvm
  897. vm.kernel = None
  898. # pretend the VM is running...
  899. vm._qubesprop_xid = 3
  900. netvm.kernel = None
  901. test_qubesdb = TestQubesDB()
  902. mock_qubesdb.write.side_effect = test_qubesdb.write
  903. mock_qubesdb.rm.side_effect = test_qubesdb.rm
  904. self.maxDiff = None
  905. iptables_header = (
  906. '# Generated by Qubes Core on {}\n'
  907. '*filter\n'
  908. ':INPUT DROP [0:0]\n'
  909. ':FORWARD DROP [0:0]\n'
  910. ':OUTPUT ACCEPT [0:0]\n'
  911. '-A INPUT -i vif+ -p udp -m udp --dport 68 -j DROP\n'
  912. '-A INPUT -m conntrack --ctstate '
  913. 'RELATED,ESTABLISHED -j ACCEPT\n'
  914. '-A INPUT -p icmp -j ACCEPT\n'
  915. '-A INPUT -i lo -j ACCEPT\n'
  916. '-A INPUT -j REJECT --reject-with '
  917. 'icmp-host-prohibited\n'
  918. '-A FORWARD -m conntrack --ctstate '
  919. 'RELATED,ESTABLISHED -j ACCEPT\n'
  920. '-A FORWARD -i vif+ -o vif+ -j DROP\n'
  921. 'COMMIT\n'.format(datetime.datetime.now().ctime()))
  922. expected = {
  923. '/name': 'test-inst-appvm',
  924. '/type': 'AppVM',
  925. '/default-user': 'user',
  926. '/qubes-vm-type': 'AppVM',
  927. '/qubes-debug-mode': '0',
  928. '/qubes-base-template': 'test-inst-template',
  929. '/qubes-timezone': 'UTC',
  930. '/qubes-random-seed': base64.b64encode(b'A' * 64),
  931. '/qubes-vm-persistence': 'rw-only',
  932. '/qubes-vm-updateable': 'False',
  933. '/qubes-block-devices': '',
  934. '/qubes-usb-devices': '',
  935. '/qubes-iptables': 'reload',
  936. '/qubes-iptables-error': '',
  937. '/qubes-iptables-header': iptables_header,
  938. '/qubes-service/qubes-update-check': '0',
  939. '/qubes-ip': '10.137.0.3',
  940. '/qubes-netmask': '255.255.255.255',
  941. '/qubes-gateway': '10.137.0.2',
  942. '/qubes-primary-dns': '10.139.1.1',
  943. '/qubes-secondary-dns': '10.139.1.2',
  944. }
  945. with self.subTest('ipv4'):
  946. vm.create_qdb_entries()
  947. self.assertEqual(test_qubesdb.data, expected)
  948. test_qubesdb.data.clear()
  949. with self.subTest('ipv6'):
  950. netvm.features['ipv6'] = True
  951. expected['/qubes-ip6'] = \
  952. qubes.config.qubes_ipv6_prefix.replace(':0000', '') + \
  953. '::a89:3'
  954. expected['/qubes-gateway6'] = expected['/qubes-ip6'][:-1] + '2'
  955. vm.create_qdb_entries()
  956. self.assertEqual(test_qubesdb.data, expected)
  957. test_qubesdb.data.clear()
  958. with self.subTest('ipv6_just_appvm'):
  959. del netvm.features['ipv6']
  960. vm.features['ipv6'] = True
  961. expected['/qubes-ip6'] = \
  962. qubes.config.qubes_ipv6_prefix.replace(':0000', '') + \
  963. '::a89:3'
  964. del expected['/qubes-gateway6']
  965. vm.create_qdb_entries()
  966. self.assertEqual(test_qubesdb.data, expected)
  967. test_qubesdb.data.clear()
  968. with self.subTest('proxy_ipv4'):
  969. del vm.features['ipv6']
  970. expected['/name'] = 'test-inst-netvm'
  971. expected['/qubes-vm-type'] = 'NetVM'
  972. del expected['/qubes-ip']
  973. del expected['/qubes-gateway']
  974. del expected['/qubes-netmask']
  975. del expected['/qubes-ip6']
  976. del expected['/qubes-primary-dns']
  977. del expected['/qubes-secondary-dns']
  978. expected['/qubes-netvm-primary-dns'] = '10.139.1.1'
  979. expected['/qubes-netvm-secondary-dns'] = '10.139.1.2'
  980. expected['/qubes-netvm-network'] = '10.137.0.2'
  981. expected['/qubes-netvm-gateway'] = '10.137.0.2'
  982. expected['/qubes-netvm-netmask'] = '255.255.255.255'
  983. expected['/qubes-iptables-domainrules/3'] = \
  984. '*filter\n' \
  985. '-A FORWARD -s 10.137.0.3 -j ACCEPT\n' \
  986. '-A FORWARD -s 10.137.0.3 -j DROP\n' \
  987. 'COMMIT\n'
  988. expected['/mapped-ip/10.137.0.3/visible-ip'] = '10.137.0.3'
  989. expected['/mapped-ip/10.137.0.3/visible-gateway'] = '10.137.0.2'
  990. expected['/qubes-firewall/10.137.0.3'] = ''
  991. expected['/qubes-firewall/10.137.0.3/0000'] = 'action=accept'
  992. expected['/qubes-firewall/10.137.0.3/policy'] = 'drop'
  993. with unittest.mock.patch('qubes.vm.qubesvm.QubesVM.is_running',
  994. lambda _: True):
  995. netvm.create_qdb_entries()
  996. self.assertEqual(test_qubesdb.data, expected)
  997. test_qubesdb.data.clear()
  998. with self.subTest('proxy_ipv6'):
  999. netvm.features['ipv6'] = True
  1000. ip6 = qubes.config.qubes_ipv6_prefix.replace(
  1001. ':0000', '') + '::a89:3'
  1002. expected['/qubes-netvm-gateway6'] = ip6[:-1] + '2'
  1003. expected['/qubes-firewall/' + ip6] = ''
  1004. expected['/qubes-firewall/' + ip6 + '/0000'] = 'action=accept'
  1005. expected['/qubes-firewall/' + ip6 + '/policy'] = 'drop'
  1006. with unittest.mock.patch('qubes.vm.qubesvm.QubesVM.is_running',
  1007. lambda _: True):
  1008. netvm.create_qdb_entries()
  1009. self.assertEqual(test_qubesdb.data, expected)