01QubesHVm.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. #!/usr/bin/python2
  2. # -*- coding: utf-8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2010 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2013 Marek Marczykowski <marmarek@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU General Public License
  11. # as published by the Free Software Foundation; either version 2
  12. # of the License, or (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program; if not, write to the Free Software
  21. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  22. #
  23. #
  24. import os
  25. import os.path
  26. import signal
  27. import subprocess
  28. import stat
  29. import sys
  30. import re
  31. from qubes.qubes import QubesVm,register_qubes_vm_class,xs,xc,dry_run
  32. from qubes.qubes import QubesException,QubesVmCollection
  33. from qubes.qubes import system_path,defaults
  34. system_path["config_template_hvm"] = '/usr/share/qubes/vm-template-hvm.conf'
  35. defaults["hvm_disk_size"] = 20*1024*1024*1024
  36. defaults["hvm_private_img_size"] = 2*1024*1024*1024
  37. defaults["hvm_memory"] = 512
  38. class QubesHVm(QubesVm):
  39. """
  40. A class that represents an HVM. A child of QubesVm.
  41. """
  42. # FIXME: logically should inherit after QubesAppVm, but none of its methods
  43. # are useful for HVM
  44. def get_attrs_config(self):
  45. attrs = super(QubesHVm, self).get_attrs_config()
  46. attrs.pop('kernel')
  47. attrs.pop('kernels_dir')
  48. attrs.pop('kernelopts')
  49. attrs.pop('uses_default_kernel')
  50. attrs.pop('uses_default_kernelopts')
  51. attrs['dir_path']['func'] = lambda value: value if value is not None \
  52. else os.path.join(system_path["qubes_appvms_dir"], self.name)
  53. attrs['config_file_template']['func'] = \
  54. lambda x: system_path["config_template_hvm"]
  55. attrs['drive'] = { 'attr': '_drive',
  56. 'save': lambda: str(self.drive) }
  57. attrs['maxmem'].pop('save')
  58. attrs['timezone'] = { 'default': 'localtime',
  59. 'save': lambda: str(self.timezone) }
  60. attrs['qrexec_installed'] = { 'default': False,
  61. 'attr': '_qrexec_installed',
  62. 'save': lambda: str(self._qrexec_installed) }
  63. attrs['guiagent_installed'] = { 'default' : False,
  64. 'attr': '_guiagent_installed',
  65. 'save': lambda: str(self._guiagent_installed) }
  66. attrs['seamless_gui_mode'] = { 'default': False,
  67. 'attr': '_seamless_gui_mode',
  68. 'save': lambda: str(self._seamless_gui_mode) }
  69. attrs['_start_guid_first']['func'] = lambda x: True
  70. attrs['services']['default'] = "{'meminfo-writer': False}"
  71. attrs['memory']['default'] = defaults["hvm_memory"]
  72. return attrs
  73. def __init__(self, **kwargs):
  74. super(QubesHVm, self).__init__(**kwargs)
  75. # Default for meminfo-writer have changed to (correct) False in the
  76. # same version as introduction of guiagent_installed, so for older VMs
  77. # with wrong setting, change is based on 'guiagent_installed' presence
  78. if "guiagent_installed" not in kwargs and \
  79. (not 'xml_element' in kwargs or kwargs['xml_element'].get('guiagent_installed') is None):
  80. self.services['meminfo-writer'] = False
  81. # HVM normally doesn't support dynamic memory management
  82. if not ('meminfo-writer' in self.services and self.services['meminfo-writer']):
  83. self.maxmem = self.memory
  84. self._stubdom_guid_process = None
  85. @property
  86. def type(self):
  87. return "HVM"
  88. def is_appvm(self):
  89. return True
  90. @classmethod
  91. def is_template_compatible(cls, template):
  92. if template and (not template.is_template() or template.type != "TemplateHVM"):
  93. return False
  94. return True
  95. def get_clone_attrs(self):
  96. attrs = super(QubesHVm, self).get_clone_attrs()
  97. attrs.remove('kernel')
  98. attrs.remove('uses_default_kernel')
  99. attrs.remove('kernelopts')
  100. attrs.remove('uses_default_kernelopts')
  101. attrs += [ 'timezone' ]
  102. attrs += [ 'qrexec_installed' ]
  103. attrs += [ 'guiagent_installed' ]
  104. return attrs
  105. @property
  106. def qrexec_installed(self):
  107. return self._qrexec_installed or \
  108. bool(self.template and self.template.qrexec_installed)
  109. @qrexec_installed.setter
  110. def qrexec_installed(self, value):
  111. if self.template and self.template.qrexec_installed and not value:
  112. print >>sys.stderr, "WARNING: When qrexec_installed set in template, it will be propagated to the VM"
  113. self._qrexec_installed = value
  114. @property
  115. def guiagent_installed(self):
  116. return self._guiagent_installed or \
  117. bool(self.template and self.template.guiagent_installed)
  118. @guiagent_installed.setter
  119. def guiagent_installed(self, value):
  120. if self.template and self.template.guiagent_installed and not value:
  121. print >>sys.stderr, "WARNING: When guiagent_installed set in template, it will be propagated to the VM"
  122. self._guiagent_installed = value
  123. @property
  124. def seamless_gui_mode(self):
  125. if not self.guiagent_installed:
  126. return False
  127. return self._seamless_gui_mode
  128. @seamless_gui_mode.setter
  129. def seamless_gui_mode(self, value):
  130. if self._seamless_gui_mode == value:
  131. return
  132. if not self.guiagent_installed and value:
  133. raise ValueError("Seamless GUI mode requires GUI agent installed")
  134. self._seamless_gui_mode = value
  135. if self.is_running():
  136. self.send_gui_mode()
  137. @property
  138. def drive(self):
  139. return self._drive
  140. @drive.setter
  141. def drive(self, value):
  142. if value is None:
  143. self._drive = None
  144. return
  145. # strip type for a moment
  146. drv_type = "cdrom"
  147. if value.startswith("hd:") or value.startswith("cdrom:"):
  148. (drv_type, unused, value) = value.partition(":")
  149. drv_type = drv_type.lower()
  150. # sanity check
  151. if drv_type not in ['hd', 'cdrom']:
  152. raise QubesException("Unsupported drive type: %s" % type)
  153. if value.count(":") == 0:
  154. value = "dom0:" + value
  155. if value.count(":/") == 0:
  156. # FIXME: when Windows backend will be supported, improve this
  157. raise QubesException("Drive path must be absolute")
  158. self._drive = drv_type + ":" + value
  159. def create_on_disk(self, verbose, source_template = None):
  160. if dry_run:
  161. return
  162. if verbose:
  163. print >> sys.stderr, "--> Creating directory: {0}".format(self.dir_path)
  164. os.mkdir (self.dir_path)
  165. if verbose:
  166. print >> sys.stderr, "--> Creating icon symlink: {0} -> {1}".format(self.icon_path, self.label.icon_path)
  167. os.symlink (self.label.icon_path, self.icon_path)
  168. self.create_config_file()
  169. # create empty disk
  170. if self.template is None:
  171. if verbose:
  172. print >> sys.stderr, "--> Creating root image: {0}".\
  173. format(self.root_img)
  174. f_root = open(self.root_img, "w")
  175. f_root.truncate(defaults["hvm_disk_size"])
  176. f_root.close()
  177. if self.template is None:
  178. # create empty private.img
  179. if verbose:
  180. print >> sys.stderr, "--> Creating private image: {0}".\
  181. format(self.private_img)
  182. f_private = open(self.private_img, "w")
  183. f_private.truncate(defaults["hvm_private_img_size"])
  184. f_private.close()
  185. else:
  186. # copy template private.img
  187. template_priv = self.template.private_img
  188. if verbose:
  189. print >> sys.stderr, "--> Copying the template's private image: {0}".\
  190. format(template_priv)
  191. # We prefer to use Linux's cp, because it nicely handles sparse files
  192. retcode = subprocess.call (["cp", template_priv, self.private_img])
  193. if retcode != 0:
  194. raise IOError ("Error while copying {0} to {1}".\
  195. format(template_priv, self.private_img))
  196. # fire hooks
  197. for hook in self.hooks_create_on_disk:
  198. hook(self, verbose, source_template=source_template)
  199. def get_private_img_sz(self):
  200. if not os.path.exists(self.private_img):
  201. return 0
  202. return os.path.getsize(self.private_img)
  203. def resize_private_img(self, size):
  204. assert size >= self.get_private_img_sz(), "Cannot shrink private.img"
  205. if self.is_running():
  206. raise NotImplementedError("Online resize of HVM's private.img not implemented, shutdown the VM first")
  207. f_private = open (self.private_img, "a+b")
  208. f_private.truncate (size)
  209. f_private.close ()
  210. def resize_root_img(self, size):
  211. if self.template:
  212. raise QubesException("Cannot resize root.img of template-based VM"
  213. ". Resize the root.img of the template "
  214. "instead.")
  215. if self.is_running():
  216. raise QubesException("Cannot resize root.img of running HVM")
  217. if size < self.get_root_img_sz():
  218. raise QubesException(
  219. "For your own safety shringing of root.img is disabled. If "
  220. "you really know what you are doing, use 'truncate' manually.")
  221. f_root = open (self.root_img, "a+b")
  222. f_root.truncate (size)
  223. f_root.close ()
  224. def get_rootdev(self, source_template=None):
  225. if self.template:
  226. return "'script:snapshot:{template_root}:{volatile},xvda,w',".format(
  227. template_root=self.template.root_img,
  228. volatile=self.volatile_img)
  229. else:
  230. return "'script:file:{root_img},xvda,w',".format(root_img=self.root_img)
  231. def get_config_params(self, source_template=None):
  232. params = super(QubesHVm, self).get_config_params(source_template=source_template)
  233. params['volatiledev'] = ''
  234. if self.drive:
  235. type_mode = ":cdrom,r"
  236. (drive_type, drive_domain, drive_path) = self.drive.split(":")
  237. if drive_type == "hd":
  238. type_mode = ",w"
  239. elif drive_type == "cdrom":
  240. type_mode = ":cdrom,r"
  241. # leave empty to use standard syntax in case of dom0
  242. if drive_domain.lower() == "dom0":
  243. backend_domain = ""
  244. else:
  245. backend_domain = "," + drive_domain
  246. # FIXME: os.stat will work only when backend in dom0...
  247. stat_res = None
  248. if backend_domain == "":
  249. stat_res = os.stat(drive_path)
  250. if stat_res and stat.S_ISBLK(stat_res.st_mode):
  251. params['otherdevs'] = "'phy:%s,xvdc%s%s'," % (
  252. drive_path, type_mode, backend_domain)
  253. else:
  254. params['otherdevs'] = "'script:file:%s,xvdc%s%s'," % (
  255. drive_path, type_mode, backend_domain)
  256. else:
  257. params['otherdevs'] = ''
  258. if self.timezone.lower() == 'localtime':
  259. params['localtime'] = '1'
  260. params['timeoffset'] = '0'
  261. elif self.timezone.isdigit():
  262. params['localtime'] = '0'
  263. params['timeoffset'] = self.timezone
  264. else:
  265. print >>sys.stderr, "WARNING: invalid 'timezone' value: %s" % self.timezone
  266. params['localtime'] = '0'
  267. params['timeoffset'] = '0'
  268. return params
  269. def verify_files(self):
  270. if dry_run:
  271. return
  272. if not os.path.exists (self.dir_path):
  273. raise QubesException (
  274. "VM directory doesn't exist: {0}".\
  275. format(self.dir_path))
  276. if self.is_updateable() and not os.path.exists (self.root_img):
  277. raise QubesException (
  278. "VM root image file doesn't exist: {0}".\
  279. format(self.root_img))
  280. if not os.path.exists (self.private_img):
  281. print >>sys.stderr, "WARNING: Creating empty VM private image file: {0}".\
  282. format(self.private_img)
  283. f_private = open(self.private_img, "w")
  284. f_private.truncate(defaults["hvm_private_img_size"])
  285. f_private.close()
  286. # fire hooks
  287. for hook in self.hooks_verify_files:
  288. hook(self)
  289. return True
  290. def reset_volatile_storage(self, **kwargs):
  291. assert not self.is_running(), "Attempt to clean volatile image of running VM!"
  292. source_template = kwargs.get("source_template", self.template)
  293. if source_template is None:
  294. # Nothing to do on non-template based VM
  295. return
  296. if os.path.exists (self.volatile_img):
  297. if self.debug:
  298. if os.path.getmtime(self.template.root_img) > os.path.getmtime(self.volatile_img):
  299. if kwargs.get("verbose", False):
  300. print >>sys.stderr, "--> WARNING: template have changed, resetting root.img"
  301. else:
  302. if kwargs.get("verbose", False):
  303. print >>sys.stderr, "--> Debug mode: not resetting root.img"
  304. print >>sys.stderr, "--> Debug mode: if you want to force root.img reset, either update template VM, or remove volatile.img file"
  305. return
  306. os.remove (self.volatile_img)
  307. f_volatile = open (self.volatile_img, "w")
  308. f_root = open (self.template.root_img, "r")
  309. f_root.seek(0, os.SEEK_END)
  310. f_volatile.truncate (f_root.tell()) # make empty sparse file of the same size as root.img
  311. f_volatile.close ()
  312. f_root.close()
  313. @property
  314. def vif(self):
  315. if self.xid < 0:
  316. return None
  317. if self.netvm is None:
  318. return None
  319. return "vif{0}.+".format(self.stubdom_xid)
  320. @property
  321. def mac(self):
  322. if self._mac is not None:
  323. return self._mac
  324. elif self.template is not None:
  325. return self.template.mac
  326. else:
  327. return "00:16:3E:5E:6C:{qid:02X}".format(qid=self.qid)
  328. @mac.setter
  329. def mac(self, value):
  330. self._mac = value
  331. def run(self, command, **kwargs):
  332. if self.qrexec_installed:
  333. if 'gui' in kwargs and kwargs['gui']==False:
  334. command = "nogui:" + command
  335. return super(QubesHVm, self).run(command, **kwargs)
  336. else:
  337. raise QubesException("Needs qrexec agent installed in VM to use this function. See also qvm-prefs.")
  338. @property
  339. def stubdom_xid(self):
  340. if self.xid < 0:
  341. return -1
  342. stubdom_xid_str = xs.read('', '/local/domain/%d/image/device-model-domid' % self.xid)
  343. if stubdom_xid_str is not None:
  344. return int(stubdom_xid_str)
  345. else:
  346. return -1
  347. def start(self, *args, **kwargs):
  348. if self.template and self.template.is_running():
  349. raise QubesException("Cannot start the HVM while its template is running")
  350. try:
  351. return super(QubesHVm, self).start(*args, **kwargs)
  352. except QubesException as e:
  353. if xc.physinfo()['virt_caps'].count('hvm') == 0:
  354. raise QubesException("Cannot start HVM without VT-x/AMD-v enabled")
  355. else:
  356. raise
  357. def start_stubdom_guid(self):
  358. cmdline = [system_path["qubes_guid_path"],
  359. "-d", str(self.stubdom_xid),
  360. "-c", self.label.color,
  361. "-i", self.label.icon_path,
  362. "-l", str(self.label.index)]
  363. retcode = subprocess.call (cmdline)
  364. if (retcode != 0) :
  365. raise QubesException("Cannot start qubes-guid!")
  366. def start_guid(self, verbose = True, notify_function = None,
  367. before_qrexec=False, **kwargs):
  368. # If user force the guiagent, start_guid will mimic a standard QubesVM
  369. if not before_qrexec and self.guiagent_installed:
  370. super(QubesHVm, self).start_guid(verbose, notify_function, extra_guid_args=["-Q"], **kwargs)
  371. stubdom_guid_pidfile = '/var/run/qubes/guid-running.%d' % self.stubdom_xid
  372. if os.path.exists(stubdom_guid_pidfile) and not self.debug:
  373. try:
  374. stubdom_guid_pid = int(open(stubdom_guid_pidfile, 'r').read())
  375. os.kill(stubdom_guid_pid, signal.SIGTERM)
  376. except Exception as ex:
  377. print >> sys.stderr, "WARNING: Failed to kill stubdom gui daemon: %s" % str(ex)
  378. elif before_qrexec and (not self.guiagent_installed or self.debug):
  379. if verbose:
  380. print >> sys.stderr, "--> Starting Qubes GUId (full screen)..."
  381. self.start_stubdom_guid()
  382. def start_qrexec_daemon(self, **kwargs):
  383. if not self.qrexec_installed:
  384. if kwargs.get('verbose', False):
  385. print >> sys.stderr, "--> Starting the qrexec daemon..."
  386. xid = self.get_xid()
  387. qrexec_env = os.environ.copy()
  388. qrexec_env['QREXEC_STARTUP_NOWAIT'] = '1'
  389. retcode = subprocess.call ([system_path["qrexec_daemon_path"], str(xid), self.name, self.default_user], env=qrexec_env)
  390. if (retcode != 0) :
  391. self.force_shutdown(xid=xid)
  392. raise OSError ("ERROR: Cannot execute qrexec-daemon!")
  393. else:
  394. super(QubesHVm, self).start_qrexec_daemon(**kwargs)
  395. if self._start_guid_first:
  396. if kwargs.get('verbose'):
  397. print >> sys.stderr, "--> Waiting for user '%s' login..." % self.default_user
  398. self.wait_for_session(notify_function=kwargs.get('notify_function', None))
  399. self.send_gui_mode()
  400. def send_gui_mode(self):
  401. if self.seamless_gui_mode:
  402. service_input = "SEAMLESS"
  403. else:
  404. service_input = "FULLSCREEN"
  405. self.run_service("qubes.SetGuiMode", input=service_input)
  406. def create_xenstore_entries(self, xid = None):
  407. if dry_run:
  408. return
  409. super(QubesHVm, self).create_xenstore_entries(xid)
  410. if xid is None:
  411. xid = self.xid
  412. domain_path = xs.get_domain_path(xid)
  413. # Prepare xenstore directory for tools advertise
  414. xs.write('',
  415. "{0}/qubes-tools".format(domain_path),
  416. '')
  417. # Allow VM writes there
  418. xs.set_permissions('', '{0}/qubes-tools'.format(domain_path),
  419. [{ 'dom': xid }])
  420. def _cleanup_zombie_domains(self):
  421. super(QubesHVm, self)._cleanup_zombie_domains()
  422. if not self.is_running():
  423. xc_stubdom = self.get_xc_dominfo(name=self.name+'-dm')
  424. if xc_stubdom is not None:
  425. if xc_stubdom['paused'] == 1:
  426. subprocess.call(['xl', 'destroy', str(xc_stubdom['domid'])])
  427. if xc_stubdom['dying'] == 1:
  428. # GUID still running?
  429. guid_pidfile = \
  430. '/var/run/qubes/guid-running.%d' % xc_stubdom['domid']
  431. if os.path.exists(guid_pidfile):
  432. guid_pid = open(guid_pidfile).read().strip()
  433. os.kill(int(guid_pid), 15)
  434. def suspend(self):
  435. if dry_run:
  436. return
  437. if not self.is_running() and not self.is_paused():
  438. raise QubesException ("VM not running!")
  439. self.pause()
  440. def pause(self):
  441. if dry_run:
  442. return
  443. xc.domain_pause(self.stubdom_xid)
  444. super(QubesHVm, self).pause()
  445. def unpause(self):
  446. if dry_run:
  447. return
  448. xc.domain_unpause(self.stubdom_xid)
  449. super(QubesHVm, self).unpause()
  450. def is_guid_running(self):
  451. # If user force the guiagent, is_guid_running will mimic a standard QubesVM
  452. if self.guiagent_installed:
  453. return super(QubesHVm, self).is_guid_running()
  454. else:
  455. xid = self.stubdom_xid
  456. if xid < 0:
  457. return False
  458. if not os.path.exists('/var/run/qubes/guid-running.%d' % xid):
  459. return False
  460. return True
  461. def is_fully_usable(self):
  462. # Running gui-daemon implies also VM running
  463. if not self.is_guid_running():
  464. return False
  465. if self.qrexec_installed and not self.is_qrexec_running():
  466. return False
  467. return True
  468. register_qubes_vm_class(QubesHVm)