app.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. # pylint: disable=protected-access,pointless-statement
  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 os
  22. import unittest.mock as mock
  23. import lxml.etree
  24. import qubes
  25. import qubes.events
  26. import qubes.tests
  27. import qubes.tests.init
  28. import qubes.tests.storage_reflink
  29. class TestApp(qubes.tests.TestEmitter):
  30. pass
  31. class TC_20_QubesHost(qubes.tests.QubesTestCase):
  32. sample_xc_domain_getinfo = [
  33. {'paused': 0, 'cpu_time': 243951379111104, 'ssidref': 0,
  34. 'hvm': 0, 'shutdown_reason': 255, 'dying': 0,
  35. 'mem_kb': 3733212, 'domid': 0, 'max_vcpu_id': 7,
  36. 'crashed': 0, 'running': 1, 'maxmem_kb': 3734236,
  37. 'shutdown': 0, 'online_vcpus': 8,
  38. 'handle': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  39. 'cpupool': 0, 'blocked': 0},
  40. {'paused': 0, 'cpu_time': 2849496569205, 'ssidref': 0,
  41. 'hvm': 0, 'shutdown_reason': 255, 'dying': 0,
  42. 'mem_kb': 303916, 'domid': 1, 'max_vcpu_id': 0,
  43. 'crashed': 0, 'running': 0, 'maxmem_kb': 308224,
  44. 'shutdown': 0, 'online_vcpus': 1,
  45. 'handle': [116, 174, 229, 207, 17, 1, 79, 39, 191, 37, 41,
  46. 186, 205, 158, 219, 8],
  47. 'cpupool': 0, 'blocked': 1},
  48. {'paused': 0, 'cpu_time': 249658663079978, 'ssidref': 0,
  49. 'hvm': 0, 'shutdown_reason': 255, 'dying': 0,
  50. 'mem_kb': 3782668, 'domid': 11, 'max_vcpu_id': 7,
  51. 'crashed': 0, 'running': 0, 'maxmem_kb': 3783692,
  52. 'shutdown': 0, 'online_vcpus': 8,
  53. 'handle': [169, 95, 55, 127, 140, 94, 79, 220, 186, 210,
  54. 117, 5, 148, 11, 185, 206],
  55. 'cpupool': 0, 'blocked': 1}]
  56. def setUp(self):
  57. super(TC_20_QubesHost, self).setUp()
  58. self.app = TestApp()
  59. self.app.vmm = mock.Mock()
  60. self.qubes_host = qubes.app.QubesHost(self.app)
  61. def test_000_get_vm_stats_single(self):
  62. self.app.vmm.configure_mock(**{
  63. 'xc.domain_getinfo.return_value': self.sample_xc_domain_getinfo
  64. })
  65. info_time, info = self.qubes_host.get_vm_stats()
  66. self.assertEqual(self.app.vmm.mock_calls, [
  67. ('xc.domain_getinfo', (0, 1024), {}),
  68. ])
  69. self.assertIsNotNone(info_time)
  70. expected_info = {
  71. 0: {
  72. 'cpu_time': 243951379111104//8,
  73. 'cpu_usage': 0,
  74. 'memory_kb': 3733212,
  75. },
  76. 1: {
  77. 'cpu_time': 2849496569205,
  78. 'cpu_usage': 0,
  79. 'memory_kb': 303916,
  80. },
  81. 11: {
  82. 'cpu_time': 249658663079978//8,
  83. 'cpu_usage': 0,
  84. 'memory_kb': 3782668,
  85. },
  86. }
  87. self.assertEqual(info, expected_info)
  88. def test_001_get_vm_stats_twice(self):
  89. self.app.vmm.configure_mock(**{
  90. 'xc.domain_getinfo.return_value': self.sample_xc_domain_getinfo
  91. })
  92. prev_time, prev_info = self.qubes_host.get_vm_stats()
  93. prev_time -= 1
  94. prev_info[0]['cpu_time'] -= 10**8
  95. prev_info[1]['cpu_time'] -= 10**9
  96. prev_info[11]['cpu_time'] -= 125 * 10**6
  97. info_time, info = self.qubes_host.get_vm_stats(prev_time, prev_info)
  98. self.assertIsNotNone(info_time)
  99. expected_info = {
  100. 0: {
  101. 'cpu_time': 243951379111104//8,
  102. 'cpu_usage': 9,
  103. 'memory_kb': 3733212,
  104. },
  105. 1: {
  106. 'cpu_time': 2849496569205,
  107. 'cpu_usage': 99,
  108. 'memory_kb': 303916,
  109. },
  110. 11: {
  111. 'cpu_time': 249658663079978//8,
  112. 'cpu_usage': 12,
  113. 'memory_kb': 3782668,
  114. },
  115. }
  116. self.assertEqual(info, expected_info)
  117. self.assertEqual(self.app.vmm.mock_calls, [
  118. ('xc.domain_getinfo', (0, 1024), {}),
  119. ('xc.domain_getinfo', (0, 1024), {}),
  120. ])
  121. def test_002_get_vm_stats_one_vm(self):
  122. self.app.vmm.configure_mock(**{
  123. 'xc.domain_getinfo.return_value': [self.sample_xc_domain_getinfo[1]]
  124. })
  125. vm = mock.Mock
  126. vm.xid = 1
  127. vm.name = 'somevm'
  128. info_time, info = self.qubes_host.get_vm_stats(only_vm=vm)
  129. self.assertIsNotNone(info_time)
  130. self.assertEqual(self.app.vmm.mock_calls, [
  131. ('xc.domain_getinfo', (1, 1), {}),
  132. ])
  133. class TC_30_VMCollection(qubes.tests.QubesTestCase):
  134. def setUp(self):
  135. super().setUp()
  136. self.app = TestApp()
  137. self.vms = qubes.app.VMCollection(self.app)
  138. self.testvm1 = qubes.tests.init.TestVM(
  139. None, None, qid=1, name='testvm1')
  140. self.testvm2 = qubes.tests.init.TestVM(
  141. None, None, qid=2, name='testvm2')
  142. self.addCleanup(self.cleanup_vmcollection)
  143. def cleanup_vmcollection(self):
  144. self.testvm1.close()
  145. self.testvm2.close()
  146. self.vms.close()
  147. del self.testvm1
  148. del self.testvm2
  149. del self.vms
  150. del self.app
  151. def test_000_contains(self):
  152. self.vms._dict = {1: self.testvm1}
  153. self.assertIn(1, self.vms)
  154. self.assertIn('testvm1', self.vms)
  155. self.assertIn(self.testvm1, self.vms)
  156. self.assertNotIn(2, self.vms)
  157. self.assertNotIn('testvm2', self.vms)
  158. self.assertNotIn(self.testvm2, self.vms)
  159. def test_001_getitem(self):
  160. self.vms._dict = {1: self.testvm1}
  161. self.assertIs(self.vms[1], self.testvm1)
  162. self.assertIs(self.vms['testvm1'], self.testvm1)
  163. self.assertIs(self.vms[self.testvm1], self.testvm1)
  164. def test_002_add(self):
  165. self.vms.add(self.testvm1)
  166. self.assertIn(1, self.vms)
  167. self.assertEventFired(self.app, 'domain-add',
  168. kwargs={'vm': self.testvm1})
  169. with self.assertRaises(TypeError):
  170. self.vms.add(object())
  171. testvm_qid_collision = qubes.tests.init.TestVM(
  172. None, None, name='testvm2', qid=1)
  173. testvm_name_collision = qubes.tests.init.TestVM(
  174. None, None, name='testvm1', qid=2)
  175. with self.assertRaises(ValueError):
  176. self.vms.add(testvm_qid_collision)
  177. with self.assertRaises(ValueError):
  178. self.vms.add(testvm_name_collision)
  179. def test_003_qids(self):
  180. self.vms.add(self.testvm1)
  181. self.vms.add(self.testvm2)
  182. self.assertCountEqual(self.vms.qids(), [1, 2])
  183. self.assertCountEqual(self.vms.keys(), [1, 2])
  184. def test_004_names(self):
  185. self.vms.add(self.testvm1)
  186. self.vms.add(self.testvm2)
  187. self.assertCountEqual(self.vms.names(), ['testvm1', 'testvm2'])
  188. def test_005_vms(self):
  189. self.vms.add(self.testvm1)
  190. self.vms.add(self.testvm2)
  191. self.assertCountEqual(self.vms.vms(), [self.testvm1, self.testvm2])
  192. self.assertCountEqual(self.vms.values(), [self.testvm1, self.testvm2])
  193. def test_006_items(self):
  194. self.vms.add(self.testvm1)
  195. self.vms.add(self.testvm2)
  196. self.assertCountEqual(self.vms.items(),
  197. [(1, self.testvm1), (2, self.testvm2)])
  198. def test_007_len(self):
  199. self.vms.add(self.testvm1)
  200. self.vms.add(self.testvm2)
  201. self.assertEqual(len(self.vms), 2)
  202. def test_008_delitem(self):
  203. self.vms.add(self.testvm1)
  204. self.vms.add(self.testvm2)
  205. del self.vms['testvm2']
  206. self.assertCountEqual(self.vms.vms(), [self.testvm1])
  207. self.assertEventFired(self.app, 'domain-delete',
  208. kwargs={'vm': self.testvm2})
  209. def test_100_get_new_unused_qid(self):
  210. self.vms.add(self.testvm1)
  211. self.vms.add(self.testvm2)
  212. self.vms.get_new_unused_qid()
  213. # def test_200_get_vms_based_on(self):
  214. # pass
  215. # def test_201_get_vms_connected_to(self):
  216. # pass
  217. class TC_80_QubesInitialPools(qubes.tests.QubesTestCase):
  218. def setUp(self):
  219. super().setUp()
  220. self.app = qubes.Qubes('/tmp/qubestest.xml', load=False,
  221. offline_mode=True)
  222. self.test_dir = '/var/tmp/test-varlibqubes'
  223. self.test_patch = mock.patch.dict(
  224. qubes.config.defaults['pool_configs']['varlibqubes'],
  225. {'dir_path': self.test_dir})
  226. self.test_patch.start()
  227. def tearDown(self):
  228. self.test_patch.stop()
  229. self.app.close()
  230. del self.app
  231. def get_driver(self, fs_type, accessible):
  232. qubes.tests.storage_reflink.mkdir_fs(self.test_dir, fs_type,
  233. accessible=accessible, cleanup_via=self.addCleanup)
  234. self.app.load_initial_values()
  235. varlibqubes = self.app.pools['varlibqubes']
  236. self.assertEqual(varlibqubes.dir_path, self.test_dir)
  237. return varlibqubes.driver
  238. def test_100_varlibqubes_btrfs_accessible(self):
  239. self.assertEqual(self.get_driver('btrfs', True), 'file-reflink')
  240. def test_101_varlibqubes_btrfs_inaccessible(self):
  241. self.assertEqual(self.get_driver('btrfs', False), 'file')
  242. def test_102_varlibqubes_ext4_accessible(self):
  243. self.assertEqual(self.get_driver('ext4', True), 'file')
  244. def test_103_varlibqubes_ext4_inaccessible(self):
  245. self.assertEqual(self.get_driver('ext4', False), 'file')
  246. class TC_89_QubesEmpty(qubes.tests.QubesTestCase):
  247. def tearDown(self):
  248. try:
  249. os.unlink('/tmp/qubestest.xml')
  250. except:
  251. pass
  252. try:
  253. self.app.close()
  254. del self.app
  255. except AttributeError:
  256. pass
  257. super().tearDown()
  258. @qubes.tests.skipUnlessDom0
  259. def test_000_init_empty(self):
  260. # pylint: disable=no-self-use,unused-variable,bare-except
  261. try:
  262. os.unlink('/tmp/qubestest.xml')
  263. except FileNotFoundError:
  264. pass
  265. qubes.Qubes.create_empty_store('/tmp/qubestest.xml').close()
  266. def test_100_property_migrate_default_fw_netvm(self):
  267. xml_template = '''<?xml version="1.0" encoding="utf-8" ?>
  268. <qubes version="3.0">
  269. <properties>
  270. <property name="default_netvm">{default_netvm}</property>
  271. <property name="default_fw_netvm">{default_fw_netvm}</property>
  272. </properties>
  273. <labels>
  274. <label id="label-1" color="#cc0000">red</label>
  275. </labels>
  276. <pools>
  277. <pool driver="file" dir_path="/tmp/qubes-test" name="default"/>
  278. </pools>
  279. <domains>
  280. <domain class="StandaloneVM" id="domain-1">
  281. <properties>
  282. <property name="qid">1</property>
  283. <property name="name">sys-net</property>
  284. <property name="provides_network">True</property>
  285. <property name="label" ref="label-1" />
  286. <property name="netvm"></property>
  287. <property name="uuid">2fcfc1f4-b2fe-4361-931a-c5294b35edfa</property>
  288. </properties>
  289. <features/>
  290. <devices class="pci"/>
  291. </domain>
  292. <domain class="StandaloneVM" id="domain-2">
  293. <properties>
  294. <property name="qid">2</property>
  295. <property name="name">sys-firewall</property>
  296. <property name="provides_network">True</property>
  297. <property name="label" ref="label-1" />
  298. <property name="uuid">9a6d9689-25f7-48c9-a15f-8205d6c5b7c6</property>
  299. </properties>
  300. </domain>
  301. <domain class="StandaloneVM" id="domain-3">
  302. <properties>
  303. <property name="qid">3</property>
  304. <property name="name">appvm</property>
  305. <property name="label" ref="label-1" />
  306. <property name="uuid">1d6aab41-3262-400a-b3d3-21aae8fdbec8</property>
  307. </properties>
  308. </domain>
  309. </domains>
  310. </qubes>
  311. '''
  312. with self.subTest('default_setup'):
  313. with open('/tmp/qubestest.xml', 'w') as xml_file:
  314. xml_file.write(xml_template.format(
  315. default_netvm='sys-firewall',
  316. default_fw_netvm='sys-net'))
  317. self.app = qubes.Qubes('/tmp/qubestest.xml', offline_mode=True)
  318. self.assertEqual(
  319. self.app.domains['sys-net'].netvm, None)
  320. self.assertEqual(
  321. self.app.domains['sys-firewall'].netvm, self.app.domains['sys-net'])
  322. # property is no longer "default"
  323. self.assertFalse(
  324. self.app.domains['sys-firewall'].property_is_default('netvm'))
  325. # verify that appvm.netvm is unaffected
  326. self.assertTrue(
  327. self.app.domains['appvm'].property_is_default('netvm'))
  328. self.assertEqual(
  329. self.app.domains['appvm'].netvm,
  330. self.app.domains['sys-firewall'])
  331. with self.assertRaises(AttributeError):
  332. self.app.default_fw_netvm
  333. self.app.close()
  334. del self.app
  335. with self.subTest('same'):
  336. with open('/tmp/qubestest.xml', 'w') as xml_file:
  337. xml_file.write(xml_template.format(
  338. default_netvm='sys-net',
  339. default_fw_netvm='sys-net'))
  340. self.app = qubes.Qubes('/tmp/qubestest.xml', offline_mode=True)
  341. self.assertEqual(
  342. self.app.domains['sys-net'].netvm, None)
  343. self.assertEqual(
  344. self.app.domains['sys-firewall'].netvm,
  345. self.app.domains['sys-net'])
  346. self.assertTrue(
  347. self.app.domains['sys-firewall'].property_is_default('netvm'))
  348. # verify that appvm.netvm is unaffected
  349. self.assertTrue(
  350. self.app.domains['appvm'].property_is_default('netvm'))
  351. self.assertEqual(
  352. self.app.domains['appvm'].netvm,
  353. self.app.domains['sys-net'])
  354. with self.assertRaises(AttributeError):
  355. self.app.default_fw_netvm
  356. with self.subTest('loop'):
  357. with open('/tmp/qubestest.xml', 'w') as xml_file:
  358. xml_file.write(xml_template.format(
  359. default_netvm='sys-firewall',
  360. default_fw_netvm='sys-firewall'))
  361. self.app = qubes.Qubes('/tmp/qubestest.xml', offline_mode=True)
  362. self.assertEqual(
  363. self.app.domains['sys-net'].netvm, None)
  364. # this was netvm loop, better set to none, to not crash qubesd
  365. self.assertEqual(
  366. self.app.domains['sys-firewall'].netvm, None)
  367. self.assertFalse(
  368. self.app.domains['sys-firewall'].property_is_default('netvm'))
  369. # verify that appvm.netvm is unaffected
  370. self.assertTrue(
  371. self.app.domains['appvm'].property_is_default('netvm'))
  372. self.assertEqual(
  373. self.app.domains['appvm'].netvm,
  374. self.app.domains['sys-firewall'])
  375. with self.assertRaises(AttributeError):
  376. self.app.default_fw_netvm
  377. class TC_90_Qubes(qubes.tests.QubesTestCase):
  378. def tearDown(self):
  379. try:
  380. os.unlink('/tmp/qubestest.xml')
  381. except:
  382. pass
  383. super().tearDown()
  384. def setUp(self):
  385. super(TC_90_Qubes, self).setUp()
  386. self.app = qubes.Qubes('/tmp/qubestest.xml', load=False,
  387. offline_mode=True)
  388. self.addCleanup(self.cleanup_qubes)
  389. self.app.load_initial_values()
  390. self.template = self.app.add_new_vm('TemplateVM', name='test-template',
  391. label='green')
  392. def cleanup_qubes(self):
  393. self.app.close()
  394. del self.app
  395. try:
  396. del self.template
  397. except AttributeError:
  398. pass
  399. def test_100_clockvm(self):
  400. appvm = self.app.add_new_vm('AppVM', name='test-vm', template=self.template,
  401. label='red')
  402. self.assertIsNone(self.app.clockvm)
  403. self.assertNotIn('service.clocksync', appvm.features)
  404. self.assertNotIn('service.clocksync', self.template.features)
  405. self.app.clockvm = appvm
  406. self.assertIn('service.clocksync', appvm.features)
  407. self.assertTrue(appvm.features['service.clocksync'])
  408. self.app.clockvm = self.template
  409. self.assertNotIn('service.clocksync', appvm.features)
  410. self.assertIn('service.clocksync', self.template.features)
  411. self.assertTrue(self.template.features['service.clocksync'])
  412. def test_110_netvm_loop(self):
  413. '''Netvm loop through default_netvm'''
  414. netvm = self.app.add_new_vm('AppVM', name='test-net',
  415. template=self.template, label='red')
  416. try:
  417. self.app.default_netvm = None
  418. netvm.netvm = qubes.property.DEFAULT
  419. with self.assertRaises(ValueError):
  420. self.app.default_netvm = netvm
  421. finally:
  422. del netvm
  423. def test_111_netvm_loop(self):
  424. '''Netvm loop through default_netvm'''
  425. netvm = self.app.add_new_vm('AppVM', name='test-net',
  426. template=self.template, label='red')
  427. try:
  428. netvm.netvm = None
  429. self.app.default_netvm = netvm
  430. with self.assertRaises(ValueError):
  431. netvm.netvm = qubes.property.DEFAULT
  432. finally:
  433. del netvm
  434. def test_200_remove_template(self):
  435. appvm = self.app.add_new_vm('AppVM', name='test-vm',
  436. template=self.template,
  437. label='red')
  438. with mock.patch.object(self.app, 'vmm'):
  439. with self.assertRaises(qubes.exc.QubesException):
  440. del self.app.domains[self.template]
  441. def test_201_remove_netvm(self):
  442. netvm = self.app.add_new_vm('AppVM', name='test-netvm',
  443. template=self.template, provides_network=True,
  444. label='red')
  445. appvm = self.app.add_new_vm('AppVM', name='test-vm',
  446. template=self.template,
  447. label='red')
  448. appvm.netvm = netvm
  449. with mock.patch.object(self.app, 'vmm'):
  450. with self.assertRaises(qubes.exc.QubesVMInUseError):
  451. del self.app.domains[netvm]
  452. def test_202_remove_default_netvm(self):
  453. netvm = self.app.add_new_vm('AppVM', name='test-netvm',
  454. template=self.template, provides_network=True,
  455. label='red')
  456. netvm.netvm = None
  457. self.app.default_netvm = netvm
  458. with mock.patch.object(self.app, 'vmm'):
  459. with self.assertRaises(qubes.exc.QubesVMInUseError):
  460. del self.app.domains[netvm]
  461. def test_203_remove_default_dispvm(self):
  462. appvm = self.app.add_new_vm('AppVM', name='test-appvm',
  463. template=self.template,
  464. label='red')
  465. self.app.default_dispvm = appvm
  466. with mock.patch.object(self.app, 'vmm'):
  467. with self.assertRaises(qubes.exc.QubesVMInUseError):
  468. del self.app.domains[appvm]
  469. def test_204_remove_appvm_dispvm(self):
  470. dispvm = self.app.add_new_vm('AppVM', name='test-appvm',
  471. template=self.template,
  472. label='red')
  473. appvm = self.app.add_new_vm('AppVM', name='test-appvm2',
  474. template=self.template, default_dispvm=dispvm,
  475. label='red')
  476. with mock.patch.object(self.app, 'vmm'):
  477. with self.assertRaises(qubes.exc.QubesVMInUseError):
  478. del self.app.domains[dispvm]
  479. def test_205_remove_appvm_dispvm(self):
  480. appvm = self.app.add_new_vm('AppVM', name='test-appvm',
  481. template=self.template, template_for_dispvms=True,
  482. label='red')
  483. dispvm = self.app.add_new_vm('DispVM', name='test-dispvm',
  484. template=appvm,
  485. label='red')
  486. with mock.patch.object(self.app, 'vmm'):
  487. with self.assertRaises(qubes.exc.QubesVMInUseError):
  488. del self.app.domains[appvm]
  489. @qubes.tests.skipUnlessGit
  490. def test_900_example_xml_in_doc(self):
  491. self.assertXMLIsValid(
  492. lxml.etree.parse(open(
  493. os.path.join(qubes.tests.in_git, 'doc/example.xml'), 'rb')),
  494. 'qubes.rng')