qubesvm.py 88 KB

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