__init__.py 19 KB

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