__init__.py 18 KB

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