__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2011-2015 Marek Marczykowski-Górecki
  8. # <marmarek@invisiblethingslab.com>
  9. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License along
  22. # with this program; if not, write to the Free Software Foundation, Inc.,
  23. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. #
  25. '''Qubes Virtual Machines
  26. '''
  27. import ast
  28. import collections
  29. import datetime
  30. import functools
  31. import os
  32. import re
  33. import subprocess
  34. import sys
  35. import xml.parsers.expat
  36. import lxml.etree
  37. import qubes
  38. import qubes.log
  39. import qubes.events
  40. import qubes.plugins
  41. import qubes.tools.qvm_ls
  42. class BaseVMMeta(qubes.plugins.Plugin, qubes.events.EmitterMeta):
  43. '''Metaclass for :py:class:`.BaseVM`'''
  44. def __init__(cls, name, bases, dict_):
  45. super(BaseVMMeta, cls).__init__(name, bases, dict_)
  46. qubes.tools.qvm_ls.process_class(cls)
  47. class DeviceCollection(object):
  48. '''Bag for devices.
  49. Used as default value for :py:meth:`DeviceManager.__missing__` factory.
  50. :param vm: VM for which we manage devices
  51. :param class_: device class
  52. '''
  53. def __init__(self, vm, class_):
  54. self._vm = vm
  55. self._class = class_
  56. self._set = set()
  57. def attach(self, device):
  58. '''Attach (add) device to domain.
  59. :param str device: device identifier (format is class-dependent)
  60. '''
  61. if device in self:
  62. raise KeyError(
  63. 'device {!r} of class {} already attached to {!r}'.format(
  64. device, self._class, self._vm))
  65. self._vm.fire_event_pre('device-pre-attached:{}'.format(self._class),
  66. device)
  67. self._set.add(device)
  68. self._vm.fire_event('device-attached:{}'.format(self._class), device)
  69. def detach(self, device):
  70. '''Detach (remove) device from domain.
  71. :param str device: device identifier (format is class-dependent)
  72. '''
  73. if device not in self:
  74. raise KeyError(
  75. 'device {!r} of class {} not attached to {!r}'.format(
  76. device, self._class, self._vm))
  77. self._vm.fire_event_pre('device-pre-detached:{}'.format(self._class),
  78. device)
  79. self._set.remove(device)
  80. self._vm.fire_event('device-detached:{}'.format(self._class), device)
  81. def __iter__(self):
  82. return iter(self._set)
  83. def __contains__(self, item):
  84. return item in self._set
  85. def __len__(self):
  86. return len(self._set)
  87. class DeviceManager(dict):
  88. '''Device manager that hold all devices by their classess.
  89. :param vm: VM for which we manage devices
  90. '''
  91. def __init__(self, vm):
  92. super(DeviceManager, self).__init__()
  93. self._vm = vm
  94. def __missing__(self, key):
  95. self[key] = DeviceCollection(self._vm, key)
  96. return self[key]
  97. class BaseVM(qubes.PropertyHolder):
  98. '''Base class for all VMs
  99. :param app: Qubes application context
  100. :type app: :py:class:`qubes.Qubes`
  101. :param xml: xml node from which to deserialise
  102. :type xml: :py:class:`lxml.etree._Element` or :py:obj:`None`
  103. This class is responsible for serializing and deserialising machines and
  104. provides basic framework. It contains no management logic. For that, see
  105. :py:class:`qubes.vm.qubesvm.QubesVM`.
  106. '''
  107. # pylint: disable=no-member
  108. __metaclass__ = BaseVMMeta
  109. def __init__(self, app, xml, services=None, devices=None, tags=None,
  110. **kwargs):
  111. # pylint: disable=redefined-outer-name
  112. super(BaseVM, self).__init__(xml, **kwargs)
  113. #: mother :py:class:`qubes.Qubes` object
  114. self.app = app
  115. #: dictionary of services that are run on this domain
  116. self.services = services or {}
  117. #: :py:class:`DeviceManager` object keeping devices that are attached to
  118. #: this domain
  119. self.devices = DeviceManager(self) if devices is None else devices
  120. #: user-specified tags
  121. self.tags = tags or {}
  122. if self.xml is not None:
  123. # services
  124. for node in xml.xpath('./services/service'):
  125. self.services[node.text] = bool(
  126. ast.literal_eval(node.get('enabled', 'True').capitalize()))
  127. # devices (pci, usb, ...)
  128. for parent in xml.xpath('./devices'):
  129. devclass = parent.get('class')
  130. for node in parent.xpath('./device'):
  131. self.devices[devclass].attach(node.text)
  132. # tags
  133. for node in xml.xpath('./tags/tag'):
  134. self.tags[node.get('name')] = node.text
  135. # TODO: firewall, policy
  136. # check if properties are appropriate
  137. all_names = set(prop.__name__ for prop in self.property_list())
  138. for node in self.xml.xpath('./properties/property'):
  139. name = node.get('name')
  140. if not name in all_names:
  141. raise TypeError(
  142. 'property {!r} not applicable to {!r}'.format(
  143. name, self.__class__.__name__))
  144. #: logger instance for logging messages related to this VM
  145. self.log = None
  146. def init_log(self):
  147. '''Initialise logger for this domain.'''
  148. self.log = qubes.log.get_vm_logger(self.name)
  149. def add_new_vm(self, vm):
  150. '''Add new Virtual Machine to colletion
  151. '''
  152. vm_cls = QubesVmClasses[vm_type]
  153. if 'template' in kwargs:
  154. if not vm_cls.is_template_compatible(kwargs['template']):
  155. raise QubesException(
  156. 'Template not compatible with selected VM type')
  157. vm = vm_cls(qid=qid, collection=self, **kwargs)
  158. if not self.verify_new_vm(vm):
  159. raise QubesException("Wrong VM description!")
  160. self[vm.qid] = vm
  161. # make first created NetVM the default one
  162. if self.default_fw_netvm_qid is None and vm.is_netvm():
  163. self.set_default_fw_netvm(vm)
  164. if self.default_netvm_qid is None and vm.is_proxyvm():
  165. self.set_default_netvm(vm)
  166. # make first created TemplateVM the default one
  167. if self.default_template_qid is None and vm.is_template():
  168. self.set_default_template(vm)
  169. # make first created ProxyVM the UpdateVM
  170. if self.updatevm_qid is None and vm.is_proxyvm():
  171. self.set_updatevm_vm(vm)
  172. # by default ClockVM is the first NetVM
  173. if self.clockvm_qid is None and vm.is_netvm():
  174. self.set_clockvm_vm(vm)
  175. return vm
  176. def __xml__(self):
  177. element = lxml.etree.Element('domain')
  178. element.set('id', 'domain-' + str(self.qid))
  179. element.set('class', self.__class__.__name__)
  180. element.append(self.xml_properties())
  181. services = lxml.etree.Element('services')
  182. for service in self.services:
  183. node = lxml.etree.Element('service')
  184. node.text = service
  185. if not self.services[service]:
  186. node.set('enabled', 'false')
  187. services.append(node)
  188. element.append(services)
  189. for devclass in self.devices:
  190. devices = lxml.etree.Element('devices')
  191. devices.set('class', devclass)
  192. for device in self.devices[devclass]:
  193. node = lxml.etree.Element('device')
  194. node.text = device
  195. devices.append(node)
  196. element.append(devices)
  197. tags = lxml.etree.Element('tags')
  198. for tag in self.tags:
  199. node = lxml.etree.Element('tag', name=tag)
  200. node.text = self.tags[tag]
  201. tags.append(node)
  202. element.append(tags)
  203. return element
  204. def __repr__(self):
  205. proprepr = []
  206. for prop in self.property_list():
  207. try:
  208. proprepr.append('{}={!r}'.format(
  209. prop.__name__, getattr(self, prop.__name__)))
  210. except AttributeError:
  211. continue
  212. return '<{} object at {:#x} {}>'.format(
  213. self.__class__.__name__, id(self), ' '.join(proprepr))
  214. #
  215. # xml serialising methods
  216. #
  217. @staticmethod
  218. def lvxml_net_dev(ip, mac, backend):
  219. '''Return ``<interface>`` node for libvirt xml.
  220. This was previously _format_net_dev
  221. :param str ip: IP address of the frontend
  222. :param str mac: MAC (Ethernet) address of the frontend
  223. :param qubes.vm.qubesvm.QubesVM backend: Backend domain
  224. :rtype: lxml.etree._Element
  225. '''
  226. interface = lxml.etree.Element('interface', type='ethernet')
  227. interface.append(lxml.etree.Element('mac', address=mac))
  228. interface.append(lxml.etree.Element('ip', address=ip))
  229. interface.append(lxml.etree.Element('domain', name=backend.name))
  230. return interface
  231. @staticmethod
  232. def lvxml_pci_dev(address):
  233. '''Return ``<hostdev>`` node for libvirt xml.
  234. This was previously _format_pci_dev
  235. :param str ip: IP address of the frontend
  236. :param str mac: MAC (Ethernet) address of the frontend
  237. :param qubes.vm.qubesvm.QubesVM backend: Backend domain
  238. :rtype: lxml.etree._Element
  239. '''
  240. dev_match = re.match(r'([0-9a-f]+):([0-9a-f]+)\.([0-9a-f]+)', address)
  241. if not dev_match:
  242. raise qubes.QubesException(
  243. 'Invalid PCI device address: {}'.format(address))
  244. hostdev = lxml.etree.Element('hostdev', type='pci', managed='yes')
  245. source = lxml.etree.Element('source')
  246. source.append(lxml.etree.Element('address',
  247. bus='0x' + dev_match.group(1),
  248. slot='0x' + dev_match.group(2),
  249. function='0x' + dev_match.group(3)))
  250. hostdev.append(source)
  251. return hostdev
  252. #
  253. # old libvirt XML
  254. # TODO rewrite it to do proper XML synthesis via lxml.etree
  255. #
  256. def get_config_params(self):
  257. '''Return parameters for libvirt's XML domain config
  258. .. deprecated:: 3.0-alpha This will go away.
  259. '''
  260. args = {}
  261. args['name'] = self.name
  262. if hasattr(self, 'kernels_dir'):
  263. args['kerneldir'] = self.kernels_dir
  264. args['uuidnode'] = '<uuid>{!r}</uuid>'.format(self.uuid) \
  265. if hasattr(self, 'uuid') else ''
  266. args['vmdir'] = self.dir_path
  267. args['pcidevs'] = ''.join(lxml.etree.tostring(self.lvxml_pci_dev(dev))
  268. for dev in self.devices['pci'])
  269. args['maxmem'] = str(self.maxmem)
  270. args['vcpus'] = str(self.vcpus)
  271. args['mem'] = str(max(self.memory, self.maxmem))
  272. if 'meminfo-writer' in self.services \
  273. and not self.services['meminfo-writer']:
  274. # If dynamic memory management disabled, set maxmem=mem
  275. args['maxmem'] = args['mem']
  276. if self.netvm is not None:
  277. args['ip'] = self.ip
  278. args['mac'] = self.mac
  279. args['gateway'] = self.netvm.gateway
  280. args['dns1'] = self.netvm.gateway
  281. args['dns2'] = self.secondary_dns
  282. args['netmask'] = self.netmask
  283. args['netdev'] = lxml.etree.tostring(
  284. self.lvxml_net_dev(self.ip, self.mac, self.netvm))
  285. args['disable_network1'] = ''
  286. args['disable_network2'] = ''
  287. else:
  288. args['ip'] = ''
  289. args['mac'] = ''
  290. args['gateway'] = ''
  291. args['dns1'] = ''
  292. args['dns2'] = ''
  293. args['netmask'] = ''
  294. args['netdev'] = ''
  295. args['disable_network1'] = '<!--'
  296. args['disable_network2'] = '-->'
  297. args.update(self.storage.get_config_params())
  298. if hasattr(self, 'kernelopts'):
  299. args['kernelopts'] = self.kernelopts
  300. if self.debug:
  301. self.log.info(
  302. "Debug mode: adding 'earlyprintk=xen' to kernel opts")
  303. args['kernelopts'] += ' earlyprintk=xen'
  304. def create_config_file(self, file_path=None, prepare_dvm=False):
  305. '''Create libvirt's XML domain config file
  306. If :py:attr:`qubes.vm.qubesvm.QubesVM.uses_custom_config` is true, this
  307. does nothing.
  308. :param str file_path: Path to file to create \
  309. (default: :py:attr:`qubes.vm.qubesvm.QubesVM.conf_file`)
  310. :param bool prepare_dvm: If we are in the process of preparing \
  311. DisposableVM
  312. '''
  313. if file_path is None:
  314. file_path = self.conf_file
  315. if self.uses_custom_config:
  316. conf_appvm = open(file_path, "r")
  317. domain_config = conf_appvm.read()
  318. conf_appvm.close()
  319. return domain_config
  320. f_conf_template = open(self.config_file_template, 'r')
  321. conf_template = f_conf_template.read()
  322. f_conf_template.close()
  323. template_params = self.get_config_params()
  324. if prepare_dvm:
  325. template_params['name'] = '%NAME%'
  326. template_params['privatedev'] = ''
  327. template_params['netdev'] = re.sub(r"address='[0-9.]*'",
  328. "address='%IP%'", template_params['netdev'])
  329. domain_config = conf_template.format(**template_params)
  330. # FIXME: This is only for debugging purposes
  331. old_umask = os.umask(002)
  332. try:
  333. conf_appvm = open(file_path, "w")
  334. conf_appvm.write(domain_config)
  335. conf_appvm.close()
  336. except:
  337. # Ignore errors
  338. pass
  339. finally:
  340. os.umask(old_umask)
  341. return domain_config
  342. #
  343. # firewall
  344. # TODO rewrite it, have <firewall/> node under <domain/>
  345. # and possibly integrate with generic policy framework
  346. #
  347. def write_firewall_conf(self, conf):
  348. '''Write firewall config file.
  349. '''
  350. defaults = self.get_firewall_conf()
  351. expiring_rules_present = False
  352. for item in defaults.keys():
  353. if item not in conf:
  354. conf[item] = defaults[item]
  355. root = lxml.etree.Element(
  356. "QubesFirewallRules",
  357. policy=("allow" if conf["allow"] else "deny"),
  358. dns=("allow" if conf["allowDns"] else "deny"),
  359. icmp=("allow" if conf["allowIcmp"] else "deny"),
  360. yumProxy=("allow" if conf["allowYumProxy"] else "deny"))
  361. for rule in conf["rules"]:
  362. # For backward compatibility
  363. if "proto" not in rule:
  364. if rule["portBegin"] is not None and rule["portBegin"] > 0:
  365. rule["proto"] = "tcp"
  366. else:
  367. rule["proto"] = "any"
  368. element = lxml.etree.Element(
  369. "rule",
  370. address=rule["address"],
  371. proto=str(rule["proto"]),
  372. )
  373. if rule["netmask"] is not None and rule["netmask"] != 32:
  374. element.set("netmask", str(rule["netmask"]))
  375. if rule.get("portBegin", None) is not None and \
  376. rule["portBegin"] > 0:
  377. element.set("port", str(rule["portBegin"]))
  378. if rule.get("portEnd", None) is not None and rule["portEnd"] > 0:
  379. element.set("toport", str(rule["portEnd"]))
  380. if "expire" in rule:
  381. element.set("expire", str(rule["expire"]))
  382. expiring_rules_present = True
  383. root.append(element)
  384. tree = lxml.etree.ElementTree(root)
  385. try:
  386. old_umask = os.umask(002)
  387. with open(self.firewall_conf, 'w') as fd:
  388. tree.write(fd, encoding="UTF-8", pretty_print=True)
  389. fd.close()
  390. os.umask(old_umask)
  391. except EnvironmentError as err:
  392. print >> sys.stderr, "{0}: save error: {1}".format(
  393. os.path.basename(sys.argv[0]), err)
  394. return False
  395. # Automatically enable/disable 'yum-proxy-setup' service based on
  396. # allowYumProxy
  397. if conf['allowYumProxy']:
  398. self.services['yum-proxy-setup'] = True
  399. else:
  400. if self.services.has_key('yum-proxy-setup'):
  401. self.services.pop('yum-proxy-setup')
  402. if expiring_rules_present:
  403. subprocess.call(["sudo", "systemctl", "start",
  404. "qubes-reload-firewall@%s.timer" % self.name])
  405. return True
  406. def has_firewall(self):
  407. return os.path.exists(self.firewall_conf)
  408. @staticmethod
  409. def get_firewall_defaults():
  410. return {
  411. 'rules': list(),
  412. 'allow': True,
  413. 'allowDns': True,
  414. 'allowIcmp': True,
  415. 'allowYumProxy': False}
  416. def get_firewall_conf(self):
  417. conf = self.get_firewall_defaults()
  418. try:
  419. tree = lxml.etree.parse(self.firewall_conf)
  420. root = tree.getroot()
  421. conf["allow"] = (root.get("policy") == "allow")
  422. conf["allowDns"] = (root.get("dns") == "allow")
  423. conf["allowIcmp"] = (root.get("icmp") == "allow")
  424. conf["allowYumProxy"] = (root.get("yumProxy") == "allow")
  425. for element in root:
  426. rule = {}
  427. attr_list = ("address", "netmask", "proto", "port", "toport",
  428. "expire")
  429. for attribute in attr_list:
  430. rule[attribute] = element.get(attribute)
  431. if rule["netmask"] is not None:
  432. rule["netmask"] = int(rule["netmask"])
  433. else:
  434. rule["netmask"] = 32
  435. if rule["port"] is not None:
  436. rule["portBegin"] = int(rule["port"])
  437. else:
  438. # backward compatibility
  439. rule["portBegin"] = 0
  440. # For backward compatibility
  441. if rule["proto"] is None:
  442. if rule["portBegin"] > 0:
  443. rule["proto"] = "tcp"
  444. else:
  445. rule["proto"] = "any"
  446. if rule["toport"] is not None:
  447. rule["portEnd"] = int(rule["toport"])
  448. else:
  449. rule["portEnd"] = None
  450. if rule["expire"] is not None:
  451. rule["expire"] = int(rule["expire"])
  452. if rule["expire"] <= int(datetime.datetime.now().strftime(
  453. "%s")):
  454. continue
  455. else:
  456. del rule["expire"]
  457. del rule["port"]
  458. del rule["toport"]
  459. conf["rules"].append(rule)
  460. except EnvironmentError as err:
  461. # problem accessing file, like ENOTFOUND, EPERM or sth
  462. # return default config
  463. return conf
  464. except (xml.parsers.expat.ExpatError,
  465. ValueError, LookupError) as err:
  466. # config is invalid
  467. print("{0}: load error: {1}".format(
  468. os.path.basename(sys.argv[0]), err))
  469. return None
  470. return conf
  471. __all__ = ['BaseVMMeta', 'DeviceCollection', 'DeviceManager', 'BaseVM'] \
  472. + qubes.plugins.load(__file__)