app.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2011-2015 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2.1 of the License, or (at your option) any later version.
  13. #
  14. # This library 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 GNU
  17. # Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  21. #
  22. import collections
  23. import copy
  24. import functools
  25. import grp
  26. import itertools
  27. import logging
  28. import os
  29. import random
  30. import sys
  31. import tempfile
  32. import time
  33. import traceback
  34. import uuid
  35. import jinja2
  36. import libvirt
  37. import lxml.etree
  38. try:
  39. import xen.lowlevel.xs # pylint: disable=wrong-import-order
  40. import xen.lowlevel.xc # pylint: disable=wrong-import-order
  41. except ImportError:
  42. pass
  43. if os.name == 'posix':
  44. # pylint: disable=wrong-import-order
  45. import fcntl
  46. elif os.name == 'nt':
  47. # pylint: disable=import-error
  48. import win32con
  49. import win32file
  50. import pywintypes
  51. else:
  52. raise RuntimeError("Qubes works only on POSIX or WinNT systems")
  53. # pylint: disable=wrong-import-position
  54. import qubes
  55. import qubes.ext
  56. import qubes.utils
  57. import qubes.storage
  58. import qubes.storage.reflink
  59. import qubes.vm
  60. import qubes.vm.adminvm
  61. import qubes.vm.qubesvm
  62. import qubes.vm.templatevm
  63. # pylint: enable=wrong-import-position
  64. class VirDomainWrapper:
  65. # pylint: disable=too-few-public-methods
  66. def __init__(self, connection, vm):
  67. self._connection = connection
  68. self._vm = vm
  69. def _reconnect_if_dead(self):
  70. is_dead = not self._vm.connect().isAlive()
  71. if is_dead:
  72. # pylint: disable=protected-access
  73. self._connection._reconnect_if_dead()
  74. self._vm = self._connection._conn.lookupByUUID(self._vm.UUID())
  75. return is_dead
  76. def __getattr__(self, attrname):
  77. attr = getattr(self._vm, attrname)
  78. if not isinstance(attr, collections.Callable):
  79. return attr
  80. @functools.wraps(attr)
  81. def wrapper(*args, **kwargs):
  82. try:
  83. return attr(*args, **kwargs)
  84. except libvirt.libvirtError:
  85. if self._reconnect_if_dead():
  86. return getattr(self._vm, attrname)(*args, **kwargs)
  87. raise
  88. return wrapper
  89. class VirConnectWrapper:
  90. # pylint: disable=too-few-public-methods
  91. def __init__(self, uri):
  92. self._conn = libvirt.open(uri)
  93. def _reconnect_if_dead(self):
  94. is_dead = not self._conn.isAlive()
  95. if is_dead:
  96. self._conn = libvirt.open(self._conn.getURI())
  97. # TODO: re-register event handlers
  98. return is_dead
  99. def _wrap_domain(self, ret):
  100. if isinstance(ret, libvirt.virDomain):
  101. ret = VirDomainWrapper(self, ret)
  102. return ret
  103. def __getattr__(self, attrname):
  104. attr = getattr(self._conn, attrname)
  105. if not isinstance(attr, collections.Callable):
  106. return attr
  107. if attrname == 'close':
  108. return attr
  109. @functools.wraps(attr)
  110. def wrapper(*args, **kwargs):
  111. try:
  112. return self._wrap_domain(attr(*args, **kwargs))
  113. except libvirt.libvirtError:
  114. if self._reconnect_if_dead():
  115. return self._wrap_domain(
  116. getattr(self._conn, attrname)(*args, **kwargs))
  117. raise
  118. return wrapper
  119. class VMMConnection:
  120. '''Connection to Virtual Machine Manager (libvirt)'''
  121. def __init__(self, offline_mode=None):
  122. '''
  123. :param offline_mode: enable/disable offline mode; default is to
  124. enable when running in chroot as root, otherwise disable
  125. '''
  126. if offline_mode is None:
  127. offline_mode = bool(os.getuid() == 0 and
  128. os.stat('/') != os.stat('/proc/1/root/.'))
  129. self._offline_mode = offline_mode
  130. self._libvirt_conn = None
  131. self._xs = None
  132. self._xc = None
  133. @property
  134. def offline_mode(self):
  135. '''Check or enable offline mode (do not actually connect to vmm)'''
  136. return self._offline_mode
  137. def _libvirt_error_handler(self, ctx, error):
  138. pass
  139. def init_vmm_connection(self):
  140. '''Initialise connection
  141. This method is automatically called when getting'''
  142. if self._libvirt_conn is not None:
  143. # Already initialized
  144. return
  145. if self._offline_mode:
  146. # Do not initialize in offline mode
  147. raise qubes.exc.QubesException(
  148. 'VMM operations disabled in offline mode')
  149. if 'xen.lowlevel.xs' in sys.modules:
  150. self._xs = xen.lowlevel.xs.xs()
  151. if 'xen.lowlevel.xc' in sys.modules:
  152. self._xc = xen.lowlevel.xc.xc()
  153. self._libvirt_conn = VirConnectWrapper(
  154. qubes.config.defaults['libvirt_uri'])
  155. libvirt.registerErrorHandler(self._libvirt_error_handler, None)
  156. @property
  157. def libvirt_conn(self):
  158. '''Connection to libvirt'''
  159. self.init_vmm_connection()
  160. return self._libvirt_conn
  161. @property
  162. def xs(self):
  163. '''Connection to Xen Store
  164. This property in available only when running on Xen.
  165. '''
  166. # XXX what about the case when we run under KVM,
  167. # but xen modules are importable?
  168. if 'xen.lowlevel.xs' not in sys.modules:
  169. raise AttributeError(
  170. 'xs object is available under Xen hypervisor only')
  171. self.init_vmm_connection()
  172. return self._xs
  173. @property
  174. def xc(self):
  175. '''Connection to Xen
  176. This property in available only when running on Xen.
  177. '''
  178. # XXX what about the case when we run under KVM,
  179. # but xen modules are importable?
  180. if 'xen.lowlevel.xc' not in sys.modules:
  181. raise AttributeError(
  182. 'xc object is available under Xen hypervisor only')
  183. self.init_vmm_connection()
  184. return self._xc
  185. def close(self):
  186. libvirt.registerErrorHandler(None, None)
  187. if self._xs:
  188. self._xs.close()
  189. self._xs = None
  190. if self._libvirt_conn:
  191. self._libvirt_conn.close()
  192. self._libvirt_conn = None
  193. self._xc = None # and pray it will get garbage-collected
  194. class QubesHost:
  195. '''Basic information about host machine
  196. :param qubes.Qubes app: Qubes application context (must have \
  197. :py:attr:`Qubes.vmm` attribute defined)
  198. '''
  199. def __init__(self, app):
  200. self.app = app
  201. self._no_cpus = None
  202. self._total_mem = None
  203. self._physinfo = None
  204. def _fetch(self):
  205. if self._no_cpus is not None:
  206. return
  207. # pylint: disable=unused-variable
  208. (model, memory, cpus, mhz, nodes, socket, cores, threads) = \
  209. self.app.vmm.libvirt_conn.getInfo()
  210. self._total_mem = int(memory) * 1024
  211. self._no_cpus = cpus
  212. self.app.log.debug('QubesHost: no_cpus={} memory_total={}'.format(
  213. self.no_cpus, self.memory_total))
  214. try:
  215. self.app.log.debug('QubesHost: xen_free_memory={}'.format(
  216. self.get_free_xen_memory()))
  217. except NotImplementedError:
  218. pass
  219. @property
  220. def memory_total(self):
  221. '''Total memory, in kbytes'''
  222. if self.app.vmm.offline_mode:
  223. return 2**64-1
  224. self._fetch()
  225. return self._total_mem
  226. @property
  227. def no_cpus(self):
  228. '''Number of CPUs'''
  229. if self.app.vmm.offline_mode:
  230. return 42
  231. self._fetch()
  232. return self._no_cpus
  233. def get_free_xen_memory(self):
  234. '''Get free memory from Xen's physinfo.
  235. :raises NotImplementedError: when not under Xen
  236. '''
  237. try:
  238. self._physinfo = self.app.xc.physinfo()
  239. except AttributeError:
  240. raise NotImplementedError('This function requires Xen hypervisor')
  241. return int(self._physinfo['free_memory'])
  242. def get_vm_stats(self, previous_time=None, previous=None, only_vm=None):
  243. '''Measure cpu usage for all domains at once.
  244. If previous measurements are given, CPU usage will be given in
  245. percents of time. Otherwise only absolute value (seconds).
  246. Return a tuple of (measurements_time, measurements),
  247. where measurements is a dictionary with key: domid, value: dict:
  248. - cpu_time - absolute CPU usage (seconds since its startup)
  249. - cpu_usage - CPU usage in %
  250. - memory_kb - current memory assigned, in kb
  251. This function requires Xen hypervisor.
  252. ..warning:
  253. This function may return info about implementation-specific VMs,
  254. like stubdomains for HVM
  255. :param previous: previous measurement
  256. :param previous_time: time of previous measurement
  257. :param only_vm: get measurements only for this VM
  258. :raises NotImplementedError: when not under Xen
  259. '''
  260. if (previous_time is None) != (previous is None):
  261. raise ValueError(
  262. 'previous and previous_time must be given together (or none)')
  263. if previous is None:
  264. previous = {}
  265. current_time = time.time()
  266. current = {}
  267. try:
  268. if only_vm:
  269. xid = only_vm.xid
  270. if xid < 0:
  271. raise qubes.exc.QubesVMNotRunningError(only_vm)
  272. info = self.app.vmm.xc.domain_getinfo(xid, 1)
  273. if info[0]['domid'] != xid:
  274. raise qubes.exc.QubesVMNotRunningError(only_vm)
  275. else:
  276. info = self.app.vmm.xc.domain_getinfo(0, 1024)
  277. except AttributeError:
  278. raise NotImplementedError(
  279. 'This function requires Xen hypervisor')
  280. # TODO: add stubdomain stats to actual VMs
  281. for vm in info:
  282. domid = vm['domid']
  283. current[domid] = {}
  284. current[domid]['memory_kb'] = vm['mem_kb']
  285. current[domid]['cpu_time'] = int(
  286. vm['cpu_time'] / max(vm['online_vcpus'], 1))
  287. if domid in previous:
  288. current[domid]['cpu_usage'] = int(
  289. (current[domid]['cpu_time'] - previous[domid]['cpu_time'])
  290. / 1000 ** 3 * 100 / (current_time - previous_time))
  291. if current[domid]['cpu_usage'] < 0:
  292. # VM has been rebooted
  293. current[domid]['cpu_usage'] = 0
  294. else:
  295. current[domid]['cpu_usage'] = 0
  296. return (current_time, current)
  297. class VMCollection:
  298. '''A collection of Qubes VMs
  299. VMCollection supports ``in`` operator. You may test for ``qid``, ``name``
  300. and whole VM object's presence.
  301. Iterating over VMCollection will yield machine objects.
  302. '''
  303. def __init__(self, app):
  304. self.app = app
  305. self._dict = dict()
  306. def close(self):
  307. del self.app
  308. self._dict.clear()
  309. del self._dict
  310. def __repr__(self):
  311. return '<{} {!r}>'.format(
  312. self.__class__.__name__, list(sorted(self.keys())))
  313. def items(self):
  314. '''Iterate over ``(qid, vm)`` pairs'''
  315. for qid in self.qids():
  316. yield (qid, self[qid])
  317. def qids(self):
  318. '''Iterate over all qids
  319. qids are sorted by numerical order.
  320. '''
  321. return iter(sorted(self._dict.keys()))
  322. keys = qids
  323. def names(self):
  324. '''Iterate over all names
  325. names are sorted by lexical order.
  326. '''
  327. return iter(sorted(vm.name for vm in self._dict.values()))
  328. def vms(self):
  329. '''Iterate over all machines
  330. vms are sorted by qid.
  331. '''
  332. return iter(sorted(self._dict.values()))
  333. __iter__ = vms
  334. values = vms
  335. def add(self, value, _enable_events=True):
  336. '''Add VM to collection
  337. :param qubes.vm.BaseVM value: VM to add
  338. :raises TypeError: when value is of wrong type
  339. :raises ValueError: when there is already VM which has equal ``qid``
  340. '''
  341. # this violates duck typing, but is needed
  342. # for VMProperty to function correctly
  343. if not isinstance(value, qubes.vm.BaseVM):
  344. raise TypeError('{} holds only BaseVM instances'.format(
  345. self.__class__.__name__))
  346. if value.qid in self:
  347. raise ValueError('This collection already holds VM that has '
  348. 'qid={!r} ({!r})'.format(value.qid, self[value.qid]))
  349. if value.name in self:
  350. raise ValueError('A VM named {!s} already exists'
  351. .format(value.name))
  352. self._dict[value.qid] = value
  353. if _enable_events:
  354. value.events_enabled = True
  355. self.app.fire_event('domain-add', vm=value)
  356. return value
  357. def __getitem__(self, key):
  358. if isinstance(key, int):
  359. return self._dict[key]
  360. if isinstance(key, str):
  361. for vm in self:
  362. if vm.name == key:
  363. return vm
  364. raise KeyError(key)
  365. if isinstance(key, qubes.vm.BaseVM):
  366. key = key.uuid
  367. if isinstance(key, uuid.UUID):
  368. for vm in self:
  369. if vm.uuid == key:
  370. return vm
  371. raise KeyError(key)
  372. raise KeyError(key)
  373. def __delitem__(self, key):
  374. vm = self[key]
  375. if not vm.is_halted():
  376. raise qubes.exc.QubesVMNotHaltedError(vm)
  377. self.app.fire_event('domain-pre-delete', pre_event=True, vm=vm)
  378. try:
  379. if vm.libvirt_domain:
  380. vm.libvirt_domain.undefine()
  381. # pylint: disable=protected-access
  382. vm._libvirt_domain = None
  383. except libvirt.libvirtError as e:
  384. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  385. # already undefined
  386. pass
  387. del self._dict[vm.qid]
  388. self.app.fire_event('domain-delete', vm=vm)
  389. def __contains__(self, key):
  390. return any((key in (vm, vm.qid, vm.name))
  391. for vm in self)
  392. def __len__(self):
  393. return len(self._dict)
  394. def get_vms_based_on(self, template):
  395. template = self[template]
  396. return set(vm for vm in self
  397. if hasattr(vm, 'template') and vm.template == template)
  398. def get_vms_connected_to(self, netvm):
  399. new_vms = set([self[netvm]])
  400. dependent_vms = set()
  401. # Dependency resolving only makes sense on NetVM (or derivative)
  402. # if not self[netvm_qid].is_netvm():
  403. # return set([])
  404. while new_vms:
  405. cur_vm = new_vms.pop()
  406. for vm in cur_vm.connected_vms:
  407. if vm in dependent_vms:
  408. continue
  409. dependent_vms.add(vm)
  410. # if vm.is_netvm():
  411. new_vms.add(vm)
  412. return dependent_vms
  413. # XXX with Qubes Admin Api this will probably lead to race condition
  414. # whole process of creating and adding should be synchronised
  415. def get_new_unused_qid(self):
  416. used_ids = set(self.qids())
  417. for i in range(1, qubes.config.max_qid):
  418. if i not in used_ids:
  419. return i
  420. raise LookupError("Cannot find unused qid!")
  421. def get_new_unused_dispid(self):
  422. for _ in range(int(qubes.config.max_dispid ** 0.5)):
  423. dispid = random.SystemRandom().randrange(qubes.config.max_dispid)
  424. if not any(getattr(vm, 'dispid', None) == dispid for vm in self):
  425. return dispid
  426. raise LookupError((
  427. 'https://xkcd.com/221/',
  428. 'http://dilbert.com/strip/2001-10-25')[random.randint(0, 1)])
  429. def _default_pool(app):
  430. ''' Default storage pool.
  431. 1. If there is one named 'default', use it.
  432. 2. Check if root fs is on LVM thin - use that
  433. 3. Look for file(-reflink)-based pool pointing to /var/lib/qubes
  434. 4. Fail
  435. '''
  436. if 'default' in app.pools:
  437. return app.pools['default']
  438. if 'DEFAULT_LVM_POOL' in os.environ:
  439. thin_pool = os.environ['DEFAULT_LVM_POOL']
  440. for pool in app.pools.values():
  441. if pool.config.get('driver', None) != 'lvm_thin':
  442. continue
  443. if pool.config['thin_pool'] == thin_pool:
  444. return pool
  445. # no DEFAULT_LVM_POOL, or pool not defined
  446. root_volume_group, root_thin_pool = \
  447. qubes.storage.DirectoryThinPool.thin_pool('/')
  448. if root_thin_pool:
  449. for pool in app.pools.values():
  450. if pool.config.get('driver', None) != 'lvm_thin':
  451. continue
  452. if (pool.config['volume_group'] == root_volume_group and
  453. pool.config['thin_pool'] == root_thin_pool):
  454. return pool
  455. # not a thin volume? look for file pools
  456. for pool in app.pools.values():
  457. if pool.config.get('driver', None) not in ('file', 'file-reflink'):
  458. continue
  459. if pool.config['dir_path'] == qubes.config.qubes_base_dir:
  460. return pool
  461. raise AttributeError('Cannot determine default storage pool')
  462. def _setter_pool(app, prop, value):
  463. if isinstance(value, qubes.storage.Pool):
  464. return value
  465. try:
  466. return app.pools[value]
  467. except KeyError:
  468. raise qubes.exc.QubesPropertyValueError(app, prop, value,
  469. 'No such storage pool')
  470. def _setter_default_netvm(app, prop, value):
  471. # skip netvm loop check while loading qubes.xml, to avoid tricky loading
  472. # order
  473. if not app.events_enabled:
  474. return value
  475. if value is None:
  476. return value
  477. # forbid setting to a value that would result in netvm loop
  478. for vm in app.domains:
  479. if not hasattr(vm, 'netvm'):
  480. continue
  481. if not vm.property_is_default('netvm'):
  482. continue
  483. if value == vm \
  484. or value in app.domains.get_vms_connected_to(vm):
  485. raise qubes.exc.QubesPropertyValueError(app, prop, value,
  486. 'Network loop on \'{!s}\''.format(vm))
  487. return value
  488. class Qubes(qubes.PropertyHolder):
  489. '''Main Qubes application
  490. :param str store: path to ``qubes.xml``
  491. The store is loaded in stages:
  492. 1. In the first stage there are loaded some basic features from store
  493. (currently labels).
  494. 2. In the second stage stubs for all VMs are loaded. They are filled
  495. with their basic properties, like ``qid`` and ``name``.
  496. 3. In the third stage all global properties are loaded. They often
  497. reference VMs, like default netvm, so they should be filled after
  498. loading VMs.
  499. 4. In the fourth stage all remaining VM properties are loaded. They
  500. also need all VMs loaded, because they represent dependencies
  501. between VMs like aforementioned netvm.
  502. 5. In the fifth stage there are some fixups to ensure sane system
  503. operation.
  504. This class emits following events:
  505. .. event:: domain-add (subject, event, vm)
  506. When domain is added.
  507. :param subject: Event emitter
  508. :param event: Event name (``'domain-add'``)
  509. :param vm: Domain object
  510. .. event:: domain-pre-delete (subject, event, vm)
  511. When domain is deleted. VM still has reference to ``app`` object,
  512. and is contained within VMCollection. You may prevent removal by
  513. raising an exception.
  514. :param subject: Event emitter
  515. :param event: Event name (``'domain-pre-delete'``)
  516. :param vm: Domain object
  517. .. event:: domain-delete (subject, event, vm)
  518. When domain is deleted. VM still has reference to ``app`` object,
  519. but is not contained within VMCollection.
  520. :param subject: Event emitter
  521. :param event: Event name (``'domain-delete'``)
  522. :param vm: Domain object
  523. Methods and attributes:
  524. '''
  525. default_netvm = qubes.VMProperty('default_netvm', load_stage=3,
  526. default=None, allow_none=True,
  527. setter=_setter_default_netvm,
  528. doc='''Default NetVM for AppVMs. Initial state is `None`, which means
  529. that AppVMs are not connected to the Internet.''')
  530. default_template = qubes.VMProperty('default_template', load_stage=3,
  531. vmclass=qubes.vm.templatevm.TemplateVM,
  532. doc='Default template for new AppVMs')
  533. updatevm = qubes.VMProperty('updatevm', load_stage=3,
  534. default=None, allow_none=True,
  535. doc='''Which VM to use as `yum` proxy for updating AdminVM and
  536. TemplateVMs''')
  537. clockvm = qubes.VMProperty('clockvm', load_stage=3,
  538. default=None, allow_none=True,
  539. doc='Which VM to use as NTP proxy for updating AdminVM')
  540. default_kernel = qubes.property('default_kernel', load_stage=3,
  541. doc='Which kernel to use when not overriden in VM')
  542. default_dispvm = qubes.VMProperty('default_dispvm', load_stage=3,
  543. default=None,
  544. doc='Default DispVM base for service calls', allow_none=True)
  545. default_pool = qubes.property('default_pool', load_stage=3,
  546. default=_default_pool,
  547. setter=_setter_pool,
  548. doc='Default storage pool')
  549. default_pool_private = qubes.property('default_pool_private', load_stage=3,
  550. default=lambda app: app.default_pool,
  551. setter=_setter_pool,
  552. doc='Default storage pool for private volumes')
  553. default_pool_root = qubes.property('default_pool_root', load_stage=3,
  554. default=lambda app: app.default_pool,
  555. setter=_setter_pool,
  556. doc='Default storage pool for root volumes')
  557. default_pool_volatile = qubes.property('default_pool_volatile',
  558. load_stage=3,
  559. default=lambda app: app.default_pool,
  560. setter=_setter_pool,
  561. doc='Default storage pool for volatile volumes')
  562. default_pool_kernel = qubes.property('default_pool_kernel', load_stage=3,
  563. default=lambda app: app.default_pool,
  564. setter=_setter_pool,
  565. doc='Default storage pool for kernel volumes')
  566. default_qrexec_timeout = qubes.property('default_qrexec_timeout',
  567. load_stage=3,
  568. default=60,
  569. type=int,
  570. doc='''Default time in seconds after which qrexec connection attempt is
  571. deemed failed''')
  572. stats_interval = qubes.property('stats_interval',
  573. default=3,
  574. type=int,
  575. doc='Interval in seconds for VM stats reporting (memory, CPU usage)')
  576. # TODO #1637 #892
  577. check_updates_vm = qubes.property('check_updates_vm',
  578. type=bool, setter=qubes.property.bool,
  579. default=True,
  580. doc='check for updates inside qubes')
  581. def __init__(self, store=None, load=True, offline_mode=None, lock=False,
  582. **kwargs):
  583. #: logger instance for logging global messages
  584. self.log = logging.getLogger('app')
  585. self.log.debug('init() -> %#x', id(self))
  586. self.log.debug('stack:')
  587. for frame in traceback.extract_stack():
  588. self.log.debug('%s', frame)
  589. self._extensions = qubes.ext.get_extensions()
  590. #: collection of all VMs managed by this Qubes instance
  591. self.domains = VMCollection(self)
  592. #: collection of all available labels for VMs
  593. self.labels = {}
  594. #: collection of all pools
  595. self.pools = {}
  596. #: Connection to VMM
  597. self.vmm = VMMConnection(offline_mode=offline_mode)
  598. #: Information about host system
  599. self.host = QubesHost(self)
  600. if store is not None:
  601. self._store = store
  602. else:
  603. self._store = os.environ.get('QUBES_XML_PATH',
  604. os.path.join(
  605. qubes.config.qubes_base_dir,
  606. qubes.config.system_path['qubes_store_filename']))
  607. super(Qubes, self).__init__(xml=None, **kwargs)
  608. self.__load_timestamp = None
  609. self.__locked_fh = None
  610. self._domain_event_callback_id = None
  611. #: jinja2 environment for libvirt XML templates
  612. self.env = jinja2.Environment(
  613. loader=jinja2.FileSystemLoader([
  614. '/etc/qubes/templates',
  615. '/usr/share/qubes/templates',
  616. ]),
  617. undefined=jinja2.StrictUndefined)
  618. if load:
  619. self.load(lock=lock)
  620. self.events_enabled = True
  621. @property
  622. def store(self):
  623. return self._store
  624. def _migrate_global_properties(self):
  625. '''Migrate renamed/dropped properties'''
  626. if self.xml is None:
  627. return
  628. # drop default_fw_netvm
  629. node_default_fw_netvm = self.xml.find(
  630. './properties/property[@name=\'default_fw_netvm\']')
  631. if node_default_fw_netvm is not None:
  632. node_default_netvm = self.xml.find(
  633. './properties/property[@name=\'default_netvm\']')
  634. try:
  635. default_fw_netvm = self.domains[node_default_fw_netvm.text]
  636. if node_default_netvm is None:
  637. default_netvm = None
  638. else:
  639. default_netvm = self.domains[node_default_netvm.text]
  640. if default_netvm != default_fw_netvm:
  641. for vm in self.domains:
  642. if not hasattr(vm, 'netvm'):
  643. continue
  644. if not getattr(vm, 'provides_network', False):
  645. continue
  646. node_netvm = vm.xml.find(
  647. './properties/property[@name=\'netvm\']')
  648. if node_netvm is not None:
  649. # non-default netvm
  650. continue
  651. # this will unfortunately break "being default"
  652. # property state, but the alternative (changing
  653. # value behind user's back) is worse
  654. properties = vm.xml.find('./properties')
  655. element = lxml.etree.Element('property',
  656. name='netvm')
  657. element.text = default_fw_netvm.name
  658. # manipulate xml directly, before loading netvm
  659. # property, to avoid hitting netvm loop detection
  660. properties.append(element)
  661. except KeyError:
  662. # if default_fw_netvm was set to invalid value, simply
  663. # drop it
  664. pass
  665. node_default_fw_netvm.getparent().remove(node_default_fw_netvm)
  666. def load(self, lock=False):
  667. '''Open qubes.xml
  668. :throws EnvironmentError: failure on parsing store
  669. :throws xml.parsers.expat.ExpatError: failure on parsing store
  670. :raises lxml.etree.XMLSyntaxError: on syntax error in qubes.xml
  671. '''
  672. fh = self._acquire_lock()
  673. self.xml = lxml.etree.parse(fh)
  674. # stage 1: load labels and pools
  675. for node in self.xml.xpath('./labels/label'):
  676. label = qubes.Label.fromxml(node)
  677. self.labels[label.index] = label
  678. for node in self.xml.xpath('./pools/pool'):
  679. name = node.get('name')
  680. assert name, "Pool name '%s' is invalid " % name
  681. try:
  682. self.pools[name] = self._get_pool(**node.attrib)
  683. except qubes.exc.QubesException as e:
  684. self.log.error(str(e))
  685. # stage 2: load VMs
  686. for node in self.xml.xpath('./domains/domain'):
  687. # pylint: disable=no-member
  688. cls = self.get_vm_class(node.get('class'))
  689. vm = cls(self, node)
  690. vm.load_properties(load_stage=2)
  691. vm.init_log()
  692. self.domains.add(vm, _enable_events=False)
  693. if 0 not in self.domains:
  694. self.domains.add(
  695. qubes.vm.adminvm.AdminVM(self, None),
  696. _enable_events=False)
  697. self._migrate_global_properties()
  698. # stage 3: load global properties
  699. self.load_properties(load_stage=3)
  700. # stage 4: fill all remaining VM properties
  701. for vm in self.domains:
  702. vm.load_properties(load_stage=4)
  703. vm.load_extras()
  704. # stage 5: misc fixups
  705. self.property_require('default_netvm', allow_none=True)
  706. self.property_require('default_template')
  707. self.property_require('clockvm', allow_none=True)
  708. self.property_require('updatevm', allow_none=True)
  709. for vm in self.domains:
  710. vm.events_enabled = True
  711. vm.fire_event('domain-load')
  712. # get a file timestamp (before closing it - still holding the lock!),
  713. # to detect whether anyone else have modified it in the meantime
  714. self.__load_timestamp = os.path.getmtime(self._store)
  715. if not lock:
  716. self._release_lock()
  717. def __xml__(self):
  718. element = lxml.etree.Element('qubes')
  719. element.append(self.xml_labels())
  720. pools_xml = lxml.etree.Element('pools')
  721. for pool in self.pools.values():
  722. xml = pool.__xml__()
  723. if xml is not None:
  724. pools_xml.append(xml)
  725. element.append(pools_xml)
  726. element.append(self.xml_properties())
  727. domains = lxml.etree.Element('domains')
  728. for vm in self.domains:
  729. domains.append(vm.__xml__())
  730. element.append(domains)
  731. return element
  732. def __str__(self):
  733. return type(self).__name__
  734. def save(self, lock=True):
  735. '''Save all data to qubes.xml
  736. There are several problems with saving :file:`qubes.xml` which must be
  737. mitigated:
  738. - Running out of disk space. No space left should not result in empty
  739. file. This is done by writing to temporary file and then renaming.
  740. - Attempts to write two or more files concurrently. This is done by
  741. sophisticated locking.
  742. :param bool lock: keep file locked after saving
  743. :throws EnvironmentError: failure on saving
  744. '''
  745. if not self.__locked_fh:
  746. self._acquire_lock(for_save=True)
  747. fh_new = tempfile.NamedTemporaryFile(
  748. prefix=self._store, delete=False)
  749. lxml.etree.ElementTree(self.__xml__()).write(
  750. fh_new, encoding='utf-8', pretty_print=True)
  751. fh_new.flush()
  752. try:
  753. os.chown(fh_new.name, -1, grp.getgrnam('qubes').gr_gid)
  754. os.chmod(fh_new.name, 0o660)
  755. except KeyError: # group 'qubes' not found
  756. # don't change mode if no 'qubes' group in the system
  757. pass
  758. os.rename(fh_new.name, self._store)
  759. # update stored mtime, in case of multiple save() calls without
  760. # loading qubes.xml again
  761. self.__load_timestamp = os.path.getmtime(self._store)
  762. # this releases lock for all other processes,
  763. # but they should instantly block on the new descriptor
  764. self.__locked_fh.close()
  765. self.__locked_fh = fh_new
  766. if not lock:
  767. self._release_lock()
  768. def close(self):
  769. '''Deconstruct the object and break circular references
  770. After calling this the object is unusable, not even for saving.'''
  771. self.log.debug('close() <- %#x', id(self))
  772. for frame in traceback.extract_stack():
  773. self.log.debug('%s', frame)
  774. super().close()
  775. if self._domain_event_callback_id is not None:
  776. self.vmm.libvirt_conn.domainEventDeregisterAny(
  777. self._domain_event_callback_id)
  778. self._domain_event_callback_id = None
  779. # Only our Lord, The God Almighty, knows what references
  780. # are kept in extensions.
  781. del self._extensions
  782. for vm in self.domains:
  783. vm.close()
  784. self.domains.close()
  785. del self.domains
  786. self.vmm.close()
  787. del self.vmm
  788. del self.host
  789. if self.__locked_fh:
  790. self._release_lock()
  791. def _acquire_lock(self, for_save=False):
  792. assert self.__locked_fh is None, 'double lock'
  793. while True:
  794. try:
  795. fd = os.open(self._store,
  796. os.O_RDWR | (os.O_CREAT * int(for_save)))
  797. except FileNotFoundError:
  798. if not for_save:
  799. raise qubes.exc.QubesException(
  800. 'Qubes XML store {!r} is missing; '
  801. 'use qubes-create tool'.format(self._store))
  802. raise
  803. # While we were waiting for lock, someone could have unlink()ed
  804. # (or rename()d) our file out of the filesystem. We have to
  805. # ensure we got lock on something linked to filesystem.
  806. # If not, try again.
  807. if os.fstat(fd) != os.stat(self._store):
  808. os.close(fd)
  809. continue
  810. if self.__load_timestamp and \
  811. os.path.getmtime(self._store) != self.__load_timestamp:
  812. os.close(fd)
  813. raise qubes.exc.QubesException(
  814. 'Someone else modified qubes.xml in the meantime')
  815. break
  816. if os.name == 'posix':
  817. fcntl.lockf(fd, fcntl.LOCK_EX)
  818. elif os.name == 'nt':
  819. # pylint: disable=protected-access
  820. overlapped = pywintypes.OVERLAPPED()
  821. win32file.LockFileEx(
  822. win32file._get_osfhandle(fd),
  823. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  824. self.__locked_fh = os.fdopen(fd, 'r+b')
  825. return self.__locked_fh
  826. def _release_lock(self):
  827. assert self.__locked_fh is not None, 'double release'
  828. # intentionally do not call explicit unlock to not unlock the file
  829. # before all buffers are flushed
  830. self.__locked_fh.close()
  831. self.__locked_fh = None
  832. def load_initial_values(self):
  833. self.labels = {
  834. 1: qubes.Label(1, '0xcc0000', 'red'),
  835. 2: qubes.Label(2, '0xf57900', 'orange'),
  836. 3: qubes.Label(3, '0xedd400', 'yellow'),
  837. 4: qubes.Label(4, '0x73d216', 'green'),
  838. 5: qubes.Label(5, '0x555753', 'gray'),
  839. 6: qubes.Label(6, '0x3465a4', 'blue'),
  840. 7: qubes.Label(7, '0x75507b', 'purple'),
  841. 8: qubes.Label(8, '0x000000', 'black'),
  842. }
  843. assert max(self.labels.keys()) == qubes.config.max_default_label
  844. pool_configs = copy.deepcopy(qubes.config.defaults['pool_configs'])
  845. root_volume_group, root_thin_pool = \
  846. qubes.storage.DirectoryThinPool.thin_pool('/')
  847. if root_thin_pool:
  848. lvm_config = {
  849. 'name': 'lvm',
  850. 'driver': 'lvm_thin',
  851. 'volume_group': root_volume_group,
  852. 'thin_pool': root_thin_pool
  853. }
  854. pool_configs[lvm_config['name']] = lvm_config
  855. for name, config in pool_configs.items():
  856. if 'driver' not in config and 'dir_path' in config:
  857. config['driver'] = 'file'
  858. try:
  859. os.makedirs(config['dir_path'], exist_ok=True)
  860. if qubes.storage.reflink.is_supported(config['dir_path']):
  861. config['driver'] = 'file-reflink'
  862. config['setup_check'] = 'no' # don't check twice
  863. except PermissionError: # looks like a testing environment
  864. pass # stay with 'file'
  865. self.pools[name] = self._get_pool(**config)
  866. self.default_pool_kernel = 'linux-kernel'
  867. self.domains.add(
  868. qubes.vm.adminvm.AdminVM(self, None, label='black'))
  869. @classmethod
  870. def create_empty_store(cls, *args, **kwargs):
  871. self = cls(*args, load=False, **kwargs)
  872. if os.path.exists(self.store):
  873. raise qubes.exc.QubesException(
  874. '{} already exists, aborting'.format(self.store))
  875. self.load_initial_values()
  876. # TODO py3 get lock= as keyword-only arg
  877. self.save(kwargs.get('lock'))
  878. return self
  879. def xml_labels(self):
  880. '''Serialise labels
  881. :rtype: lxml.etree._Element
  882. '''
  883. labels = lxml.etree.Element('labels')
  884. for label in sorted(self.labels.values(), key=lambda labl: labl.index):
  885. labels.append(label.__xml__())
  886. return labels
  887. @staticmethod
  888. def get_vm_class(clsname):
  889. '''Find the class for a domain.
  890. Classes are registered as setuptools' entry points in ``qubes.vm``
  891. group. Any package may supply their own classes.
  892. :param str clsname: name of the class
  893. :return type: class
  894. '''
  895. try:
  896. return qubes.utils.get_entry_point_one(
  897. qubes.vm.VM_ENTRY_POINT, clsname)
  898. except KeyError:
  899. raise qubes.exc.QubesException(
  900. 'no such VM class: {!r}'.format(clsname))
  901. # don't catch TypeError
  902. def add_new_vm(self, cls, qid=None, **kwargs):
  903. '''Add new Virtual Machine to collection
  904. '''
  905. if qid is None:
  906. qid = self.domains.get_new_unused_qid()
  907. if isinstance(cls, str):
  908. cls = self.get_vm_class(cls)
  909. # handle default template; specifically allow template=None (do not
  910. # override it with default template)
  911. if 'template' not in kwargs and hasattr(cls, 'template'):
  912. if cls == self.get_vm_class('DispVM'):
  913. kwargs['template'] = self.default_dispvm
  914. else:
  915. kwargs['template'] = self.default_template
  916. elif 'template' in kwargs and isinstance(kwargs['template'], str):
  917. kwargs['template'] = self.domains[kwargs['template']]
  918. return self.domains.add(cls(self, None, qid=qid, **kwargs))
  919. def get_label(self, label):
  920. '''Get label as identified by index or name
  921. :throws KeyError: when label is not found
  922. '''
  923. # first search for index, verbatim
  924. try:
  925. return self.labels[label]
  926. except KeyError:
  927. pass
  928. # then search for name
  929. for i in self.labels.values():
  930. if i.name == label:
  931. return i
  932. # last call, if label is a number represented as str, search in indices
  933. try:
  934. return self.labels[int(label)]
  935. except (KeyError, ValueError):
  936. pass
  937. raise KeyError(label)
  938. def setup_pools(self):
  939. """ Run implementation specific setup for each storage pool. """
  940. for pool in self.pools.values():
  941. pool.setup()
  942. def add_pool(self, name, **kwargs):
  943. """ Add a storage pool to config."""
  944. if name in self.pools.keys():
  945. raise qubes.exc.QubesException('pool named %s already exists \n' %
  946. name)
  947. kwargs['name'] = name
  948. pool = self._get_pool(**kwargs)
  949. pool.setup()
  950. self.pools[name] = pool
  951. return pool
  952. def remove_pool(self, name):
  953. """ Remove a storage pool from config file. """
  954. try:
  955. pool = self.pools[name]
  956. del self.pools[name]
  957. pool.destroy()
  958. except KeyError:
  959. return
  960. def get_pool(self, pool):
  961. ''' Returns a :py:class:`qubes.storage.Pool` instance '''
  962. if isinstance(pool, qubes.storage.Pool):
  963. return pool
  964. try:
  965. return self.pools[pool]
  966. except KeyError:
  967. raise qubes.exc.QubesException('Unknown storage pool ' + pool)
  968. @staticmethod
  969. def _get_pool(**kwargs):
  970. try:
  971. name = kwargs['name']
  972. assert name, 'Name needs to be an non empty string'
  973. except KeyError:
  974. raise qubes.exc.QubesException('No pool name for pool')
  975. try:
  976. driver = kwargs['driver']
  977. except KeyError:
  978. raise qubes.exc.QubesException('No driver specified for pool ' +
  979. name)
  980. try:
  981. klass = qubes.utils.get_entry_point_one(
  982. qubes.storage.STORAGE_ENTRY_POINT, driver)
  983. del kwargs['driver']
  984. return klass(**kwargs)
  985. except KeyError:
  986. raise qubes.exc.QubesException('No driver %s for pool %s' %
  987. (driver, name))
  988. def register_event_handlers(self):
  989. '''Register libvirt event handlers, which will translate libvirt
  990. events into qubes.events. This function should be called only in
  991. 'qubesd' process and only when mainloop has been already set.
  992. '''
  993. self._domain_event_callback_id = (
  994. self.vmm.libvirt_conn.domainEventRegisterAny(
  995. None, # any domain
  996. libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
  997. self._domain_event_callback,
  998. None))
  999. def _domain_event_callback(self, _conn, domain, event, _detail, _opaque):
  1000. '''Generic libvirt event handler (virConnectDomainEventCallback),
  1001. translate libvirt event into qubes.events.
  1002. '''
  1003. if not self.events_enabled:
  1004. return
  1005. try:
  1006. vm = self.domains[domain.name()]
  1007. except KeyError:
  1008. # ignore events for unknown domains
  1009. return
  1010. if event == libvirt.VIR_DOMAIN_EVENT_STOPPED:
  1011. vm.on_libvirt_domain_stopped()
  1012. elif event == libvirt.VIR_DOMAIN_EVENT_SUSPENDED:
  1013. try:
  1014. vm.fire_event('domain-paused')
  1015. except Exception: # pylint: disable=broad-except
  1016. self.log.exception(
  1017. 'Uncaught exception from domain-paused handler '
  1018. 'for domain %s', vm.name)
  1019. elif event == libvirt.VIR_DOMAIN_EVENT_RESUMED:
  1020. try:
  1021. vm.fire_event('domain-unpaused')
  1022. except Exception: # pylint: disable=broad-except
  1023. self.log.exception(
  1024. 'Uncaught exception from domain-unpaused handler '
  1025. 'for domain %s', vm.name)
  1026. @qubes.events.handler('domain-pre-delete')
  1027. def on_domain_pre_deleted(self, event, vm):
  1028. # pylint: disable=unused-argument
  1029. for obj in itertools.chain(self.domains, (self,)):
  1030. for prop in obj.property_list():
  1031. try:
  1032. if isinstance(prop, qubes.vm.VMProperty) and \
  1033. getattr(obj, prop.__name__) == vm:
  1034. self.log.error(
  1035. 'Cannot remove %s, used by %s.%s',
  1036. vm, obj, prop.__name__)
  1037. raise qubes.exc.QubesVMInUseError(vm, 'Domain is in '
  1038. 'use: {!r}; see /var/log/qubes/qubes.log in dom0 for '
  1039. 'details'.format(vm.name))
  1040. except AttributeError:
  1041. pass
  1042. @qubes.events.handler('domain-delete')
  1043. def on_domain_deleted(self, event, vm):
  1044. # pylint: disable=unused-argument
  1045. for propname in (
  1046. 'default_netvm',
  1047. 'default_fw_netvm',
  1048. 'clockvm',
  1049. 'updatevm',
  1050. 'default_template',
  1051. ):
  1052. try:
  1053. if getattr(self, propname) == vm:
  1054. delattr(self, propname)
  1055. except AttributeError:
  1056. pass
  1057. @qubes.events.handler('property-pre-set:clockvm')
  1058. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1059. # pylint: disable=unused-argument,no-self-use
  1060. if newvalue is None:
  1061. return
  1062. if 'service.clocksync' not in newvalue.features:
  1063. newvalue.features['service.clocksync'] = True
  1064. @qubes.events.handler('property-set:clockvm')
  1065. def on_property_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1066. # pylint: disable=unused-argument,no-self-use
  1067. if oldvalue and oldvalue.features.get('service.clocksync', False):
  1068. del oldvalue.features['service.clocksync']
  1069. @qubes.events.handler('property-pre-set:default_netvm')
  1070. def on_property_pre_set_default_netvm(self, event, name, newvalue,
  1071. oldvalue=None):
  1072. # pylint: disable=unused-argument,invalid-name
  1073. if newvalue is not None and oldvalue is not None \
  1074. and oldvalue.is_running() and not newvalue.is_running() \
  1075. and self.domains.get_vms_connected_to(oldvalue):
  1076. raise qubes.exc.QubesVMNotRunningError(newvalue,
  1077. 'Cannot change {!r} to domain that '
  1078. 'is not running ({!r}).'.format(name, newvalue.name))
  1079. @qubes.events.handler('property-set:default_fw_netvm')
  1080. def on_property_set_default_fw_netvm(self, event, name, newvalue,
  1081. oldvalue=None):
  1082. # pylint: disable=unused-argument,invalid-name
  1083. for vm in self.domains:
  1084. if hasattr(vm, 'provides_network') and vm.provides_network and \
  1085. hasattr(vm, 'netvm') and vm.property_is_default('netvm'):
  1086. # fire property-del:netvm as it is responsible for resetting
  1087. # netvm to it's default value
  1088. vm.fire_event('property-pre-del:netvm', pre_event=True,
  1089. name='netvm', oldvalue=oldvalue)
  1090. vm.fire_event('property-del:netvm',
  1091. name='netvm', oldvalue=oldvalue)
  1092. @qubes.events.handler('property-set:default_netvm')
  1093. def on_property_set_default_netvm(self, event, name, newvalue,
  1094. oldvalue=None):
  1095. # pylint: disable=unused-argument
  1096. for vm in self.domains:
  1097. if hasattr(vm, 'provides_network') and not vm.provides_network and \
  1098. hasattr(vm, 'netvm') and vm.property_is_default('netvm'):
  1099. # fire property-del:netvm as it is responsible for resetting
  1100. # netvm to it's default value
  1101. vm.fire_event('property-pre-del:netvm', pre_event=True,
  1102. name='netvm', oldvalue=oldvalue)
  1103. vm.fire_event('property-del:netvm',
  1104. name='netvm', oldvalue=oldvalue)