qubesvm.py 57 KB

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