01QubesHVm.py 20 KB

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