app.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. # -*- encoding: utf8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU Lesser General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program 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
  16. # GNU Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. import os
  21. import shutil
  22. import socket
  23. import subprocess
  24. import unittest
  25. import multiprocessing
  26. try:
  27. import unittest.mock as mock
  28. except ImportError:
  29. import mock
  30. import tempfile
  31. import qubesadmin.exc
  32. import qubesadmin.tests
  33. class TC_00_VMCollection(qubesadmin.tests.QubesTestCase):
  34. def test_000_list(self):
  35. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  36. b'0\x00test-vm class=AppVM state=Running\n'
  37. self.assertEqual(
  38. list(self.app.domains.keys()),
  39. ['test-vm'])
  40. self.assertAllCalled()
  41. def test_001_getitem(self):
  42. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  43. b'0\x00test-vm class=AppVM state=Running\n'
  44. try:
  45. vm = self.app.domains['test-vm']
  46. self.assertEqual(vm.name, 'test-vm')
  47. except KeyError:
  48. self.fail('VM not found in collection')
  49. self.assertAllCalled()
  50. with self.assertRaises(KeyError):
  51. vm = self.app.domains['test-non-existent']
  52. self.assertAllCalled()
  53. def test_002_in(self):
  54. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  55. b'0\x00test-vm class=AppVM state=Running\n'
  56. self.assertIn('test-vm', self.app.domains)
  57. self.assertAllCalled()
  58. self.assertNotIn('test-non-existent', self.app.domains)
  59. self.assertAllCalled()
  60. def test_003_iter(self):
  61. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  62. b'0\x00test-vm class=AppVM state=Running\n'
  63. self.assertEqual([vm.name for vm in self.app.domains], ['test-vm'])
  64. self.assertAllCalled()
  65. def test_004_delitem(self):
  66. self.app.expected_calls[('test-vm', 'admin.vm.Remove', None, None)] = \
  67. b'0\x00'
  68. del self.app.domains['test-vm']
  69. self.assertAllCalled()
  70. def test_005_keys(self):
  71. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  72. b'0\x00test-vm class=AppVM state=Running\n' \
  73. b'test-vm2 class=AppVM state=Running\n'
  74. self.assertEqual(set(self.app.domains.keys()),
  75. set(['test-vm', 'test-vm2']))
  76. self.assertAllCalled()
  77. def test_006_values(self):
  78. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  79. b'0\x00test-vm class=AppVM state=Running\n' \
  80. b'test-vm2 class=AppVM state=Running\n'
  81. values = self.app.domains.values()
  82. for obj in values:
  83. self.assertIsInstance(obj, qubesadmin.vm.QubesVM)
  84. self.assertEqual(set([vm.name for vm in values]),
  85. set(['test-vm', 'test-vm2']))
  86. self.assertAllCalled()
  87. def test_007_getitem_blind_mode(self):
  88. self.app.blind_mode = True
  89. try:
  90. vm = self.app.domains['test-vm']
  91. self.assertEqual(vm.name, 'test-vm')
  92. except KeyError:
  93. self.fail('VM not found in collection')
  94. self.assertAllCalled()
  95. with self.assertNotRaises(KeyError):
  96. vm = self.app.domains['test-non-existent']
  97. self.assertAllCalled()
  98. def test_008_in_blind_mode(self):
  99. self.app.blind_mode = True
  100. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  101. b'0\x00test-vm class=AppVM state=Running\n'
  102. self.assertIn('test-vm', self.app.domains)
  103. self.assertAllCalled()
  104. self.assertNotIn('test-non-existent', self.app.domains)
  105. self.assertAllCalled()
  106. def test_009_getitem_cache_class(self):
  107. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  108. b'0\x00test-vm class=AppVM state=Running\n'
  109. try:
  110. vm = self.app.domains['test-vm']
  111. self.assertEqual(vm.name, 'test-vm')
  112. self.assertEqual(vm.klass, 'AppVM')
  113. except KeyError:
  114. self.fail('VM not found in collection')
  115. self.assertAllCalled()
  116. class TC_10_QubesBase(qubesadmin.tests.QubesTestCase):
  117. def test_010_new_simple(self):
  118. self.app.expected_calls[('dom0', 'admin.vm.Create.AppVM', None,
  119. b'name=new-vm label=red')] = b'0\x00'
  120. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  121. b'0\x00new-vm class=AppVM state=Running\n'
  122. vm = self.app.add_new_vm('AppVM', 'new-vm', 'red')
  123. self.assertEqual(vm.name, 'new-vm')
  124. self.assertEqual(vm.klass, 'AppVM')
  125. self.assertAllCalled()
  126. def test_011_new_template(self):
  127. self.app.expected_calls[('dom0', 'admin.vm.Create.TemplateVM', None,
  128. b'name=new-template label=red')] = b'0\x00'
  129. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  130. b'0\x00new-template class=TemplateVM state=Running\n'
  131. vm = self.app.add_new_vm('TemplateVM', 'new-template', 'red')
  132. self.assertEqual(vm.name, 'new-template')
  133. self.assertEqual(vm.klass, 'TemplateVM')
  134. self.assertAllCalled()
  135. def test_012_new_template_based(self):
  136. self.app.expected_calls[('dom0', 'admin.vm.Create.AppVM',
  137. 'some-template', b'name=new-vm label=red')] = b'0\x00'
  138. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  139. b'0\x00new-vm class=AppVM state=Running\n'
  140. vm = self.app.add_new_vm('AppVM', 'new-vm', 'red', 'some-template')
  141. self.assertEqual(vm.name, 'new-vm')
  142. self.assertEqual(vm.klass, 'AppVM')
  143. self.assertAllCalled()
  144. def test_013_new_objects_params(self):
  145. self.app.expected_calls[('dom0', 'admin.vm.Create.AppVM',
  146. 'some-template', b'name=new-vm label=red')] = b'0\x00'
  147. self.app.expected_calls[('dom0', 'admin.label.List', None, None)] = \
  148. b'0\x00red\nblue\n'
  149. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  150. b'0\x00new-vm class=AppVM state=Running\n' \
  151. b'some-template class=TemplateVM state=Running\n'
  152. vm = self.app.add_new_vm(self.app.get_vm_class('AppVM'), 'new-vm',
  153. self.app.get_label('red'), self.app.domains['some-template'])
  154. self.assertEqual(vm.name, 'new-vm')
  155. self.assertEqual(vm.klass, 'AppVM')
  156. self.assertAllCalled()
  157. def test_014_new_pool(self):
  158. self.app.expected_calls[('dom0', 'admin.vm.CreateInPool.AppVM', None,
  159. b'name=new-vm label=red pool=some-pool')] = b'0\x00'
  160. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  161. b'0\x00new-vm class=AppVM state=Running\n'
  162. vm = self.app.add_new_vm('AppVM', 'new-vm', 'red', pool='some-pool')
  163. self.assertEqual(vm.name, 'new-vm')
  164. self.assertEqual(vm.klass, 'AppVM')
  165. self.assertAllCalled()
  166. def test_015_new_pools(self):
  167. self.app.expected_calls[('dom0', 'admin.vm.CreateInPool.AppVM', None,
  168. b'name=new-vm label=red pool:private=some-pool '
  169. b'pool:volatile=other-pool')] = b'0\x00'
  170. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  171. b'0\x00new-vm class=AppVM state=Running\n'
  172. vm = self.app.add_new_vm('AppVM', 'new-vm', 'red',
  173. pools={'private': 'some-pool', 'volatile': 'other-pool'})
  174. self.assertEqual(vm.name, 'new-vm')
  175. self.assertEqual(vm.klass, 'AppVM')
  176. self.assertAllCalled()
  177. def test_016_new_template_based_default(self):
  178. self.app.expected_calls[('dom0', 'admin.vm.Create.AppVM',
  179. None, b'name=new-vm label=red')] = b'0\x00'
  180. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  181. b'0\x00new-vm class=AppVM state=Running\n'
  182. vm = self.app.add_new_vm('AppVM', 'new-vm', 'red',
  183. template=qubesadmin.DEFAULT)
  184. self.assertEqual(vm.name, 'new-vm')
  185. self.assertEqual(vm.klass, 'AppVM')
  186. self.assertAllCalled()
  187. def test_020_get_label(self):
  188. self.app.expected_calls[('dom0', 'admin.label.List', None, None)] = \
  189. b'0\x00red\nblue\n'
  190. label = self.app.get_label('red')
  191. self.assertEqual(label.name, 'red')
  192. self.assertAllCalled()
  193. def clone_setup_common_calls(self, src, dst):
  194. # have each property type with default=no, each special-cased,
  195. # and some with default=yes
  196. properties = {
  197. 'label': 'default=False type=label red',
  198. 'template': 'default=False type=vm test-template',
  199. 'memory': 'default=False type=int 400',
  200. 'kernel': 'default=False type=str 4.9.31',
  201. 'netvm': 'default=False type=vm test-net',
  202. 'virt_mode': 'default=False type=str hvm',
  203. 'default_user': 'default=True type=str user',
  204. }
  205. self.app.expected_calls[
  206. (src, 'admin.vm.property.List', None, None)] = \
  207. b'0\0qid\nname\n' + \
  208. b'\n'.join(prop.encode() for prop in properties.keys()) + \
  209. b'\n'
  210. for prop, value in properties.items():
  211. self.app.expected_calls[
  212. (src, 'admin.vm.property.Get', prop, None)] = \
  213. b'0\0' + value.encode()
  214. # special cases handled by admin.vm.Create call
  215. if prop in ('label', 'template'):
  216. continue
  217. # default properties should not be set
  218. if 'default=True' in value:
  219. continue
  220. self.app.expected_calls[
  221. (dst, 'admin.vm.property.Set', prop,
  222. value.split()[-1].encode())] = b'0\0'
  223. # tags
  224. self.app.expected_calls[
  225. (src, 'admin.vm.tag.List', None, None)] = \
  226. b'0\0tag1\ntag2\n'
  227. self.app.expected_calls[
  228. (dst, 'admin.vm.tag.Set', 'tag1', None)] = b'0\0'
  229. self.app.expected_calls[
  230. (dst, 'admin.vm.tag.Set', 'tag2', None)] = b'0\0'
  231. # features
  232. self.app.expected_calls[
  233. (src, 'admin.vm.feature.List', None, None)] = \
  234. b'0\0feat1\nfeat2\n'
  235. self.app.expected_calls[
  236. (src, 'admin.vm.feature.Get', 'feat1', None)] = \
  237. b'0\0feat1-value with spaces'
  238. self.app.expected_calls[
  239. (src, 'admin.vm.feature.Get', 'feat2', None)] = \
  240. b'0\x001'
  241. self.app.expected_calls[
  242. (dst, 'admin.vm.feature.Set', 'feat1',
  243. b'feat1-value with spaces')] = b'0\0'
  244. self.app.expected_calls[
  245. (dst, 'admin.vm.feature.Set', 'feat2', b'1')] = b'0\0'
  246. # firewall
  247. rules = (
  248. b'action=drop dst4=192.168.0.0/24\n'
  249. b'action=accept\n'
  250. )
  251. self.app.expected_calls[
  252. (src, 'admin.vm.firewall.Get', None, None)] = \
  253. b'0\x00' + rules
  254. self.app.expected_calls[
  255. (dst, 'admin.vm.firewall.Set', None, rules)] = \
  256. b'0\x00'
  257. # storage
  258. self.app.expected_calls[
  259. (dst, 'admin.vm.volume.List', None, None)] = \
  260. b'0\x00root\nprivate\nvolatile\nkernel\n'
  261. self.app.expected_calls[
  262. (dst, 'admin.vm.volume.Info', 'root', None)] = \
  263. b'0\x00pool=lvm\n' \
  264. b'vid=vm-test-vm/root\n' \
  265. b'size=10737418240\n' \
  266. b'usage=2147483648\n' \
  267. b'rw=False\n' \
  268. b'internal=True\n' \
  269. b'source=vm-test-template/root\n' \
  270. b'save_on_stop=False\n' \
  271. b'snap_on_start=True\n'
  272. self.app.expected_calls[
  273. (dst, 'admin.vm.volume.Info', 'private', None)] = \
  274. b'0\x00pool=lvm\n' \
  275. b'vid=vm-test-vm/private\n' \
  276. b'size=2147483648\n' \
  277. b'usage=214748364\n' \
  278. b'rw=True\n' \
  279. b'internal=True\n' \
  280. b'save_on_stop=True\n' \
  281. b'snap_on_start=False\n'
  282. self.app.expected_calls[
  283. (dst, 'admin.vm.volume.Info', 'volatile', None)] = \
  284. b'0\x00pool=lvm\n' \
  285. b'vid=vm-test-vm/volatile\n' \
  286. b'size=10737418240\n' \
  287. b'usage=0\n' \
  288. b'rw=True\n' \
  289. b'internal=True\n' \
  290. b'source=None\n' \
  291. b'save_on_stop=False\n' \
  292. b'snap_on_start=False\n'
  293. self.app.expected_calls[
  294. (dst, 'admin.vm.volume.Info', 'kernel', None)] = \
  295. b'0\x00pool=linux-kernel\n' \
  296. b'vid=\n' \
  297. b'size=0\n' \
  298. b'usage=0\n' \
  299. b'rw=False\n' \
  300. b'internal=True\n' \
  301. b'source=None\n' \
  302. b'save_on_stop=False\n' \
  303. b'snap_on_start=False\n'
  304. self.app.expected_calls[
  305. (src, 'admin.vm.volume.List', None, None)] = \
  306. b'0\x00root\nprivate\nvolatile\nkernel\n'
  307. self.app.expected_calls[
  308. (src, 'admin.vm.volume.CloneFrom', 'private', None)] = \
  309. b'0\x00token-private'
  310. self.app.expected_calls[
  311. (dst, 'admin.vm.volume.CloneTo', 'private', b'token-private')] = \
  312. b'0\x00'
  313. def test_030_clone(self):
  314. self.clone_setup_common_calls('test-vm', 'new-name')
  315. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  316. b'0\x00new-name class=AppVM state=Halted\n' \
  317. b'test-vm class=AppVM state=Halted\n' \
  318. b'test-template class=TemplateVM state=Halted\n' \
  319. b'test-net class=AppVM state=Halted\n'
  320. self.app.expected_calls[('dom0', 'admin.vm.Create.AppVM',
  321. 'test-template', b'name=new-name label=red')] = b'0\x00'
  322. new_vm = self.app.clone_vm('test-vm', 'new-name')
  323. self.assertEqual(new_vm.name, 'new-name')
  324. self.assertAllCalled()
  325. def test_031_clone_object(self):
  326. self.clone_setup_common_calls('test-vm', 'new-name')
  327. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  328. b'0\x00new-name class=AppVM state=Halted\n' \
  329. b'test-vm class=AppVM state=Halted\n' \
  330. b'test-template class=TemplateVM state=Halted\n' \
  331. b'test-net class=AppVM state=Halted\n'
  332. self.app.expected_calls[('dom0', 'admin.vm.Create.AppVM',
  333. 'test-template', b'name=new-name label=red')] = b'0\x00'
  334. new_vm = self.app.clone_vm(self.app.domains['test-vm'], 'new-name')
  335. self.assertEqual(new_vm.name, 'new-name')
  336. self.assertAllCalled()
  337. def test_032_clone_pool(self):
  338. self.clone_setup_common_calls('test-vm', 'new-name')
  339. self.app.expected_calls[('dom0', 'admin.vm.CreateInPool.AppVM',
  340. 'test-template',
  341. b'name=new-name label=red pool=some-pool')] = b'0\x00'
  342. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  343. b'0\x00new-name class=AppVM state=Halted\n' \
  344. b'test-vm class=AppVM state=Halted\n' \
  345. b'test-template class=TemplateVM state=Halted\n' \
  346. b'test-net class=AppVM state=Halted\n'
  347. new_vm = self.app.clone_vm('test-vm', 'new-name', pool='some-pool')
  348. self.assertEqual(new_vm.name, 'new-name')
  349. self.assertAllCalled()
  350. def test_033_clone_pools(self):
  351. self.clone_setup_common_calls('test-vm', 'new-name')
  352. self.app.expected_calls[('dom0', 'admin.vm.CreateInPool.AppVM',
  353. 'test-template',
  354. b'name=new-name label=red pool:private=some-pool '
  355. b'pool:volatile=other-pool')] = b'0\x00'
  356. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  357. b'0\x00new-name class=AppVM state=Halted\n' \
  358. b'test-vm class=AppVM state=Halted\n' \
  359. b'test-template class=TemplateVM state=Halted\n' \
  360. b'test-net class=AppVM state=Halted\n'
  361. new_vm = self.app.clone_vm('test-vm', 'new-name',
  362. pools={'private': 'some-pool', 'volatile': 'other-pool'})
  363. self.assertEqual(new_vm.name, 'new-name')
  364. self.assertAllCalled()
  365. def test_034_clone_class_change(self):
  366. self.clone_setup_common_calls('test-vm', 'new-name')
  367. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  368. b'0\x00new-name class=StandaloneVM state=Halted\n' \
  369. b'test-vm class=AppVM state=Halted\n' \
  370. b'test-template class=TemplateVM state=Halted\n' \
  371. b'test-net class=AppVM state=Halted\n'
  372. self.app.expected_calls[('dom0', 'admin.vm.Create.StandaloneVM',
  373. 'test-template', b'name=new-name label=red')] = b'0\x00'
  374. self.app.expected_calls[
  375. ('new-name', 'admin.vm.volume.Info', 'root', None)] = \
  376. b'0\x00pool=lvm\n' \
  377. b'vid=vm-new-name/root\n' \
  378. b'size=10737418240\n' \
  379. b'usage=2147483648\n' \
  380. b'rw=True\n' \
  381. b'internal=True\n' \
  382. b'source=None\n' \
  383. b'save_on_stop=True\n' \
  384. b'snap_on_start=False\n'
  385. self.app.expected_calls[
  386. ('test-vm', 'admin.vm.volume.CloneFrom', 'root', None)] = \
  387. b'0\x00token-root'
  388. self.app.expected_calls[
  389. ('new-name', 'admin.vm.volume.CloneTo', 'root', b'token-root')] = \
  390. b'0\x00'
  391. new_vm = self.app.clone_vm('test-vm', 'new-name',
  392. new_cls='StandaloneVM')
  393. self.assertEqual(new_vm.name, 'new-name')
  394. self.assertEqual(new_vm.klass, 'StandaloneVM')
  395. self.assertAllCalled()
  396. def test_035_clone_fail(self):
  397. self.app.expected_calls[
  398. ('test-vm', 'admin.vm.property.List', None, None)] = \
  399. b'0\0qid\nname\ntemplate\nlabel\nmemory\n'
  400. self.app.expected_calls[
  401. ('test-vm', 'admin.vm.property.Get', 'label', None)] = \
  402. b'0\0default=False type=label red'
  403. self.app.expected_calls[
  404. ('test-vm', 'admin.vm.property.Get', 'template', None)] = \
  405. b'0\0default=False type=vm test-template'
  406. self.app.expected_calls[
  407. ('test-vm', 'admin.vm.property.Get', 'memory', None)] = \
  408. b'0\0default=False type=int 400'
  409. self.app.expected_calls[
  410. ('new-name', 'admin.vm.property.Set', 'memory', b'400')] = \
  411. b'2\0QubesException\0\0something happened\0'
  412. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  413. b'0\x00new-name class=AppVM state=Halted\n' \
  414. b'test-vm class=AppVM state=Halted\n' \
  415. b'test-template class=TemplateVM state=Halted\n' \
  416. b'test-net class=AppVM state=Halted\n'
  417. self.app.expected_calls[('dom0', 'admin.vm.Create.AppVM',
  418. 'test-template', b'name=new-name label=red')] = b'0\x00'
  419. self.app.expected_calls[('new-name', 'admin.vm.Remove', None, None)] = \
  420. b'0\x00'
  421. with self.assertRaises(qubesadmin.exc.QubesException):
  422. self.app.clone_vm('test-vm', 'new-name')
  423. self.assertAllCalled()
  424. def test_036_clone_ignore_errors_prop(self):
  425. self.clone_setup_common_calls('test-vm', 'new-name')
  426. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  427. b'0\x00new-name class=AppVM state=Halted\n' \
  428. b'test-vm class=AppVM state=Halted\n' \
  429. b'test-template class=TemplateVM state=Halted\n' \
  430. b'test-net class=AppVM state=Halted\n'
  431. self.app.expected_calls[('dom0', 'admin.vm.Create.AppVM',
  432. 'test-template', b'name=new-name label=red')] = b'0\x00'
  433. self.app.expected_calls[
  434. ('new-name', 'admin.vm.property.Set', 'memory', b'400')] = \
  435. b'2\0QubesException\0\0something happened\0'
  436. new_vm = self.app.clone_vm('test-vm', 'new-name', ignore_errors=True)
  437. self.assertEqual(new_vm.name, 'new-name')
  438. self.assertAllCalled()
  439. def test_037_clone_ignore_errors_feature(self):
  440. self.clone_setup_common_calls('test-vm', 'new-name')
  441. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  442. b'0\x00new-name class=AppVM state=Halted\n' \
  443. b'test-vm class=AppVM state=Halted\n' \
  444. b'test-template class=TemplateVM state=Halted\n' \
  445. b'test-net class=AppVM state=Halted\n'
  446. self.app.expected_calls[('dom0', 'admin.vm.Create.AppVM',
  447. 'test-template', b'name=new-name label=red')] = b'0\x00'
  448. self.app.expected_calls[
  449. ('new-name', 'admin.vm.feature.Set', 'feat2', b'1')] = \
  450. b'2\0QubesException\0\0something happened\0'
  451. new_vm = self.app.clone_vm('test-vm', 'new-name', ignore_errors=True)
  452. self.assertEqual(new_vm.name, 'new-name')
  453. self.assertAllCalled()
  454. def test_038_clone_ignore_errors_tag(self):
  455. self.clone_setup_common_calls('test-vm', 'new-name')
  456. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  457. b'0\x00new-name class=AppVM state=Halted\n' \
  458. b'test-vm class=AppVM state=Halted\n' \
  459. b'test-template class=TemplateVM state=Halted\n' \
  460. b'test-net class=AppVM state=Halted\n'
  461. self.app.expected_calls[('dom0', 'admin.vm.Create.AppVM',
  462. 'test-template', b'name=new-name label=red')] = b'0\x00'
  463. self.app.expected_calls[
  464. ('new-name', 'admin.vm.tag.Set', 'tag1', None)] = \
  465. b'2\0QubesException\0\0something happened\0'
  466. new_vm = self.app.clone_vm('test-vm', 'new-name', ignore_errors=True)
  467. self.assertEqual(new_vm.name, 'new-name')
  468. self.assertAllCalled()
  469. def test_039_clone_ignore_errors_firewall(self):
  470. self.clone_setup_common_calls('test-vm', 'new-name')
  471. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  472. b'0\x00new-name class=AppVM state=Halted\n' \
  473. b'test-vm class=AppVM state=Halted\n' \
  474. b'test-template class=TemplateVM state=Halted\n' \
  475. b'test-net class=AppVM state=Halted\n'
  476. self.app.expected_calls[('dom0', 'admin.vm.Create.AppVM',
  477. 'test-template', b'name=new-name label=red')] = b'0\x00'
  478. self.app.expected_calls[
  479. ('new-name', 'admin.vm.firewall.Set', None,
  480. b'action=drop dst4=192.168.0.0/24\naction=accept\n')] = \
  481. b'2\0QubesException\0\0something happened\0'
  482. new_vm = self.app.clone_vm('test-vm', 'new-name', ignore_errors=True)
  483. self.assertEqual(new_vm.name, 'new-name')
  484. self.assertAllCalled()
  485. def test_040_clone_ignore_errors_storage(self):
  486. self.clone_setup_common_calls('test-vm', 'new-name')
  487. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  488. b'0\x00new-name class=AppVM state=Halted\n' \
  489. b'test-vm class=AppVM state=Halted\n' \
  490. b'test-template class=TemplateVM state=Halted\n' \
  491. b'test-net class=AppVM state=Halted\n'
  492. self.app.expected_calls[('dom0', 'admin.vm.Create.AppVM',
  493. 'test-template', b'name=new-name label=red')] = b'0\x00'
  494. self.app.expected_calls[
  495. ('new-name', 'admin.vm.volume.CloneTo', 'private',
  496. b'token-private')] = \
  497. b'2\0QubesException\0\0something happened\0'
  498. self.app.expected_calls[('new-name', 'admin.vm.Remove', None, None)] = \
  499. b'0\x00'
  500. del self.app.expected_calls[
  501. ('new-name', 'admin.vm.volume.Info', 'root', None)]
  502. del self.app.expected_calls[
  503. ('new-name', 'admin.vm.volume.Info', 'volatile', None)]
  504. with self.assertRaises(qubesadmin.exc.QubesException):
  505. self.app.clone_vm('test-vm', 'new-name', ignore_errors=True)
  506. self.assertAllCalled()
  507. def test_041_clone_fail_storage(self):
  508. self.clone_setup_common_calls('test-vm', 'new-name')
  509. self.app.expected_calls[('dom0', 'admin.vm.List', None, None)] = \
  510. b'0\x00new-name class=AppVM state=Halted\n' \
  511. b'test-vm class=AppVM state=Halted\n' \
  512. b'test-template class=TemplateVM state=Halted\n' \
  513. b'test-net class=AppVM state=Halted\n'
  514. self.app.expected_calls[('dom0', 'admin.vm.Create.AppVM',
  515. 'test-template', b'name=new-name label=red')] = b'0\x00'
  516. self.app.expected_calls[
  517. ('new-name', 'admin.vm.volume.CloneTo', 'private',
  518. b'token-private')] = \
  519. b'2\0QubesException\0\0something happened\0'
  520. self.app.expected_calls[('new-name', 'admin.vm.Remove', None, None)] = \
  521. b'0\x00'
  522. del self.app.expected_calls[
  523. ('new-name', 'admin.vm.volume.Info', 'root', None)]
  524. del self.app.expected_calls[
  525. ('new-name', 'admin.vm.volume.Info', 'volatile', None)]
  526. with self.assertRaises(qubesadmin.exc.QubesException):
  527. self.app.clone_vm('test-vm', 'new-name')
  528. self.assertAllCalled()
  529. class TC_20_QubesLocal(unittest.TestCase):
  530. def setUp(self):
  531. super(TC_20_QubesLocal, self).setUp()
  532. self.socket_dir = tempfile.mkdtemp()
  533. self.orig_sock = qubesadmin.config.QUBESD_SOCKET
  534. qubesadmin.config.QUBESD_SOCKET = os.path.join(self.socket_dir, 'sock')
  535. self.proc = None
  536. self.app = qubesadmin.app.QubesLocal()
  537. def listen_and_send(self, send_data):
  538. '''Listen on socket and send data in response.
  539. :param bytes send_data: data to send
  540. '''
  541. self.socket_pipe, child_pipe = multiprocessing.Pipe()
  542. self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  543. self.socket.bind(os.path.join(self.socket_dir, 'sock'))
  544. self.socket.listen(1)
  545. def worker(sock, pipe, send_data_):
  546. conn, addr = sock.accept()
  547. pipe.send(conn.makefile('rb').read())
  548. conn.sendall(send_data_)
  549. conn.close()
  550. self.proc = multiprocessing.Process(target=worker,
  551. args=(self.socket, child_pipe, send_data))
  552. self.proc.start()
  553. self.socket.close()
  554. def get_request(self):
  555. '''Get request sent to "qubesd" mock'''
  556. return self.socket_pipe.recv()
  557. def tearDown(self):
  558. qubesadmin.config.QUBESD_SOCKET = self.orig_sock
  559. if self.proc is not None:
  560. try:
  561. self.proc.terminate()
  562. except OSError:
  563. pass
  564. shutil.rmtree(self.socket_dir)
  565. super(TC_20_QubesLocal, self).tearDown()
  566. def test_000_qubesd_call(self):
  567. self.listen_and_send(b'0\0')
  568. self.app.qubesd_call('test-vm', 'some.method', 'arg1', b'payload')
  569. self.assertEqual(self.get_request(),
  570. b'dom0\0some.method\0test-vm\0arg1\0payload')
  571. def test_001_qubesd_call_none_arg(self):
  572. self.listen_and_send(b'0\0')
  573. self.app.qubesd_call('test-vm', 'some.method', None, b'payload')
  574. self.assertEqual(self.get_request(),
  575. b'dom0\0some.method\0test-vm\0\0payload')
  576. def test_002_qubesd_call_none_payload(self):
  577. self.listen_and_send(b'0\0')
  578. self.app.qubesd_call('test-vm', 'some.method', None, None)
  579. self.assertEqual(self.get_request(),
  580. b'dom0\0some.method\0test-vm\0\0')
  581. def test_003_qubesd_call_payload_stream(self):
  582. # this should really be in setUp()...
  583. tmpdir = tempfile.mkdtemp()
  584. self.addCleanup(shutil.rmtree, tmpdir)
  585. service_path = os.path.join(tmpdir, 'test.service')
  586. payload_input = os.path.join(tmpdir, 'payload-input')
  587. with open(service_path, 'w') as f:
  588. f.write('#!/bin/bash\n'
  589. 'env > {dir}/env\n'
  590. 'echo "$@" > {dir}/args\n'
  591. 'cat > {dir}/payload\n'
  592. 'echo -en \'0\\0return-value\'\n'.format(dir=tmpdir))
  593. os.chmod(service_path, 0o755)
  594. with open(payload_input, 'w+') as payload_file:
  595. payload_file.write('some payload\n')
  596. payload_file.seek(0)
  597. with mock.patch('qubesadmin.config.QREXEC_SERVICES_DIR',
  598. tmpdir):
  599. value = self.app.qubesd_call('test-vm', 'test.service',
  600. 'some-arg', payload_stream=payload_file)
  601. self.assertEqual(value, b'return-value')
  602. self.assertTrue(os.path.exists(tmpdir + '/env'))
  603. with open(tmpdir + '/env') as env:
  604. self.assertIn('QREXEC_REMOTE_DOMAIN=dom0\n', env)
  605. self.assertIn('QREXEC_REQUESTED_TARGET=test-vm\n', env)
  606. self.assertTrue(os.path.exists(tmpdir + '/args'))
  607. with open(tmpdir + '/args') as args:
  608. self.assertEqual(args.read(), 'some-arg\n')
  609. self.assertTrue(os.path.exists(tmpdir + '/payload'))
  610. with open(tmpdir + '/payload') as payload:
  611. self.assertEqual(payload.read(), 'some payload\n')
  612. def test_004_qubesd_call_payload_stream_proc(self):
  613. # this should really be in setUp()...
  614. tmpdir = tempfile.mkdtemp()
  615. self.addCleanup(shutil.rmtree, tmpdir)
  616. service_path = os.path.join(tmpdir, 'test.service')
  617. echo = subprocess.Popen(['echo', 'some payload'],
  618. stdout=subprocess.PIPE)
  619. with open(service_path, 'w') as f:
  620. f.write('#!/bin/bash\n'
  621. 'env > {dir}/env\n'
  622. 'echo "$@" > {dir}/args\n'
  623. 'cat > {dir}/payload\n'
  624. 'echo -en \'0\\0return-value\'\n'.format(dir=tmpdir))
  625. os.chmod(service_path, 0o755)
  626. with mock.patch('qubesadmin.config.QREXEC_SERVICES_DIR',
  627. tmpdir):
  628. value = self.app.qubesd_call('test-vm', 'test.service',
  629. 'some-arg', payload_stream=echo.stdout)
  630. echo.stdout.close()
  631. self.assertEqual(value, b'return-value')
  632. self.assertTrue(os.path.exists(tmpdir + '/env'))
  633. with open(tmpdir + '/env') as env:
  634. self.assertIn('QREXEC_REMOTE_DOMAIN=dom0\n', env)
  635. self.assertIn('QREXEC_REQUESTED_TARGET=test-vm\n', env)
  636. self.assertTrue(os.path.exists(tmpdir + '/args'))
  637. with open(tmpdir + '/args') as args:
  638. self.assertEqual(args.read(), 'some-arg\n')
  639. self.assertTrue(os.path.exists(tmpdir + '/payload'))
  640. with open(tmpdir + '/payload') as payload:
  641. self.assertEqual(payload.read(), 'some payload\n')
  642. @mock.patch('os.isatty', lambda fd: fd == 2)
  643. def test_010_run_service(self):
  644. self.listen_and_send(b'0\0')
  645. with mock.patch('subprocess.Popen') as mock_proc:
  646. p = self.app.run_service('some-vm', 'service.name')
  647. mock_proc.assert_called_once_with([
  648. qubesadmin.config.QREXEC_CLIENT,
  649. '-d', 'some-vm', '-T', 'DEFAULT:QUBESRPC service.name dom0'],
  650. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  651. stderr=subprocess.PIPE)
  652. self.assertEqual(self.get_request(),
  653. b'dom0\0admin.vm.Start\0some-vm\0\0')
  654. def test_011_run_service_filter_esc(self):
  655. self.listen_and_send(b'0\0')
  656. with mock.patch('subprocess.Popen') as mock_proc:
  657. p = self.app.run_service('some-vm', 'service.name', filter_esc=True)
  658. mock_proc.assert_called_once_with([
  659. qubesadmin.config.QREXEC_CLIENT,
  660. '-d', 'some-vm', '-t', '-T',
  661. 'DEFAULT:QUBESRPC service.name dom0'],
  662. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  663. stderr=subprocess.PIPE)
  664. self.assertEqual(self.get_request(),
  665. b'dom0\0admin.vm.Start\0some-vm\0\0')
  666. @mock.patch('os.isatty', lambda fd: fd == 2)
  667. def test_012_run_service_user(self):
  668. self.listen_and_send(b'0\0')
  669. with mock.patch('subprocess.Popen') as mock_proc:
  670. p = self.app.run_service('some-vm', 'service.name', user='user')
  671. mock_proc.assert_called_once_with([
  672. qubesadmin.config.QREXEC_CLIENT,
  673. '-d', 'some-vm', '-T',
  674. 'user:QUBESRPC service.name dom0'],
  675. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  676. stderr=subprocess.PIPE)
  677. self.assertEqual(self.get_request(),
  678. b'dom0\0admin.vm.Start\0some-vm\0\0')
  679. def test_013_run_service_default_target(self):
  680. with self.assertRaises(ValueError):
  681. self.app.run_service('', 'service.name')
  682. class TC_30_QubesRemote(unittest.TestCase):
  683. def setUp(self):
  684. super(TC_30_QubesRemote, self).setUp()
  685. self.proc_mock = mock.Mock()
  686. self.proc_mock.configure_mock(**{
  687. 'return_value.returncode': 0
  688. })
  689. self.proc_patch = mock.patch('subprocess.Popen', self.proc_mock)
  690. self.proc_patch.start()
  691. self.app = qubesadmin.app.QubesRemote()
  692. def set_proc_stdout(self, send_data):
  693. self.proc_mock.configure_mock(**{
  694. 'return_value.communicate.return_value': (send_data, None)
  695. })
  696. def tearDown(self):
  697. self.proc_patch.stop()
  698. super(TC_30_QubesRemote, self).tearDown()
  699. def test_000_qubesd_call(self):
  700. self.set_proc_stdout(b'0\0')
  701. self.app.qubesd_call('test-vm', 'some.method', 'arg1', b'payload')
  702. self.assertEqual(self.proc_mock.mock_calls, [
  703. mock.call([qubesadmin.config.QREXEC_CLIENT_VM, 'test-vm',
  704. 'some.method+arg1'],
  705. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  706. stderr=subprocess.PIPE),
  707. mock.call().communicate(b'payload')
  708. ])
  709. def test_001_qubesd_call_none_arg(self):
  710. self.set_proc_stdout(b'0\0')
  711. self.app.qubesd_call('test-vm', 'some.method', None, b'payload')
  712. self.assertEqual(self.proc_mock.mock_calls, [
  713. mock.call([qubesadmin.config.QREXEC_CLIENT_VM, 'test-vm',
  714. 'some.method'],
  715. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  716. stderr=subprocess.PIPE),
  717. mock.call().communicate(b'payload')
  718. ])
  719. def test_002_qubesd_call_none_payload(self):
  720. self.set_proc_stdout(b'0\0')
  721. self.app.qubesd_call('test-vm', 'some.method', None, None)
  722. self.assertEqual(self.proc_mock.mock_calls, [
  723. mock.call([qubesadmin.config.QREXEC_CLIENT_VM, 'test-vm',
  724. 'some.method'],
  725. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  726. stderr=subprocess.PIPE),
  727. mock.call().communicate(None)
  728. ])
  729. def test_003_qubesd_call_payload_stream(self):
  730. self.set_proc_stdout(b'0\0return-value')
  731. tmpdir = tempfile.mkdtemp()
  732. self.addCleanup(shutil.rmtree, tmpdir)
  733. payload_input = os.path.join(tmpdir, 'payload-input')
  734. with open(payload_input, 'w+') as payload_file:
  735. payload_file.write('some payload\n')
  736. payload_file.seek(0)
  737. value = self.app.qubesd_call('test-vm', 'some.method',
  738. 'some-arg', payload_stream=payload_file)
  739. self.assertEqual(self.proc_mock.mock_calls, [
  740. mock.call([qubesadmin.config.QREXEC_CLIENT_VM, 'test-vm',
  741. 'some.method+some-arg'],
  742. stdin=payload_file, stdout=subprocess.PIPE,
  743. stderr=subprocess.PIPE),
  744. mock.call().communicate(None)
  745. ])
  746. self.assertEqual(value, b'return-value')
  747. def test_010_run_service(self):
  748. self.app.run_service('some-vm', 'service.name')
  749. self.proc_mock.assert_called_once_with([
  750. qubesadmin.config.QREXEC_CLIENT_VM,
  751. 'some-vm', 'service.name'],
  752. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  753. stderr=subprocess.PIPE)
  754. def test_011_run_service_filter_esc(self):
  755. with self.assertRaises(NotImplementedError):
  756. p = self.app.run_service('some-vm', 'service.name', filter_esc=True)
  757. def test_012_run_service_user(self):
  758. with self.assertRaises(ValueError):
  759. p = self.app.run_service('some-vm', 'service.name', user='user')
  760. def test_013_run_service_default_target(self):
  761. self.app.run_service('', 'service.name')
  762. self.proc_mock.assert_called_once_with([
  763. qubesadmin.config.QREXEC_CLIENT_VM,
  764. '', 'service.name'],
  765. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  766. stderr=subprocess.PIPE)