qubesvm.py 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175
  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. '', '')
  466. # TODO?
  467. # self.assertPropertyInvalidValue(vm, 'kernelopts', None),
  468. @unittest.skip('test not implemented')
  469. def test_261_kernelopts_pcidevs(self):
  470. vm = self.get_vm()
  471. # how to do that here? use dummy DeviceManager/DeviceCollection?
  472. # Disable events?
  473. vm.devices['pci'].attach('something')
  474. self.assertPropertyDefaultValue(vm, 'kernelopts',
  475. qubes.config.defaults['kernelopts_pcidevs'])
  476. @unittest.mock.patch.dict(qubes.config.system_path,
  477. {'qubes_kernels_base_dir': '/tmp'})
  478. def test_262_kernelopts(self):
  479. d = tempfile.mkdtemp(prefix='/tmp/')
  480. self.addCleanup(shutil.rmtree, d)
  481. open(d + '/vmlinuz', 'w').close()
  482. open(d + '/initramfs', 'w').close()
  483. with open(d + '/default-kernelopts-nopci.txt', 'w') as f:
  484. f.write('some default options')
  485. vm = self.get_vm()
  486. vm.kernel = os.path.basename(d)
  487. self.assertPropertyDefaultValue(vm, 'kernelopts',
  488. 'some default options')
  489. self.assertPropertyValue(vm, 'kernelopts', 'some options',
  490. 'some options', 'some options')
  491. del vm.kernelopts
  492. self.assertPropertyDefaultValue(vm, 'kernelopts',
  493. 'some default options')
  494. self.assertPropertyValue(vm, 'kernelopts', '',
  495. '', '')
  496. def test_270_qrexec_timeout(self):
  497. vm = self.get_vm()
  498. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 60)
  499. self.assertPropertyValue(vm, 'qrexec_timeout', 3, 3, '3')
  500. del vm.qrexec_timeout
  501. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 60)
  502. self.assertPropertyValue(vm, 'qrexec_timeout', '3', 3, '3')
  503. def test_271_qrexec_timeout_invalid(self):
  504. vm = self.get_vm()
  505. self.assertPropertyInvalidValue(vm, 'qrexec_timeout', -2)
  506. self.assertPropertyInvalidValue(vm, 'qrexec_timeout', '-2')
  507. self.assertPropertyInvalidValue(vm, 'qrexec_timeout', '')
  508. def test_272_qrexec_timeout_global_changed(self):
  509. self.app.default_qrexec_timeout = 123
  510. vm = self.get_vm()
  511. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 123)
  512. self.assertPropertyValue(vm, 'qrexec_timeout', 3, 3, '3')
  513. del vm.qrexec_timeout
  514. self.assertPropertyDefaultValue(vm, 'qrexec_timeout', 123)
  515. self.assertPropertyValue(vm, 'qrexec_timeout', '3', 3, '3')
  516. def test_280_autostart(self):
  517. vm = self.get_vm()
  518. # FIXME any better idea to not involve systemctl call at this stage?
  519. vm.events_enabled = False
  520. self._test_generic_bool_property(vm, 'autostart', False)
  521. @qubes.tests.skipUnlessDom0
  522. def test_281_autostart_systemd(self):
  523. vm = self.get_vm()
  524. self.assertFalse(os.path.exists(
  525. '/etc/systemd/system/multi-user.target.wants/'
  526. 'qubes-vm@{}.service'.format(vm.name)),
  527. "systemd service enabled before setting autostart")
  528. vm.autostart = True
  529. self.assertTrue(os.path.exists(
  530. '/etc/systemd/system/multi-user.target.wants/'
  531. 'qubes-vm@{}.service'.format(vm.name)),
  532. "systemd service not enabled by autostart=True")
  533. vm.autostart = False
  534. self.assertFalse(os.path.exists(
  535. '/etc/systemd/system/multi-user.target.wants/'
  536. 'qubes-vm@{}.service'.format(vm.name)),
  537. "systemd service not disabled by autostart=False")
  538. vm.autostart = True
  539. del vm.autostart
  540. self.assertFalse(os.path.exists(
  541. '/etc/systemd/system/multi-user.target.wants/'
  542. 'qubes-vm@{}.service'.format(vm.name)),
  543. "systemd service not disabled by resetting autostart")
  544. def test_290_management_dispvm(self):
  545. vm = self.get_vm()
  546. vm2 = self.get_vm('test2', qid=2)
  547. self.app.management_dispvm = None
  548. self.assertPropertyDefaultValue(vm, 'management_dispvm', None)
  549. self.app.management_dispvm = vm
  550. try:
  551. self.assertPropertyDefaultValue(vm, 'management_dispvm', vm)
  552. self.assertPropertyValue(vm, 'management_dispvm',
  553. 'test-inst-test2', vm2)
  554. finally:
  555. self.app.management_dispvm = None
  556. def test_291_management_dispvm_template_based(self):
  557. tpl = self.get_vm(name='tpl', cls=qubes.vm.templatevm.TemplateVM)
  558. vm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=tpl, qid=2)
  559. vm2 = self.get_vm('test2', qid=3)
  560. del vm.volumes
  561. self.app.management_dispvm = None
  562. try:
  563. self.assertPropertyDefaultValue(vm, 'management_dispvm', None)
  564. self.app.management_dispvm = vm
  565. self.assertPropertyDefaultValue(vm, 'management_dispvm', vm)
  566. tpl.management_dispvm = vm2
  567. self.assertPropertyDefaultValue(vm, 'management_dispvm', vm2)
  568. self.assertPropertyValue(vm, 'management_dispvm',
  569. 'test-inst-test2', vm2)
  570. finally:
  571. self.app.management_dispvm = None
  572. @unittest.skip('TODO')
  573. def test_320_seamless_gui_mode(self):
  574. vm = self.get_vm()
  575. self._test_generic_bool_property(vm, 'seamless_gui_mode')
  576. # TODO: reject setting to True when guiagent_installed is false
  577. def test_330_mac(self):
  578. vm = self.get_vm()
  579. # TODO: calculate proper default here
  580. default_mac = vm.mac
  581. self.assertIsNotNone(default_mac)
  582. self.assertPropertyDefaultValue(vm, 'mac', default_mac)
  583. self.assertPropertyValue(vm, 'mac', '00:11:22:33:44:55',
  584. '00:11:22:33:44:55', '00:11:22:33:44:55')
  585. del vm.mac
  586. self.assertPropertyDefaultValue(vm, 'mac', default_mac)
  587. def test_331_mac_invalid(self):
  588. vm = self.get_vm()
  589. self.assertPropertyInvalidValue(vm, 'mac', 123)
  590. self.assertPropertyInvalidValue(vm, 'mac', 'invalid')
  591. self.assertPropertyInvalidValue(vm, 'mac', '00:11:22:33:44:55:66')
  592. def test_340_default_user(self):
  593. vm = self.get_vm()
  594. self.assertPropertyDefaultValue(vm, 'default_user', 'user')
  595. self.assertPropertyValue(vm, 'default_user', 'someuser', 'someuser',
  596. 'someuser')
  597. del vm.default_user
  598. self.assertPropertyDefaultValue(vm, 'default_user', 'user')
  599. self.assertPropertyValue(vm, 'default_user', 123, '123', '123')
  600. vm.default_user = 'user'
  601. # TODO: check propagation for template-based VMs
  602. @unittest.skip('TODO')
  603. def test_350_timezone(self):
  604. vm = self.get_vm()
  605. self.assertPropertyDefaultValue(vm, 'timezone', 'localtime')
  606. self.assertPropertyValue(vm, 'timezone', 0, 0, '0')
  607. del vm.timezone
  608. self.assertPropertyDefaultValue(vm, 'timezone', 'localtime')
  609. self.assertPropertyValue(vm, 'timezone', '0', 0, '0')
  610. self.assertPropertyValue(vm, 'timezone', -3600, -3600, '-3600')
  611. self.assertPropertyValue(vm, 'timezone', 7200, 7200, '7200')
  612. @unittest.skip('TODO')
  613. def test_350_timezone_invalid(self):
  614. vm = self.get_vm()
  615. self.assertPropertyInvalidValue(vm, 'timezone', 'xxx')
  616. @unittest.skip('TODO')
  617. def test_360_drive(self):
  618. vm = self.get_vm()
  619. self.assertPropertyDefaultValue(vm, 'drive', None)
  620. # self.execute_tests('drive', [
  621. # ('hd:dom0:/tmp/drive.img', 'hd:dom0:/tmp/drive.img', True),
  622. # ('hd:/tmp/drive.img', 'hd:dom0:/tmp/drive.img', True),
  623. # ('cdrom:dom0:/tmp/drive.img', 'cdrom:dom0:/tmp/drive.img', True),
  624. # ('cdrom:/tmp/drive.img', 'cdrom:dom0:/tmp/drive.img', True),
  625. # ('/tmp/drive.img', 'cdrom:dom0:/tmp/drive.img', True),
  626. # ('hd:drive.img', '', False),
  627. # ('drive.img', '', False),
  628. # ])
  629. def test_400_backup_timestamp(self):
  630. vm = self.get_vm()
  631. timestamp = datetime.datetime(2016, 1, 1, 12, 14, 2)
  632. timestamp_str = timestamp.strftime('%s')
  633. self.assertPropertyDefaultValue(vm, 'backup_timestamp', None)
  634. self.assertPropertyValue(vm, 'backup_timestamp', int(timestamp_str),
  635. int(timestamp_str), timestamp_str)
  636. del vm.backup_timestamp
  637. self.assertPropertyDefaultValue(vm, 'backup_timestamp', None)
  638. self.assertPropertyValue(vm, 'backup_timestamp', timestamp_str,
  639. int(timestamp_str))
  640. def test_401_backup_timestamp_invalid(self):
  641. vm = self.get_vm()
  642. self.assertPropertyInvalidValue(vm, 'backup_timestamp', 'xxx')
  643. self.assertPropertyInvalidValue(vm, 'backup_timestamp', None)
  644. def test_500_property_migrate_virt_mode(self):
  645. xml_template = '''
  646. <domain class="QubesVM" id="domain-1">
  647. <properties>
  648. <property name="qid">1</property>
  649. <property name="name">testvm</property>
  650. <property name="label" ref="label-1" />
  651. <property name="hvm">{hvm_value}</property>
  652. </properties>
  653. </domain>
  654. '''
  655. xml = lxml.etree.XML(xml_template.format(hvm_value='True'))
  656. vm = qubes.vm.qubesvm.QubesVM(self.app, xml)
  657. self.assertEqual(vm.virt_mode, 'hvm')
  658. with self.assertRaises(AttributeError):
  659. vm.hvm
  660. xml = lxml.etree.XML(xml_template.format(hvm_value='False'))
  661. vm = qubes.vm.qubesvm.QubesVM(self.app, xml)
  662. self.assertEqual(vm.virt_mode, 'pv')
  663. with self.assertRaises(AttributeError):
  664. vm.hvm
  665. def test_600_libvirt_xml_pv(self):
  666. expected = '''<domain type="xen">
  667. <name>test-inst-test</name>
  668. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  669. <memory unit="MiB">500</memory>
  670. <currentMemory unit="MiB">400</currentMemory>
  671. <vcpu placement="static">2</vcpu>
  672. <os>
  673. <type arch="x86_64" machine="xenpv">linux</type>
  674. <kernel>/tmp/kernel/vmlinuz</kernel>
  675. <initrd>/tmp/kernel/initramfs</initrd>
  676. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  677. </os>
  678. <features>
  679. </features>
  680. <clock offset='utc' adjustment='reset'>
  681. <timer name="tsc" mode="native"/>
  682. </clock>
  683. <on_poweroff>destroy</on_poweroff>
  684. <on_reboot>destroy</on_reboot>
  685. <on_crash>destroy</on_crash>
  686. <devices>
  687. <disk type="block" device="disk">
  688. <driver name="phy" />
  689. <source dev="/tmp/kernel/modules.img" />
  690. <target dev="xvdd" />
  691. <backenddomain name="dom0" />
  692. </disk>
  693. <console type="pty">
  694. <target type="xen" port="0"/>
  695. </console>
  696. </devices>
  697. </domain>
  698. '''
  699. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  700. vm = self.get_vm(uuid=my_uuid)
  701. vm.netvm = None
  702. vm.virt_mode = 'pv'
  703. with unittest.mock.patch('qubes.config.qubes_base_dir',
  704. '/tmp/qubes-test'):
  705. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  706. os.makedirs(kernel_dir, exist_ok=True)
  707. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  708. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  709. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  710. vm.kernel = 'dummy'
  711. # tests for storage are later
  712. vm.volumes['kernel'] = unittest.mock.Mock(**{
  713. 'kernels_dir': '/tmp/kernel',
  714. 'block_device.return_value.domain': 'dom0',
  715. 'block_device.return_value.script': None,
  716. 'block_device.return_value.path': '/tmp/kernel/modules.img',
  717. 'block_device.return_value.devtype': 'disk',
  718. 'block_device.return_value.name': 'kernel',
  719. })
  720. libvirt_xml = vm.create_config_file()
  721. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  722. lxml.etree.XML(expected))
  723. def test_600_libvirt_xml_hvm(self):
  724. expected = '''<domain type="xen">
  725. <name>test-inst-test</name>
  726. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  727. <memory unit="MiB">400</memory>
  728. <currentMemory unit="MiB">400</currentMemory>
  729. <vcpu placement="static">2</vcpu>
  730. <cpu mode='host-passthrough'>
  731. <!-- disable nested HVM -->
  732. <feature name='vmx' policy='disable'/>
  733. <feature name='svm' policy='disable'/>
  734. <!-- disable SMAP inside VM, because of Linux bug -->
  735. <feature name='smap' policy='disable'/>
  736. </cpu>
  737. <os>
  738. <type arch="x86_64" machine="xenfv">hvm</type>
  739. <!--
  740. For the libxl backend libvirt switches between OVMF (UEFI)
  741. and SeaBIOS based on the loader type. This has nothing to
  742. do with the hvmloader binary.
  743. -->
  744. <loader type="rom">hvmloader</loader>
  745. <boot dev="cdrom" />
  746. <boot dev="hd" />
  747. </os>
  748. <features>
  749. <pae/>
  750. <acpi/>
  751. <apic/>
  752. <viridian/>
  753. </features>
  754. <clock offset="variable" adjustment="0" basis="localtime" />
  755. <on_poweroff>destroy</on_poweroff>
  756. <on_reboot>destroy</on_reboot>
  757. <on_crash>destroy</on_crash>
  758. <devices>
  759. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  760. <emulator type="stubdom-linux" />
  761. <input type="tablet" bus="usb"/>
  762. <video>
  763. <model type="vga"/>
  764. </video>
  765. <graphics type="qubes"/>
  766. <console type="pty">
  767. <target type="xen" port="0"/>
  768. </console>
  769. </devices>
  770. </domain>
  771. '''
  772. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  773. vm = self.get_vm(uuid=my_uuid)
  774. vm.netvm = None
  775. vm.virt_mode = 'hvm'
  776. libvirt_xml = vm.create_config_file()
  777. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  778. lxml.etree.XML(expected))
  779. def test_600_libvirt_xml_hvm_dom0_kernel(self):
  780. expected = '''<domain type="xen">
  781. <name>test-inst-test</name>
  782. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  783. <memory unit="MiB">500</memory>
  784. <currentMemory unit="MiB">400</currentMemory>
  785. <vcpu placement="static">2</vcpu>
  786. <cpu mode='host-passthrough'>
  787. <!-- disable nested HVM -->
  788. <feature name='vmx' policy='disable'/>
  789. <feature name='svm' policy='disable'/>
  790. <!-- disable SMAP inside VM, because of Linux bug -->
  791. <feature name='smap' policy='disable'/>
  792. </cpu>
  793. <os>
  794. <type arch="x86_64" machine="xenfv">hvm</type>
  795. <!--
  796. For the libxl backend libvirt switches between OVMF (UEFI)
  797. and SeaBIOS based on the loader type. This has nothing to
  798. do with the hvmloader binary.
  799. -->
  800. <loader type="rom">hvmloader</loader>
  801. <boot dev="cdrom" />
  802. <boot dev="hd" />
  803. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  804. </os>
  805. <features>
  806. <pae/>
  807. <acpi/>
  808. <apic/>
  809. <viridian/>
  810. </features>
  811. <clock offset="variable" adjustment="0" basis="localtime" />
  812. <on_poweroff>destroy</on_poweroff>
  813. <on_reboot>destroy</on_reboot>
  814. <on_crash>destroy</on_crash>
  815. <devices>
  816. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  817. <emulator type="stubdom-linux" />
  818. <input type="tablet" bus="usb"/>
  819. <video>
  820. <model type="vga"/>
  821. </video>
  822. <graphics type="qubes"/>
  823. <console type="pty">
  824. <target type="xen" port="0"/>
  825. </console>
  826. </devices>
  827. </domain>
  828. '''
  829. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  830. vm = self.get_vm(uuid=my_uuid)
  831. vm.netvm = None
  832. vm.virt_mode = 'hvm'
  833. vm.features['qrexec'] = True
  834. with unittest.mock.patch('qubes.config.qubes_base_dir',
  835. '/tmp/qubes-test'):
  836. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  837. os.makedirs(kernel_dir, exist_ok=True)
  838. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  839. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  840. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  841. vm.kernel = 'dummy'
  842. libvirt_xml = vm.create_config_file()
  843. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  844. lxml.etree.XML(expected))
  845. def test_600_libvirt_xml_hvm_dom0_kernel_kernelopts(self):
  846. expected = '''<domain type="xen">
  847. <name>test-inst-test</name>
  848. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  849. <memory unit="MiB">500</memory>
  850. <currentMemory unit="MiB">400</currentMemory>
  851. <vcpu placement="static">2</vcpu>
  852. <cpu mode='host-passthrough'>
  853. <!-- disable nested HVM -->
  854. <feature name='vmx' policy='disable'/>
  855. <feature name='svm' policy='disable'/>
  856. <!-- disable SMAP inside VM, because of Linux bug -->
  857. <feature name='smap' policy='disable'/>
  858. </cpu>
  859. <os>
  860. <type arch="x86_64" machine="xenfv">hvm</type>
  861. <!--
  862. For the libxl backend libvirt switches between OVMF (UEFI)
  863. and SeaBIOS based on the loader type. This has nothing to
  864. do with the hvmloader binary.
  865. -->
  866. <loader type="rom">hvmloader</loader>
  867. <boot dev="cdrom" />
  868. <boot dev="hd" />
  869. <cmdline>kernel specific options nopat</cmdline>
  870. </os>
  871. <features>
  872. <pae/>
  873. <acpi/>
  874. <apic/>
  875. <viridian/>
  876. </features>
  877. <clock offset="variable" adjustment="0" basis="localtime" />
  878. <on_poweroff>destroy</on_poweroff>
  879. <on_reboot>destroy</on_reboot>
  880. <on_crash>destroy</on_crash>
  881. <devices>
  882. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  883. <emulator type="stubdom-linux" />
  884. <input type="tablet" bus="usb"/>
  885. <video>
  886. <model type="vga"/>
  887. </video>
  888. <graphics type="qubes"/>
  889. <console type="pty">
  890. <target type="xen" port="0"/>
  891. </console>
  892. </devices>
  893. </domain>
  894. '''
  895. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  896. vm = self.get_vm(uuid=my_uuid)
  897. vm.netvm = None
  898. vm.virt_mode = 'hvm'
  899. vm.features['qrexec'] = True
  900. with unittest.mock.patch('qubes.config.qubes_base_dir',
  901. '/tmp/qubes-test'):
  902. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  903. os.makedirs(kernel_dir, exist_ok=True)
  904. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  905. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  906. with open(os.path.join(kernel_dir,
  907. 'default-kernelopts-common.txt'), 'w') as f:
  908. f.write('kernel specific options \n')
  909. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  910. vm.kernel = 'dummy'
  911. libvirt_xml = vm.create_config_file()
  912. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  913. lxml.etree.XML(expected))
  914. def test_600_libvirt_xml_pvh(self):
  915. expected = '''<domain type="xen">
  916. <name>test-inst-test</name>
  917. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  918. <memory unit="MiB">500</memory>
  919. <currentMemory unit="MiB">400</currentMemory>
  920. <vcpu placement="static">2</vcpu>
  921. <cpu mode='host-passthrough'>
  922. <!-- disable nested HVM -->
  923. <feature name='vmx' policy='disable'/>
  924. <feature name='svm' policy='disable'/>
  925. <!-- disable SMAP inside VM, because of Linux bug -->
  926. <feature name='smap' policy='disable'/>
  927. </cpu>
  928. <os>
  929. <type arch="x86_64" machine="xenpvh">xenpvh</type>
  930. <kernel>/tmp/kernel/vmlinuz</kernel>
  931. <initrd>/tmp/kernel/initramfs</initrd>
  932. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  933. </os>
  934. <features>
  935. <pae/>
  936. <acpi/>
  937. <apic/>
  938. <viridian/>
  939. </features>
  940. <clock offset='utc' adjustment='reset'>
  941. <timer name="tsc" mode="native"/>
  942. </clock>
  943. <on_poweroff>destroy</on_poweroff>
  944. <on_reboot>destroy</on_reboot>
  945. <on_crash>destroy</on_crash>
  946. <devices>
  947. <disk type="block" device="disk">
  948. <driver name="phy" />
  949. <source dev="/tmp/kernel/modules.img" />
  950. <target dev="xvdd" />
  951. <backenddomain name="dom0" />
  952. </disk>
  953. <console type="pty">
  954. <target type="xen" port="0"/>
  955. </console>
  956. </devices>
  957. </domain>
  958. '''
  959. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  960. vm = self.get_vm(uuid=my_uuid)
  961. vm.netvm = None
  962. vm.virt_mode = 'pvh'
  963. with unittest.mock.patch('qubes.config.qubes_base_dir',
  964. '/tmp/qubes-test'):
  965. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  966. os.makedirs(kernel_dir, exist_ok=True)
  967. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  968. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  969. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  970. vm.kernel = 'dummy'
  971. # tests for storage are later
  972. vm.volumes['kernel'] = unittest.mock.Mock(**{
  973. 'kernels_dir': '/tmp/kernel',
  974. 'block_device.return_value.domain': 'dom0',
  975. 'block_device.return_value.script': None,
  976. 'block_device.return_value.path': '/tmp/kernel/modules.img',
  977. 'block_device.return_value.devtype': 'disk',
  978. 'block_device.return_value.name': 'kernel',
  979. })
  980. libvirt_xml = vm.create_config_file()
  981. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  982. lxml.etree.XML(expected))
  983. def test_600_libvirt_xml_pvh_no_membalance(self):
  984. expected = '''<domain type="xen">
  985. <name>test-inst-test</name>
  986. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  987. <memory unit="MiB">400</memory>
  988. <currentMemory unit="MiB">400</currentMemory>
  989. <vcpu placement="static">2</vcpu>
  990. <cpu mode='host-passthrough'>
  991. <!-- disable nested HVM -->
  992. <feature name='vmx' policy='disable'/>
  993. <feature name='svm' policy='disable'/>
  994. <!-- disable SMAP inside VM, because of Linux bug -->
  995. <feature name='smap' policy='disable'/>
  996. </cpu>
  997. <os>
  998. <type arch="x86_64" machine="xenpvh">xenpvh</type>
  999. <kernel>/tmp/kernel/vmlinuz</kernel>
  1000. <initrd>/tmp/kernel/initramfs</initrd>
  1001. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  1002. </os>
  1003. <features>
  1004. <pae/>
  1005. <acpi/>
  1006. <apic/>
  1007. <viridian/>
  1008. </features>
  1009. <clock offset='utc' adjustment='reset'>
  1010. <timer name="tsc" mode="native"/>
  1011. </clock>
  1012. <on_poweroff>destroy</on_poweroff>
  1013. <on_reboot>destroy</on_reboot>
  1014. <on_crash>destroy</on_crash>
  1015. <devices>
  1016. <disk type="block" device="disk">
  1017. <driver name="phy" />
  1018. <source dev="/tmp/kernel/modules.img" />
  1019. <target dev="xvdd" />
  1020. <backenddomain name="dom0" />
  1021. </disk>
  1022. <console type="pty">
  1023. <target type="xen" port="0"/>
  1024. </console>
  1025. </devices>
  1026. </domain>
  1027. '''
  1028. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1029. vm = self.get_vm(uuid=my_uuid)
  1030. vm.netvm = None
  1031. vm.virt_mode = 'pvh'
  1032. vm.maxmem = 0
  1033. with unittest.mock.patch('qubes.config.qubes_base_dir',
  1034. '/tmp/qubes-test'):
  1035. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  1036. os.makedirs(kernel_dir, exist_ok=True)
  1037. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  1038. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  1039. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  1040. vm.kernel = 'dummy'
  1041. # tests for storage are later
  1042. vm.volumes['kernel'] = unittest.mock.Mock(**{
  1043. 'kernels_dir': '/tmp/kernel',
  1044. 'block_device.return_value.domain': 'dom0',
  1045. 'block_device.return_value.script': None,
  1046. 'block_device.return_value.path': '/tmp/kernel/modules.img',
  1047. 'block_device.return_value.devtype': 'disk',
  1048. 'block_device.return_value.name': 'kernel',
  1049. })
  1050. libvirt_xml = vm.create_config_file()
  1051. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1052. lxml.etree.XML(expected))
  1053. def test_600_libvirt_xml_hvm_pcidev(self):
  1054. expected = '''<domain type="xen">
  1055. <name>test-inst-test</name>
  1056. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1057. <memory unit="MiB">400</memory>
  1058. <currentMemory unit="MiB">400</currentMemory>
  1059. <vcpu placement="static">2</vcpu>
  1060. <cpu mode='host-passthrough'>
  1061. <!-- disable nested HVM -->
  1062. <feature name='vmx' policy='disable'/>
  1063. <feature name='svm' policy='disable'/>
  1064. <!-- disable SMAP inside VM, because of Linux bug -->
  1065. <feature name='smap' policy='disable'/>
  1066. </cpu>
  1067. <os>
  1068. <type arch="x86_64" machine="xenfv">hvm</type>
  1069. <!--
  1070. For the libxl backend libvirt switches between OVMF (UEFI)
  1071. and SeaBIOS based on the loader type. This has nothing to
  1072. do with the hvmloader binary.
  1073. -->
  1074. <loader type="rom">hvmloader</loader>
  1075. <boot dev="cdrom" />
  1076. <boot dev="hd" />
  1077. </os>
  1078. <features>
  1079. <pae/>
  1080. <acpi/>
  1081. <apic/>
  1082. <viridian/>
  1083. <xen>
  1084. <e820_host state="on"/>
  1085. </xen>
  1086. </features>
  1087. <clock offset="variable" adjustment="0" basis="localtime" />
  1088. <on_poweroff>destroy</on_poweroff>
  1089. <on_reboot>destroy</on_reboot>
  1090. <on_crash>destroy</on_crash>
  1091. <devices>
  1092. <hostdev type="pci" managed="yes">
  1093. <source>
  1094. <address
  1095. bus="0x00"
  1096. slot="0x00"
  1097. function="0x0" />
  1098. </source>
  1099. </hostdev>
  1100. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1101. <emulator type="stubdom-linux" />
  1102. <input type="tablet" bus="usb"/>
  1103. <video>
  1104. <model type="vga"/>
  1105. </video>
  1106. <graphics type="qubes"/>
  1107. <console type="pty">
  1108. <target type="xen" port="0"/>
  1109. </console>
  1110. </devices>
  1111. </domain>
  1112. '''
  1113. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1114. # required for PCI devices listing
  1115. self.app.vmm.offline_mode = False
  1116. vm = self.get_vm(uuid=my_uuid)
  1117. vm.netvm = None
  1118. vm.virt_mode = 'hvm'
  1119. vm.kernel = None
  1120. # even with meminfo-writer enabled, should have memory==maxmem
  1121. vm.features['service.meminfo-writer'] = True
  1122. assignment = qubes.devices.DeviceAssignment(
  1123. vm, # this is violation of API, but for PCI the argument
  1124. # is unused
  1125. '00_00.0',
  1126. bus='pci',
  1127. persistent=True)
  1128. vm.devices['pci']._set.add(
  1129. assignment)
  1130. libvirt_xml = vm.create_config_file()
  1131. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1132. lxml.etree.XML(expected))
  1133. def test_600_libvirt_xml_hvm_cdrom_boot(self):
  1134. expected = '''<domain type="xen">
  1135. <name>test-inst-test</name>
  1136. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1137. <memory unit="MiB">400</memory>
  1138. <currentMemory unit="MiB">400</currentMemory>
  1139. <vcpu placement="static">2</vcpu>
  1140. <cpu mode='host-passthrough'>
  1141. <!-- disable nested HVM -->
  1142. <feature name='vmx' policy='disable'/>
  1143. <feature name='svm' policy='disable'/>
  1144. <!-- disable SMAP inside VM, because of Linux bug -->
  1145. <feature name='smap' policy='disable'/>
  1146. </cpu>
  1147. <os>
  1148. <type arch="x86_64" machine="xenfv">hvm</type>
  1149. <!--
  1150. For the libxl backend libvirt switches between OVMF (UEFI)
  1151. and SeaBIOS based on the loader type. This has nothing to
  1152. do with the hvmloader binary.
  1153. -->
  1154. <loader type="rom">hvmloader</loader>
  1155. <boot dev="cdrom" />
  1156. <boot dev="hd" />
  1157. </os>
  1158. <features>
  1159. <pae/>
  1160. <acpi/>
  1161. <apic/>
  1162. <viridian/>
  1163. </features>
  1164. <clock offset="variable" adjustment="0" basis="localtime" />
  1165. <on_poweroff>destroy</on_poweroff>
  1166. <on_reboot>destroy</on_reboot>
  1167. <on_crash>destroy</on_crash>
  1168. <devices>
  1169. <disk type="block" device="cdrom">
  1170. <driver name="phy" />
  1171. <source dev="/dev/sda" />
  1172. <!-- prefer xvdd for CDROM -->
  1173. <target dev="xvdd" />
  1174. <readonly/>
  1175. </disk>
  1176. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1177. <emulator type="stubdom-linux" />
  1178. <input type="tablet" bus="usb"/>
  1179. <video>
  1180. <model type="vga"/>
  1181. </video>
  1182. <graphics type="qubes"/>
  1183. <console type="pty">
  1184. <target type="xen" port="0"/>
  1185. </console>
  1186. </devices>
  1187. </domain>
  1188. '''
  1189. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1190. qdb = {
  1191. '/qubes-block-devices/sda': b'',
  1192. '/qubes-block-devices/sda/desc': b'Test device',
  1193. '/qubes-block-devices/sda/size': b'1024000',
  1194. '/qubes-block-devices/sda/mode': b'r',
  1195. }
  1196. test_qdb = TestQubesDB(qdb)
  1197. dom0 = qubes.vm.adminvm.AdminVM(self.app, None)
  1198. dom0._qdb_connection = test_qdb
  1199. self.get_vm('dom0', vm=dom0)
  1200. vm = self.get_vm(uuid=my_uuid)
  1201. vm.netvm = None
  1202. vm.virt_mode = 'hvm'
  1203. vm.kernel = None
  1204. dom0.events_enabled = True
  1205. self.app.vmm.offline_mode = False
  1206. dev = qubes.devices.DeviceAssignment(
  1207. dom0, 'sda',
  1208. {'devtype': 'cdrom', 'read-only': 'yes'}, persistent=True)
  1209. self.loop.run_until_complete(vm.devices['block'].attach(dev))
  1210. libvirt_xml = vm.create_config_file()
  1211. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1212. lxml.etree.XML(expected))
  1213. def test_600_libvirt_xml_hvm_cdrom_dom0_kernel_boot(self):
  1214. expected = '''<domain type="xen">
  1215. <name>test-inst-test</name>
  1216. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1217. <memory unit="MiB">400</memory>
  1218. <currentMemory unit="MiB">400</currentMemory>
  1219. <vcpu placement="static">2</vcpu>
  1220. <cpu mode='host-passthrough'>
  1221. <!-- disable nested HVM -->
  1222. <feature name='vmx' policy='disable'/>
  1223. <feature name='svm' policy='disable'/>
  1224. <!-- disable SMAP inside VM, because of Linux bug -->
  1225. <feature name='smap' policy='disable'/>
  1226. </cpu>
  1227. <os>
  1228. <type arch="x86_64" machine="xenfv">hvm</type>
  1229. <!--
  1230. For the libxl backend libvirt switches between OVMF (UEFI)
  1231. and SeaBIOS based on the loader type. This has nothing to
  1232. do with the hvmloader binary.
  1233. -->
  1234. <loader type="rom">hvmloader</loader>
  1235. <boot dev="cdrom" />
  1236. <boot dev="hd" />
  1237. <cmdline>root=/dev/mapper/dmroot ro nomodeset console=hvc0 rd_NO_PLYMOUTH rd.plymouth.enable=0 plymouth.enable=0 nopat</cmdline>
  1238. </os>
  1239. <features>
  1240. <pae/>
  1241. <acpi/>
  1242. <apic/>
  1243. <viridian/>
  1244. </features>
  1245. <clock offset="variable" adjustment="0" basis="localtime" />
  1246. <on_poweroff>destroy</on_poweroff>
  1247. <on_reboot>destroy</on_reboot>
  1248. <on_crash>destroy</on_crash>
  1249. <devices>
  1250. <disk type="block" device="disk">
  1251. <driver name="phy" />
  1252. <source dev="/tmp/kernel/modules.img" />
  1253. <target dev="xvdd" />
  1254. <backenddomain name="dom0" />
  1255. </disk>
  1256. <disk type="block" device="cdrom">
  1257. <driver name="phy" />
  1258. <source dev="/dev/sda" />
  1259. <target dev="xvdi" />
  1260. <readonly/>
  1261. </disk>
  1262. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1263. <emulator type="stubdom-linux" />
  1264. <input type="tablet" bus="usb"/>
  1265. <video>
  1266. <model type="vga"/>
  1267. </video>
  1268. <graphics type="qubes"/>
  1269. <console type="pty">
  1270. <target type="xen" port="0"/>
  1271. </console>
  1272. </devices>
  1273. </domain>
  1274. '''
  1275. qdb = {
  1276. '/qubes-block-devices/sda': b'',
  1277. '/qubes-block-devices/sda/desc': b'Test device',
  1278. '/qubes-block-devices/sda/size': b'1024000',
  1279. '/qubes-block-devices/sda/mode': b'r',
  1280. }
  1281. test_qdb = TestQubesDB(qdb)
  1282. dom0 = qubes.vm.adminvm.AdminVM(self.app, None)
  1283. dom0._qdb_connection = test_qdb
  1284. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1285. vm = self.get_vm(uuid=my_uuid)
  1286. vm.netvm = None
  1287. vm.virt_mode = 'hvm'
  1288. with unittest.mock.patch('qubes.config.qubes_base_dir',
  1289. '/tmp/qubes-test'):
  1290. kernel_dir = '/tmp/qubes-test/vm-kernels/dummy'
  1291. os.makedirs(kernel_dir, exist_ok=True)
  1292. open(os.path.join(kernel_dir, 'vmlinuz'), 'w').close()
  1293. open(os.path.join(kernel_dir, 'initramfs'), 'w').close()
  1294. self.addCleanup(shutil.rmtree, '/tmp/qubes-test')
  1295. vm.kernel = 'dummy'
  1296. # tests for storage are later
  1297. vm.volumes['kernel'] = unittest.mock.Mock(**{
  1298. 'kernels_dir': '/tmp/kernel',
  1299. 'block_device.return_value.domain': 'dom0',
  1300. 'block_device.return_value.script': None,
  1301. 'block_device.return_value.path': '/tmp/kernel/modules.img',
  1302. 'block_device.return_value.devtype': 'disk',
  1303. 'block_device.return_value.name': 'kernel',
  1304. })
  1305. dom0.events_enabled = True
  1306. self.app.vmm.offline_mode = False
  1307. dev = qubes.devices.DeviceAssignment(
  1308. dom0, 'sda',
  1309. {'devtype': 'cdrom', 'read-only': 'yes'}, persistent=True)
  1310. self.loop.run_until_complete(vm.devices['block'].attach(dev))
  1311. libvirt_xml = vm.create_config_file()
  1312. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1313. lxml.etree.XML(expected))
  1314. def test_610_libvirt_xml_network(self):
  1315. expected = '''<domain type="xen">
  1316. <name>test-inst-test</name>
  1317. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1318. <memory unit="MiB">500</memory>
  1319. <currentMemory unit="MiB">400</currentMemory>
  1320. <vcpu placement="static">2</vcpu>
  1321. <cpu mode='host-passthrough'>
  1322. <!-- disable nested HVM -->
  1323. <feature name='vmx' policy='disable'/>
  1324. <feature name='svm' policy='disable'/>
  1325. <!-- disable SMAP inside VM, because of Linux bug -->
  1326. <feature name='smap' policy='disable'/>
  1327. </cpu>
  1328. <os>
  1329. <type arch="x86_64" machine="xenfv">hvm</type>
  1330. <!--
  1331. For the libxl backend libvirt switches between OVMF (UEFI)
  1332. and SeaBIOS based on the loader type. This has nothing to
  1333. do with the hvmloader binary.
  1334. -->
  1335. <loader type="rom">hvmloader</loader>
  1336. <boot dev="cdrom" />
  1337. <boot dev="hd" />
  1338. </os>
  1339. <features>
  1340. <pae/>
  1341. <acpi/>
  1342. <apic/>
  1343. <viridian/>
  1344. </features>
  1345. <clock offset="variable" adjustment="0" basis="localtime" />
  1346. <on_poweroff>destroy</on_poweroff>
  1347. <on_reboot>destroy</on_reboot>
  1348. <on_crash>destroy</on_crash>
  1349. <devices>
  1350. <interface type="ethernet">
  1351. <mac address="00:16:3e:5e:6c:00" />
  1352. <ip address="10.137.0.1" />
  1353. {extra_ip}
  1354. <backenddomain name="test-inst-netvm" />
  1355. <script path="vif-route-qubes" />
  1356. </interface>
  1357. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1358. <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" />
  1359. <input type="tablet" bus="usb"/>
  1360. <video>
  1361. <model type="vga"/>
  1362. </video>
  1363. <graphics type="qubes"/>
  1364. <console type="pty">
  1365. <target type="xen" port="0"/>
  1366. </console>
  1367. </devices>
  1368. </domain>
  1369. '''
  1370. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1371. netvm = self.get_vm(qid=2, name='netvm', provides_network=True)
  1372. vm = self.get_vm(uuid=my_uuid)
  1373. vm.netvm = netvm
  1374. vm.virt_mode = 'hvm'
  1375. vm.features['qrexec'] = True
  1376. with self.subTest('ipv4_only'):
  1377. libvirt_xml = vm.create_config_file()
  1378. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1379. lxml.etree.XML(expected.format(extra_ip='')))
  1380. with self.subTest('ipv6'):
  1381. netvm.features['ipv6'] = True
  1382. libvirt_xml = vm.create_config_file()
  1383. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1384. lxml.etree.XML(expected.format(
  1385. extra_ip='<ip address="{}::a89:1" family=\'ipv6\'/>'.format(
  1386. qubes.config.qubes_ipv6_prefix.replace(':0000', '')))))
  1387. def test_615_libvirt_xml_block_devices(self):
  1388. expected = '''<domain type="xen">
  1389. <name>test-inst-test</name>
  1390. <uuid>7db78950-c467-4863-94d1-af59806384ea</uuid>
  1391. <memory unit="MiB">400</memory>
  1392. <currentMemory unit="MiB">400</currentMemory>
  1393. <vcpu placement="static">2</vcpu>
  1394. <cpu mode='host-passthrough'>
  1395. <!-- disable nested HVM -->
  1396. <feature name='vmx' policy='disable'/>
  1397. <feature name='svm' policy='disable'/>
  1398. <!-- disable SMAP inside VM, because of Linux bug -->
  1399. <feature name='smap' policy='disable'/>
  1400. </cpu>
  1401. <os>
  1402. <type arch="x86_64" machine="xenfv">hvm</type>
  1403. <!--
  1404. For the libxl backend libvirt switches between OVMF (UEFI)
  1405. and SeaBIOS based on the loader type. This has nothing to
  1406. do with the hvmloader binary.
  1407. -->
  1408. <loader type="rom">hvmloader</loader>
  1409. <boot dev="cdrom" />
  1410. <boot dev="hd" />
  1411. </os>
  1412. <features>
  1413. <pae/>
  1414. <acpi/>
  1415. <apic/>
  1416. <viridian/>
  1417. </features>
  1418. <clock offset="variable" adjustment="0" basis="localtime" />
  1419. <on_poweroff>destroy</on_poweroff>
  1420. <on_reboot>destroy</on_reboot>
  1421. <on_crash>destroy</on_crash>
  1422. <devices>
  1423. <disk type="block" device="disk">
  1424. <driver name="phy" />
  1425. <source dev="/dev/loop0" />
  1426. <target dev="xvda" />
  1427. <backenddomain name="dom0" />
  1428. <script path="/tmp/script" />
  1429. </disk>
  1430. <disk type="block" device="disk">
  1431. <driver name="phy" />
  1432. <source dev="/dev/loop1" />
  1433. <target dev="xvde" />
  1434. <backenddomain name="dom0" />
  1435. </disk>
  1436. <disk type="block" device="disk">
  1437. <driver name="phy" />
  1438. <source dev="/dev/loop2" />
  1439. <target dev="xvdf" />
  1440. <backenddomain name="dom0" />
  1441. </disk>
  1442. <disk type="block" device="disk">
  1443. <driver name="phy" />
  1444. <source dev="/dev/sdb" />
  1445. <target dev="xvdl" />
  1446. </disk>
  1447. <disk type="block" device="cdrom">
  1448. <driver name="phy" />
  1449. <source dev="/dev/sda" />
  1450. <!-- prefer xvdd for CDROM -->
  1451. <target dev="xvdd" />
  1452. </disk>
  1453. <disk type="block" device="disk">
  1454. <driver name="phy" />
  1455. <source dev="/dev/loop0" />
  1456. <target dev="xvdi" />
  1457. <backenddomain name="backend0" />
  1458. </disk>
  1459. <disk type="block" device="disk">
  1460. <driver name="phy" />
  1461. <source dev="/dev/loop0" />
  1462. <target dev="xvdj" />
  1463. <backenddomain name="backend1" />
  1464. </disk>
  1465. <!-- server_ip is the address of stubdomain. It hosts it's own DNS server. -->
  1466. <emulator type="stubdom-linux" />
  1467. <input type="tablet" bus="usb"/>
  1468. <video>
  1469. <model type="vga"/>
  1470. </video>
  1471. <graphics type="qubes"/>
  1472. <console type="pty">
  1473. <target type="xen" port="0"/>
  1474. </console>
  1475. </devices>
  1476. </domain>
  1477. '''
  1478. my_uuid = '7db78950-c467-4863-94d1-af59806384ea'
  1479. vm = self.get_vm(uuid=my_uuid)
  1480. vm.netvm = None
  1481. vm.virt_mode = 'hvm'
  1482. vm.volumes['root'] = unittest.mock.Mock(**{
  1483. 'block_device.return_value.name': 'root',
  1484. 'block_device.return_value.path': '/dev/loop0',
  1485. 'block_device.return_value.devtype': 'disk',
  1486. 'block_device.return_value.domain': 'dom0',
  1487. 'block_device.return_value.script': '/tmp/script',
  1488. })
  1489. vm.volumes['other'] = unittest.mock.Mock(**{
  1490. 'block_device.return_value.name': 'other',
  1491. 'block_device.return_value.path': '/dev/loop1',
  1492. 'block_device.return_value.devtype': 'disk',
  1493. 'block_device.return_value.domain': 'dom0',
  1494. 'block_device.return_value.script': None,
  1495. })
  1496. vm.volumes['other2'] = unittest.mock.Mock(**{
  1497. 'block_device.return_value.name': 'other',
  1498. 'block_device.return_value.path': '/dev/loop2',
  1499. 'block_device.return_value.devtype': 'disk',
  1500. 'block_device.return_value.domain': 'dom0',
  1501. 'block_device.return_value.script': None,
  1502. })
  1503. assignments = [
  1504. unittest.mock.Mock(**{
  1505. 'options': {'frontend-dev': 'xvdl'},
  1506. 'device.device_node': '/dev/sdb',
  1507. 'device.backend_domain.name': 'dom0',
  1508. }),
  1509. unittest.mock.Mock(**{
  1510. 'options': {'devtype': 'cdrom'},
  1511. 'device.device_node': '/dev/sda',
  1512. 'device.backend_domain.name': 'dom0',
  1513. }),
  1514. unittest.mock.Mock(**{
  1515. 'options': {'read-only': True},
  1516. 'device.device_node': '/dev/loop0',
  1517. 'device.backend_domain.name': 'backend0',
  1518. }),
  1519. unittest.mock.Mock(**{
  1520. 'options': {},
  1521. 'device.device_node': '/dev/loop0',
  1522. 'device.backend_domain.name': 'backend1',
  1523. }),
  1524. ]
  1525. vm.devices['block'].assignments = lambda persistent: assignments
  1526. libvirt_xml = vm.create_config_file()
  1527. self.assertXMLEqual(lxml.etree.XML(libvirt_xml),
  1528. lxml.etree.XML(expected))
  1529. @unittest.mock.patch('qubes.utils.get_timezone')
  1530. @unittest.mock.patch('qubes.utils.urandom')
  1531. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.untrusted_qdb')
  1532. def test_620_qdb_standalone(self, mock_qubesdb, mock_urandom,
  1533. mock_timezone):
  1534. mock_urandom.return_value = b'A' * 64
  1535. mock_timezone.return_value = 'UTC'
  1536. vm = self.get_vm(cls=qubes.vm.standalonevm.StandaloneVM)
  1537. vm.netvm = None
  1538. vm.events_enabled = True
  1539. test_qubesdb = TestQubesDB()
  1540. mock_qubesdb.write.side_effect = test_qubesdb.write
  1541. mock_qubesdb.rm.side_effect = test_qubesdb.rm
  1542. vm.create_qdb_entries()
  1543. self.maxDiff = None
  1544. iptables_header = (
  1545. '# Generated by Qubes Core on {}\n'
  1546. '*filter\n'
  1547. ':INPUT DROP [0:0]\n'
  1548. ':FORWARD DROP [0:0]\n'
  1549. ':OUTPUT ACCEPT [0:0]\n'
  1550. '-A INPUT -i vif+ -p udp -m udp --dport 68 -j DROP\n'
  1551. '-A INPUT -m conntrack --ctstate '
  1552. 'RELATED,ESTABLISHED -j ACCEPT\n'
  1553. '-A INPUT -p icmp -j ACCEPT\n'
  1554. '-A INPUT -i lo -j ACCEPT\n'
  1555. '-A INPUT -j REJECT --reject-with '
  1556. 'icmp-host-prohibited\n'
  1557. '-A FORWARD -m conntrack --ctstate '
  1558. 'RELATED,ESTABLISHED -j ACCEPT\n'
  1559. '-A FORWARD -i vif+ -o vif+ -j DROP\n'
  1560. 'COMMIT\n'.format(datetime.datetime.now().ctime()))
  1561. self.assertEqual(test_qubesdb.data, {
  1562. '/name': 'test-inst-test',
  1563. '/type': 'StandaloneVM',
  1564. '/default-user': 'user',
  1565. '/qubes-vm-type': 'AppVM',
  1566. '/qubes-debug-mode': '0',
  1567. '/qubes-base-template': '',
  1568. '/qubes-timezone': 'UTC',
  1569. '/qubes-random-seed': base64.b64encode(b'A' * 64),
  1570. '/qubes-vm-persistence': 'full',
  1571. '/qubes-vm-updateable': 'True',
  1572. '/qubes-block-devices': '',
  1573. '/qubes-usb-devices': '',
  1574. '/qubes-iptables': 'reload',
  1575. '/qubes-iptables-error': '',
  1576. '/qubes-iptables-header': iptables_header,
  1577. '/qubes-service/qubes-update-check': '0',
  1578. '/qubes-service/meminfo-writer': '1',
  1579. '/connected-ips': '',
  1580. '/connected-ips6': '',
  1581. })
  1582. @unittest.mock.patch('datetime.datetime')
  1583. @unittest.mock.patch('qubes.utils.get_timezone')
  1584. @unittest.mock.patch('qubes.utils.urandom')
  1585. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.untrusted_qdb')
  1586. def test_621_qdb_vm_with_network(self, mock_qubesdb, mock_urandom,
  1587. mock_timezone, mock_datetime):
  1588. mock_urandom.return_value = b'A' * 64
  1589. mock_timezone.return_value = 'UTC'
  1590. template = self.get_vm(cls=qubes.vm.templatevm.TemplateVM, name='template')
  1591. template.netvm = None
  1592. netvm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1593. name='netvm', qid=2, provides_network=True)
  1594. vm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1595. name='appvm', qid=3)
  1596. vm.netvm = netvm
  1597. vm.kernel = None
  1598. # pretend the VM is running...
  1599. vm._qubesprop_xid = 3
  1600. netvm.kernel = None
  1601. test_qubesdb = TestQubesDB()
  1602. mock_qubesdb.write.side_effect = test_qubesdb.write
  1603. mock_qubesdb.rm.side_effect = test_qubesdb.rm
  1604. self.maxDiff = None
  1605. mock_datetime.now.returnvalue = \
  1606. datetime.datetime(2019, 2, 27, 15, 12, 15, 385822)
  1607. iptables_header = (
  1608. '# Generated by Qubes Core on {}\n'
  1609. '*filter\n'
  1610. ':INPUT DROP [0:0]\n'
  1611. ':FORWARD DROP [0:0]\n'
  1612. ':OUTPUT ACCEPT [0:0]\n'
  1613. '-A INPUT -i vif+ -p udp -m udp --dport 68 -j DROP\n'
  1614. '-A INPUT -m conntrack --ctstate '
  1615. 'RELATED,ESTABLISHED -j ACCEPT\n'
  1616. '-A INPUT -p icmp -j ACCEPT\n'
  1617. '-A INPUT -i lo -j ACCEPT\n'
  1618. '-A INPUT -j REJECT --reject-with '
  1619. 'icmp-host-prohibited\n'
  1620. '-A FORWARD -m conntrack --ctstate '
  1621. 'RELATED,ESTABLISHED -j ACCEPT\n'
  1622. '-A FORWARD -i vif+ -o vif+ -j DROP\n'
  1623. 'COMMIT\n'.format(datetime.datetime.now().ctime()))
  1624. expected = {
  1625. '/name': 'test-inst-appvm',
  1626. '/type': 'AppVM',
  1627. '/default-user': 'user',
  1628. '/qubes-vm-type': 'AppVM',
  1629. '/qubes-debug-mode': '0',
  1630. '/qubes-base-template': 'test-inst-template',
  1631. '/qubes-timezone': 'UTC',
  1632. '/qubes-random-seed': base64.b64encode(b'A' * 64),
  1633. '/qubes-vm-persistence': 'rw-only',
  1634. '/qubes-vm-updateable': 'False',
  1635. '/qubes-block-devices': '',
  1636. '/qubes-usb-devices': '',
  1637. '/qubes-iptables': 'reload',
  1638. '/qubes-iptables-error': '',
  1639. '/qubes-iptables-header': iptables_header,
  1640. '/qubes-service/qubes-update-check': '0',
  1641. '/qubes-service/meminfo-writer': '1',
  1642. '/qubes-mac': '00:16:3e:5e:6c:00',
  1643. '/qubes-ip': '10.137.0.3',
  1644. '/qubes-netmask': '255.255.255.255',
  1645. '/qubes-gateway': '10.137.0.2',
  1646. '/qubes-primary-dns': '10.139.1.1',
  1647. '/qubes-secondary-dns': '10.139.1.2',
  1648. '/connected-ips': '',
  1649. '/connected-ips6': '',
  1650. }
  1651. with self.subTest('ipv4'):
  1652. vm.create_qdb_entries()
  1653. self.assertEqual(test_qubesdb.data, expected)
  1654. test_qubesdb.data.clear()
  1655. with self.subTest('ipv6'):
  1656. netvm.features['ipv6'] = True
  1657. expected['/qubes-ip6'] = \
  1658. qubes.config.qubes_ipv6_prefix.replace(':0000', '') + \
  1659. '::a89:3'
  1660. expected['/qubes-gateway6'] = expected['/qubes-ip6'][:-1] + '2'
  1661. vm.create_qdb_entries()
  1662. self.assertEqual(test_qubesdb.data, expected)
  1663. test_qubesdb.data.clear()
  1664. with self.subTest('ipv6_just_appvm'):
  1665. del netvm.features['ipv6']
  1666. vm.features['ipv6'] = True
  1667. expected['/qubes-ip6'] = \
  1668. qubes.config.qubes_ipv6_prefix.replace(':0000', '') + \
  1669. '::a89:3'
  1670. del expected['/qubes-gateway6']
  1671. vm.create_qdb_entries()
  1672. self.assertEqual(test_qubesdb.data, expected)
  1673. test_qubesdb.data.clear()
  1674. with self.subTest('proxy_ipv4'):
  1675. del vm.features['ipv6']
  1676. expected['/name'] = 'test-inst-netvm'
  1677. expected['/qubes-vm-type'] = 'NetVM'
  1678. del expected['/qubes-ip']
  1679. del expected['/qubes-gateway']
  1680. del expected['/qubes-netmask']
  1681. del expected['/qubes-ip6']
  1682. del expected['/qubes-primary-dns']
  1683. del expected['/qubes-secondary-dns']
  1684. del expected['/qubes-mac']
  1685. expected['/qubes-netvm-primary-dns'] = '10.139.1.1'
  1686. expected['/qubes-netvm-secondary-dns'] = '10.139.1.2'
  1687. expected['/qubes-netvm-network'] = '10.137.0.2'
  1688. expected['/qubes-netvm-gateway'] = '10.137.0.2'
  1689. expected['/qubes-netvm-netmask'] = '255.255.255.255'
  1690. expected['/qubes-iptables-domainrules/3'] = \
  1691. '*filter\n' \
  1692. '-A FORWARD -s 10.137.0.3 -j ACCEPT\n' \
  1693. '-A FORWARD -s 10.137.0.3 -j DROP\n' \
  1694. 'COMMIT\n'
  1695. expected['/mapped-ip/10.137.0.3/visible-ip'] = '10.137.0.3'
  1696. expected['/mapped-ip/10.137.0.3/visible-gateway'] = '10.137.0.2'
  1697. expected['/qubes-firewall/10.137.0.3'] = ''
  1698. expected['/qubes-firewall/10.137.0.3/0000'] = 'action=accept'
  1699. expected['/qubes-firewall/10.137.0.3/policy'] = 'drop'
  1700. expected['/connected-ips'] = '10.137.0.3'
  1701. with unittest.mock.patch('qubes.vm.qubesvm.QubesVM.is_running',
  1702. lambda _: True):
  1703. netvm.create_qdb_entries()
  1704. self.assertEqual(test_qubesdb.data, expected)
  1705. test_qubesdb.data.clear()
  1706. with self.subTest('proxy_ipv6'):
  1707. netvm.features['ipv6'] = True
  1708. ip6 = qubes.config.qubes_ipv6_prefix.replace(
  1709. ':0000', '') + '::a89:3'
  1710. expected['/qubes-netvm-gateway6'] = ip6[:-1] + '2'
  1711. expected['/qubes-firewall/' + ip6] = ''
  1712. expected['/qubes-firewall/' + ip6 + '/0000'] = 'action=accept'
  1713. expected['/qubes-firewall/' + ip6 + '/policy'] = 'drop'
  1714. expected['/connected-ips6'] = ip6
  1715. with unittest.mock.patch('qubes.vm.qubesvm.QubesVM.is_running',
  1716. lambda _: True):
  1717. netvm.create_qdb_entries()
  1718. self.assertEqual(test_qubesdb.data, expected)
  1719. @unittest.mock.patch('qubes.utils.get_timezone')
  1720. @unittest.mock.patch('qubes.utils.urandom')
  1721. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.untrusted_qdb')
  1722. def test_622_qdb_guivm_keyboard_layout(self, mock_qubesdb, mock_urandom,
  1723. mock_timezone):
  1724. mock_urandom.return_value = b'A' * 64
  1725. mock_timezone.return_value = 'UTC'
  1726. template = self.get_vm(
  1727. cls=qubes.vm.templatevm.TemplateVM, name='template')
  1728. template.netvm = None
  1729. guivm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1730. name='sys-gui', qid=2, provides_network=False)
  1731. vm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1732. name='appvm', qid=3)
  1733. vm.netvm = None
  1734. vm.guivm = guivm
  1735. guivm.features['keyboard-layout'] = 'fr++'
  1736. guivm.is_running = lambda: True
  1737. vm.events_enabled = True
  1738. test_qubesdb = TestQubesDB()
  1739. mock_qubesdb.write.side_effect = test_qubesdb.write
  1740. mock_qubesdb.rm.side_effect = test_qubesdb.rm
  1741. vm.create_qdb_entries()
  1742. self.maxDiff = None
  1743. self.assertEqual(test_qubesdb.data, {
  1744. '/name': 'test-inst-appvm',
  1745. '/type': 'AppVM',
  1746. '/default-user': 'user',
  1747. '/keyboard-layout': 'fr++',
  1748. '/qubes-vm-type': 'AppVM',
  1749. '/qubes-gui-domain-xid': '{}'.format(guivm.xid),
  1750. '/qubes-debug-mode': '0',
  1751. '/qubes-base-template': 'test-inst-template',
  1752. '/qubes-timezone': 'UTC',
  1753. '/qubes-random-seed': base64.b64encode(b'A' * 64),
  1754. '/qubes-vm-persistence': 'rw-only',
  1755. '/qubes-vm-updateable': 'False',
  1756. '/qubes-block-devices': '',
  1757. '/qubes-usb-devices': '',
  1758. '/qubes-iptables': 'reload',
  1759. '/qubes-iptables-error': '',
  1760. '/qubes-iptables-header': unittest.mock.ANY,
  1761. '/qubes-service/qubes-update-check': '0',
  1762. '/qubes-service/meminfo-writer': '1',
  1763. '/connected-ips': '',
  1764. '/connected-ips6': '',
  1765. })
  1766. @unittest.mock.patch('qubes.utils.get_timezone')
  1767. @unittest.mock.patch('qubes.utils.urandom')
  1768. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.untrusted_qdb')
  1769. def test_623_qdb_audiovm(self, mock_qubesdb, mock_urandom,
  1770. mock_timezone):
  1771. mock_urandom.return_value = b'A' * 64
  1772. mock_timezone.return_value = 'UTC'
  1773. template = self.get_vm(
  1774. cls=qubes.vm.templatevm.TemplateVM, name='template')
  1775. template.netvm = None
  1776. audiovm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1777. name='sys-audio', qid=2, provides_network=False)
  1778. vm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1779. name='appvm', qid=3)
  1780. vm.netvm = None
  1781. vm.audiovm = audiovm
  1782. audiovm.is_running = lambda: True
  1783. vm.events_enabled = True
  1784. test_qubesdb = TestQubesDB()
  1785. mock_qubesdb.write.side_effect = test_qubesdb.write
  1786. mock_qubesdb.rm.side_effect = test_qubesdb.rm
  1787. vm.create_qdb_entries()
  1788. self.maxDiff = None
  1789. self.assertEqual(test_qubesdb.data, {
  1790. '/name': 'test-inst-appvm',
  1791. '/type': 'AppVM',
  1792. '/default-user': 'user',
  1793. '/qubes-vm-type': 'AppVM',
  1794. '/qubes-audio-domain-xid': '{}'.format(audiovm.xid),
  1795. '/qubes-debug-mode': '0',
  1796. '/qubes-base-template': 'test-inst-template',
  1797. '/qubes-timezone': 'UTC',
  1798. '/qubes-random-seed': base64.b64encode(b'A' * 64),
  1799. '/qubes-vm-persistence': 'rw-only',
  1800. '/qubes-vm-updateable': 'False',
  1801. '/qubes-block-devices': '',
  1802. '/qubes-usb-devices': '',
  1803. '/qubes-iptables': 'reload',
  1804. '/qubes-iptables-error': '',
  1805. '/qubes-iptables-header': unittest.mock.ANY,
  1806. '/qubes-service/qubes-update-check': '0',
  1807. '/qubes-service/meminfo-writer': '1',
  1808. '/connected-ips': '',
  1809. '/connected-ips6': '',
  1810. })
  1811. @unittest.mock.patch('qubes.utils.get_timezone')
  1812. @unittest.mock.patch('qubes.utils.urandom')
  1813. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.untrusted_qdb')
  1814. def test_624_qdb_guivm_invalid_keyboard_layout(self, mock_qubesdb,
  1815. mock_urandom, mock_timezone):
  1816. mock_urandom.return_value = b'A' * 64
  1817. mock_timezone.return_value = 'UTC'
  1818. template = self.get_vm(
  1819. cls=qubes.vm.templatevm.TemplateVM, name='template')
  1820. guivm = self.get_vm(cls=qubes.vm.appvm.AppVM, template=template,
  1821. name='sys-gui', qid=2, provides_network=False)
  1822. guivm.is_running = lambda: True
  1823. guivm.events_enabled = True
  1824. with self.assertRaises(qubes.exc.QubesValueError):
  1825. guivm.features['keyboard-layout'] = 'fr123++'
  1826. @asyncio.coroutine
  1827. def coroutine_mock(self, mock, *args, **kwargs):
  1828. return mock(*args, **kwargs)
  1829. @unittest.mock.patch('asyncio.create_subprocess_exec')
  1830. def test_700_run_service(self, mock_subprocess):
  1831. func_mock = unittest.mock.Mock()
  1832. mock_subprocess.side_effect = functools.partial(
  1833. self.coroutine_mock, func_mock)
  1834. start_mock = unittest.mock.Mock()
  1835. vm = self.get_vm(cls=qubes.vm.standalonevm.StandaloneVM,
  1836. name='vm')
  1837. vm.is_running = lambda: True
  1838. vm.is_qrexec_running = lambda: True
  1839. vm.start = functools.partial(self.coroutine_mock, start_mock)
  1840. with self.subTest('running'):
  1841. self.loop.run_until_complete(vm.run_service('test.service'))
  1842. func_mock.assert_called_once_with(
  1843. '/usr/bin/qrexec-client', '-d', 'test-inst-vm',
  1844. 'user:QUBESRPC test.service dom0')
  1845. self.assertFalse(start_mock.called)
  1846. func_mock.reset_mock()
  1847. start_mock.reset_mock()
  1848. with self.subTest('not_running'):
  1849. vm.is_running = lambda: False
  1850. with self.assertRaises(qubes.exc.QubesVMNotRunningError):
  1851. self.loop.run_until_complete(vm.run_service('test.service'))
  1852. self.assertFalse(func_mock.called)
  1853. func_mock.reset_mock()
  1854. start_mock.reset_mock()
  1855. with self.subTest('autostart'):
  1856. vm.is_running = lambda: False
  1857. self.loop.run_until_complete(vm.run_service(
  1858. 'test.service', autostart=True))
  1859. func_mock.assert_called_once_with(
  1860. '/usr/bin/qrexec-client', '-d', 'test-inst-vm',
  1861. 'user:QUBESRPC test.service dom0')
  1862. self.assertTrue(start_mock.called)
  1863. func_mock.reset_mock()
  1864. start_mock.reset_mock()
  1865. with self.subTest('no_qrexec'):
  1866. vm.is_running = lambda: True
  1867. vm.is_qrexec_running = lambda: False
  1868. with self.assertRaises(qubes.exc.QubesVMError):
  1869. self.loop.run_until_complete(vm.run_service('test.service'))
  1870. self.assertFalse(start_mock.called)
  1871. self.assertFalse(func_mock.called)
  1872. func_mock.reset_mock()
  1873. start_mock.reset_mock()
  1874. with self.subTest('other_user'):
  1875. vm.is_running = lambda: True
  1876. vm.is_qrexec_running = lambda: True
  1877. self.loop.run_until_complete(vm.run_service('test.service',
  1878. user='other'))
  1879. func_mock.assert_called_once_with(
  1880. '/usr/bin/qrexec-client', '-d', 'test-inst-vm',
  1881. 'other:QUBESRPC test.service dom0')
  1882. self.assertFalse(start_mock.called)
  1883. func_mock.reset_mock()
  1884. start_mock.reset_mock()
  1885. with self.subTest('other_source'):
  1886. vm.is_running = lambda: True
  1887. vm.is_qrexec_running = lambda: True
  1888. self.loop.run_until_complete(vm.run_service('test.service',
  1889. source='test-inst-vm'))
  1890. func_mock.assert_called_once_with(
  1891. '/usr/bin/qrexec-client', '-d', 'test-inst-vm',
  1892. 'user:QUBESRPC test.service test-inst-vm')
  1893. self.assertFalse(start_mock.called)
  1894. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.run')
  1895. def test_710_run_for_stdio(self, mock_run):
  1896. vm = self.get_vm(cls=qubes.vm.standalonevm.StandaloneVM,
  1897. name='vm')
  1898. func_mock = unittest.mock.Mock()
  1899. mock_run.side_effect = functools.partial(
  1900. self.coroutine_mock, func_mock)
  1901. communicate_mock = unittest.mock.Mock()
  1902. func_mock.return_value.communicate.side_effect = functools.partial(
  1903. self.coroutine_mock, communicate_mock)
  1904. communicate_mock.return_value = (b'stdout', b'stderr')
  1905. func_mock.return_value.returncode = 0
  1906. with self.subTest('default'):
  1907. value = self.loop.run_until_complete(
  1908. vm.run_for_stdio('cat'))
  1909. func_mock.assert_called_once_with(
  1910. 'cat',
  1911. stdout=subprocess.PIPE,
  1912. stderr=subprocess.PIPE,
  1913. stdin=subprocess.PIPE)
  1914. communicate_mock.assert_called_once_with(input=b'')
  1915. self.assertEqual(value, (b'stdout', b'stderr'))
  1916. func_mock.reset_mock()
  1917. communicate_mock.reset_mock()
  1918. with self.subTest('with_input'):
  1919. value = self.loop.run_until_complete(
  1920. vm.run_for_stdio('cat', input=b'abc'))
  1921. func_mock.assert_called_once_with(
  1922. 'cat',
  1923. stdout=subprocess.PIPE,
  1924. stderr=subprocess.PIPE,
  1925. stdin=subprocess.PIPE)
  1926. communicate_mock.assert_called_once_with(input=b'abc')
  1927. self.assertEqual(value, (b'stdout', b'stderr'))
  1928. func_mock.reset_mock()
  1929. communicate_mock.reset_mock()
  1930. with self.subTest('error'):
  1931. func_mock.return_value.returncode = 1
  1932. with self.assertRaises(subprocess.CalledProcessError) as exc:
  1933. self.loop.run_until_complete(
  1934. vm.run_for_stdio('cat'))
  1935. func_mock.assert_called_once_with(
  1936. 'cat',
  1937. stdout=subprocess.PIPE,
  1938. stderr=subprocess.PIPE,
  1939. stdin=subprocess.PIPE)
  1940. communicate_mock.assert_called_once_with(input=b'')
  1941. self.assertEqual(exc.exception.returncode, 1)
  1942. self.assertEqual(exc.exception.output, b'stdout')
  1943. self.assertEqual(exc.exception.stderr, b'stderr')
  1944. @unittest.mock.patch('qubes.vm.qubesvm.QubesVM.run_service')
  1945. def test_711_run_service_for_stdio(self, mock_run_service):
  1946. vm = self.get_vm(cls=qubes.vm.standalonevm.StandaloneVM,
  1947. name='vm')
  1948. func_mock = unittest.mock.Mock()
  1949. mock_run_service.side_effect = functools.partial(
  1950. self.coroutine_mock, func_mock)
  1951. communicate_mock = unittest.mock.Mock()
  1952. func_mock.return_value.communicate.side_effect = functools.partial(
  1953. self.coroutine_mock, communicate_mock)
  1954. communicate_mock.return_value = (b'stdout', b'stderr')
  1955. func_mock.return_value.returncode = 0
  1956. with self.subTest('default'):
  1957. value = self.loop.run_until_complete(
  1958. vm.run_service_for_stdio('test.service'))
  1959. func_mock.assert_called_once_with(
  1960. 'test.service',
  1961. stdout=subprocess.PIPE,
  1962. stderr=subprocess.PIPE,
  1963. stdin=subprocess.PIPE)
  1964. communicate_mock.assert_called_once_with(input=b'')
  1965. self.assertEqual(value, (b'stdout', b'stderr'))
  1966. func_mock.reset_mock()
  1967. communicate_mock.reset_mock()
  1968. with self.subTest('with_input'):
  1969. value = self.loop.run_until_complete(
  1970. vm.run_service_for_stdio('test.service', input=b'abc'))
  1971. func_mock.assert_called_once_with(
  1972. 'test.service',
  1973. stdout=subprocess.PIPE,
  1974. stderr=subprocess.PIPE,
  1975. stdin=subprocess.PIPE)
  1976. communicate_mock.assert_called_once_with(input=b'abc')
  1977. self.assertEqual(value, (b'stdout', b'stderr'))
  1978. func_mock.reset_mock()
  1979. communicate_mock.reset_mock()
  1980. with self.subTest('error'):
  1981. func_mock.return_value.returncode = 1
  1982. with self.assertRaises(subprocess.CalledProcessError) as exc:
  1983. self.loop.run_until_complete(
  1984. vm.run_service_for_stdio('test.service'))
  1985. func_mock.assert_called_once_with(
  1986. 'test.service',
  1987. stdout=subprocess.PIPE,
  1988. stderr=subprocess.PIPE,
  1989. stdin=subprocess.PIPE)
  1990. communicate_mock.assert_called_once_with(input=b'')
  1991. self.assertEqual(exc.exception.returncode, 1)
  1992. self.assertEqual(exc.exception.output, b'stdout')
  1993. self.assertEqual(exc.exception.stderr, b'stderr')
  1994. @unittest.mock.patch('os.path.exists')
  1995. def test_720_is_fully_usable(self, mock_os_path_exists):
  1996. vm_name = 'workvm'
  1997. qrexec_file_name = '/var/run/qubes/qrexec.{}'.format(
  1998. 'test-inst-{}'.format(vm_name))
  1999. vm = self.get_vm(cls=qubes.vm.appvm.AppVM, name=vm_name)
  2000. # Dummy xid; greater than 0 to indicate a running AppVM
  2001. vm._qubesprop_xid = 10
  2002. self.assertGreater(vm.xid, 0)
  2003. with self.subTest('with_qrexec_started'):
  2004. mock_os_path_exists.return_value = True
  2005. vm.features['qrexec'] = True
  2006. fully_usable = vm.is_fully_usable()
  2007. mock_os_path_exists.assert_called_once_with(qrexec_file_name)
  2008. self.assertEqual(fully_usable, True)
  2009. mock_os_path_exists.reset_mock()
  2010. with self.subTest('with_qrexec_error'):
  2011. mock_os_path_exists.return_value = False
  2012. vm.features['qrexec'] = True
  2013. fully_usable = vm.is_fully_usable()
  2014. mock_os_path_exists.assert_called_once_with(qrexec_file_name)
  2015. self.assertEqual(fully_usable, False)
  2016. mock_os_path_exists.reset_mock()
  2017. with self.subTest('without_qrexec'):
  2018. vm.features['qrexec'] = False
  2019. fully_usable = vm.is_fully_usable()
  2020. mock_os_path_exists.assert_not_called()
  2021. self.assertEqual(fully_usable, True)