2016-09-08 04:10:02 +02:00
|
|
|
# pylint: disable=too-few-public-methods
|
2017-01-18 22:16:46 +01:00
|
|
|
|
2016-09-08 04:10:02 +02:00
|
|
|
#
|
|
|
|
# The Qubes OS Project, https://www.qubes-os.org/
|
|
|
|
#
|
|
|
|
# Copyright (C) 2016
|
|
|
|
# Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
|
|
|
|
#
|
2017-10-12 00:11:50 +02:00
|
|
|
# This library is free software; you can redistribute it and/or
|
|
|
|
# modify it under the terms of the GNU Lesser General Public
|
|
|
|
# License as published by the Free Software Foundation; either
|
|
|
|
# version 2.1 of the License, or (at your option) any later version.
|
2016-09-08 04:10:02 +02:00
|
|
|
#
|
2017-10-12 00:11:50 +02:00
|
|
|
# This library is distributed in the hope that it will be useful,
|
2016-09-08 04:10:02 +02:00
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
2017-10-12 00:11:50 +02:00
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
|
|
|
# Lesser General Public License for more details.
|
2016-09-08 04:10:02 +02:00
|
|
|
#
|
2017-10-12 00:11:50 +02:00
|
|
|
# You should have received a copy of the GNU Lesser General Public
|
|
|
|
# License along with this library; if not, see <https://www.gnu.org/licenses/>.
|
2016-09-08 04:10:02 +02:00
|
|
|
#
|
2017-01-18 22:16:46 +01:00
|
|
|
|
2016-09-08 04:10:02 +02:00
|
|
|
import datetime
|
2017-06-26 12:58:14 +02:00
|
|
|
import string
|
2016-09-08 04:10:02 +02:00
|
|
|
|
2016-09-09 03:14:16 +02:00
|
|
|
import itertools
|
2016-09-08 04:10:02 +02:00
|
|
|
import os
|
|
|
|
import socket
|
2018-02-07 02:40:56 +01:00
|
|
|
|
|
|
|
import asyncio
|
2016-09-19 18:12:57 +02:00
|
|
|
import lxml.etree
|
2016-09-08 04:10:02 +02:00
|
|
|
|
|
|
|
import qubes
|
|
|
|
import qubes.vm.qubesvm
|
|
|
|
|
|
|
|
|
|
|
|
class RuleOption(object):
|
2017-06-26 12:58:14 +02:00
|
|
|
def __init__(self, untrusted_value):
|
|
|
|
# subset of string.punctuation
|
|
|
|
safe_set = string.ascii_letters + string.digits + \
|
|
|
|
':;,./-_[]'
|
|
|
|
assert all(x in safe_set for x in str(untrusted_value))
|
|
|
|
value = str(untrusted_value)
|
|
|
|
self._value = value
|
2016-09-08 04:10:02 +02:00
|
|
|
|
|
|
|
@property
|
|
|
|
def rule(self):
|
|
|
|
raise NotImplementedError
|
|
|
|
|
2017-06-26 12:58:14 +02:00
|
|
|
@property
|
|
|
|
def api_rule(self):
|
|
|
|
return self.rule
|
|
|
|
|
2016-09-08 04:10:02 +02:00
|
|
|
def __str__(self):
|
|
|
|
return self._value
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
return str(self) == other
|
|
|
|
|
|
|
|
# noinspection PyAbstractClass
|
|
|
|
class RuleChoice(RuleOption):
|
|
|
|
# pylint: disable=abstract-method
|
2017-06-26 12:58:14 +02:00
|
|
|
def __init__(self, untrusted_value):
|
|
|
|
# preliminary validation
|
|
|
|
super(RuleChoice, self).__init__(untrusted_value)
|
2016-09-08 04:10:02 +02:00
|
|
|
self.allowed_values = \
|
|
|
|
[v for k, v in self.__class__.__dict__.items()
|
2017-01-18 22:16:46 +01:00
|
|
|
if not k.startswith('__') and isinstance(v, str) and
|
2016-09-08 04:10:02 +02:00
|
|
|
not v.startswith('__')]
|
2017-06-26 12:58:14 +02:00
|
|
|
if untrusted_value not in self.allowed_values:
|
|
|
|
raise ValueError(untrusted_value)
|
2016-09-08 04:10:02 +02:00
|
|
|
|
|
|
|
|
|
|
|
class Action(RuleChoice):
|
|
|
|
accept = 'accept'
|
|
|
|
drop = 'drop'
|
|
|
|
|
|
|
|
@property
|
|
|
|
def rule(self):
|
|
|
|
return 'action=' + str(self)
|
|
|
|
|
|
|
|
|
|
|
|
class Proto(RuleChoice):
|
|
|
|
tcp = 'tcp'
|
|
|
|
udp = 'udp'
|
|
|
|
icmp = 'icmp'
|
|
|
|
|
|
|
|
@property
|
|
|
|
def rule(self):
|
|
|
|
return 'proto=' + str(self)
|
|
|
|
|
|
|
|
|
|
|
|
class DstHost(RuleOption):
|
|
|
|
'''Represent host/network address: either IPv4, IPv6, or DNS name'''
|
2017-06-26 12:58:14 +02:00
|
|
|
def __init__(self, untrusted_value, prefixlen=None):
|
|
|
|
if untrusted_value.count('/') > 1:
|
|
|
|
raise ValueError('Too many /: ' + untrusted_value)
|
|
|
|
elif not untrusted_value.count('/'):
|
2016-09-08 04:10:02 +02:00
|
|
|
# add prefix length to bare IP addresses
|
|
|
|
try:
|
2017-06-26 12:58:14 +02:00
|
|
|
socket.inet_pton(socket.AF_INET6, untrusted_value)
|
|
|
|
value = untrusted_value
|
2016-09-08 04:10:02 +02:00
|
|
|
self.prefixlen = prefixlen or 128
|
|
|
|
if self.prefixlen < 0 or self.prefixlen > 128:
|
|
|
|
raise ValueError(
|
|
|
|
'netmask for IPv6 must be between 0 and 128')
|
|
|
|
value += '/' + str(self.prefixlen)
|
|
|
|
self.type = 'dst6'
|
|
|
|
except socket.error:
|
|
|
|
try:
|
2017-06-26 12:58:14 +02:00
|
|
|
socket.inet_pton(socket.AF_INET, untrusted_value)
|
|
|
|
if untrusted_value.count('.') != 3:
|
2016-09-08 04:10:02 +02:00
|
|
|
raise ValueError(
|
|
|
|
'Invalid number of dots in IPv4 address')
|
2017-06-26 12:58:14 +02:00
|
|
|
value = untrusted_value
|
2016-09-08 04:10:02 +02:00
|
|
|
self.prefixlen = prefixlen or 32
|
|
|
|
if self.prefixlen < 0 or self.prefixlen > 32:
|
|
|
|
raise ValueError(
|
|
|
|
'netmask for IPv4 must be between 0 and 32')
|
|
|
|
value += '/' + str(self.prefixlen)
|
|
|
|
self.type = 'dst4'
|
|
|
|
except socket.error:
|
|
|
|
self.type = 'dsthost'
|
|
|
|
self.prefixlen = 0
|
2017-06-26 12:58:14 +02:00
|
|
|
safe_set = string.ascii_lowercase + string.digits + '-._'
|
2017-07-25 14:19:29 +02:00
|
|
|
if not all(c in safe_set for c in untrusted_value):
|
|
|
|
raise ValueError('Invalid hostname')
|
2017-06-26 12:58:14 +02:00
|
|
|
value = untrusted_value
|
2016-09-08 04:10:02 +02:00
|
|
|
else:
|
2017-06-26 12:58:14 +02:00
|
|
|
untrusted_host, untrusted_prefixlen = untrusted_value.split('/', 1)
|
|
|
|
prefixlen = int(untrusted_prefixlen)
|
2016-09-08 04:10:02 +02:00
|
|
|
if prefixlen < 0:
|
|
|
|
raise ValueError('netmask must be non-negative')
|
|
|
|
self.prefixlen = prefixlen
|
|
|
|
try:
|
2017-06-26 12:58:14 +02:00
|
|
|
socket.inet_pton(socket.AF_INET6, untrusted_host)
|
|
|
|
value = untrusted_value
|
2016-09-08 04:10:02 +02:00
|
|
|
if prefixlen > 128:
|
|
|
|
raise ValueError('netmask for IPv6 must be <= 128')
|
|
|
|
self.type = 'dst6'
|
|
|
|
except socket.error:
|
|
|
|
try:
|
2017-06-26 12:58:14 +02:00
|
|
|
socket.inet_pton(socket.AF_INET, untrusted_host)
|
2016-09-08 04:10:02 +02:00
|
|
|
if prefixlen > 32:
|
|
|
|
raise ValueError('netmask for IPv4 must be <= 32')
|
|
|
|
self.type = 'dst4'
|
2017-06-26 12:58:14 +02:00
|
|
|
if untrusted_host.count('.') != 3:
|
2016-09-08 04:10:02 +02:00
|
|
|
raise ValueError(
|
|
|
|
'Invalid number of dots in IPv4 address')
|
2017-06-26 12:58:14 +02:00
|
|
|
value = untrusted_value
|
2016-09-08 04:10:02 +02:00
|
|
|
except socket.error:
|
2017-06-26 12:58:14 +02:00
|
|
|
raise ValueError('Invalid IP address: ' + untrusted_host)
|
2016-09-08 04:10:02 +02:00
|
|
|
|
|
|
|
super(DstHost, self).__init__(value)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def rule(self):
|
|
|
|
return self.type + '=' + str(self)
|
|
|
|
|
|
|
|
|
|
|
|
class DstPorts(RuleOption):
|
2017-06-26 12:58:14 +02:00
|
|
|
def __init__(self, untrusted_value):
|
|
|
|
if isinstance(untrusted_value, int):
|
|
|
|
untrusted_value = str(untrusted_value)
|
|
|
|
if untrusted_value.count('-') == 1:
|
|
|
|
self.range = [int(x) for x in untrusted_value.split('-', 1)]
|
|
|
|
elif not untrusted_value.count('-'):
|
|
|
|
self.range = [int(untrusted_value), int(untrusted_value)]
|
2016-09-08 04:10:02 +02:00
|
|
|
else:
|
2017-06-26 12:58:14 +02:00
|
|
|
raise ValueError(untrusted_value)
|
2016-09-08 04:10:02 +02:00
|
|
|
if any(port < 0 or port > 65536 for port in self.range):
|
|
|
|
raise ValueError('Ports out of range')
|
|
|
|
if self.range[0] > self.range[1]:
|
|
|
|
raise ValueError('Invalid port range')
|
|
|
|
super(DstPorts, self).__init__(
|
|
|
|
str(self.range[0]) if self.range[0] == self.range[1]
|
|
|
|
else '-'.join(map(str, self.range)))
|
|
|
|
|
|
|
|
@property
|
|
|
|
def rule(self):
|
|
|
|
return 'dstports=' + '{!s}-{!s}'.format(*self.range)
|
|
|
|
|
|
|
|
|
|
|
|
class IcmpType(RuleOption):
|
2017-06-26 12:58:14 +02:00
|
|
|
def __init__(self, untrusted_value):
|
|
|
|
untrusted_value = int(untrusted_value)
|
|
|
|
if untrusted_value < 0 or untrusted_value > 255:
|
2016-09-08 04:10:02 +02:00
|
|
|
raise ValueError('ICMP type out of range')
|
2017-06-26 12:58:14 +02:00
|
|
|
super(IcmpType, self).__init__(untrusted_value)
|
2016-09-08 04:10:02 +02:00
|
|
|
|
|
|
|
@property
|
|
|
|
def rule(self):
|
|
|
|
return 'icmptype=' + str(self)
|
|
|
|
|
|
|
|
|
|
|
|
class SpecialTarget(RuleChoice):
|
|
|
|
dns = 'dns'
|
|
|
|
|
|
|
|
@property
|
|
|
|
def rule(self):
|
|
|
|
return 'specialtarget=' + str(self)
|
|
|
|
|
|
|
|
|
|
|
|
class Expire(RuleOption):
|
2017-06-26 12:58:14 +02:00
|
|
|
def __init__(self, untrusted_value):
|
|
|
|
super(Expire, self).__init__(untrusted_value)
|
2018-03-07 22:40:07 +01:00
|
|
|
self.datetime = datetime.datetime.fromtimestamp(int(untrusted_value))
|
2016-09-08 04:10:02 +02:00
|
|
|
|
|
|
|
@property
|
|
|
|
def rule(self):
|
|
|
|
return None
|
|
|
|
|
2017-06-26 12:58:14 +02:00
|
|
|
@property
|
|
|
|
def api_rule(self):
|
|
|
|
return 'expire=' + str(self)
|
|
|
|
|
2016-09-08 04:10:02 +02:00
|
|
|
@property
|
|
|
|
def expired(self):
|
2018-03-07 22:40:07 +01:00
|
|
|
return self.datetime < datetime.datetime.now()
|
2016-09-08 04:10:02 +02:00
|
|
|
|
|
|
|
|
|
|
|
class Comment(RuleOption):
|
2017-06-26 12:58:14 +02:00
|
|
|
# noinspection PyMissingConstructor
|
|
|
|
def __init__(self, untrusted_value):
|
|
|
|
# pylint: disable=super-init-not-called
|
|
|
|
# subset of string.punctuation
|
|
|
|
safe_set = string.ascii_letters + string.digits + \
|
|
|
|
':;,./-_[] '
|
|
|
|
assert all(x in safe_set for x in str(untrusted_value))
|
|
|
|
value = str(untrusted_value)
|
|
|
|
self._value = value
|
|
|
|
|
2016-09-08 04:10:02 +02:00
|
|
|
@property
|
|
|
|
def rule(self):
|
|
|
|
return None
|
|
|
|
|
2017-06-26 12:58:14 +02:00
|
|
|
@property
|
|
|
|
def api_rule(self):
|
|
|
|
return 'comment=' + str(self)
|
|
|
|
|
2016-09-08 04:10:02 +02:00
|
|
|
|
|
|
|
class Rule(qubes.PropertyHolder):
|
2016-09-19 17:47:42 +02:00
|
|
|
def __init__(self, xml=None, **kwargs):
|
|
|
|
'''Single firewall rule
|
|
|
|
|
|
|
|
:param xml: XML element describing rule, or None
|
|
|
|
:param kwargs: rule elements
|
|
|
|
'''
|
2016-09-08 04:10:02 +02:00
|
|
|
super(Rule, self).__init__(xml, **kwargs)
|
|
|
|
self.load_properties()
|
|
|
|
self.events_enabled = True
|
|
|
|
# validate dependencies
|
|
|
|
if self.dstports:
|
|
|
|
self.on_set_dstports('property-set:dstports', 'dstports',
|
|
|
|
self.dstports, None)
|
|
|
|
if self.icmptype:
|
|
|
|
self.on_set_icmptype('property-set:icmptype', 'icmptype',
|
|
|
|
self.icmptype, None)
|
|
|
|
self.property_require('action', False, True)
|
|
|
|
|
|
|
|
action = qubes.property('action',
|
|
|
|
type=Action,
|
|
|
|
order=0,
|
|
|
|
doc='rule action')
|
|
|
|
|
|
|
|
proto = qubes.property('proto',
|
|
|
|
type=Proto,
|
|
|
|
default=None,
|
|
|
|
order=1,
|
|
|
|
doc='protocol to match')
|
|
|
|
|
|
|
|
dsthost = qubes.property('dsthost',
|
|
|
|
type=DstHost,
|
|
|
|
default=None,
|
|
|
|
order=1,
|
|
|
|
doc='destination host/network')
|
|
|
|
|
|
|
|
dstports = qubes.property('dstports',
|
|
|
|
type=DstPorts,
|
|
|
|
default=None,
|
|
|
|
order=2,
|
|
|
|
doc='Destination port(s) (for \'tcp\' and \'udp\' protocol only)')
|
|
|
|
|
|
|
|
icmptype = qubes.property('icmptype',
|
|
|
|
type=IcmpType,
|
|
|
|
default=None,
|
|
|
|
order=2,
|
|
|
|
doc='ICMP packet type (for \'icmp\' protocol only)')
|
|
|
|
|
|
|
|
specialtarget = qubes.property('specialtarget',
|
|
|
|
type=SpecialTarget,
|
|
|
|
default=None,
|
|
|
|
order=1,
|
|
|
|
doc='Special target, for now only \'dns\' supported')
|
|
|
|
|
|
|
|
expire = qubes.property('expire',
|
|
|
|
type=Expire,
|
|
|
|
default=None,
|
|
|
|
doc='Timestamp (UNIX epoch) on which this rule expire')
|
|
|
|
|
|
|
|
comment = qubes.property('comment',
|
|
|
|
type=Comment,
|
|
|
|
default=None,
|
|
|
|
doc='User comment')
|
|
|
|
|
|
|
|
# noinspection PyUnusedLocal
|
|
|
|
@qubes.events.handler('property-pre-set:dstports')
|
2017-02-21 14:09:06 +01:00
|
|
|
def on_set_dstports(self, event, name, newvalue, oldvalue=None):
|
|
|
|
# pylint: disable=unused-argument
|
2016-09-08 04:10:02 +02:00
|
|
|
if self.proto not in ('tcp', 'udp'):
|
|
|
|
raise ValueError(
|
|
|
|
'dstports valid only for \'tcp\' and \'udp\' protocols')
|
|
|
|
|
|
|
|
# noinspection PyUnusedLocal
|
|
|
|
@qubes.events.handler('property-pre-set:icmptype')
|
2017-02-21 14:09:06 +01:00
|
|
|
def on_set_icmptype(self, event, name, newvalue, oldvalue=None):
|
|
|
|
# pylint: disable=unused-argument
|
2016-09-08 04:10:02 +02:00
|
|
|
if self.proto not in ('icmp',):
|
|
|
|
raise ValueError('icmptype valid only for \'icmp\' protocol')
|
|
|
|
|
|
|
|
# noinspection PyUnusedLocal
|
|
|
|
@qubes.events.handler('property-set:proto')
|
2017-02-21 14:09:06 +01:00
|
|
|
def on_set_proto(self, event, name, newvalue, oldvalue=None):
|
|
|
|
# pylint: disable=unused-argument
|
|
|
|
if newvalue not in ('tcp', 'udp'):
|
2016-09-08 04:10:02 +02:00
|
|
|
self.dstports = qubes.property.DEFAULT
|
2017-02-21 14:09:06 +01:00
|
|
|
if newvalue not in ('icmp',):
|
2016-09-08 04:10:02 +02:00
|
|
|
self.icmptype = qubes.property.DEFAULT
|
|
|
|
|
|
|
|
@qubes.events.handler('property-del:proto')
|
2017-02-21 14:09:06 +01:00
|
|
|
def on_del_proto(self, event, name, oldvalue):
|
|
|
|
# pylint: disable=unused-argument
|
2016-09-08 04:10:02 +02:00
|
|
|
self.dstports = qubes.property.DEFAULT
|
|
|
|
self.icmptype = qubes.property.DEFAULT
|
|
|
|
|
|
|
|
@property
|
|
|
|
def rule(self):
|
|
|
|
if self.expire and self.expire.expired:
|
|
|
|
return None
|
|
|
|
values = []
|
|
|
|
for prop in self.property_list():
|
|
|
|
value = getattr(self, prop.__name__)
|
|
|
|
if value is None:
|
|
|
|
continue
|
|
|
|
if value.rule is None:
|
|
|
|
continue
|
|
|
|
values.append(value.rule)
|
|
|
|
return ' '.join(values)
|
|
|
|
|
2017-06-26 12:58:14 +02:00
|
|
|
@property
|
|
|
|
def api_rule(self):
|
|
|
|
values = []
|
2017-10-16 01:47:20 +02:00
|
|
|
if self.expire and self.expire.expired:
|
|
|
|
return None
|
2017-06-26 12:58:14 +02:00
|
|
|
# put comment at the end
|
|
|
|
for prop in sorted(self.property_list(),
|
|
|
|
key=(lambda p: p.__name__ == 'comment')):
|
|
|
|
value = getattr(self, prop.__name__)
|
|
|
|
if value is None:
|
|
|
|
continue
|
|
|
|
if value.api_rule is None:
|
|
|
|
continue
|
|
|
|
values.append(value.api_rule)
|
|
|
|
return ' '.join(values)
|
|
|
|
|
2016-09-08 04:10:02 +02:00
|
|
|
@classmethod
|
|
|
|
def from_xml_v1(cls, node, action):
|
|
|
|
netmask = node.get('netmask')
|
|
|
|
if netmask is None:
|
|
|
|
netmask = 32
|
|
|
|
else:
|
|
|
|
netmask = int(netmask)
|
|
|
|
address = node.get('address')
|
|
|
|
if address:
|
|
|
|
dsthost = DstHost(address, netmask)
|
|
|
|
else:
|
|
|
|
dsthost = None
|
|
|
|
|
|
|
|
proto = node.get('proto')
|
|
|
|
|
|
|
|
port = node.get('port')
|
|
|
|
toport = node.get('toport')
|
|
|
|
if port and toport:
|
|
|
|
dstports = port + '-' + toport
|
|
|
|
elif port:
|
|
|
|
dstports = port
|
|
|
|
else:
|
|
|
|
dstports = None
|
|
|
|
|
|
|
|
# backward compatibility: protocol defaults to TCP if port is specified
|
|
|
|
if dstports and not proto:
|
|
|
|
proto = 'tcp'
|
|
|
|
|
|
|
|
if proto == 'any':
|
|
|
|
proto = None
|
|
|
|
|
|
|
|
expire = node.get('expire')
|
|
|
|
|
|
|
|
kwargs = {
|
|
|
|
'action': action,
|
|
|
|
}
|
|
|
|
if dsthost:
|
|
|
|
kwargs['dsthost'] = dsthost
|
|
|
|
if dstports:
|
|
|
|
kwargs['dstports'] = dstports
|
|
|
|
if proto:
|
|
|
|
kwargs['proto'] = proto
|
|
|
|
if expire:
|
|
|
|
kwargs['expire'] = expire
|
|
|
|
|
2016-09-19 17:47:42 +02:00
|
|
|
return cls(**kwargs)
|
2016-09-08 04:10:02 +02:00
|
|
|
|
2017-06-26 12:58:14 +02:00
|
|
|
@classmethod
|
|
|
|
def from_api_string(cls, untrusted_rule):
|
|
|
|
'''Parse a single line of firewall rule'''
|
|
|
|
# comment is allowed to have spaces
|
|
|
|
untrusted_options, _, untrusted_comment = untrusted_rule.partition(
|
|
|
|
'comment=')
|
|
|
|
# appropriate handlers in __init__ of individual options will perform
|
|
|
|
# option-specific validation
|
|
|
|
kwargs = {}
|
|
|
|
if untrusted_comment:
|
2017-06-26 18:41:27 +02:00
|
|
|
kwargs['comment'] = Comment(untrusted_value=untrusted_comment)
|
2017-06-26 12:58:14 +02:00
|
|
|
|
|
|
|
for untrusted_option in untrusted_options.strip().split(' '):
|
|
|
|
untrusted_key, untrusted_value = untrusted_option.split('=', 1)
|
|
|
|
if untrusted_key in kwargs:
|
|
|
|
raise ValueError('Option \'{}\' already set'.format(
|
|
|
|
untrusted_key))
|
|
|
|
if untrusted_key in [str(prop) for prop in cls.property_list()]:
|
2017-06-26 18:41:27 +02:00
|
|
|
kwargs[untrusted_key] = cls.property_get_def(
|
|
|
|
untrusted_key).type(untrusted_value=untrusted_value)
|
2017-06-26 12:58:14 +02:00
|
|
|
elif untrusted_key in ('dst4', 'dst6', 'dstname'):
|
2017-06-26 18:41:27 +02:00
|
|
|
if 'dsthost' in kwargs:
|
|
|
|
raise ValueError('Option \'{}\' already set'.format(
|
|
|
|
'dsthost'))
|
|
|
|
kwargs['dsthost'] = DstHost(untrusted_value=untrusted_value)
|
2017-06-26 12:58:14 +02:00
|
|
|
else:
|
|
|
|
raise ValueError('Unknown firewall option')
|
|
|
|
|
|
|
|
return cls(**kwargs)
|
|
|
|
|
2016-09-08 04:10:02 +02:00
|
|
|
def __eq__(self, other):
|
2017-06-26 12:58:14 +02:00
|
|
|
if isinstance(other, Rule):
|
|
|
|
return self.api_rule == other.api_rule
|
|
|
|
return self.api_rule == str(other)
|
|
|
|
|
|
|
|
def __hash__(self):
|
|
|
|
return hash(self.api_rule)
|
2016-09-08 04:10:02 +02:00
|
|
|
|
2017-05-15 13:04:59 +02:00
|
|
|
|
2016-09-08 04:10:02 +02:00
|
|
|
class Firewall(object):
|
|
|
|
def __init__(self, vm, load=True):
|
|
|
|
assert hasattr(vm, 'firewall_conf')
|
|
|
|
self.vm = vm
|
|
|
|
#: firewall rules
|
|
|
|
self.rules = []
|
|
|
|
|
|
|
|
if load:
|
|
|
|
self.load()
|
|
|
|
|
2017-06-26 05:11:24 +02:00
|
|
|
@property
|
|
|
|
def policy(self):
|
|
|
|
''' Default action - always 'drop' '''
|
|
|
|
return Action('drop')
|
|
|
|
|
2017-05-15 13:04:59 +02:00
|
|
|
def __eq__(self, other):
|
|
|
|
if isinstance(other, Firewall):
|
2017-06-26 05:11:24 +02:00
|
|
|
return self.rules == other.rules
|
2017-05-15 13:04:59 +02:00
|
|
|
return NotImplemented
|
|
|
|
|
2016-09-08 04:10:02 +02:00
|
|
|
def load_defaults(self):
|
2017-05-15 13:04:59 +02:00
|
|
|
'''Load default firewall settings'''
|
2017-06-26 05:11:24 +02:00
|
|
|
self.rules = [Rule(None, action='accept')]
|
2016-09-08 04:10:02 +02:00
|
|
|
|
2017-05-15 13:04:59 +02:00
|
|
|
def clone(self, other):
|
|
|
|
'''Clone firewall settings from other instance.
|
|
|
|
This method discards pre-existing firewall settings.
|
|
|
|
|
|
|
|
:param other: other :py:class:`Firewall` instance
|
|
|
|
'''
|
|
|
|
rules = []
|
|
|
|
for rule in other.rules:
|
2017-08-06 12:49:19 +02:00
|
|
|
# Rule constructor require some action, will be overwritten by
|
|
|
|
# clone_properties below
|
|
|
|
new_rule = Rule(action='drop')
|
2017-05-15 13:04:59 +02:00
|
|
|
new_rule.clone_properties(rule)
|
|
|
|
rules.append(new_rule)
|
|
|
|
self.rules = rules
|
|
|
|
|
2016-09-08 04:10:02 +02:00
|
|
|
def load(self):
|
2017-05-15 13:04:59 +02:00
|
|
|
'''Load firewall settings from a file'''
|
2016-09-08 04:10:02 +02:00
|
|
|
firewall_conf = os.path.join(self.vm.dir_path, self.vm.firewall_conf)
|
|
|
|
if os.path.exists(firewall_conf):
|
|
|
|
self.rules = []
|
|
|
|
tree = lxml.etree.parse(firewall_conf)
|
|
|
|
root = tree.getroot()
|
|
|
|
|
|
|
|
version = root.get('version', '1')
|
|
|
|
if version == '1':
|
|
|
|
self.load_v1(root)
|
|
|
|
elif version == '2':
|
|
|
|
self.load_v2(root)
|
|
|
|
else:
|
|
|
|
raise qubes.exc.QubesVMError(self.vm,
|
|
|
|
'Unsupported firewall.xml version: {}'.format(version))
|
|
|
|
else:
|
|
|
|
self.load_defaults()
|
|
|
|
|
|
|
|
def load_v1(self, xml_root):
|
2017-05-15 13:04:59 +02:00
|
|
|
'''Load old (Qubes < 4.0) firewall XML format'''
|
2016-09-08 04:10:02 +02:00
|
|
|
policy_v1 = xml_root.get('policy')
|
|
|
|
assert policy_v1 in ('allow', 'deny')
|
2017-06-26 18:45:59 +02:00
|
|
|
default_policy_is_accept = (policy_v1 == 'allow')
|
2016-09-08 04:10:02 +02:00
|
|
|
|
|
|
|
def _translate_action(key):
|
|
|
|
if xml_root.get(key, policy_v1) == 'allow':
|
|
|
|
return Action.accept
|
2017-04-21 15:43:46 +02:00
|
|
|
return Action.drop
|
2016-09-08 04:10:02 +02:00
|
|
|
|
|
|
|
self.rules.append(Rule(None,
|
|
|
|
action=_translate_action('dns'),
|
|
|
|
specialtarget=SpecialTarget('dns')))
|
|
|
|
|
|
|
|
self.rules.append(Rule(None,
|
|
|
|
action=_translate_action('icmp'),
|
|
|
|
proto=Proto.icmp))
|
|
|
|
|
2017-06-26 18:45:59 +02:00
|
|
|
if default_policy_is_accept:
|
2016-09-08 04:10:02 +02:00
|
|
|
rule_action = Action.drop
|
|
|
|
else:
|
|
|
|
rule_action = Action.accept
|
|
|
|
|
|
|
|
for element in xml_root:
|
|
|
|
rule = Rule.from_xml_v1(element, rule_action)
|
|
|
|
self.rules.append(rule)
|
2017-06-26 18:45:59 +02:00
|
|
|
if default_policy_is_accept:
|
2017-06-26 05:11:24 +02:00
|
|
|
self.rules.append(Rule(None, action='accept'))
|
2016-09-08 04:10:02 +02:00
|
|
|
|
|
|
|
def load_v2(self, xml_root):
|
2017-05-15 13:04:59 +02:00
|
|
|
'''Load new (Qubes >= 4.0) firewall XML format'''
|
2016-09-08 04:10:02 +02:00
|
|
|
xml_rules = xml_root.find('rules')
|
|
|
|
for xml_rule in xml_rules:
|
|
|
|
rule = Rule(xml_rule)
|
|
|
|
self.rules.append(rule)
|
|
|
|
|
2018-02-07 02:40:56 +01:00
|
|
|
def _expire_rules(self):
|
|
|
|
'''Function called to reload expired rules'''
|
|
|
|
old_rules = self.rules
|
|
|
|
self.load()
|
|
|
|
if self.rules != old_rules:
|
|
|
|
# this will both save rules skipping those expired and trigger
|
|
|
|
# QubesDB update; and possibly schedule another timer
|
|
|
|
self.save()
|
|
|
|
|
2016-09-08 04:10:02 +02:00
|
|
|
def save(self):
|
2017-05-15 13:04:59 +02:00
|
|
|
'''Save firewall rules to a file'''
|
2016-09-08 04:10:02 +02:00
|
|
|
firewall_conf = os.path.join(self.vm.dir_path, self.vm.firewall_conf)
|
2018-03-07 22:37:44 +01:00
|
|
|
nearest_expire = None
|
2016-09-08 04:10:02 +02:00
|
|
|
|
|
|
|
xml_root = lxml.etree.Element('firewall', version=str(2))
|
|
|
|
|
|
|
|
xml_rules = lxml.etree.Element('rules')
|
|
|
|
for rule in self.rules:
|
|
|
|
if rule.expire:
|
|
|
|
if rule.expire and rule.expire.expired:
|
|
|
|
continue
|
|
|
|
else:
|
2018-02-07 02:40:56 +01:00
|
|
|
if nearest_expire is None or rule.expire.datetime < \
|
|
|
|
nearest_expire:
|
|
|
|
nearest_expire = rule.expire.datetime
|
2016-09-08 04:10:02 +02:00
|
|
|
xml_rule = lxml.etree.Element('rule')
|
|
|
|
xml_rule.append(rule.xml_properties())
|
|
|
|
xml_rules.append(xml_rule)
|
|
|
|
|
|
|
|
xml_root.append(xml_rules)
|
|
|
|
|
|
|
|
xml_tree = lxml.etree.ElementTree(xml_root)
|
|
|
|
|
|
|
|
try:
|
|
|
|
old_umask = os.umask(0o002)
|
2017-01-18 22:16:46 +01:00
|
|
|
with open(firewall_conf, 'wb') as firewall_xml:
|
2016-09-08 04:10:02 +02:00
|
|
|
xml_tree.write(firewall_xml, encoding="UTF-8",
|
|
|
|
pretty_print=True)
|
|
|
|
os.umask(old_umask)
|
|
|
|
except EnvironmentError as err:
|
|
|
|
self.vm.log.error("save error: {}".format(err))
|
|
|
|
raise qubes.exc.QubesException('save error: {}'.format(err))
|
|
|
|
|
2016-09-09 03:14:16 +02:00
|
|
|
self.vm.fire_event('firewall-changed')
|
|
|
|
|
2018-02-07 02:40:56 +01:00
|
|
|
if nearest_expire and not self.vm.app.vmm.offline_mode:
|
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
# by documentation call_at use loop.time() clock, which not
|
|
|
|
# necessary must be the same as time module; calculate delay and
|
|
|
|
# use call_later instead
|
|
|
|
expire_when = nearest_expire - datetime.datetime.now()
|
2018-03-07 22:37:44 +01:00
|
|
|
loop.call_later(expire_when.total_seconds(), self._expire_rules)
|
2016-09-09 03:14:16 +02:00
|
|
|
|
2016-09-12 06:02:07 +02:00
|
|
|
def qdb_entries(self, addr_family=None):
|
2017-05-15 13:04:59 +02:00
|
|
|
'''Return firewall settings serialized for QubesDB entries
|
|
|
|
|
|
|
|
:param addr_family: include rules only for IPv4 (4) or IPv6 (6); if
|
|
|
|
None, include both
|
|
|
|
'''
|
2016-09-09 03:14:16 +02:00
|
|
|
entries = {
|
|
|
|
'policy': str(self.policy)
|
|
|
|
}
|
2016-09-12 06:02:07 +02:00
|
|
|
exclude_dsttype = None
|
|
|
|
if addr_family is not None:
|
|
|
|
exclude_dsttype = 'dst4' if addr_family == 6 else 'dst6'
|
2016-09-09 03:14:16 +02:00
|
|
|
for ruleno, rule in zip(itertools.count(), self.rules):
|
2017-10-16 01:47:20 +02:00
|
|
|
if rule.expire and rule.expire.expired:
|
|
|
|
continue
|
2016-09-12 06:02:07 +02:00
|
|
|
# exclude rules for another address family
|
|
|
|
if rule.dsthost and rule.dsthost.type == exclude_dsttype:
|
|
|
|
continue
|
2016-09-09 03:14:16 +02:00
|
|
|
entries['{:04}'.format(ruleno)] = rule.rule
|
|
|
|
return entries
|