qvm_template_postprocess.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2016 Marek Marczykowski-Górecki
  5. # <marmarek@invisiblethingslab.com>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU Lesser General Public License as published by
  9. # the Free Software Foundation; either version 2.1 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. ''' Tool for importing rpm-installed template'''
  21. import asyncio
  22. import glob
  23. import os
  24. import shutil
  25. import subprocess
  26. import sys
  27. import grp
  28. import qubesadmin
  29. import qubesadmin.exc
  30. import qubesadmin.tools
  31. try:
  32. # pylint: disable=wrong-import-position
  33. import qubesadmin.events.utils
  34. have_events = True
  35. except ImportError:
  36. have_events = False
  37. parser = qubesadmin.tools.QubesArgumentParser(
  38. description='Postprocess template package')
  39. parser.add_argument('--really', action='store_true', default=False,
  40. help='Really perform the action, YOU SHOULD REALLY KNOW WHAT YOU ARE DOING')
  41. parser.add_argument('--skip-start', action='store_true',
  42. help='Do not start the VM - do not retrieve menu entries etc.')
  43. parser.add_argument('--keep-source', action='store_true',
  44. help='Do not remove source data (*dir* directory) after import')
  45. parser.add_argument('--no-installed-by-rpm', action='store_true',
  46. help='Do not set installed_by_rpm')
  47. parser.add_argument('--allow-pv', action='store_true',
  48. help='Allow setting virt_mode to pv in configuration file.')
  49. parser.add_argument('--pool',
  50. help='Specify pool to store created VMs in.')
  51. parser.add_argument('action', choices=['post-install', 'pre-remove'],
  52. help='Action to perform')
  53. parser.add_argument('name', action='store',
  54. help='Template name')
  55. parser.add_argument('dir', action='store',
  56. help='Template directory')
  57. def get_root_img_size(source_dir):
  58. '''Extract size of root.img to be imported'''
  59. root_path = os.path.join(source_dir, 'root.img')
  60. # deal with both cases: split tar and non-split tar
  61. part_path = root_path + '.part.00'
  62. tar_path = root_path + '.tar'
  63. if os.path.exists(part_path) or os.path.exists(tar_path):
  64. # get just file root_size from the tar header
  65. path = part_path if os.path.exists(part_path) else tar_path
  66. p = subprocess.Popen(['tar', 'tvf', path],
  67. stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
  68. (stdout, _) = p.communicate()
  69. # -rw-r--r-- 0/0 1073741824 1970-01-01 01:00 root.img
  70. root_size = int(stdout.split()[2])
  71. elif os.path.exists(root_path):
  72. root_size = os.path.getsize(root_path)
  73. else:
  74. raise qubesadmin.exc.QubesException('root.img not found')
  75. return root_size
  76. def import_root_img(vm, source_dir):
  77. '''Import root.img into VM object'''
  78. # Try not break existing data in the volume in case of import failure. If
  79. # volume needs to be extended, do it before import, if reduced - after.
  80. root_size = get_root_img_size(source_dir)
  81. if vm.volumes['root'].size < root_size:
  82. vm.volumes['root'].resize(root_size)
  83. root_path = os.path.join(source_dir, 'root.img')
  84. if os.path.exists(root_path + '.part.00'):
  85. input_files = glob.glob(root_path + '.part.*')
  86. cat = subprocess.Popen(['cat'] + sorted(input_files),
  87. stdout=subprocess.PIPE)
  88. tar = subprocess.Popen(['tar', 'xSOf', '-'],
  89. stdin=cat.stdout,
  90. stdout=subprocess.PIPE)
  91. cat.stdout.close()
  92. vm.volumes['root'].import_data(stream=tar.stdout)
  93. if tar.wait() != 0:
  94. raise qubesadmin.exc.QubesException('root.img extraction failed')
  95. if cat.wait() != 0:
  96. raise qubesadmin.exc.QubesException('root.img extraction failed')
  97. elif os.path.exists(root_path + '.tar'):
  98. tar = subprocess.Popen(['tar', 'xSOf', root_path + '.tar'],
  99. stdout=subprocess.PIPE)
  100. vm.volumes['root'].import_data(stream=tar.stdout)
  101. if tar.wait() != 0:
  102. raise qubesadmin.exc.QubesException('root.img extraction failed')
  103. elif os.path.exists(root_path):
  104. if vm.app.qubesd_connection_type == 'socket':
  105. # check if root.img was already overwritten, i.e. if the source
  106. # and destination paths are the same
  107. vid = vm.volumes['root'].vid
  108. pool = vm.app.pools[vm.volumes['root'].pool]
  109. if (pool.driver in ('file', 'file-reflink')
  110. and root_path == os.path.join(pool.config['dir_path'],
  111. vid + '.img')):
  112. vm.log.info('root.img already in place, do not re-import')
  113. return
  114. with open(root_path, 'rb') as root_file:
  115. vm.volumes['root'].import_data(stream=root_file)
  116. if vm.volumes['root'].size > root_size:
  117. try:
  118. vm.volumes['root'].resize(root_size)
  119. except qubesadmin.exc.QubesException as err:
  120. vm.log.warning(
  121. 'Failed to resize root volume of {} from {} to {} after '
  122. 'import: {}'.format(vm.name, vm.volumes['root'].size,
  123. root_size, str(err)))
  124. def reset_private_img(vm):
  125. '''Clear private volume'''
  126. vm.volumes['private'].clear_data()
  127. def import_appmenus(vm, source_dir, skip_generate=True):
  128. """Import appmenus settings into VM object (later: GUI VM)
  129. :param vm: QubesVM object of just imported template
  130. :param source_dir: directory with source files
  131. :param skip_generate: do not generate actual menu entries,
  132. only set item lists
  133. """
  134. if os.getuid() == 0:
  135. try:
  136. qubes_group = grp.getgrnam('qubes')
  137. user = qubes_group.gr_mem[0]
  138. cmd_prefix = ['runuser', '-u', user, '--', 'env', 'DISPLAY=:0']
  139. except KeyError as e:
  140. vm.log.warning('Default user not found, not importing appmenus: ' +
  141. str(e))
  142. return
  143. else:
  144. cmd_prefix = []
  145. # store the whitelists in VM features
  146. # separated by spaces should be ok as there should be no spaces in the file
  147. # name according to the FreeDesktop spec
  148. with open(os.path.join(source_dir, 'vm-whitelisted-appmenus.list'), 'r') \
  149. as fd:
  150. vm.features['default-menu-items'] = ' '.join([x.rstrip() for x in fd])
  151. with open(os.path.join(source_dir, 'whitelisted-appmenus.list'), 'r') \
  152. as fd:
  153. vm.features['menu-items'] = ' '.join([x.rstrip() for x in fd])
  154. with open(
  155. os.path.join(source_dir, 'netvm-whitelisted-appmenus.list'), 'r') \
  156. as fd:
  157. vm.features['netvm-menu-items'] = ' '.join([x.rstrip() for x in fd])
  158. if skip_generate:
  159. return
  160. # TODO: change this to qrexec calls to GUI VM, when GUI VM will be
  161. # implemented
  162. try:
  163. subprocess.check_call(cmd_prefix + ['qvm-appmenus',
  164. '--set-default-whitelist={}'.format(os.path.join(source_dir,
  165. 'vm-whitelisted-appmenus.list')), vm.name])
  166. subprocess.check_call(cmd_prefix + ['qvm-appmenus',
  167. '--set-whitelist={}'.format(os.path.join(source_dir,
  168. 'whitelisted-appmenus.list')), vm.name])
  169. except subprocess.CalledProcessError as e:
  170. vm.log.warning('Failed to set default application list: %s', e)
  171. def parse_template_config(path):
  172. '''Parse template.conf from template package. (KEY=VALUE format)'''
  173. with open(path, 'r') as fd:
  174. return dict(line.rstrip('\n').split('=', 1) for line in fd)
  175. @asyncio.coroutine
  176. def call_postinstall_service(vm):
  177. '''Call qubes.PostInstall service
  178. And adjust related settings (netvm, features).
  179. '''
  180. # just created, so no need to save previous value - we know what it was
  181. vm.netvm = None
  182. # temporarily enable qrexec feature - so vm.start() will wait for it;
  183. # if start fails, rollback it
  184. vm.features['qrexec'] = True
  185. try:
  186. vm.start()
  187. except qubesadmin.exc.QubesException:
  188. del vm.features['qrexec']
  189. else:
  190. try:
  191. vm.run_service_for_stdio('qubes.PostInstall')
  192. except subprocess.CalledProcessError:
  193. vm.log.error('qubes.PostInstall service failed')
  194. vm.shutdown()
  195. if have_events:
  196. try:
  197. # pylint: disable=no-member
  198. yield from asyncio.wait_for(
  199. qubesadmin.events.utils.wait_for_domain_shutdown([vm]),
  200. qubesadmin.config.defaults['shutdown_timeout'])
  201. except asyncio.TimeoutError:
  202. vm.kill()
  203. else:
  204. timeout = qubesadmin.config.defaults['shutdown_timeout']
  205. while timeout >= 0:
  206. if vm.is_halted():
  207. break
  208. yield from asyncio.sleep(1)
  209. timeout -= 1
  210. if not vm.is_halted():
  211. try:
  212. vm.kill()
  213. except qubesadmin.exc.QubesVMNotStartedError:
  214. pass
  215. finally:
  216. vm.netvm = qubesadmin.DEFAULT
  217. def validate_ip(ip):
  218. """Check if given string has a valid IP address syntax"""
  219. try:
  220. return all(0 <= int(part) <= 255 for part in ip.split('.', 3))
  221. except ValueError:
  222. return False
  223. @asyncio.coroutine
  224. def post_install(args):
  225. '''Handle post-installation tasks'''
  226. app = args.app
  227. vm_created = False
  228. # reinstall and running in dom0, using the same directory as qubes core
  229. local_reinstall = False
  230. try:
  231. # reinstall
  232. vm = app.domains[args.name]
  233. if app.qubesd_connection_type == 'socket' and \
  234. args.dir == '/var/lib/qubes/vm-templates/' + args.name:
  235. # VM exists and use use the same directory as target vm - on
  236. # final cleanup remove only some files, not the whole directory
  237. local_reinstall = True
  238. except KeyError:
  239. if app.qubesd_connection_type == 'socket' and \
  240. args.dir == '/var/lib/qubes/vm-templates/' + args.name:
  241. # vm.create_on_disk() need to create the directory on its own,
  242. # move it away from its way
  243. tmp_sourcedir = os.path.join('/var/lib/qubes/vm-templates',
  244. 'tmp-' + args.name)
  245. shutil.move(args.dir, tmp_sourcedir)
  246. args.dir = tmp_sourcedir
  247. vm = app.add_new_vm('TemplateVM',
  248. name=args.name,
  249. label=qubesadmin.config.defaults['template_label'],
  250. pool=args.pool)
  251. vm_created = True
  252. vm.log.info('Importing data')
  253. try:
  254. import_root_img(vm, args.dir)
  255. except:
  256. # if data import fails, remove half-created VM
  257. if vm_created:
  258. del app.domains[vm.name]
  259. raise
  260. if not vm_created:
  261. vm.log.info('Clearing private volume')
  262. reset_private_img(vm)
  263. vm.installed_by_rpm = not args.no_installed_by_rpm
  264. # do not generate actual menu entries, if post-install service will be
  265. # executed anyway
  266. import_appmenus(vm, args.dir, skip_generate=not args.skip_start)
  267. conf_path = os.path.join(args.dir, 'template.conf')
  268. if os.path.exists(conf_path):
  269. conf = parse_template_config(conf_path)
  270. # Import qvm-feature tags
  271. for key in (
  272. 'no-monitor-layout',
  273. 'pci-e820-host',
  274. 'linux-stubdom',
  275. 'gui',
  276. 'gui-emulated'
  277. 'qrexec'):
  278. if key in conf:
  279. if conf[key] == '1':
  280. vm.features[key] = conf[key]
  281. else:
  282. vm.log.warning(
  283. 'ignoring boolean config flags that are not \'1\'')
  284. for key in (
  285. 'net.fake-ip',
  286. 'net.fake-gateway',
  287. 'net.fake-netmask'):
  288. if key in conf:
  289. if validate_ip(conf[key]):
  290. vm.features[key] = conf[key]
  291. else:
  292. vm.log.warning(
  293. 'ignoring invalid value for \'%s\'', key)
  294. if 'virt-mode' in conf:
  295. if conf['virt-mode'] == 'pv' and args.allow_pv:
  296. vm.virt_mode = 'pv'
  297. elif conf['virt-mode'] == 'pv':
  298. vm.log.warning(
  299. '--allow-pv not set, ignoring request to change virt-mode')
  300. elif conf['virt-mode'] in ('pvh', 'hvm'):
  301. vm.virt_mode = conf['virt-mode']
  302. else:
  303. vm.log.warning('ignoring invalid value for virt-mode')
  304. if 'kernel' in conf:
  305. if conf['kernel'] == '':
  306. vm.kernel = ''
  307. else:
  308. vm.log.warning(
  309. 'Currently only supports setting kernel to (none)')
  310. if not args.skip_start:
  311. yield from call_postinstall_service(vm)
  312. if not args.keep_source:
  313. if local_reinstall:
  314. # remove only imported root img
  315. root_path = os.path.join(args.dir, 'root.img')
  316. for root_part in glob.glob(root_path + '.part.*'):
  317. os.unlink(root_part)
  318. else:
  319. shutil.rmtree(args.dir)
  320. # if running as root, tell underlying storage layer about just freed
  321. # data blocks
  322. if os.getuid() == 0:
  323. subprocess.call(['sync', '-f', os.path.dirname(args.dir)])
  324. subprocess.call(['fstrim', os.path.dirname(args.dir)])
  325. return 0
  326. def pre_remove(args):
  327. '''Handle pre-removal tasks'''
  328. app = args.app
  329. try:
  330. tpl = app.domains[args.name]
  331. except KeyError:
  332. parser.error('No Qube with this name exists')
  333. for appvm in tpl.appvms:
  334. parser.error('Qube {} uses this template'.format(appvm.name))
  335. tpl.installed_by_rpm = False
  336. del app.domains[args.name]
  337. return 0
  338. def is_chroot():
  339. '''Detect if running inside chroot'''
  340. try:
  341. stat_root = os.stat('/')
  342. stat_init_root = os.stat('/proc/1/root/.')
  343. return (
  344. stat_root.st_dev != stat_init_root.st_dev or
  345. stat_root.st_ino != stat_init_root.st_ino)
  346. except IOError:
  347. return False
  348. def main(args=None, app=None):
  349. '''Main function of qvm-template-postprocess'''
  350. args = parser.parse_args(args, app=app)
  351. if is_chroot():
  352. print('Running in chroot, ignoring request. Import template with:',
  353. file=sys.stderr)
  354. print(' '.join(sys.argv), file=sys.stderr)
  355. return
  356. if not args.really:
  357. parser.error('Do not call this tool directly.')
  358. if args.action == 'post-install':
  359. loop = asyncio.get_event_loop()
  360. try:
  361. loop.run_until_complete(post_install(args))
  362. loop.stop()
  363. loop.run_forever()
  364. finally:
  365. loop.close()
  366. elif args.action == 'pre-remove':
  367. pre_remove(args)
  368. else:
  369. parser.error('Unknown action')
  370. return 0
  371. if __name__ == '__main__':
  372. sys.exit(main())