qubesvm.py 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005
  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 subprocess
  24. import tempfile
  25. import unittest
  26. import uuid
  27. import datetime
  28. import asyncio
  29. import functools
  30. import lxml.etree
  31. import unittest.mock
  32. import shutil
  33. import qubes
  34. import qubes.exc
  35. import qubes.config
  36. import qubes.devices
  37. import qubes.vm
  38. import qubes.vm.qubesvm
  39. import qubes.tests
  40. import qubes.tests.vm
  41. class TestApp(object):
  42. labels = {1: qubes.Label(1, '0xcc0000', 'red')}
  43. def __init__(self):
  44. self.domains = {}
  45. self.host = unittest.mock.Mock()
  46. self.host.memory_total = 4096 * 1024
  47. class TestFeatures(dict):
  48. def __init__(self, vm, **kwargs) -> None:
  49. self.vm = vm
  50. super().__init__(**kwargs)
  51. def check_with_template(self, feature, default):
  52. vm = self.vm
  53. while vm is not None:
  54. try:
  55. return vm.features[feature]
  56. except KeyError:
  57. vm = getattr(vm, 'template', None)
  58. return default
  59. class TestProp(object):
  60. # pylint: disable=too-few-public-methods
  61. __name__ = 'testprop'
  62. class TestDeviceCollection(object):
  63. def __init__(self):
  64. self._list = []
  65. def persistent(self):
  66. return self._list
  67. class TestQubesDB(object):
  68. def __init__(self, data=None):
  69. self.data = {}
  70. if data:
  71. self.data = data
  72. def write(self, path, value):
  73. self.data[path] = value
  74. def rm(self, path):
  75. if path.endswith('/'):
  76. for key in [x for x in self.data if x.startswith(path)]:
  77. del self.data[key]
  78. else:
  79. self.data.pop(path, None)
  80. def list(self, prefix):
  81. return [key for key in self.data if key.startswith(prefix)]
  82. def close(self):
  83. pass
  84. class TestVM(object):
  85. # pylint: disable=too-few-public-methods
  86. app = TestApp()
  87. def __init__(self, **kwargs):
  88. self.running = False
  89. self.installed_by_rpm = False
  90. for k, v in kwargs.items():
  91. setattr(self, k, v)
  92. self.devices = {'pci': TestDeviceCollection()}
  93. self.features = TestFeatures(self)
  94. def is_running(self):
  95. return self.running
  96. class TC_00_setters(qubes.tests.QubesTestCase):
  97. def setUp(self):
  98. super().setUp()
  99. self.vm = TestVM()
  100. self.prop = TestProp()
  101. def test_000_setter_qid(self):
  102. self.assertEqual(
  103. qubes.vm._setter_qid(self.vm, self.prop, 5), 5)
  104. def test_001_setter_qid_lt_0(self):
  105. with self.assertRaises(ValueError):
  106. qubes.vm._setter_qid(self.vm, self.prop, -1)
  107. def test_002_setter_qid_gt_max(self):
  108. with self.assertRaises(ValueError):
  109. qubes.vm._setter_qid(self.vm,
  110. self.prop, qubes.config.max_qid + 5)
  111. @unittest.skip('test not implemented')
  112. def test_020_setter_kernel(self):
  113. pass
  114. def test_030_setter_label_object(self):
  115. label = TestApp.labels[1]
  116. self.assertIs(label,
  117. qubes.vm.setter_label(self.vm, self.prop, label))
  118. def test_031_setter_label_getitem(self):
  119. label = TestApp.labels[1]
  120. self.assertIs(label,
  121. qubes.vm.setter_label(self.vm, self.prop, 'label-1'))
  122. # there is no check for self.app.get_label()
  123. def test_040_setter_virt_mode(self):
  124. self.assertEqual(
  125. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'hvm'),
  126. 'hvm')
  127. self.assertEqual(
  128. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'HVM'),
  129. 'hvm')
  130. self.assertEqual(
  131. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'PV'),
  132. 'pv')
  133. self.assertEqual(
  134. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'pvh'),
  135. 'pvh')
  136. self.vm.devices['pci']._list.append(object())
  137. with self.assertRaises(ValueError):
  138. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'pvh')
  139. with self.assertRaises(ValueError):
  140. qubes.vm.qubesvm._setter_virt_mode(self.vm, self.prop, 'True')
  141. class TC_10_default(qubes.tests.QubesTestCase):
  142. def setUp(self):
  143. super().setUp()
  144. self.app = TestApp()
  145. self.vm = TestVM(app=self.app)
  146. self.prop = TestProp()
  147. def test_000_default_with_template_simple(self):
  148. default_getter = qubes.vm.qubesvm._default_with_template('kernel',
  149. 'dfl-kernel')
  150. self.assertEqual(default_getter(self.vm), 'dfl-kernel')
  151. self.vm.template = None
  152. self.assertEqual(default_getter(self.vm), '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_001_default_with_template_callable(self):
  157. default_getter = qubes.vm.qubesvm._default_with_template('kernel',
  158. lambda x: x.app.default_kernel)
  159. self.app.default_kernel = 'global-dfl-kernel'
  160. self.assertEqual(default_getter(self.vm), 'global-dfl-kernel')
  161. self.vm.template = None
  162. self.assertEqual(default_getter(self.vm), 'global-dfl-kernel')
  163. self.vm.template = unittest.mock.Mock()
  164. self.vm.template.kernel = 'template-kernel'
  165. self.assertEqual(default_getter(self.vm), 'template-kernel')
  166. def test_010_default_virt_mode(self):
  167. self.assertEqual(qubes.vm.qubesvm._default_virt_mode(self.vm),
  168. 'pvh')
  169. self.vm.template = unittest.mock.Mock()
  170. self.vm.template.virt_mode = 'hvm'
  171. self.assertEqual(qubes.vm.qubesvm._default_virt_mode(self.vm),
  172. 'hvm')
  173. self.vm.template = None
  174. self.assertEqual(qubes.vm.qubesvm._default_virt_mode(self.vm),
  175. 'pvh')
  176. self.vm.devices['pci'].persistent().append('some-dev')
  177. self.assertEqual(qubes.vm.qubesvm._default_virt_mode(self.vm),
  178. 'hvm')
  179. def test_020_default_maxmem(self):
  180. default_maxmem = 2048
  181. self.vm.is_memory_balancing_possible = \
  182. lambda: qubes.vm.qubesvm.QubesVM.is_memory_balancing_possible(
  183. self.vm)
  184. self.vm.virt_mode = 'pvh'
  185. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm),
  186. default_maxmem)
  187. self.vm.virt_mode = 'hvm'
  188. # HVM without qubes tools
  189. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm), 0)
  190. # just 'qrexec' feature
  191. self.vm.features['qrexec'] = True
  192. print(self.vm.features.check_with_template('qrexec', False))
  193. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm),
  194. default_maxmem)
  195. # some supported-service.*, but not meminfo-writer
  196. self.vm.features['supported-service.qubes-firewall'] = True
  197. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm), 0)
  198. # then add meminfo-writer
  199. self.vm.features['supported-service.meminfo-writer'] = True
  200. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm),
  201. default_maxmem)
  202. def test_021_default_maxmem_with_pcidevs(self):
  203. self.vm.is_memory_balancing_possible = \
  204. lambda: qubes.vm.qubesvm.QubesVM.is_memory_balancing_possible(
  205. self.vm)
  206. self.vm.devices['pci'].persistent().append('00_00.0')
  207. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm), 0)
  208. def test_022_default_maxmem_linux(self):
  209. self.vm.is_memory_balancing_possible = \
  210. lambda: qubes.vm.qubesvm.QubesVM.is_memory_balancing_possible(
  211. self.vm)
  212. self.vm.virt_mode = 'pvh'
  213. self.vm.memory = 400
  214. self.vm.features['os'] = 'Linux'
  215. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm), 2048)
  216. self.vm.memory = 100
  217. self.assertEqual(qubes.vm.qubesvm._default_maxmem(self.vm), 1000)
  218. class QubesVMTestsMixin(object):
  219. property_no_default = object()
  220. def setUp(self):
  221. super(QubesVMTestsMixin, self).setUp()
  222. self.app = qubes.tests.vm.TestApp()
  223. self.app.vmm.offline_mode = True
  224. self.app.default_kernel = None
  225. # when full test run is called, extensions are loaded by earlier
  226. # tests, but if just this test class is run, load them manually here,
  227. # to have the same behaviour
  228. qubes.ext.get_extensions()
  229. def tearDown(self):
  230. try:
  231. # self.app is not a real events emiter, so make the call manually
  232. for handler in qubes.Qubes.__handlers__.get('qubes-close'):
  233. handler(self.app, 'qubes-close')
  234. self.app.domains.close()
  235. except AttributeError:
  236. pass
  237. super(QubesVMTestsMixin, self).tearDown()
  238. def get_vm(self, name='test', cls=qubes.vm.qubesvm.QubesVM, vm=None, **kwargs):
  239. if not vm:
  240. vm = cls(self.app, None,
  241. qid=kwargs.pop('qid', 1), name=qubes.tests.VMPREFIX + name,
  242. **kwargs)
  243. self.app.domains[vm.qid] = vm
  244. self.app.domains[vm.uuid] = vm
  245. self.app.domains[vm.name] = vm
  246. self.app.domains[vm] = vm
  247. self.addCleanup(vm.close)
  248. return vm
  249. def assertPropertyValue(self, vm, prop_name, set_value, expected_value,
  250. expected_xml_content=None):
  251. # FIXME: any better exception list? or maybe all of that should be a
  252. # single exception?
  253. with self.assertNotRaises((ValueError, TypeError, KeyError)):
  254. setattr(vm, prop_name, set_value)
  255. self.assertEqual(getattr(vm, prop_name), expected_value)
  256. if expected_xml_content is not None:
  257. xml = vm.__xml__()
  258. prop_xml = xml.xpath(
  259. './properties/property[@name=\'{}\']'.format(prop_name))
  260. self.assertEqual(len(prop_xml), 1, "Property not found in XML")
  261. self.assertEqual(prop_xml[0].text, expected_xml_content)
  262. def assertPropertyInvalidValue(self, vm, prop_name, set_value):
  263. orig_value_set = True
  264. orig_value = None
  265. try:
  266. orig_value = getattr(vm, prop_name)
  267. except AttributeError:
  268. orig_value_set = False
  269. # FIXME: any better exception list? or maybe all of that should be a
  270. # single exception?
  271. with self.assertRaises((ValueError, TypeError, KeyError)):
  272. setattr(vm, prop_name, set_value)
  273. if orig_value_set:
  274. self.assertEqual(getattr(vm, prop_name), orig_value)
  275. else:
  276. with self.assertRaises(AttributeError):
  277. getattr(vm, prop_name)
  278. def assertPropertyDefaultValue(self, vm, prop_name,
  279. expected_default=property_no_default):
  280. if expected_default is self.property_no_default:
  281. with self.assertRaises(AttributeError):
  282. getattr(vm, prop_name)
  283. else:
  284. with self.assertNotRaises(AttributeError):
  285. self.assertEqual(getattr(vm, prop_name), expected_default)
  286. xml = vm.__xml__()
  287. prop_xml = xml.xpath(
  288. './properties/property[@name=\'{}\']'.format(prop_name))
  289. self.assertEqual(len(prop_xml), 0, "Property still found in XML")
  290. def _test_generic_bool_property(self, vm, prop_name, default=False):
  291. self.assertPropertyDefaultValue(vm, prop_name, default)
  292. self.assertPropertyValue(vm, prop_name, False, False, 'False')
  293. self.assertPropertyValue(vm, prop_name, True, True, 'True')
  294. delattr(vm, prop_name)
  295. self.assertPropertyDefaultValue(vm, prop_name, default)
  296. self.assertPropertyValue(vm, prop_name, 'True', True, 'True')
  297. self.assertPropertyValue(vm, prop_name, 'False', False, 'False')
  298. self.assertPropertyInvalidValue(vm, prop_name, 'xxx')
  299. self.assertPropertyValue(vm, prop_name, 123, True)
  300. self.assertPropertyInvalidValue(vm, prop_name, '')
  301. class TC_90_QubesVM(QubesVMTestsMixin, qubes.tests.QubesTestCase):
  302. def test_000_init(self):
  303. self.get_vm()
  304. def test_001_init_no_qid_or_name(self):
  305. with self.assertRaises(AssertionError):
  306. qubes.vm.qubesvm.QubesVM(self.app, None,
  307. name=qubes.tests.VMPREFIX + 'test')
  308. with self.assertRaises(AssertionError):
  309. qubes.vm.qubesvm.QubesVM(self.app, None,
  310. qid=1)
  311. def test_003_init_fire_domain_init(self):
  312. class TestVM2(qubes.vm.qubesvm.QubesVM):
  313. event_fired = False
  314. @qubes.events.handler('domain-init')
  315. def on_domain_init(self, event): # pylint: disable=unused-argument
  316. self.__class__.event_fired = True
  317. TestVM2(self.app, None, qid=1, name=qubes.tests.VMPREFIX + 'test')
  318. self.assertTrue(TestVM2.event_fired)
  319. def test_004_uuid_autogen(self):
  320. vm = self.get_vm()
  321. self.assertTrue(hasattr(vm, 'uuid'))
  322. def test_100_qid(self):
  323. vm = self.get_vm()
  324. self.assertIsInstance(vm.qid, int)
  325. with self.assertRaises(AttributeError):
  326. vm.qid = 2
  327. def test_110_name(self):
  328. vm = self.get_vm()
  329. self.assertIsInstance(vm.name, str)
  330. def test_120_uuid(self):
  331. my_uuid = uuid.uuid4()
  332. vm = self.get_vm(uuid=my_uuid)
  333. self.assertIsInstance(vm.uuid, uuid.UUID)
  334. self.assertIs(vm.uuid, my_uuid)
  335. with self.assertRaises(AttributeError):
  336. vm.uuid = uuid.uuid4()
  337. @unittest.skip('TODO: how to not fail on making an icon symlink here?')
  338. def test_130_label(self):
  339. vm = self.get_vm()
  340. self.assertPropertyDefaultValue(vm, 'label')
  341. self.assertPropertyValue(vm, 'label', self.app.labels[1],
  342. self.app.labels[1], 'label-1')
  343. del vm.label
  344. self.assertPropertyDefaultValue(vm, 'label')
  345. self.assertPropertyValue(vm, 'label', 'red',
  346. self.app.labels[1], 'label-1')
  347. self.assertPropertyValue(vm, 'label', 'label-1',
  348. self.app.labels[1], 'label-1')
  349. def test_131_label_invalid(self):
  350. vm = self.get_vm()
  351. self.assertPropertyInvalidValue(vm, 'label', 'invalid')
  352. self.assertPropertyInvalidValue(vm, 'label', 123)
  353. def test_160_memory(self):
  354. vm = self.get_vm()
  355. self.assertPropertyDefaultValue(vm, 'memory', 400)
  356. self.assertPropertyValue(vm, 'memory', 500, 500, '500')
  357. del vm.memory
  358. self.assertPropertyDefaultValue(vm, 'memory', 400)
  359. self.assertPropertyValue(vm, 'memory', '500', 500, '500')
  360. def test_161_memory_invalid(self):
  361. vm = self.get_vm()
  362. self.assertPropertyInvalidValue(vm, 'memory', -100)
  363. self.assertPropertyInvalidValue(vm, 'memory', '-100')
  364. self.assertPropertyInvalidValue(vm, 'memory', '')
  365. # TODO: higher than maxmem
  366. # TODO: human readable setter (500M, 4G)?
  367. def test_170_maxmem(self):
  368. vm = self.get_vm()
  369. self.assertPropertyDefaultValue(vm, 'maxmem',
  370. self.app.host.memory_total / 1024 / 2)
  371. self.assertPropertyValue(vm, 'maxmem', 500, 500, '500')
  372. del vm.maxmem
  373. self.assertPropertyDefaultValue(vm, 'maxmem',
  374. self.app.host.memory_total / 1024 / 2)
  375. self.assertPropertyValue(vm, 'maxmem', '500', 500, '500')
  376. def test_171_maxmem_invalid(self):
  377. vm = self.get_vm()
  378. self.assertPropertyInvalidValue(vm, 'maxmem', -100)
  379. self.assertPropertyInvalidValue(vm, 'maxmem', '-100')
  380. self.assertPropertyInvalidValue(vm, 'maxmem', '')
  381. # TODO: lower than memory
  382. # TODO: human readable setter (500M, 4G)?
  383. def test_190_vcpus(self):
  384. vm = self.get_vm()
  385. self.assertPropertyDefaultValue(vm, 'vcpus', 2)
  386. self.assertPropertyValue(vm, 'vcpus', 3, 3, '3')
  387. del vm.vcpus
  388. self.assertPropertyDefaultValue(vm, 'vcpus', 2)
  389. self.assertPropertyValue(vm, 'vcpus', '3', 3, '3')
  390. def test_191_vcpus_invalid(self):
  391. vm = self.get_vm()
  392. self.assertPropertyInvalidValue(vm, 'vcpus', 0)
  393. self.assertPropertyInvalidValue(vm, 'vcpus', -2)
  394. self.assertPropertyInvalidValue(vm, 'vcpus', '-2')
  395. self.assertPropertyInvalidValue(vm, 'vcpus', '')
  396. def test_200_debug(self):
  397. vm = self.get_vm()
  398. self._test_generic_bool_property(vm, 'debug', False)
  399. def test_210_installed_by_rpm(self):
  400. vm = self.get_vm()
  401. self._test_generic_bool_property(vm, 'installed_by_rpm', False)
  402. def test_220_include_in_backups(self):
  403. vm = self.get_vm()
  404. self._test_generic_bool_property(vm, 'include_in_backups', True)
  405. @qubes.tests.skipUnlessDom0
  406. def test_250_kernel(self):
  407. kernels = os.listdir(os.path.join(
  408. qubes.config.qubes_base_dir,
  409. qubes.config.system_path['qubes_kernels_base_dir']))
  410. if not len(kernels):
  411. self.skipTest('Needs at least one kernel installed')
  412. self.app.default_kernel = kernels[0]
  413. vm = self.get_vm()
  414. self.assertPropertyDefaultValue(vm, 'kernel', kernels[0])
  415. self.assertPropertyValue(vm, 'kernel', kernels[-1], kernels[-1],
  416. kernels[-1])
  417. del vm.kernel
  418. self.assertPropertyDefaultValue(vm, 'kernel', kernels[0])
  419. @qubes.tests.skipUnlessDom0
  420. def test_251_kernel_invalid(self):
  421. vm = self.get_vm()
  422. self.assertPropertyInvalidValue(vm, 'kernel', 123)
  423. self.assertPropertyInvalidValue(vm, 'kernel', 'invalid')
  424. def test_252_kernel_empty(self):
  425. vm = self.get_vm()
  426. self.assertPropertyValue(vm, 'kernel', '', '', '')
  427. self.assertPropertyValue(vm, 'kernel', None, '', '')
  428. @unittest.mock.patch.dict(qubes.config.system_path,
  429. {'qubes_kernels_base_dir': '/tmp'})
  430. def test_260_kernelopts(self):
  431. d = tempfile.mkdtemp(prefix='/tmp/')
  432. self.addCleanup(shutil.rmtree, d)
  433. open(d + '/vmlinuz', 'w').close()
  434. open(d + '/initramfs', 'w').close()
  435. vm = self.get_vm()
  436. vm.kernel = os.path.basename(d)
  437. self.assertPropertyDefaultValue(vm, 'kernelopts',
  438. qubes.config.defaults['kernelopts'])
  439. self.assertPropertyValue(vm, 'kernelopts', 'some options',
  440. 'some options', 'some options')
  441. del vm.kernelopts
  442. self.assertPropertyDefaultValue(vm, 'kernelopts',
  443. qubes.config.defaults['kernelopts'])
  444. self.assertPropertyValue(vm, 'kernelopts', '',
  445. '', '')
  446. # TODO?
  447. # self.assertPropertyInvalidValue(vm, 'kernelopts', None),
  448. @unittest.skip('test not implemented')
  449. def test_261_kernelopts_pcidevs(self):
  450. vm = self.get_vm()
  451. # how to do that here? use dummy DeviceManager/DeviceCollection?
  452. # Disable events?
  453. vm.devices['pci'].attach('something')
  454. self.assertPropertyDefaultValue(vm, 'kernelopts',
  455. qubes.config.defaults['kernelopts_pcidevs'])
  456. @unittest.mock.patch.dict(qubes.config.system_path,
  457. {'qubes_kernels_base_dir': '/tmp'})
  458. def test_262_kernelopts(self):
  459. d = tempfile.mkdtemp(prefix='/tmp/')
  460. self.addCleanup(shutil.rmtree, d)
  461. open(d + '/vmlinuz', 'w').close()
  462. open(d + '/initramfs', 'w').close()
  463. with open(d + '/default-kernelopts-nopci.txt', 'w') as f:
  464. f.write('some default options')
  465. vm = self.get_vm()
  466. vm.kernel = os.path.basename(d)
  467. self.assertPropertyDefaultValue(vm, 'kernelopts',
  468. 'some default options')
  469. self.assertPropertyValue(vm, 'kernelopts', 'some options',
  470. 'some options', 'some options')
  471. del vm.kernelopts
  472. self.assertPropertyDefaultValue(vm, 'kernelopts',
  473. 'some default options')
  474. self.assertPropertyValue(vm, 'kernelopts', '',
  475. '', '')
  476. def test_270_qrexec_timeout(self):
  477. vm = self.get_vm()
  478. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 60)
  479. self.assertPropertyValue(vm, 'qrexec_timeout', 3, 3, '3')
  480. del vm.qrexec_timeout
  481. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 60)
  482. self.assertPropertyValue(vm, 'qrexec_timeout', '3', 3, '3')
  483. def test_271_qrexec_timeout_invalid(self):
  484. vm = self.get_vm()
  485. self.assertPropertyInvalidValue(vm, 'qrexec_timeout', -2)
  486. self.assertPropertyInvalidValue(vm, 'qrexec_timeout', '-2')
  487. self.assertPropertyInvalidValue(vm, 'qrexec_timeout', '')
  488. def test_272_qrexec_timeout_global_changed(self):
  489. self.app.default_qrexec_timeout = 123
  490. vm = self.get_vm()
  491. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 123)
  492. self.assertPropertyValue(vm, 'qrexec_timeout', 3, 3, '3')
  493. del vm.qrexec_timeout
  494. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 123)
  495. self.assertPropertyValue(vm, 'qrexec_timeout', '3', 3, '3')
  496. def test_280_autostart(self):
  497. vm = self.get_vm()
  498. # FIXME any better idea to not involve systemctl call at this stage?
  499. vm.events_enabled = False
  500. self._test_generic_bool_property(vm, 'autostart', False)
  501. @qubes.tests.skipUnlessDom0
  502. def test_281_autostart_systemd(self):
  503. vm = self.get_vm()
  504. self.assertFalse(os.path.exists(
  505. '/etc/systemd/system/multi-user.target.wants/'
  506. 'qubes-vm@{}.service'.format(vm.name)),
  507. "systemd service enabled before setting autostart")
  508. vm.autostart = True
  509. self.assertTrue(os.path.exists(
  510. '/etc/systemd/system/multi-user.target.wants/'
  511. 'qubes-vm@{}.service'.format(vm.name)),
  512. "systemd service not enabled by autostart=True")
  513. vm.autostart = False
  514. self.assertFalse(os.path.exists(
  515. '/etc/systemd/system/multi-user.target.wants/'
  516. 'qubes-vm@{}.service'.format(vm.name)),
  517. "systemd service not disabled by autostart=False")
  518. vm.autostart = True
  519. del vm.autostart
  520. self.assertFalse(os.path.exists(
  521. '/etc/systemd/system/multi-user.target.wants/'
  522. 'qubes-vm@{}.service'.format(vm.name)),
  523. "systemd service not disabled by resetting autostart")
  524. def test_290_management_dispvm(self):
  525. vm = self.get_vm()
  526. vm2 = self.get_vm('test2', qid=2)
  527. self.app.management_dispvm = None
  528. self.assertPropertyDefaultValue(vm, 'management_dispvm', None)
  529. self.app.management_dispvm = vm
  530. try:
  531. self.assertPropertyDefaultValue(vm, 'management_dispvm', vm)
  532. self.assertPropertyValue(vm, 'management_dispvm',
  533. 'test-inst-test2', vm2)
  534. finally:
  535. self.app.management_dispvm = None
  536. def test_291_management_dispvm_template_based(self):
  537. tpl = self.get_vm(name='tpl', cls=qubes.vm.templatevm.TemplateVM)
  538. vm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=tpl, qid=2)
  539. vm2 = self.get_vm('test2', qid=3)
  540. del vm.volumes
  541. self.app.management_dispvm = None
  542. try:
  543. self.assertPropertyDefaultValue(vm, 'management_dispvm', None)
  544. self.app.management_dispvm = vm
  545. self.assertPropertyDefaultValue(vm, 'management_dispvm', vm)
  546. tpl.management_dispvm = vm2
  547. self.assertPropertyDefaultValue(vm, 'management_dispvm', vm2)
  548. self.assertPropertyValue(vm, 'management_dispvm',
  549. 'test-inst-test2', vm2)
  550. finally:
  551. self.app.management_dispvm = None
  552. @unittest.skip('TODO')
  553. def test_320_seamless_gui_mode(self):
  554. vm = self.get_vm()
  555. self._test_generic_bool_property(vm, 'seamless_gui_mode')
  556. # TODO: reject setting to True when guiagent_installed is false
  557. def test_330_mac(self):
  558. vm = self.get_vm()
  559. # TODO: calculate proper default here
  560. default_mac = vm.mac
  561. self.assertIsNotNone(default_mac)
  562. self.assertPropertyDefaultValue(vm, 'mac', default_mac)
  563. self.assertPropertyValue(vm, 'mac', '00:11:22:33:44:55',
  564. '00:11:22:33:44:55', '00:11:22:33:44:55')
  565. del vm.mac
  566. self.assertPropertyDefaultValue(vm, 'mac', default_mac)
  567. def test_331_mac_invalid(self):
  568. vm = self.get_vm()
  569. self.assertPropertyInvalidValue(vm, 'mac', 123)
  570. self.assertPropertyInvalidValue(vm, 'mac', 'invalid')
  571. self.assertPropertyInvalidValue(vm, 'mac', '00:11:22:33:44:55:66')
  572. def test_340_default_user(self):
  573. vm = self.get_vm()
  574. self.assertPropertyDefaultValue(vm, 'default_user', 'user')
  575. self.assertPropertyValue(vm, 'default_user', 'someuser', 'someuser',
  576. 'someuser')
  577. del vm.default_user
  578. self.assertPropertyDefaultValue(vm, 'default_user', 'user')
  579. self.assertPropertyValue(vm, 'default_user', 123, '123', '123')
  580. vm.default_user = 'user'
  581. # TODO: check propagation for template-based VMs
  582. @unittest.skip('TODO')
  583. def test_350_timezone(self):
  584. vm = self.get_vm()
  585. self.assertPropertyDefaultValue(vm, 'timezone', 'localtime')
  586. self.assertPropertyValue(vm, 'timezone', 0, 0, '0')
  587. del vm.timezone
  588. self.assertPropertyDefaultValue(vm, 'timezone', 'localtime')
  589. self.assertPropertyValue(vm, 'timezone', '0', 0, '0')
  590. self.assertPropertyValue(vm, 'timezone', -3600, -3600, '-3600')
  591. self.assertPropertyValue(vm, 'timezone', 7200, 7200, '7200')
  592. @unittest.skip('TODO')
  593. def test_350_timezone_invalid(self):
  594. vm = self.get_vm()
  595. self.assertPropertyInvalidValue(vm, 'timezone', 'xxx')
  596. @unittest.skip('TODO')
  597. def test_360_drive(self):
  598. vm = self.get_vm()
  599. self.assertPropertyDefaultValue(vm, 'drive', None)
  600. # self.execute_tests('drive', [
  601. # ('hd:dom0:/tmp/drive.img', 'hd:dom0:/tmp/drive.img', True),
  602. # ('hd:/tmp/drive.img', 'hd:dom0:/tmp/drive.img', True),
  603. # ('cdrom:dom0:/tmp/drive.img', 'cdrom:dom0:/tmp/drive.img', True),
  604. # ('cdrom:/tmp/drive.img', 'cdrom:dom0:/tmp/drive.img', True),
  605. # ('/tmp/drive.img', 'cdrom:dom0:/tmp/drive.img', True),
  606. # ('hd:drive.img', '', False),
  607. # ('drive.img', '', False),
  608. # ])
  609. def test_400_backup_timestamp(self):
  610. vm = self.get_vm()
  611. timestamp = datetime.datetime(2016, 1, 1, 12, 14, 2)
  612. timestamp_str = timestamp.strftime('%s')
  613. self.assertPropertyDefaultValue(vm, 'backup_timestamp', None)
  614. self.assertPropertyValue(vm, 'backup_timestamp', int(timestamp_str),
  615. int(timestamp_str), timestamp_str)
  616. del vm.backup_timestamp
  617. self.assertPropertyDefaultValue(vm, 'backup_timestamp', None)
  618. self.assertPropertyValue(vm, 'backup_timestamp', timestamp_str,
  619. int(timestamp_str))
  620. def test_401_backup_timestamp_invalid(self):
  621. vm = self.get_vm()
  622. self.assertPropertyInvalidValue(vm, 'backup_timestamp', 'xxx')
  623. self.assertPropertyInvalidValue(vm, 'backup_timestamp', None)
  624. def test_500_property_migrate_virt_mode(self):
  625. xml_template = '''
  626. <domain class="QubesVM" id="domain-1">
  627. <properties>
  628. <property name="qid">1</property>
  629. <property name="name">testvm</property>
  630. <property name="label" ref="label-1" />
  631. <property name="hvm">{hvm_value}</property>
  632. </properties>
  633. </domain>
  634. '''
  635. xml = lxml.etree.XML(xml_template.format(hvm_value='True'))
  636. vm = qubes.vm.qubesvm.QubesVM(self.app, xml)
  637. self.assertEqual(vm.virt_mode, 'hvm')
  638. with self.assertRaises(AttributeError):
  639. vm.hvm
  640. xml = lxml.etree.XML(xml_template.format(hvm_value='False'))
  641. vm = qubes.vm.qubesvm.QubesVM(self.app, xml)
  642. self.assertEqual(vm.virt_mode, 'pv')
  643. with self.assertRaises(AttributeError):
  644. vm.hvm
  645. def test_600_libvirt_xml_pv(self):
  646. expected = '''<domain type="xen">
  647. <name>test-inst-test</name>
  648. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  649. <memory unit="MiB">500</memory>
  650. <currentMemory unit="MiB">400</currentMemory>
  651. <vcpu placement="static">2</vcpu>
  652. <os>
  653. <type arch="x86_64" machine="xenpv">linux</type>
  654. <kernel>/tmp/kernel/vmlinuz</kernel>
  655. <initrd>/tmp/kernel/initramfs</initrd>
  656. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  657. </os>
  658. <features>
  659. </features>
  660. <clock offset='utc' adjustment='reset'>
  661. <timer name="tsc" mode="native"/>
  662. </clock>
  663. <on_poweroff>destroy</on_poweroff>
  664. <on_reboot>destroy</on_reboot>
  665. <on_crash>destroy</on_crash>
  666. <devices>
  667. <disk type="block" device="disk">
  668. <driver name="phy" />
  669. <source dev="/tmp/kernel/modules.img" />
  670. <target dev="xvdd" />
  671. <backenddomain name="dom0" />
  672. </disk>
  673. <console type="pty">
  674. <target type="xen" port="0"/>
  675. </console>
  676. </devices>
  677. </domain>
  678. '''
  679. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  680. vm = self.get_vm(uuid=my_uuid)
  681. vm.netvm = None
  682. vm.virt_mode = 'pv'
  683. with unittest.mock.patch('qubes.config.qubes_base_dir',
  684. '/tmp/qubes-test'):
  685. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  686. os.makedirs(kernel_dir, exist_ok=True)
  687. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  688. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  689. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  690. vm.kernel = 'dummy'
  691. # tests for storage are later
  692. vm.volumes['kernel'] = unittest.mock.Mock(**{
  693. 'kernels_dir': '/tmp/kernel',
  694. 'block_device.return_value.domain': 'dom0',
  695. 'block_device.return_value.script': None,
  696. 'block_device.return_value.path': '/tmp/kernel/modules.img',
  697. 'block_device.return_value.devtype': 'disk',
  698. 'block_device.return_value.name': 'kernel',
  699. })
  700. libvirt_xml = vm.create_config_file()
  701. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  702. lxml.etree.XML(expected))
  703. def test_600_libvirt_xml_hvm(self):
  704. expected = '''<domain type="xen">
  705. <name>test-inst-test</name>
  706. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  707. <memory unit="MiB">400</memory>
  708. <currentMemory unit="MiB">400</currentMemory>
  709. <vcpu placement="static">2</vcpu>
  710. <cpu mode='host-passthrough'>
  711. <!-- disable nested HVM -->
  712. <feature name='vmx' policy='disable'/>
  713. <feature name='svm' policy='disable'/>
  714. <!-- disable SMAP inside VM, because of Linux bug -->
  715. <feature name='smap' policy='disable'/>
  716. </cpu>
  717. <os>
  718. <type arch="x86_64" machine="xenfv">hvm</type>
  719. <!--
  720. For the libxl backend libvirt switches between OVMF (UEFI)
  721. and SeaBIOS based on the loader type. This has nothing to
  722. do with the hvmloader binary.
  723. -->
  724. <loader type="rom">hvmloader</loader>
  725. <boot dev="cdrom" />
  726. <boot dev="hd" />
  727. </os>
  728. <features>
  729. <pae/>
  730. <acpi/>
  731. <apic/>
  732. <viridian/>
  733. </features>
  734. <clock offset="variable" adjustment="0" basis="localtime" />
  735. <on_poweroff>destroy</on_poweroff>
  736. <on_reboot>destroy</on_reboot>
  737. <on_crash>destroy</on_crash>
  738. <devices>
  739. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  740. <emulator type="stubdom-linux" />
  741. <input type="tablet" bus="usb"/>
  742. <video>
  743. <model type="vga"/>
  744. </video>
  745. <graphics type="qubes"/>
  746. <console type="pty">
  747. <target type="xen" port="0"/>
  748. </console>
  749. </devices>
  750. </domain>
  751. '''
  752. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  753. vm = self.get_vm(uuid=my_uuid)
  754. vm.netvm = None
  755. vm.virt_mode = 'hvm'
  756. libvirt_xml = vm.create_config_file()
  757. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  758. lxml.etree.XML(expected))
  759. def test_600_libvirt_xml_hvm_dom0_kernel(self):
  760. expected = '''<domain type="xen">
  761. <name>test-inst-test</name>
  762. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  763. <memory unit="MiB">500</memory>
  764. <currentMemory unit="MiB">400</currentMemory>
  765. <vcpu placement="static">2</vcpu>
  766. <cpu mode='host-passthrough'>
  767. <!-- disable nested HVM -->
  768. <feature name='vmx' policy='disable'/>
  769. <feature name='svm' policy='disable'/>
  770. <!-- disable SMAP inside VM, because of Linux bug -->
  771. <feature name='smap' policy='disable'/>
  772. </cpu>
  773. <os>
  774. <type arch="x86_64" machine="xenfv">hvm</type>
  775. <!--
  776. For the libxl backend libvirt switches between OVMF (UEFI)
  777. and SeaBIOS based on the loader type. This has nothing to
  778. do with the hvmloader binary.
  779. -->
  780. <loader type="rom">hvmloader</loader>
  781. <boot dev="cdrom" />
  782. <boot dev="hd" />
  783. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  784. </os>
  785. <features>
  786. <pae/>
  787. <acpi/>
  788. <apic/>
  789. <viridian/>
  790. </features>
  791. <clock offset="variable" adjustment="0" basis="localtime" />
  792. <on_poweroff>destroy</on_poweroff>
  793. <on_reboot>destroy</on_reboot>
  794. <on_crash>destroy</on_crash>
  795. <devices>
  796. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  797. <emulator type="stubdom-linux" />
  798. <input type="tablet" bus="usb"/>
  799. <video>
  800. <model type="vga"/>
  801. </video>
  802. <graphics type="qubes"/>
  803. <console type="pty">
  804. <target type="xen" port="0"/>
  805. </console>
  806. </devices>
  807. </domain>
  808. '''
  809. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  810. vm = self.get_vm(uuid=my_uuid)
  811. vm.netvm = None
  812. vm.virt_mode = 'hvm'
  813. vm.features['qrexec'] = True
  814. with unittest.mock.patch('qubes.config.qubes_base_dir',
  815. '/tmp/qubes-test'):
  816. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  817. os.makedirs(kernel_dir, exist_ok=True)
  818. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  819. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  820. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  821. vm.kernel = 'dummy'
  822. libvirt_xml = vm.create_config_file()
  823. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  824. lxml.etree.XML(expected))
  825. def test_600_libvirt_xml_hvm_dom0_kernel_kernelopts(self):
  826. expected = '''<domain type="xen">
  827. <name>test-inst-test</name>
  828. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  829. <memory unit="MiB">500</memory>
  830. <currentMemory unit="MiB">400</currentMemory>
  831. <vcpu placement="static">2</vcpu>
  832. <cpu mode='host-passthrough'>
  833. <!-- disable nested HVM -->
  834. <feature name='vmx' policy='disable'/>
  835. <feature name='svm' policy='disable'/>
  836. <!-- disable SMAP inside VM, because of Linux bug -->
  837. <feature name='smap' policy='disable'/>
  838. </cpu>
  839. <os>
  840. <type arch="x86_64" machine="xenfv">hvm</type>
  841. <!--
  842. For the libxl backend libvirt switches between OVMF (UEFI)
  843. and SeaBIOS based on the loader type. This has nothing to
  844. do with the hvmloader binary.
  845. -->
  846. <loader type="rom">hvmloader</loader>
  847. <boot dev="cdrom" />
  848. <boot dev="hd" />
  849. <cmdline>kernel specific options nopat</cmdline>
  850. </os>
  851. <features>
  852. <pae/>
  853. <acpi/>
  854. <apic/>
  855. <viridian/>
  856. </features>
  857. <clock offset="variable" adjustment="0" basis="localtime" />
  858. <on_poweroff>destroy</on_poweroff>
  859. <on_reboot>destroy</on_reboot>
  860. <on_crash>destroy</on_crash>
  861. <devices>
  862. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  863. <emulator type="stubdom-linux" />
  864. <input type="tablet" bus="usb"/>
  865. <video>
  866. <model type="vga"/>
  867. </video>
  868. <graphics type="qubes"/>
  869. <console type="pty">
  870. <target type="xen" port="0"/>
  871. </console>
  872. </devices>
  873. </domain>
  874. '''
  875. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  876. vm = self.get_vm(uuid=my_uuid)
  877. vm.netvm = None
  878. vm.virt_mode = 'hvm'
  879. vm.features['qrexec'] = True
  880. with unittest.mock.patch('qubes.config.qubes_base_dir',
  881. '/tmp/qubes-test'):
  882. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  883. os.makedirs(kernel_dir, exist_ok=True)
  884. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  885. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  886. with open(os.path.join(kernel_dir,
  887. 'default-kernelopts-common.txt'), 'w') as f:
  888. f.write('kernel specific options \n')
  889. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  890. vm.kernel = 'dummy'
  891. libvirt_xml = vm.create_config_file()
  892. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  893. lxml.etree.XML(expected))
  894. def test_600_libvirt_xml_pvh(self):
  895. expected = '''<domain type="xen">
  896. <name>test-inst-test</name>
  897. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  898. <memory unit="MiB">500</memory>
  899. <currentMemory unit="MiB">400</currentMemory>
  900. <vcpu placement="static">2</vcpu>
  901. <cpu mode='host-passthrough'>
  902. <!-- disable nested HVM -->
  903. <feature name='vmx' policy='disable'/>
  904. <feature name='svm' policy='disable'/>
  905. <!-- disable SMAP inside VM, because of Linux bug -->
  906. <feature name='smap' policy='disable'/>
  907. </cpu>
  908. <os>
  909. <type arch="x86_64" machine="xenpvh">xenpvh</type>
  910. <kernel>/tmp/kernel/vmlinuz</kernel>
  911. <initrd>/tmp/kernel/initramfs</initrd>
  912. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  913. </os>
  914. <features>
  915. <pae/>
  916. <acpi/>
  917. <apic/>
  918. <viridian/>
  919. </features>
  920. <clock offset='utc' adjustment='reset'>
  921. <timer name="tsc" mode="native"/>
  922. </clock>
  923. <on_poweroff>destroy</on_poweroff>
  924. <on_reboot>destroy</on_reboot>
  925. <on_crash>destroy</on_crash>
  926. <devices>
  927. <disk type="block" device="disk">
  928. <driver name="phy" />
  929. <source dev="/tmp/kernel/modules.img" />
  930. <target dev="xvdd" />
  931. <backenddomain name="dom0" />
  932. </disk>
  933. <console type="pty">
  934. <target type="xen" port="0"/>
  935. </console>
  936. </devices>
  937. </domain>
  938. '''
  939. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  940. vm = self.get_vm(uuid=my_uuid)
  941. vm.netvm = None
  942. vm.virt_mode = 'pvh'
  943. with unittest.mock.patch('qubes.config.qubes_base_dir',
  944. '/tmp/qubes-test'):
  945. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  946. os.makedirs(kernel_dir, exist_ok=True)
  947. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  948. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  949. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  950. vm.kernel = 'dummy'
  951. # tests for storage are later
  952. vm.volumes['kernel'] = unittest.mock.Mock(**{
  953. 'kernels_dir': '/tmp/kernel',
  954. 'block_device.return_value.domain': 'dom0',
  955. 'block_device.return_value.script': None,
  956. 'block_device.return_value.path': '/tmp/kernel/modules.img',
  957. 'block_device.return_value.devtype': 'disk',
  958. 'block_device.return_value.name': 'kernel',
  959. })
  960. libvirt_xml = vm.create_config_file()
  961. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  962. lxml.etree.XML(expected))
  963. def test_600_libvirt_xml_pvh_no_membalance(self):
  964. expected = '''<domain type="xen">
  965. <name>test-inst-test</name>
  966. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  967. <memory unit="MiB">400</memory>
  968. <currentMemory unit="MiB">400</currentMemory>
  969. <vcpu placement="static">2</vcpu>
  970. <cpu mode='host-passthrough'>
  971. <!-- disable nested HVM -->
  972. <feature name='vmx' policy='disable'/>
  973. <feature name='svm' policy='disable'/>
  974. <!-- disable SMAP inside VM, because of Linux bug -->
  975. <feature name='smap' policy='disable'/>
  976. </cpu>
  977. <os>
  978. <type arch="x86_64" machine="xenpvh">xenpvh</type>
  979. <kernel>/tmp/kernel/vmlinuz</kernel>
  980. <initrd>/tmp/kernel/initramfs</initrd>
  981. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  982. </os>
  983. <features>
  984. <pae/>
  985. <acpi/>
  986. <apic/>
  987. <viridian/>
  988. </features>
  989. <clock offset='utc' adjustment='reset'>
  990. <timer name="tsc" mode="native"/>
  991. </clock>
  992. <on_poweroff>destroy</on_poweroff>
  993. <on_reboot>destroy</on_reboot>
  994. <on_crash>destroy</on_crash>
  995. <devices>
  996. <disk type="block" device="disk">
  997. <driver name="phy" />
  998. <source dev="/tmp/kernel/modules.img" />
  999. <target dev="xvdd" />
  1000. <backenddomain name="dom0" />
  1001. </disk>
  1002. <console type="pty">
  1003. <target type="xen" port="0"/>
  1004. </console>
  1005. </devices>
  1006. </domain>
  1007. '''
  1008. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1009. vm = self.get_vm(uuid=my_uuid)
  1010. vm.netvm = None
  1011. vm.virt_mode = 'pvh'
  1012. vm.maxmem = 0
  1013. with unittest.mock.patch('qubes.config.qubes_base_dir',
  1014. '/tmp/qubes-test'):
  1015. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  1016. os.makedirs(kernel_dir, exist_ok=True)
  1017. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  1018. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  1019. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  1020. vm.kernel = 'dummy'
  1021. # tests for storage are later
  1022. vm.volumes['kernel'] = unittest.mock.Mock(**{
  1023. 'kernels_dir': '/tmp/kernel',
  1024. 'block_device.return_value.domain': 'dom0',
  1025. 'block_device.return_value.script': None,
  1026. 'block_device.return_value.path': '/tmp/kernel/modules.img',
  1027. 'block_device.return_value.devtype': 'disk',
  1028. 'block_device.return_value.name': 'kernel',
  1029. })
  1030. libvirt_xml = vm.create_config_file()
  1031. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1032. lxml.etree.XML(expected))
  1033. def test_600_libvirt_xml_hvm_pcidev(self):
  1034. expected = '''<domain type="xen">
  1035. <name>test-inst-test</name>
  1036. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1037. <memory unit="MiB">400</memory>
  1038. <currentMemory unit="MiB">400</currentMemory>
  1039. <vcpu placement="static">2</vcpu>
  1040. <cpu mode='host-passthrough'>
  1041. <!-- disable nested HVM -->
  1042. <feature name='vmx' policy='disable'/>
  1043. <feature name='svm' policy='disable'/>
  1044. <!-- disable SMAP inside VM, because of Linux bug -->
  1045. <feature name='smap' policy='disable'/>
  1046. </cpu>
  1047. <os>
  1048. <type arch="x86_64" machine="xenfv">hvm</type>
  1049. <!--
  1050. For the libxl backend libvirt switches between OVMF (UEFI)
  1051. and SeaBIOS based on the loader type. This has nothing to
  1052. do with the hvmloader binary.
  1053. -->
  1054. <loader type="rom">hvmloader</loader>
  1055. <boot dev="cdrom" />
  1056. <boot dev="hd" />
  1057. </os>
  1058. <features>
  1059. <pae/>
  1060. <acpi/>
  1061. <apic/>
  1062. <viridian/>
  1063. <xen>
  1064. <e820_host state="on"/>
  1065. </xen>
  1066. </features>
  1067. <clock offset="variable" adjustment="0" basis="localtime" />
  1068. <on_poweroff>destroy</on_poweroff>
  1069. <on_reboot>destroy</on_reboot>
  1070. <on_crash>destroy</on_crash>
  1071. <devices>
  1072. <hostdev type="pci" managed="yes">
  1073. <source>
  1074. <address
  1075. bus="0x00"
  1076. slot="0x00"
  1077. function="0x0" />
  1078. </source>
  1079. </hostdev>
  1080. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1081. <emulator type="stubdom-linux" />
  1082. <input type="tablet" bus="usb"/>
  1083. <video>
  1084. <model type="vga"/>
  1085. </video>
  1086. <graphics type="qubes"/>
  1087. <console type="pty">
  1088. <target type="xen" port="0"/>
  1089. </console>
  1090. </devices>
  1091. </domain>
  1092. '''
  1093. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1094. # required for PCI devices listing
  1095. self.app.vmm.offline_mode = False
  1096. vm = self.get_vm(uuid=my_uuid)
  1097. vm.netvm = None
  1098. vm.virt_mode = 'hvm'
  1099. vm.kernel = None
  1100. # even with meminfo-writer enabled, should have memory==maxmem
  1101. vm.features['service.meminfo-writer'] = True
  1102. assignment = qubes.devices.DeviceAssignment(
  1103. vm, # this is violation of API, but for PCI the argument
  1104. # is unused
  1105. '00_00.0',
  1106. bus='pci',
  1107. persistent=True)
  1108. vm.devices['pci']._set.add(
  1109. assignment)
  1110. libvirt_xml = vm.create_config_file()
  1111. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1112. lxml.etree.XML(expected))
  1113. def test_600_libvirt_xml_hvm_cdrom_boot(self):
  1114. expected = '''<domain type="xen">
  1115. <name>test-inst-test</name>
  1116. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1117. <memory unit="MiB">400</memory>
  1118. <currentMemory unit="MiB">400</currentMemory>
  1119. <vcpu placement="static">2</vcpu>
  1120. <cpu mode='host-passthrough'>
  1121. <!-- disable nested HVM -->
  1122. <feature name='vmx' policy='disable'/>
  1123. <feature name='svm' policy='disable'/>
  1124. <!-- disable SMAP inside VM, because of Linux bug -->
  1125. <feature name='smap' policy='disable'/>
  1126. </cpu>
  1127. <os>
  1128. <type arch="x86_64" machine="xenfv">hvm</type>
  1129. <!--
  1130. For the libxl backend libvirt switches between OVMF (UEFI)
  1131. and SeaBIOS based on the loader type. This has nothing to
  1132. do with the hvmloader binary.
  1133. -->
  1134. <loader type="rom">hvmloader</loader>
  1135. <boot dev="cdrom" />
  1136. <boot dev="hd" />
  1137. </os>
  1138. <features>
  1139. <pae/>
  1140. <acpi/>
  1141. <apic/>
  1142. <viridian/>
  1143. </features>
  1144. <clock offset="variable" adjustment="0" basis="localtime" />
  1145. <on_poweroff>destroy</on_poweroff>
  1146. <on_reboot>destroy</on_reboot>
  1147. <on_crash>destroy</on_crash>
  1148. <devices>
  1149. <disk type="block" device="cdrom">
  1150. <driver name="phy" />
  1151. <source dev="/dev/sda" />
  1152. <!-- prefer xvdd for CDROM -->
  1153. <target dev="xvdd" />
  1154. <readonly/>
  1155. </disk>
  1156. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1157. <emulator type="stubdom-linux" />
  1158. <input type="tablet" bus="usb"/>
  1159. <video>
  1160. <model type="vga"/>
  1161. </video>
  1162. <graphics type="qubes"/>
  1163. <console type="pty">
  1164. <target type="xen" port="0"/>
  1165. </console>
  1166. </devices>
  1167. </domain>
  1168. '''
  1169. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1170. qdb = {
  1171. '/qubes-block-devices/sda': b'',
  1172. '/qubes-block-devices/sda/desc': b'Test device',
  1173. '/qubes-block-devices/sda/size': b'1024000',
  1174. '/qubes-block-devices/sda/mode': b'r',
  1175. }
  1176. test_qdb = TestQubesDB(qdb)
  1177. dom0 = qubes.vm.adminvm.AdminVM(self.app, None)
  1178. dom0._qdb_connection = test_qdb
  1179. self.get_vm('dom0', vm=dom0)
  1180. vm = self.get_vm(uuid=my_uuid)
  1181. vm.netvm = None
  1182. vm.virt_mode = 'hvm'
  1183. vm.kernel = None
  1184. dom0.events_enabled = True
  1185. self.app.vmm.offline_mode = False
  1186. dev = qubes.devices.DeviceAssignment(
  1187. dom0, 'sda',
  1188. {'devtype': 'cdrom', 'read-only': 'yes'}, persistent=True)
  1189. self.loop.run_until_complete(vm.devices['block'].attach(dev))
  1190. libvirt_xml = vm.create_config_file()
  1191. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1192. lxml.etree.XML(expected))
  1193. def test_600_libvirt_xml_hvm_cdrom_dom0_kernel_boot(self):
  1194. expected = '''<domain type="xen">
  1195. <name>test-inst-test</name>
  1196. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1197. <memory unit="MiB">400</memory>
  1198. <currentMemory unit="MiB">400</currentMemory>
  1199. <vcpu placement="static">2</vcpu>
  1200. <cpu mode='host-passthrough'>
  1201. <!-- disable nested HVM -->
  1202. <feature name='vmx' policy='disable'/>
  1203. <feature name='svm' policy='disable'/>
  1204. <!-- disable SMAP inside VM, because of Linux bug -->
  1205. <feature name='smap' policy='disable'/>
  1206. </cpu>
  1207. <os>
  1208. <type arch="x86_64" machine="xenfv">hvm</type>
  1209. <!--
  1210. For the libxl backend libvirt switches between OVMF (UEFI)
  1211. and SeaBIOS based on the loader type. This has nothing to
  1212. do with the hvmloader binary.
  1213. -->
  1214. <loader type="rom">hvmloader</loader>
  1215. <boot dev="cdrom" />
  1216. <boot dev="hd" />
  1217. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  1218. </os>
  1219. <features>
  1220. <pae/>
  1221. <acpi/>
  1222. <apic/>
  1223. <viridian/>
  1224. </features>
  1225. <clock offset="variable" adjustment="0" basis="localtime" />
  1226. <on_poweroff>destroy</on_poweroff>
  1227. <on_reboot>destroy</on_reboot>
  1228. <on_crash>destroy</on_crash>
  1229. <devices>
  1230. <disk type="block" device="disk">
  1231. <driver name="phy" />
  1232. <source dev="/tmp/kernel/modules.img" />
  1233. <target dev="xvdd" />
  1234. <backenddomain name="dom0" />
  1235. </disk>
  1236. <disk type="block" device="cdrom">
  1237. <driver name="phy" />
  1238. <source dev="/dev/sda" />
  1239. <target dev="xvdi" />
  1240. <readonly/>
  1241. </disk>
  1242. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1243. <emulator type="stubdom-linux" />
  1244. <input type="tablet" bus="usb"/>
  1245. <video>
  1246. <model type="vga"/>
  1247. </video>
  1248. <graphics type="qubes"/>
  1249. <console type="pty">
  1250. <target type="xen" port="0"/>
  1251. </console>
  1252. </devices>
  1253. </domain>
  1254. '''
  1255. qdb = {
  1256. '/qubes-block-devices/sda': b'',
  1257. '/qubes-block-devices/sda/desc': b'Test device',
  1258. '/qubes-block-devices/sda/size': b'1024000',
  1259. '/qubes-block-devices/sda/mode': b'r',
  1260. }
  1261. test_qdb = TestQubesDB(qdb)
  1262. dom0 = qubes.vm.adminvm.AdminVM(self.app, None)
  1263. dom0._qdb_connection = test_qdb
  1264. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1265. vm = self.get_vm(uuid=my_uuid)
  1266. vm.netvm = None
  1267. vm.virt_mode = 'hvm'
  1268. with unittest.mock.patch('qubes.config.qubes_base_dir',
  1269. '/tmp/qubes-test'):
  1270. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  1271. os.makedirs(kernel_dir, exist_ok=True)
  1272. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  1273. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  1274. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  1275. vm.kernel = 'dummy'
  1276. # tests for storage are later
  1277. vm.volumes['kernel'] = unittest.mock.Mock(**{
  1278. 'kernels_dir': '/tmp/kernel',
  1279. 'block_device.return_value.domain': 'dom0',
  1280. 'block_device.return_value.script': None,
  1281. 'block_device.return_value.path': '/tmp/kernel/modules.img',
  1282. 'block_device.return_value.devtype': 'disk',
  1283. 'block_device.return_value.name': 'kernel',
  1284. })
  1285. dom0.events_enabled = True
  1286. self.app.vmm.offline_mode = False
  1287. dev = qubes.devices.DeviceAssignment(
  1288. dom0, 'sda',
  1289. {'devtype': 'cdrom', 'read-only': 'yes'}, persistent=True)
  1290. self.loop.run_until_complete(vm.devices['block'].attach(dev))
  1291. libvirt_xml = vm.create_config_file()
  1292. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1293. lxml.etree.XML(expected))
  1294. def test_610_libvirt_xml_network(self):
  1295. expected = '''<domain type="xen">
  1296. <name>test-inst-test</name>
  1297. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1298. <memory unit="MiB">500</memory>
  1299. <currentMemory unit="MiB">400</currentMemory>
  1300. <vcpu placement="static">2</vcpu>
  1301. <cpu mode='host-passthrough'>
  1302. <!-- disable nested HVM -->
  1303. <feature name='vmx' policy='disable'/>
  1304. <feature name='svm' policy='disable'/>
  1305. <!-- disable SMAP inside VM, because of Linux bug -->
  1306. <feature name='smap' policy='disable'/>
  1307. </cpu>
  1308. <os>
  1309. <type arch="x86_64" machine="xenfv">hvm</type>
  1310. <!--
  1311. For the libxl backend libvirt switches between OVMF (UEFI)
  1312. and SeaBIOS based on the loader type. This has nothing to
  1313. do with the hvmloader binary.
  1314. -->
  1315. <loader type="rom">hvmloader</loader>
  1316. <boot dev="cdrom" />
  1317. <boot dev="hd" />
  1318. </os>
  1319. <features>
  1320. <pae/>
  1321. <acpi/>
  1322. <apic/>
  1323. <viridian/>
  1324. </features>
  1325. <clock offset="variable" adjustment="0" basis="localtime" />
  1326. <on_poweroff>destroy</on_poweroff>
  1327. <on_reboot>destroy</on_reboot>
  1328. <on_crash>destroy</on_crash>
  1329. <devices>
  1330. <interface type="ethernet">
  1331. <mac address="00:16:3e:5e:6c:00" />
  1332. <ip address="10.137.0.1" />
  1333. {extra_ip}
  1334. <backenddomain name="test-inst-netvm" />
  1335. <script path="vif-route-qubes" />
  1336. </interface>
  1337. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1338. <emulator type="stubdom-linux" cmdline="-qubes-net:client_ip=10.137.0.1,dns_0=10.139.1.1,dns_1=10.139.1.2,gw=10.137.0.2,netmask=255.255.255.255" />
  1339. <input type="tablet" bus="usb"/>
  1340. <video>
  1341. <model type="vga"/>
  1342. </video>
  1343. <graphics type="qubes"/>
  1344. <console type="pty">
  1345. <target type="xen" port="0"/>
  1346. </console>
  1347. </devices>
  1348. </domain>
  1349. '''
  1350. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1351. netvm = self.get_vm(qid=2, name='netvm', provides_network=True)
  1352. vm = self.get_vm(uuid=my_uuid)
  1353. vm.netvm = netvm
  1354. vm.virt_mode = 'hvm'
  1355. vm.features['qrexec'] = True
  1356. with self.subTest('ipv4_only'):
  1357. libvirt_xml = vm.create_config_file()
  1358. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1359. lxml.etree.XML(expected.format(extra_ip='')))
  1360. with self.subTest('ipv6'):
  1361. netvm.features['ipv6'] = True
  1362. libvirt_xml = vm.create_config_file()
  1363. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1364. lxml.etree.XML(expected.format(
  1365. extra_ip='<ip address="{}::a89:1" family=\'ipv6\'/>'.format(
  1366. qubes.config.qubes_ipv6_prefix.replace(':0000', '')))))
  1367. def test_615_libvirt_xml_block_devices(self):
  1368. expected = '''<domain type="xen">
  1369. <name>test-inst-test</name>
  1370. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1371. <memory unit="MiB">400</memory>
  1372. <currentMemory unit="MiB">400</currentMemory>
  1373. <vcpu placement="static">2</vcpu>
  1374. <cpu mode='host-passthrough'>
  1375. <!-- disable nested HVM -->
  1376. <feature name='vmx' policy='disable'/>
  1377. <feature name='svm' policy='disable'/>
  1378. <!-- disable SMAP inside VM, because of Linux bug -->
  1379. <feature name='smap' policy='disable'/>
  1380. </cpu>
  1381. <os>
  1382. <type arch="x86_64" machine="xenfv">hvm</type>
  1383. <!--
  1384. For the libxl backend libvirt switches between OVMF (UEFI)
  1385. and SeaBIOS based on the loader type. This has nothing to
  1386. do with the hvmloader binary.
  1387. -->
  1388. <loader type="rom">hvmloader</loader>
  1389. <boot dev="cdrom" />
  1390. <boot dev="hd" />
  1391. </os>
  1392. <features>
  1393. <pae/>
  1394. <acpi/>
  1395. <apic/>
  1396. <viridian/>
  1397. </features>
  1398. <clock offset="variable" adjustment="0" basis="localtime" />
  1399. <on_poweroff>destroy</on_poweroff>
  1400. <on_reboot>destroy</on_reboot>
  1401. <on_crash>destroy</on_crash>
  1402. <devices>
  1403. <disk type="block" device="disk">
  1404. <driver name="phy" />
  1405. <source dev="/dev/loop0" />
  1406. <target dev="xvda" />
  1407. <backenddomain name="dom0" />
  1408. <script path="/tmp/script" />
  1409. </disk>
  1410. <disk type="block" device="disk">
  1411. <driver name="phy" />
  1412. <source dev="/dev/loop1" />
  1413. <target dev="xvde" />
  1414. <backenddomain name="dom0" />
  1415. </disk>
  1416. <disk type="block" device="disk">
  1417. <driver name="phy" />
  1418. <source dev="/dev/loop2" />
  1419. <target dev="xvdf" />
  1420. <backenddomain name="dom0" />
  1421. </disk>
  1422. <disk type="block" device="disk">
  1423. <driver name="phy" />
  1424. <source dev="/dev/sdb" />
  1425. <target dev="xvdl" />
  1426. </disk>
  1427. <disk type="block" device="cdrom">
  1428. <driver name="phy" />
  1429. <source dev="/dev/sda" />
  1430. <!-- prefer xvdd for CDROM -->
  1431. <target dev="xvdd" />
  1432. </disk>
  1433. <disk type="block" device="disk">
  1434. <driver name="phy" />
  1435. <source dev="/dev/loop0" />
  1436. <target dev="xvdi" />
  1437. <backenddomain name="backend0" />
  1438. </disk>
  1439. <disk type="block" device="disk">
  1440. <driver name="phy" />
  1441. <source dev="/dev/loop0" />
  1442. <target dev="xvdj" />
  1443. <backenddomain name="backend1" />
  1444. </disk>
  1445. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1446. <emulator type="stubdom-linux" />
  1447. <input type="tablet" bus="usb"/>
  1448. <video>
  1449. <model type="vga"/>
  1450. </video>
  1451. <graphics type="qubes"/>
  1452. <console type="pty">
  1453. <target type="xen" port="0"/>
  1454. </console>
  1455. </devices>
  1456. </domain>
  1457. '''
  1458. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1459. vm = self.get_vm(uuid=my_uuid)
  1460. vm.netvm = None
  1461. vm.virt_mode = 'hvm'
  1462. vm.volumes['root'] = unittest.mock.Mock(**{
  1463. 'block_device.return_value.name': 'root',
  1464. 'block_device.return_value.path': '/dev/loop0',
  1465. 'block_device.return_value.devtype': 'disk',
  1466. 'block_device.return_value.domain': 'dom0',
  1467. 'block_device.return_value.script': '/tmp/script',
  1468. })
  1469. vm.volumes['other'] = unittest.mock.Mock(**{
  1470. 'block_device.return_value.name': 'other',
  1471. 'block_device.return_value.path': '/dev/loop1',
  1472. 'block_device.return_value.devtype': 'disk',
  1473. 'block_device.return_value.domain': 'dom0',
  1474. 'block_device.return_value.script': None,
  1475. })
  1476. vm.volumes['other2'] = unittest.mock.Mock(**{
  1477. 'block_device.return_value.name': 'other',
  1478. 'block_device.return_value.path': '/dev/loop2',
  1479. 'block_device.return_value.devtype': 'disk',
  1480. 'block_device.return_value.domain': 'dom0',
  1481. 'block_device.return_value.script': None,
  1482. })
  1483. assignments = [
  1484. unittest.mock.Mock(**{
  1485. 'options': {'frontend-dev': 'xvdl'},
  1486. 'device.device_node': '/dev/sdb',
  1487. 'device.backend_domain.name': 'dom0',
  1488. }),
  1489. unittest.mock.Mock(**{
  1490. 'options': {'devtype': 'cdrom'},
  1491. 'device.device_node': '/dev/sda',
  1492. 'device.backend_domain.name': 'dom0',
  1493. }),
  1494. unittest.mock.Mock(**{
  1495. 'options': {'read-only': True},
  1496. 'device.device_node': '/dev/loop0',
  1497. 'device.backend_domain.name': 'backend0',
  1498. }),
  1499. unittest.mock.Mock(**{
  1500. 'options': {},
  1501. 'device.device_node': '/dev/loop0',
  1502. 'device.backend_domain.name': 'backend1',
  1503. }),
  1504. ]
  1505. vm.devices['block'].assignments = lambda persistent: assignments
  1506. libvirt_xml = vm.create_config_file()
  1507. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1508. lxml.etree.XML(expected))
  1509. @unittest.mock.patch('qubes.utils.get_timezone')
  1510. @unittest.mock.patch('qubes.utils.urandom')
  1511. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.untrusted_qdb')
  1512. def test_620_qdb_standalone(self, mock_qubesdb, mock_urandom,
  1513. mock_timezone):
  1514. mock_urandom.return_value = b'A' * 64
  1515. mock_timezone.return_value = 'UTC'
  1516. vm = self.get_vm(cls=qubes.vm.standalonevm.StandaloneVM)
  1517. vm.netvm = None
  1518. vm.events_enabled = True
  1519. test_qubesdb = TestQubesDB()
  1520. mock_qubesdb.write.side_effect = test_qubesdb.write
  1521. mock_qubesdb.rm.side_effect = test_qubesdb.rm
  1522. vm.create_qdb_entries()
  1523. self.maxDiff = None
  1524. iptables_header = (
  1525. '# Generated by Qubes Core on {}\n'
  1526. '*filter\n'
  1527. ':INPUT DROP [0:0]\n'
  1528. ':FORWARD DROP [0:0]\n'
  1529. ':OUTPUT ACCEPT [0:0]\n'
  1530. '-A INPUT -i vif+ -p udp -m udp --dport 68 -j DROP\n'
  1531. '-A INPUT -m conntrack --ctstate '
  1532. 'RELATED,ESTABLISHED -j ACCEPT\n'
  1533. '-A INPUT -p icmp -j ACCEPT\n'
  1534. '-A INPUT -i lo -j ACCEPT\n'
  1535. '-A INPUT -j REJECT --reject-with '
  1536. 'icmp-host-prohibited\n'
  1537. '-A FORWARD -m conntrack --ctstate '
  1538. 'RELATED,ESTABLISHED -j ACCEPT\n'
  1539. '-A FORWARD -i vif+ -o vif+ -j DROP\n'
  1540. 'COMMIT\n'.format(datetime.datetime.now().ctime()))
  1541. self.assertEqual(test_qubesdb.data, {
  1542. '/name': 'test-inst-test',
  1543. '/type': 'StandaloneVM',
  1544. '/default-user': 'user',
  1545. '/qubes-vm-type': 'AppVM',
  1546. '/qubes-debug-mode': '0',
  1547. '/qubes-base-template': '',
  1548. '/qubes-timezone': 'UTC',
  1549. '/qubes-random-seed': base64.b64encode(b'A' * 64),
  1550. '/qubes-vm-persistence': 'full',
  1551. '/qubes-vm-updateable': 'True',
  1552. '/qubes-block-devices': '',
  1553. '/qubes-usb-devices': '',
  1554. '/qubes-iptables': 'reload',
  1555. '/qubes-iptables-error': '',
  1556. '/qubes-iptables-header': iptables_header,
  1557. '/qubes-service/qubes-update-check': '0',
  1558. '/qubes-service/meminfo-writer': '1',
  1559. '/connected-ips': '',
  1560. '/connected-ips6': '',
  1561. })
  1562. @unittest.mock.patch('datetime.datetime')
  1563. @unittest.mock.patch('qubes.utils.get_timezone')
  1564. @unittest.mock.patch('qubes.utils.urandom')
  1565. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.untrusted_qdb')
  1566. def test_621_qdb_vm_with_network(self, mock_qubesdb, mock_urandom,
  1567. mock_timezone, mock_datetime):
  1568. mock_urandom.return_value = b'A' * 64
  1569. mock_timezone.return_value = 'UTC'
  1570. template = self.get_vm(cls=qubes.vm.templatevm.TemplateVM, name='template')
  1571. template.netvm = None
  1572. netvm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1573. name='netvm', qid=2, provides_network=True)
  1574. vm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1575. name='appvm', qid=3)
  1576. vm.netvm = netvm
  1577. vm.kernel = None
  1578. # pretend the VM is running...
  1579. vm._qubesprop_xid = 3
  1580. netvm.kernel = None
  1581. test_qubesdb = TestQubesDB()
  1582. mock_qubesdb.write.side_effect = test_qubesdb.write
  1583. mock_qubesdb.rm.side_effect = test_qubesdb.rm
  1584. self.maxDiff = None
  1585. mock_datetime.now.returnvalue = \
  1586. datetime.datetime(2019, 2, 27, 15, 12, 15, 385822)
  1587. iptables_header = (
  1588. '# Generated by Qubes Core on {}\n'
  1589. '*filter\n'
  1590. ':INPUT DROP [0:0]\n'
  1591. ':FORWARD DROP [0:0]\n'
  1592. ':OUTPUT ACCEPT [0:0]\n'
  1593. '-A INPUT -i vif+ -p udp -m udp --dport 68 -j DROP\n'
  1594. '-A INPUT -m conntrack --ctstate '
  1595. 'RELATED,ESTABLISHED -j ACCEPT\n'
  1596. '-A INPUT -p icmp -j ACCEPT\n'
  1597. '-A INPUT -i lo -j ACCEPT\n'
  1598. '-A INPUT -j REJECT --reject-with '
  1599. 'icmp-host-prohibited\n'
  1600. '-A FORWARD -m conntrack --ctstate '
  1601. 'RELATED,ESTABLISHED -j ACCEPT\n'
  1602. '-A FORWARD -i vif+ -o vif+ -j DROP\n'
  1603. 'COMMIT\n'.format(datetime.datetime.now().ctime()))
  1604. expected = {
  1605. '/name': 'test-inst-appvm',
  1606. '/type': 'AppVM',
  1607. '/default-user': 'user',
  1608. '/qubes-vm-type': 'AppVM',
  1609. '/qubes-debug-mode': '0',
  1610. '/qubes-base-template': 'test-inst-template',
  1611. '/qubes-timezone': 'UTC',
  1612. '/qubes-random-seed': base64.b64encode(b'A' * 64),
  1613. '/qubes-vm-persistence': 'rw-only',
  1614. '/qubes-vm-updateable': 'False',
  1615. '/qubes-block-devices': '',
  1616. '/qubes-usb-devices': '',
  1617. '/qubes-iptables': 'reload',
  1618. '/qubes-iptables-error': '',
  1619. '/qubes-iptables-header': iptables_header,
  1620. '/qubes-service/qubes-update-check': '0',
  1621. '/qubes-service/meminfo-writer': '1',
  1622. '/qubes-mac': '00:16:3e:5e:6c:00',
  1623. '/qubes-ip': '10.137.0.3',
  1624. '/qubes-netmask': '255.255.255.255',
  1625. '/qubes-gateway': '10.137.0.2',
  1626. '/qubes-primary-dns': '10.139.1.1',
  1627. '/qubes-secondary-dns': '10.139.1.2',
  1628. '/connected-ips': '',
  1629. '/connected-ips6': '',
  1630. }
  1631. with self.subTest('ipv4'):
  1632. vm.create_qdb_entries()
  1633. self.assertEqual(test_qubesdb.data, expected)
  1634. test_qubesdb.data.clear()
  1635. with self.subTest('ipv6'):
  1636. netvm.features['ipv6'] = True
  1637. expected['/qubes-ip6'] = \
  1638. qubes.config.qubes_ipv6_prefix.replace(':0000', '') + \
  1639. '::a89:3'
  1640. expected['/qubes-gateway6'] = expected['/qubes-ip6'][:-1] + '2'
  1641. vm.create_qdb_entries()
  1642. self.assertEqual(test_qubesdb.data, expected)
  1643. test_qubesdb.data.clear()
  1644. with self.subTest('ipv6_just_appvm'):
  1645. del netvm.features['ipv6']
  1646. vm.features['ipv6'] = True
  1647. expected['/qubes-ip6'] = \
  1648. qubes.config.qubes_ipv6_prefix.replace(':0000', '') + \
  1649. '::a89:3'
  1650. del expected['/qubes-gateway6']
  1651. vm.create_qdb_entries()
  1652. self.assertEqual(test_qubesdb.data, expected)
  1653. test_qubesdb.data.clear()
  1654. with self.subTest('proxy_ipv4'):
  1655. del vm.features['ipv6']
  1656. expected['/name'] = 'test-inst-netvm'
  1657. expected['/qubes-vm-type'] = 'NetVM'
  1658. del expected['/qubes-ip']
  1659. del expected['/qubes-gateway']
  1660. del expected['/qubes-netmask']
  1661. del expected['/qubes-ip6']
  1662. del expected['/qubes-primary-dns']
  1663. del expected['/qubes-secondary-dns']
  1664. del expected['/qubes-mac']
  1665. expected['/qubes-netvm-primary-dns'] = '10.139.1.1'
  1666. expected['/qubes-netvm-secondary-dns'] = '10.139.1.2'
  1667. expected['/qubes-netvm-network'] = '10.137.0.2'
  1668. expected['/qubes-netvm-gateway'] = '10.137.0.2'
  1669. expected['/qubes-netvm-netmask'] = '255.255.255.255'
  1670. expected['/qubes-iptables-domainrules/3'] = \
  1671. '*filter\n' \
  1672. '-A FORWARD -s 10.137.0.3 -j ACCEPT\n' \
  1673. '-A FORWARD -s 10.137.0.3 -j DROP\n' \
  1674. 'COMMIT\n'
  1675. expected['/mapped-ip/10.137.0.3/visible-ip'] = '10.137.0.3'
  1676. expected['/mapped-ip/10.137.0.3/visible-gateway'] = '10.137.0.2'
  1677. expected['/qubes-firewall/10.137.0.3'] = ''
  1678. expected['/qubes-firewall/10.137.0.3/0000'] = 'action=accept'
  1679. expected['/qubes-firewall/10.137.0.3/policy'] = 'drop'
  1680. expected['/connected-ips'] = '10.137.0.3'
  1681. with unittest.mock.patch('qubes.vm.qubesvm.QubesVM.is_running',
  1682. lambda _: True):
  1683. netvm.create_qdb_entries()
  1684. self.assertEqual(test_qubesdb.data, expected)
  1685. test_qubesdb.data.clear()
  1686. with self.subTest('proxy_ipv6'):
  1687. netvm.features['ipv6'] = True
  1688. ip6 = qubes.config.qubes_ipv6_prefix.replace(
  1689. ':0000', '') + '::a89:3'
  1690. expected['/qubes-netvm-gateway6'] = ip6[:-1] + '2'
  1691. expected['/qubes-firewall/' + ip6] = ''
  1692. expected['/qubes-firewall/' + ip6 + '/0000'] = 'action=accept'
  1693. expected['/qubes-firewall/' + ip6 + '/policy'] = 'drop'
  1694. expected['/connected-ips6'] = ip6
  1695. with unittest.mock.patch('qubes.vm.qubesvm.QubesVM.is_running',
  1696. lambda _: True):
  1697. netvm.create_qdb_entries()
  1698. self.assertEqual(test_qubesdb.data, expected)
  1699. @unittest.mock.patch('qubes.utils.get_timezone')
  1700. @unittest.mock.patch('qubes.utils.urandom')
  1701. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.untrusted_qdb')
  1702. def test_622_qdb_keyboard_layout(self, mock_qubesdb, mock_urandom,
  1703. mock_timezone):
  1704. mock_urandom.return_value = b'A' * 64
  1705. mock_timezone.return_value = 'UTC'
  1706. template = self.get_vm(
  1707. cls=qubes.vm.templatevm.TemplateVM, name='template')
  1708. template.netvm = None
  1709. guivm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1710. name='sys-gui', qid=2, provides_network=False)
  1711. vm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1712. name='appvm', qid=3)
  1713. vm.netvm = None
  1714. vm.guivm = guivm
  1715. guivm.features['keyboard-layout'] = 'fr'
  1716. xkb_keymap = \
  1717. 'xkb_keymap {\x0a\x09xkb_keycodes { include ' \
  1718. '"evdev"\x09};\x0a\x09xkb_types { include ' \
  1719. '"complete"\x09};\x0a\x09xkb_compat { include ' \
  1720. '"complete"\x09};\x0a\x09xkb_symbols { include ' \
  1721. '"pc+fr+inet(evdev)"\x09};\x0a\x09xkb_geometry ' \
  1722. '{ include "pc(pc105)"\x09};\x0a};'
  1723. vm.events_enabled = True
  1724. test_qubesdb = TestQubesDB()
  1725. mock_qubesdb.write.side_effect = test_qubesdb.write
  1726. mock_qubesdb.rm.side_effect = test_qubesdb.rm
  1727. vm.create_qdb_entries()
  1728. self.maxDiff = None
  1729. self.assertEqual(test_qubesdb.data, {
  1730. '/name': 'test-inst-appvm',
  1731. '/type': 'AppVM',
  1732. '/default-user': 'user',
  1733. '/qubes-keyboard': xkb_keymap,
  1734. '/keyboard-layout': 'fr',
  1735. '/qubes-vm-type': 'AppVM',
  1736. '/qubes-gui-domain-xid': '{}'.format(guivm.xid),
  1737. '/qubes-debug-mode': '0',
  1738. '/qubes-base-template': 'test-inst-template',
  1739. '/qubes-timezone': 'UTC',
  1740. '/qubes-random-seed': base64.b64encode(b'A' * 64),
  1741. '/qubes-vm-persistence': 'rw-only',
  1742. '/qubes-vm-updateable': 'False',
  1743. '/qubes-block-devices': '',
  1744. '/qubes-usb-devices': '',
  1745. '/qubes-iptables': 'reload',
  1746. '/qubes-iptables-error': '',
  1747. '/qubes-iptables-header': unittest.mock.ANY,
  1748. '/qubes-service/qubes-update-check': '0',
  1749. '/qubes-service/meminfo-writer': '1',
  1750. '/connected-ips': '',
  1751. '/connected-ips6': '',
  1752. })
  1753. @asyncio.coroutine
  1754. def coroutine_mock(self, mock, *args, **kwargs):
  1755. return mock(*args, **kwargs)
  1756. @unittest.mock.patch('asyncio.create_subprocess_exec')
  1757. def test_700_run_service(self, mock_subprocess):
  1758. func_mock = unittest.mock.Mock()
  1759. mock_subprocess.side_effect = functools.partial(
  1760. self.coroutine_mock, func_mock)
  1761. start_mock = unittest.mock.Mock()
  1762. vm = self.get_vm(cls=qubes.vm.standalonevm.StandaloneVM,
  1763. name='vm')
  1764. vm.is_running = lambda: True
  1765. vm.is_qrexec_running = lambda: True
  1766. vm.start = functools.partial(self.coroutine_mock, start_mock)
  1767. with self.subTest('running'):
  1768. self.loop.run_until_complete(vm.run_service('test.service'))
  1769. func_mock.assert_called_once_with(
  1770. '/usr/bin/qrexec-client', '-d', 'test-inst-vm',
  1771. 'user:QUBESRPC test.service dom0')
  1772. self.assertFalse(start_mock.called)
  1773. func_mock.reset_mock()
  1774. start_mock.reset_mock()
  1775. with self.subTest('not_running'):
  1776. vm.is_running = lambda: False
  1777. with self.assertRaises(qubes.exc.QubesVMNotRunningError):
  1778. self.loop.run_until_complete(vm.run_service('test.service'))
  1779. self.assertFalse(func_mock.called)
  1780. func_mock.reset_mock()
  1781. start_mock.reset_mock()
  1782. with self.subTest('autostart'):
  1783. vm.is_running = lambda: False
  1784. self.loop.run_until_complete(vm.run_service(
  1785. 'test.service', autostart=True))
  1786. func_mock.assert_called_once_with(
  1787. '/usr/bin/qrexec-client', '-d', 'test-inst-vm',
  1788. 'user:QUBESRPC test.service dom0')
  1789. self.assertTrue(start_mock.called)
  1790. func_mock.reset_mock()
  1791. start_mock.reset_mock()
  1792. with self.subTest('no_qrexec'):
  1793. vm.is_running = lambda: True
  1794. vm.is_qrexec_running = lambda: False
  1795. with self.assertRaises(qubes.exc.QubesVMError):
  1796. self.loop.run_until_complete(vm.run_service('test.service'))
  1797. self.assertFalse(start_mock.called)
  1798. self.assertFalse(func_mock.called)
  1799. func_mock.reset_mock()
  1800. start_mock.reset_mock()
  1801. with self.subTest('other_user'):
  1802. vm.is_running = lambda: True
  1803. vm.is_qrexec_running = lambda: True
  1804. self.loop.run_until_complete(vm.run_service('test.service',
  1805. user='other'))
  1806. func_mock.assert_called_once_with(
  1807. '/usr/bin/qrexec-client', '-d', 'test-inst-vm',
  1808. 'other:QUBESRPC test.service dom0')
  1809. self.assertFalse(start_mock.called)
  1810. func_mock.reset_mock()
  1811. start_mock.reset_mock()
  1812. with self.subTest('other_source'):
  1813. vm.is_running = lambda: True
  1814. vm.is_qrexec_running = lambda: True
  1815. self.loop.run_until_complete(vm.run_service('test.service',
  1816. source='test-inst-vm'))
  1817. func_mock.assert_called_once_with(
  1818. '/usr/bin/qrexec-client', '-d', 'test-inst-vm',
  1819. 'user:QUBESRPC test.service test-inst-vm')
  1820. self.assertFalse(start_mock.called)
  1821. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.run_service')
  1822. def test_710_run_service_for_stdio(self, mock_run_service):
  1823. vm = self.get_vm(cls=qubes.vm.standalonevm.StandaloneVM,
  1824. name='vm')
  1825. func_mock = unittest.mock.Mock()
  1826. mock_run_service.side_effect = functools.partial(
  1827. self.coroutine_mock, func_mock)
  1828. communicate_mock = unittest.mock.Mock()
  1829. func_mock.return_value.communicate.side_effect = functools.partial(
  1830. self.coroutine_mock, communicate_mock)
  1831. communicate_mock.return_value = (b'stdout', b'stderr')
  1832. func_mock.return_value.returncode = 0
  1833. with self.subTest('default'):
  1834. value = self.loop.run_until_complete(
  1835. vm.run_service_for_stdio('test.service'))
  1836. func_mock.assert_called_once_with(
  1837. 'test.service',
  1838. stdout=subprocess.PIPE,
  1839. stderr=subprocess.PIPE,
  1840. stdin=subprocess.PIPE)
  1841. communicate_mock.assert_called_once_with(input=None)
  1842. self.assertEqual(value, (b'stdout', b'stderr'))
  1843. func_mock.reset_mock()
  1844. communicate_mock.reset_mock()
  1845. with self.subTest('with_input'):
  1846. value = self.loop.run_until_complete(
  1847. vm.run_service_for_stdio('test.service', input=b'abc'))
  1848. func_mock.assert_called_once_with(
  1849. 'test.service',
  1850. stdout=subprocess.PIPE,
  1851. stderr=subprocess.PIPE,
  1852. stdin=subprocess.PIPE)
  1853. communicate_mock.assert_called_once_with(input=b'abc')
  1854. self.assertEqual(value, (b'stdout', b'stderr'))
  1855. func_mock.reset_mock()
  1856. communicate_mock.reset_mock()
  1857. with self.subTest('error'):
  1858. func_mock.return_value.returncode = 1
  1859. with self.assertRaises(subprocess.CalledProcessError) as exc:
  1860. self.loop.run_until_complete(
  1861. vm.run_service_for_stdio('test.service'))
  1862. func_mock.assert_called_once_with(
  1863. 'test.service',
  1864. stdout=subprocess.PIPE,
  1865. stderr=subprocess.PIPE,
  1866. stdin=subprocess.PIPE)
  1867. communicate_mock.assert_called_once_with(input=None)
  1868. self.assertEqual(exc.exception.returncode, 1)
  1869. self.assertEqual(exc.exception.output, b'stdout')
  1870. self.assertEqual(exc.exception.stderr, b'stderr')