2014-11-13 14:38:41 +01:00
|
|
|
#!/usr/bin/python2 -O
|
2015-01-19 17:06:30 +01:00
|
|
|
# vim: fileencoding=utf-8
|
|
|
|
|
|
|
|
#
|
|
|
|
# The Qubes OS Project, https://www.qubes-os.org/
|
|
|
|
#
|
|
|
|
# Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
|
|
|
|
# Copyright (C) 2011-2015 Marek Marczykowski-Górecki
|
|
|
|
# <marmarek@invisiblethingslab.com>
|
|
|
|
# Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
|
|
|
|
#
|
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation; either version 2 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License along
|
|
|
|
# with this program; if not, write to the Free Software Foundation, Inc.,
|
|
|
|
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
|
|
#
|
2014-11-13 14:38:41 +01:00
|
|
|
|
2014-11-13 18:10:27 +01:00
|
|
|
'''Qubes Virtual Machines
|
|
|
|
|
|
|
|
'''
|
|
|
|
|
2014-11-18 17:35:05 +01:00
|
|
|
import ast
|
2014-11-13 14:38:41 +01:00
|
|
|
import collections
|
2015-01-19 18:14:15 +01:00
|
|
|
import datetime
|
2014-11-13 14:38:41 +01:00
|
|
|
import functools
|
2016-01-21 13:08:56 +01:00
|
|
|
import itertools
|
2015-01-19 18:14:15 +01:00
|
|
|
import os
|
|
|
|
import re
|
|
|
|
import subprocess
|
2014-11-13 14:38:41 +01:00
|
|
|
import sys
|
2015-01-19 18:14:15 +01:00
|
|
|
import xml.parsers.expat
|
2014-11-13 14:38:41 +01:00
|
|
|
|
2014-12-05 14:58:05 +01:00
|
|
|
import lxml.etree
|
2014-11-13 14:38:41 +01:00
|
|
|
|
2014-12-05 14:58:05 +01:00
|
|
|
import qubes
|
2015-01-21 17:03:17 +01:00
|
|
|
import qubes.log
|
2016-03-02 12:17:29 +01:00
|
|
|
import qubes.devices
|
2014-12-09 14:14:24 +01:00
|
|
|
import qubes.events
|
2015-01-23 18:37:40 +01:00
|
|
|
import qubes.tools.qvm_ls
|
2014-11-13 14:38:41 +01:00
|
|
|
|
|
|
|
|
2016-03-03 13:03:27 +01:00
|
|
|
class Features(dict):
|
|
|
|
'''Manager of the features.
|
|
|
|
|
2016-03-09 16:53:36 +01:00
|
|
|
Features can have three distinct values: no value (not present in mapping,
|
|
|
|
which is closest thing to :py:obj:`None`), empty string (which is
|
|
|
|
interpreted as :py:obj:`False`) and non-empty string, which is
|
|
|
|
:py:obj:`True`. Anything assigned to the mapping is coerced to strings,
|
|
|
|
however if you assign instances of :py:class:`bool`, they are converted as
|
|
|
|
described above. Be aware that assigning the number `0` (which is considered
|
|
|
|
false in Python) will result in string `'0'`, which is considered true.
|
|
|
|
|
2016-03-03 13:03:27 +01:00
|
|
|
This class inherits from dict, but has most of the methods that manipulate
|
|
|
|
the item disarmed (they raise NotImplementedError). The ones that are left
|
|
|
|
fire appropriate events on the qube that owns an instance of this class.
|
|
|
|
'''
|
|
|
|
|
|
|
|
#
|
|
|
|
# Those are the methods that affect contents. Either disarm them or make
|
|
|
|
# them report appropriate events. Good approach is to rewrite them carefully
|
|
|
|
# using official documentation, but use only our (overloaded) methods.
|
|
|
|
#
|
|
|
|
def __init__(self, vm, other=None, **kwargs):
|
|
|
|
super(Features, self).__init__()
|
|
|
|
self.vm = vm
|
|
|
|
self.update(other, **kwargs)
|
|
|
|
|
|
|
|
def __delitem__(self, key):
|
|
|
|
super(Features, self).__delitem__(key)
|
|
|
|
self.vm.fire_event('domain-feature-delete', key)
|
|
|
|
|
|
|
|
def __setitem__(self, key, value):
|
2016-04-03 03:43:01 +02:00
|
|
|
if value is None or isinstance(value, bool):
|
2016-03-09 16:53:36 +01:00
|
|
|
value = '1' if value else ''
|
|
|
|
else:
|
|
|
|
value = str(value)
|
2016-03-03 13:03:27 +01:00
|
|
|
self.vm.fire_event('domain-feature-set', key, value)
|
|
|
|
super(Features, self).__setitem__(key, value)
|
|
|
|
|
|
|
|
def clear(self):
|
|
|
|
for key in self:
|
|
|
|
del self[key]
|
|
|
|
|
|
|
|
def pop(self):
|
|
|
|
'''Not implemented
|
|
|
|
:raises: NotImplementedError
|
|
|
|
'''
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def popitem(self):
|
|
|
|
'''Not implemented
|
|
|
|
:raises: NotImplementedError
|
|
|
|
'''
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def setdefault(self):
|
|
|
|
'''Not implemented
|
|
|
|
:raises: NotImplementedError
|
|
|
|
'''
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def update(self, other=None, **kwargs):
|
|
|
|
if other is not None:
|
|
|
|
if hasattr(other, 'keys'):
|
|
|
|
for key in other:
|
|
|
|
self[key] = other[key]
|
|
|
|
else:
|
|
|
|
for key, value in other:
|
|
|
|
self[key] = value
|
|
|
|
|
|
|
|
for key in kwargs:
|
|
|
|
self[key] = kwargs[key]
|
|
|
|
|
|
|
|
#
|
|
|
|
# end of overriding
|
|
|
|
#
|
|
|
|
|
|
|
|
_NO_DEFAULT = object()
|
|
|
|
def check_with_template(self, feature, default=_NO_DEFAULT):
|
|
|
|
if feature in self:
|
|
|
|
return self[feature]
|
|
|
|
|
|
|
|
if hasattr(self.vm, 'template') and self.vm.template is not None \
|
|
|
|
and feature in self.vm.template.features:
|
|
|
|
return self.vm.template.features[feature]
|
|
|
|
|
|
|
|
if default is self._NO_DEFAULT:
|
|
|
|
raise KeyError(feature)
|
|
|
|
|
|
|
|
return default
|
|
|
|
|
|
|
|
|
2016-03-04 13:03:43 +01:00
|
|
|
class BaseVMMeta(qubes.events.EmitterMeta):
|
2014-11-13 18:10:27 +01:00
|
|
|
'''Metaclass for :py:class:`.BaseVM`'''
|
2015-01-23 18:37:40 +01:00
|
|
|
def __init__(cls, name, bases, dict_):
|
|
|
|
super(BaseVMMeta, cls).__init__(name, bases, dict_)
|
|
|
|
qubes.tools.qvm_ls.process_class(cls)
|
|
|
|
|
2014-11-13 14:38:41 +01:00
|
|
|
|
2014-12-09 18:34:00 +01:00
|
|
|
class BaseVM(qubes.PropertyHolder):
|
2014-11-18 17:35:05 +01:00
|
|
|
'''Base class for all VMs
|
|
|
|
|
2014-12-09 14:14:24 +01:00
|
|
|
:param app: Qubes application context
|
|
|
|
:type app: :py:class:`qubes.Qubes`
|
2014-11-18 17:35:05 +01:00
|
|
|
:param xml: xml node from which to deserialise
|
|
|
|
:type xml: :py:class:`lxml.etree._Element` or :py:obj:`None`
|
|
|
|
|
2014-12-18 14:36:09 +01:00
|
|
|
This class is responsible for serializing and deserialising machines and
|
2014-11-18 17:35:05 +01:00
|
|
|
provides basic framework. It contains no management logic. For that, see
|
|
|
|
:py:class:`qubes.vm.qubesvm.QubesVM`.
|
|
|
|
'''
|
2015-01-19 19:02:28 +01:00
|
|
|
# pylint: disable=no-member
|
2014-11-18 17:35:05 +01:00
|
|
|
|
2014-12-09 14:14:24 +01:00
|
|
|
__metaclass__ = BaseVMMeta
|
2014-11-13 14:38:41 +01:00
|
|
|
|
2016-03-03 13:03:27 +01:00
|
|
|
def __init__(self, app, xml, features=None, devices=None, tags=None,
|
2015-01-21 15:24:29 +01:00
|
|
|
**kwargs):
|
2015-01-19 19:02:28 +01:00
|
|
|
# pylint: disable=redefined-outer-name
|
2015-01-21 15:24:29 +01:00
|
|
|
|
2015-07-01 17:10:10 +02:00
|
|
|
# self.app must be set before super().__init__, because some property
|
|
|
|
# setters need working .app attribute
|
2015-01-19 18:03:23 +01:00
|
|
|
#: mother :py:class:`qubes.Qubes` object
|
2014-12-05 14:58:05 +01:00
|
|
|
self.app = app
|
2015-01-19 18:03:23 +01:00
|
|
|
|
2015-07-01 17:10:10 +02:00
|
|
|
super(BaseVM, self).__init__(xml, **kwargs)
|
|
|
|
|
2016-03-03 13:03:27 +01:00
|
|
|
#: dictionary of features of this qube
|
|
|
|
self.features = Features(self, features)
|
2015-01-19 18:03:23 +01:00
|
|
|
|
2015-01-22 19:25:00 +01:00
|
|
|
#: :py:class:`DeviceManager` object keeping devices that are attached to
|
2015-01-19 18:03:23 +01:00
|
|
|
#: this domain
|
2016-03-02 12:17:29 +01:00
|
|
|
self.devices = devices or qubes.devices.DeviceManager(self)
|
2015-01-19 18:03:23 +01:00
|
|
|
|
|
|
|
#: user-specified tags
|
2015-01-20 16:32:25 +01:00
|
|
|
self.tags = tags or {}
|
2014-12-05 14:58:05 +01:00
|
|
|
|
2015-01-21 15:24:29 +01:00
|
|
|
if self.xml is not None:
|
2016-03-03 13:03:27 +01:00
|
|
|
# features
|
2016-04-03 03:43:01 +02:00
|
|
|
for node in xml.xpath('./features/feature'):
|
2016-03-03 13:03:27 +01:00
|
|
|
self.features[node.get('name')] = node.text
|
2015-01-21 15:24:29 +01:00
|
|
|
|
|
|
|
# devices (pci, usb, ...)
|
|
|
|
for parent in xml.xpath('./devices'):
|
|
|
|
devclass = parent.get('class')
|
|
|
|
for node in parent.xpath('./device'):
|
|
|
|
self.devices[devclass].attach(node.text)
|
2014-11-13 14:38:41 +01:00
|
|
|
|
2015-01-21 15:24:29 +01:00
|
|
|
# tags
|
|
|
|
for node in xml.xpath('./tags/tag'):
|
|
|
|
self.tags[node.get('name')] = node.text
|
2014-11-18 17:35:05 +01:00
|
|
|
|
2015-01-21 15:24:29 +01:00
|
|
|
# TODO: firewall, policy
|
|
|
|
|
|
|
|
# check if properties are appropriate
|
|
|
|
all_names = set(prop.__name__ for prop in self.property_list())
|
|
|
|
|
|
|
|
for node in self.xml.xpath('./properties/property'):
|
|
|
|
name = node.get('name')
|
|
|
|
if not name in all_names:
|
|
|
|
raise TypeError(
|
|
|
|
'property {!r} not applicable to {!r}'.format(
|
|
|
|
name, self.__class__.__name__))
|
2014-12-09 18:34:00 +01:00
|
|
|
|
2015-01-21 17:03:17 +01:00
|
|
|
#: logger instance for logging messages related to this VM
|
|
|
|
self.log = None
|
|
|
|
|
2015-09-23 16:25:53 +02:00
|
|
|
if hasattr(self, 'name'):
|
|
|
|
self.init_log()
|
|
|
|
|
2015-01-21 17:03:17 +01:00
|
|
|
|
|
|
|
def init_log(self):
|
|
|
|
'''Initialise logger for this domain.'''
|
|
|
|
self.log = qubes.log.get_vm_logger(self.name)
|
|
|
|
|
2014-12-09 18:34:00 +01:00
|
|
|
|
2014-12-05 14:58:05 +01:00
|
|
|
def __xml__(self):
|
2015-01-12 18:57:37 +01:00
|
|
|
element = lxml.etree.Element('domain')
|
|
|
|
element.set('id', 'domain-' + str(self.qid))
|
|
|
|
element.set('class', self.__class__.__name__)
|
2014-12-05 14:58:05 +01:00
|
|
|
|
2015-01-13 15:56:10 +01:00
|
|
|
element.append(self.xml_properties())
|
2014-12-05 14:58:05 +01:00
|
|
|
|
2016-03-03 13:03:27 +01:00
|
|
|
features = lxml.etree.Element('features')
|
|
|
|
for feature in self.features:
|
2016-04-03 03:43:01 +02:00
|
|
|
node = lxml.etree.Element('feature', name=feature)
|
2016-03-09 16:53:36 +01:00
|
|
|
node.text = self.features[feature]
|
2016-03-03 13:03:27 +01:00
|
|
|
features.append(node)
|
|
|
|
element.append(features)
|
2014-12-05 14:58:05 +01:00
|
|
|
|
|
|
|
for devclass in self.devices:
|
|
|
|
devices = lxml.etree.Element('devices')
|
|
|
|
devices.set('class', devclass)
|
|
|
|
for device in self.devices[devclass]:
|
|
|
|
node = lxml.etree.Element('device')
|
|
|
|
node.text = device
|
|
|
|
devices.append(node)
|
|
|
|
element.append(devices)
|
|
|
|
|
|
|
|
tags = lxml.etree.Element('tags')
|
|
|
|
for tag in self.tags:
|
|
|
|
node = lxml.etree.Element('tag', name=tag)
|
|
|
|
node.text = self.tags[tag]
|
|
|
|
tags.append(node)
|
|
|
|
element.append(tags)
|
|
|
|
|
|
|
|
return element
|
2014-11-13 14:38:41 +01:00
|
|
|
|
|
|
|
def __repr__(self):
|
2014-12-17 13:32:58 +01:00
|
|
|
proprepr = []
|
2015-01-21 12:50:00 +01:00
|
|
|
for prop in self.property_list():
|
2014-12-17 13:32:58 +01:00
|
|
|
try:
|
2016-03-07 01:00:15 +01:00
|
|
|
proprepr.append('{}={!s}'.format(
|
2014-12-17 13:32:58 +01:00
|
|
|
prop.__name__, getattr(self, prop.__name__)))
|
|
|
|
except AttributeError:
|
|
|
|
continue
|
2014-11-13 14:38:41 +01:00
|
|
|
|
2014-12-17 13:32:58 +01:00
|
|
|
return '<{} object at {:#x} {}>'.format(
|
|
|
|
self.__class__.__name__, id(self), ' '.join(proprepr))
|
2014-12-05 14:58:05 +01:00
|
|
|
|
2014-11-13 14:38:41 +01:00
|
|
|
|
2014-12-29 12:46:16 +01:00
|
|
|
#
|
|
|
|
# xml serialising methods
|
|
|
|
#
|
|
|
|
|
|
|
|
@staticmethod
|
2015-01-13 15:56:10 +01:00
|
|
|
def lvxml_net_dev(ip, mac, backend):
|
2014-12-29 12:46:16 +01:00
|
|
|
'''Return ``<interface>`` node for libvirt xml.
|
|
|
|
|
|
|
|
This was previously _format_net_dev
|
|
|
|
|
|
|
|
:param str ip: IP address of the frontend
|
|
|
|
:param str mac: MAC (Ethernet) address of the frontend
|
2015-01-22 19:25:00 +01:00
|
|
|
:param qubes.vm.qubesvm.QubesVM backend: Backend domain
|
2014-12-29 12:46:16 +01:00
|
|
|
:rtype: lxml.etree._Element
|
|
|
|
'''
|
|
|
|
|
|
|
|
interface = lxml.etree.Element('interface', type='ethernet')
|
|
|
|
interface.append(lxml.etree.Element('mac', address=mac))
|
|
|
|
interface.append(lxml.etree.Element('ip', address=ip))
|
2016-01-21 15:33:54 +01:00
|
|
|
interface.append(lxml.etree.Element('backenddomain', name=backend.name))
|
|
|
|
interface.append(lxml.etree.Element('script', path="vif-route-qubes"))
|
2014-12-29 12:46:16 +01:00
|
|
|
|
|
|
|
return interface
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
2015-01-13 15:56:10 +01:00
|
|
|
def lvxml_pci_dev(address):
|
2014-12-29 12:46:16 +01:00
|
|
|
'''Return ``<hostdev>`` node for libvirt xml.
|
|
|
|
|
|
|
|
This was previously _format_pci_dev
|
|
|
|
|
|
|
|
:param str ip: IP address of the frontend
|
|
|
|
:param str mac: MAC (Ethernet) address of the frontend
|
2015-01-22 19:25:00 +01:00
|
|
|
:param qubes.vm.qubesvm.QubesVM backend: Backend domain
|
2014-12-29 12:46:16 +01:00
|
|
|
:rtype: lxml.etree._Element
|
|
|
|
'''
|
|
|
|
|
2015-01-20 14:41:19 +01:00
|
|
|
dev_match = re.match(r'([0-9a-f]+):([0-9a-f]+)\.([0-9a-f]+)', address)
|
2014-12-29 12:46:16 +01:00
|
|
|
if not dev_match:
|
2015-10-14 22:02:11 +02:00
|
|
|
raise ValueError('Invalid PCI device address: {!r}'.format(address))
|
2014-12-29 12:46:16 +01:00
|
|
|
|
|
|
|
hostdev = lxml.etree.Element('hostdev', type='pci', managed='yes')
|
|
|
|
source = lxml.etree.Element('source')
|
|
|
|
source.append(lxml.etree.Element('address',
|
|
|
|
bus='0x' + dev_match.group(1),
|
|
|
|
slot='0x' + dev_match.group(2),
|
|
|
|
function='0x' + dev_match.group(3)))
|
|
|
|
hostdev.append(source)
|
|
|
|
return hostdev
|
|
|
|
|
|
|
|
#
|
|
|
|
# old libvirt XML
|
|
|
|
# TODO rewrite it to do proper XML synthesis via lxml.etree
|
|
|
|
#
|
|
|
|
|
|
|
|
def get_config_params(self):
|
|
|
|
'''Return parameters for libvirt's XML domain config
|
|
|
|
|
|
|
|
.. deprecated:: 3.0-alpha This will go away.
|
|
|
|
'''
|
|
|
|
|
|
|
|
args = {}
|
|
|
|
args['name'] = self.name
|
2015-09-28 23:34:29 +02:00
|
|
|
args['uuid'] = str(self.uuid)
|
2014-12-29 12:46:16 +01:00
|
|
|
args['vmdir'] = self.dir_path
|
2015-01-13 15:56:10 +01:00
|
|
|
args['pcidevs'] = ''.join(lxml.etree.tostring(self.lvxml_pci_dev(dev))
|
2014-12-29 12:46:16 +01:00
|
|
|
for dev in self.devices['pci'])
|
|
|
|
args['maxmem'] = str(self.maxmem)
|
|
|
|
args['vcpus'] = str(self.vcpus)
|
2015-10-02 12:26:06 +02:00
|
|
|
args['mem'] = str(min(self.memory, self.maxmem))
|
2014-12-29 12:46:16 +01:00
|
|
|
|
2016-03-03 13:03:27 +01:00
|
|
|
# If dynamic memory management disabled, set maxmem=mem
|
|
|
|
if not self.features.get('meminfo-writer', True):
|
2014-12-29 12:46:16 +01:00
|
|
|
args['maxmem'] = args['mem']
|
|
|
|
|
|
|
|
if self.netvm is not None:
|
|
|
|
args['ip'] = self.ip
|
|
|
|
args['mac'] = self.mac
|
|
|
|
args['gateway'] = self.netvm.gateway
|
2016-01-21 13:08:56 +01:00
|
|
|
|
|
|
|
for i, addr in zip(itertools.count(start=1), self.dns):
|
|
|
|
args['dns{}'.format(i)] = addr
|
|
|
|
|
2014-12-29 12:46:16 +01:00
|
|
|
args['netmask'] = self.netmask
|
2015-01-19 17:06:30 +01:00
|
|
|
args['netdev'] = lxml.etree.tostring(
|
|
|
|
self.lvxml_net_dev(self.ip, self.mac, self.netvm))
|
2016-03-03 01:05:23 +01:00
|
|
|
args['network_begin'] = ''
|
|
|
|
args['network_end'] = ''
|
|
|
|
args['no_network_begin'] = '<!--'
|
|
|
|
args['no_network_end'] = '-->'
|
2014-12-29 12:46:16 +01:00
|
|
|
else:
|
|
|
|
args['ip'] = ''
|
|
|
|
args['mac'] = ''
|
|
|
|
args['gateway'] = ''
|
|
|
|
args['dns1'] = ''
|
|
|
|
args['dns2'] = ''
|
|
|
|
args['netmask'] = ''
|
|
|
|
args['netdev'] = ''
|
2016-03-03 01:05:23 +01:00
|
|
|
args['network_begin'] = '<!--'
|
|
|
|
args['network_end'] = '-->'
|
|
|
|
args['no_network_begin'] = ''
|
|
|
|
args['no_network_end'] = ''
|
2014-12-29 12:46:16 +01:00
|
|
|
|
|
|
|
args.update(self.storage.get_config_params())
|
|
|
|
|
|
|
|
if hasattr(self, 'kernelopts'):
|
|
|
|
args['kernelopts'] = self.kernelopts
|
|
|
|
if self.debug:
|
2015-01-19 17:06:30 +01:00
|
|
|
self.log.info(
|
|
|
|
"Debug mode: adding 'earlyprintk=xen' to kernel opts")
|
2014-12-29 12:46:16 +01:00
|
|
|
args['kernelopts'] += ' earlyprintk=xen'
|
|
|
|
|
2015-09-17 12:08:03 +02:00
|
|
|
return args
|
|
|
|
|
2014-12-29 12:46:16 +01:00
|
|
|
|
|
|
|
def create_config_file(self, file_path=None, prepare_dvm=False):
|
|
|
|
'''Create libvirt's XML domain config file
|
|
|
|
|
|
|
|
If :py:attr:`qubes.vm.qubesvm.QubesVM.uses_custom_config` is true, this
|
|
|
|
does nothing.
|
|
|
|
|
2015-01-19 17:06:30 +01:00
|
|
|
:param str file_path: Path to file to create \
|
|
|
|
(default: :py:attr:`qubes.vm.qubesvm.QubesVM.conf_file`)
|
|
|
|
:param bool prepare_dvm: If we are in the process of preparing \
|
|
|
|
DisposableVM
|
2014-12-29 12:46:16 +01:00
|
|
|
'''
|
|
|
|
|
|
|
|
if file_path is None:
|
|
|
|
file_path = self.conf_file
|
2016-02-09 00:25:06 +01:00
|
|
|
# TODO
|
|
|
|
# if self.uses_custom_config:
|
|
|
|
# conf_appvm = open(file_path, "r")
|
|
|
|
# domain_config = conf_appvm.read()
|
|
|
|
# conf_appvm.close()
|
|
|
|
# return domain_config
|
2014-12-29 12:46:16 +01:00
|
|
|
|
2016-03-02 12:17:29 +01:00
|
|
|
domain_config = self.app.env.get_template('libvirt/xen.xml').render(
|
|
|
|
vm=self, prepare_dvm=prepare_dvm)
|
2014-12-29 12:46:16 +01:00
|
|
|
|
|
|
|
# FIXME: This is only for debugging purposes
|
|
|
|
old_umask = os.umask(002)
|
|
|
|
try:
|
|
|
|
conf_appvm = open(file_path, "w")
|
|
|
|
conf_appvm.write(domain_config)
|
|
|
|
conf_appvm.close()
|
2015-10-05 23:46:25 +02:00
|
|
|
except: # pylint: disable=bare-except
|
2014-12-29 12:46:16 +01:00
|
|
|
# Ignore errors
|
|
|
|
pass
|
|
|
|
finally:
|
|
|
|
os.umask(old_umask)
|
|
|
|
|
|
|
|
return domain_config
|
|
|
|
|
|
|
|
|
|
|
|
#
|
|
|
|
# firewall
|
|
|
|
# TODO rewrite it, have <firewall/> node under <domain/>
|
|
|
|
# and possibly integrate with generic policy framework
|
|
|
|
#
|
|
|
|
|
|
|
|
def write_firewall_conf(self, conf):
|
|
|
|
'''Write firewall config file.
|
|
|
|
'''
|
|
|
|
defaults = self.get_firewall_conf()
|
|
|
|
expiring_rules_present = False
|
|
|
|
for item in defaults.keys():
|
|
|
|
if item not in conf:
|
|
|
|
conf[item] = defaults[item]
|
|
|
|
|
|
|
|
root = lxml.etree.Element(
|
|
|
|
"QubesFirewallRules",
|
2015-01-19 17:06:30 +01:00
|
|
|
policy=("allow" if conf["allow"] else "deny"),
|
|
|
|
dns=("allow" if conf["allowDns"] else "deny"),
|
|
|
|
icmp=("allow" if conf["allowIcmp"] else "deny"),
|
|
|
|
yumProxy=("allow" if conf["allowYumProxy"] else "deny"))
|
2014-12-29 12:46:16 +01:00
|
|
|
|
|
|
|
for rule in conf["rules"]:
|
|
|
|
# For backward compatibility
|
|
|
|
if "proto" not in rule:
|
|
|
|
if rule["portBegin"] is not None and rule["portBegin"] > 0:
|
|
|
|
rule["proto"] = "tcp"
|
|
|
|
else:
|
|
|
|
rule["proto"] = "any"
|
|
|
|
element = lxml.etree.Element(
|
|
|
|
"rule",
|
|
|
|
address=rule["address"],
|
|
|
|
proto=str(rule["proto"]),
|
|
|
|
)
|
|
|
|
if rule["netmask"] is not None and rule["netmask"] != 32:
|
|
|
|
element.set("netmask", str(rule["netmask"]))
|
|
|
|
if rule.get("portBegin", None) is not None and \
|
|
|
|
rule["portBegin"] > 0:
|
|
|
|
element.set("port", str(rule["portBegin"]))
|
|
|
|
if rule.get("portEnd", None) is not None and rule["portEnd"] > 0:
|
|
|
|
element.set("toport", str(rule["portEnd"]))
|
|
|
|
if "expire" in rule:
|
|
|
|
element.set("expire", str(rule["expire"]))
|
|
|
|
expiring_rules_present = True
|
|
|
|
|
|
|
|
root.append(element)
|
|
|
|
|
|
|
|
tree = lxml.etree.ElementTree(root)
|
|
|
|
|
|
|
|
try:
|
|
|
|
old_umask = os.umask(002)
|
2016-03-07 01:16:49 +01:00
|
|
|
with open(os.path.join(self.dir_path,
|
|
|
|
self.firewall_conf), 'w') as fd:
|
2015-01-20 14:41:19 +01:00
|
|
|
tree.write(fd, encoding="UTF-8", pretty_print=True)
|
|
|
|
fd.close()
|
2014-12-29 12:46:16 +01:00
|
|
|
os.umask(old_umask)
|
2015-10-05 23:46:25 +02:00
|
|
|
except EnvironmentError as err: # pylint: disable=broad-except
|
2014-12-29 12:46:16 +01:00
|
|
|
print >> sys.stderr, "{0}: save error: {1}".format(
|
|
|
|
os.path.basename(sys.argv[0]), err)
|
|
|
|
return False
|
|
|
|
|
2016-03-07 03:26:59 +01:00
|
|
|
# Automatically enable/disable 'updates-proxy-setup' service based on
|
2015-01-19 17:06:30 +01:00
|
|
|
# allowYumProxy
|
2014-12-29 12:46:16 +01:00
|
|
|
if conf['allowYumProxy']:
|
2016-03-07 03:26:59 +01:00
|
|
|
self.features['updates-proxy-setup'] = '1'
|
2014-12-29 12:46:16 +01:00
|
|
|
else:
|
2016-03-03 13:03:27 +01:00
|
|
|
try:
|
2016-03-07 03:26:59 +01:00
|
|
|
del self.features['updates-proxy-setup']
|
2016-03-03 13:03:27 +01:00
|
|
|
except KeyError:
|
|
|
|
pass
|
2014-12-29 12:46:16 +01:00
|
|
|
|
|
|
|
if expiring_rules_present:
|
|
|
|
subprocess.call(["sudo", "systemctl", "start",
|
|
|
|
"qubes-reload-firewall@%s.timer" % self.name])
|
|
|
|
|
2016-03-07 01:22:27 +01:00
|
|
|
# XXX any better idea? some arguments?
|
|
|
|
self.fire_event('firewall-changed')
|
|
|
|
|
2014-12-29 12:46:16 +01:00
|
|
|
return True
|
|
|
|
|
|
|
|
def has_firewall(self):
|
2016-03-07 01:16:49 +01:00
|
|
|
return os.path.exists(os.path.join(self.dir_path, self.firewall_conf))
|
2014-12-29 12:46:16 +01:00
|
|
|
|
2015-01-20 16:32:25 +01:00
|
|
|
@staticmethod
|
|
|
|
def get_firewall_defaults():
|
2015-01-19 17:06:30 +01:00
|
|
|
return {
|
|
|
|
'rules': list(),
|
|
|
|
'allow': True,
|
|
|
|
'allowDns': True,
|
|
|
|
'allowIcmp': True,
|
|
|
|
'allowYumProxy': False}
|
2014-12-29 12:46:16 +01:00
|
|
|
|
|
|
|
def get_firewall_conf(self):
|
|
|
|
conf = self.get_firewall_defaults()
|
|
|
|
|
|
|
|
try:
|
2016-03-07 01:16:49 +01:00
|
|
|
tree = lxml.etree.parse(os.path.join(self.dir_path,
|
|
|
|
self.firewall_conf))
|
2014-12-29 12:46:16 +01:00
|
|
|
root = tree.getroot()
|
|
|
|
|
|
|
|
conf["allow"] = (root.get("policy") == "allow")
|
|
|
|
conf["allowDns"] = (root.get("dns") == "allow")
|
|
|
|
conf["allowIcmp"] = (root.get("icmp") == "allow")
|
|
|
|
conf["allowYumProxy"] = (root.get("yumProxy") == "allow")
|
|
|
|
|
|
|
|
for element in root:
|
|
|
|
rule = {}
|
|
|
|
attr_list = ("address", "netmask", "proto", "port", "toport",
|
|
|
|
"expire")
|
|
|
|
|
|
|
|
for attribute in attr_list:
|
|
|
|
rule[attribute] = element.get(attribute)
|
|
|
|
|
|
|
|
if rule["netmask"] is not None:
|
|
|
|
rule["netmask"] = int(rule["netmask"])
|
|
|
|
else:
|
|
|
|
rule["netmask"] = 32
|
|
|
|
|
|
|
|
if rule["port"] is not None:
|
|
|
|
rule["portBegin"] = int(rule["port"])
|
|
|
|
else:
|
|
|
|
# backward compatibility
|
|
|
|
rule["portBegin"] = 0
|
|
|
|
|
|
|
|
# For backward compatibility
|
|
|
|
if rule["proto"] is None:
|
|
|
|
if rule["portBegin"] > 0:
|
|
|
|
rule["proto"] = "tcp"
|
|
|
|
else:
|
|
|
|
rule["proto"] = "any"
|
|
|
|
|
|
|
|
if rule["toport"] is not None:
|
|
|
|
rule["portEnd"] = int(rule["toport"])
|
|
|
|
else:
|
|
|
|
rule["portEnd"] = None
|
|
|
|
|
|
|
|
if rule["expire"] is not None:
|
|
|
|
rule["expire"] = int(rule["expire"])
|
|
|
|
if rule["expire"] <= int(datetime.datetime.now().strftime(
|
|
|
|
"%s")):
|
|
|
|
continue
|
|
|
|
else:
|
2015-01-19 17:06:30 +01:00
|
|
|
del rule["expire"]
|
2014-12-29 12:46:16 +01:00
|
|
|
|
2015-01-19 17:06:30 +01:00
|
|
|
del rule["port"]
|
|
|
|
del rule["toport"]
|
2014-12-29 12:46:16 +01:00
|
|
|
|
|
|
|
conf["rules"].append(rule)
|
|
|
|
|
2015-10-05 23:46:25 +02:00
|
|
|
except EnvironmentError as err: # pylint: disable=broad-except
|
2015-01-13 15:40:43 +01:00
|
|
|
# problem accessing file, like ENOTFOUND, EPERM or sth
|
|
|
|
# return default config
|
2014-12-29 12:46:16 +01:00
|
|
|
return conf
|
2015-01-13 15:40:43 +01:00
|
|
|
|
2014-12-29 12:46:16 +01:00
|
|
|
except (xml.parsers.expat.ExpatError,
|
|
|
|
ValueError, LookupError) as err:
|
2015-01-13 15:40:43 +01:00
|
|
|
# config is invalid
|
2014-12-29 12:46:16 +01:00
|
|
|
print("{0}: load error: {1}".format(
|
|
|
|
os.path.basename(sys.argv[0]), err))
|
|
|
|
return None
|
|
|
|
|
|
|
|
return conf
|