380
395
config["approval_delay"])
381
396
self.approval_duration = string_to_delta(
382
397
config["approval_duration"])
383
self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
398
self.changedstate = (multiprocessing_manager
399
.Condition(multiprocessing_manager
401
self.client_structure = [attr for attr in self.__dict__.iterkeys() if not attr.startswith("_")]
402
self.client_structure.append("client_structure")
405
for name, t in inspect.getmembers(type(self),
406
lambda obj: isinstance(obj, property)):
407
if not name.startswith("_"):
408
self.client_structure.append(name)
410
# Send notice to process children that client state has changed
385
411
def send_changedstate(self):
386
self.changedstate.acquire()
387
self.changedstate.notify_all()
388
self.changedstate.release()
412
with self.changedstate:
413
self.changedstate.notify_all()
390
415
def enable(self):
391
416
"""Start this client's checker and timeout hooks"""
392
417
if getattr(self, "enabled", False):
393
418
# Already enabled
395
420
self.send_changedstate()
396
# Schedule a new checker to be started an 'interval' from now,
397
# and every interval from then on.
398
self.checker_initiator_tag = (gobject.timeout_add
399
(self.interval_milliseconds(),
401
# Schedule a disable() when 'timeout' has passed
402
421
self.expires = datetime.datetime.utcnow() + self.timeout
403
self.disable_initiator_tag = (gobject.timeout_add
404
(self.timeout_milliseconds(),
406
422
self.enabled = True
407
423
self.last_enabled = datetime.datetime.utcnow()
408
# Also start a new checker *right now*.
411
426
def disable(self, quiet=True):
412
427
"""Disable this client."""
563
592
self.checker = None
594
# Encrypts a client secret and stores it in a varible encrypted_secret
595
def encrypt_secret(self, key):
596
# Encryption-key need to be of a specific size, so we hash inputed key
597
hasheng = hashlib.sha256()
599
encryptionkey = hasheng.digest()
601
# Create validation hash so we know at decryption if it was sucessful
602
hasheng = hashlib.sha256()
603
hasheng.update(self.secret)
604
validationhash = hasheng.digest()
607
iv = os.urandom(Crypto.Cipher.AES.block_size)
608
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
609
Crypto.Cipher.AES.MODE_CFB, iv)
610
ciphertext = ciphereng.encrypt(validationhash+self.secret)
611
self.encrypted_secret = (ciphertext, iv)
613
# Decrypt a encrypted client secret
614
def decrypt_secret(self, key):
615
# Decryption-key need to be of a specific size, so we hash inputed key
616
hasheng = hashlib.sha256()
618
encryptionkey = hasheng.digest()
620
# Decrypt encrypted secret
621
ciphertext, iv = self.encrypted_secret
622
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
623
Crypto.Cipher.AES.MODE_CFB, iv)
624
plain = ciphereng.decrypt(ciphertext)
626
# Validate decrypted secret to know if it was succesful
627
hasheng = hashlib.sha256()
628
validationhash = plain[:hasheng.digest_size]
629
secret = plain[hasheng.digest_size:]
630
hasheng.update(secret)
632
# if validation fails, we use key as new secret. Otherwhise, we use
633
# the decrypted secret
634
if hasheng.digest() == validationhash:
638
del self.encrypted_secret
566
641
def dbus_service_property(dbus_interface, signature="v",
567
642
access="readwrite", byte_arrays=False):
755
832
return dbus.String(dt.isoformat(),
756
833
variant_level=variant_level)
758
class transitional_dbus_metaclass(DBusObjectWithProperties.__metaclass__):
835
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
837
"""Applied to an empty subclass of a D-Bus object, this metaclass
838
will add additional D-Bus attributes matching a certain pattern.
759
840
def __new__(mcs, name, bases, attr):
760
for attrname, old_dbusobj in inspect.getmembers(bases[0]):
761
new_interface = getattr(old_dbusobj, "_dbus_interface", "").replace("se.bsnet.fukt.", "se.recompile.")
762
if (getattr(old_dbusobj, "_dbus_is_signal", False)
763
and old_dbusobj._dbus_interface.startswith("se.bsnet.fukt.Mandos")):
764
unwrappedfunc = dict(zip(old_dbusobj.func_code.co_freevars,
765
old_dbusobj.__closure__))["func"].cell_contents
766
newfunc = types.FunctionType(unwrappedfunc.func_code,
767
unwrappedfunc.func_globals,
768
unwrappedfunc.func_name,
769
unwrappedfunc.func_defaults,
770
unwrappedfunc.func_closure)
771
new_dbusfunc = dbus.service.signal(
772
new_interface, old_dbusobj._dbus_signature)(newfunc)
773
attr["_transitional_" + attrname] = new_dbusfunc
775
def fixscope(func1, func2):
776
def newcall(*args, **kwargs):
777
func1(*args, **kwargs)
778
func2(*args, **kwargs)
781
attr[attrname] = fixscope(old_dbusobj, new_dbusfunc)
783
elif (getattr(old_dbusobj, "_dbus_is_method", False)
784
and old_dbusobj._dbus_interface.startswith("se.bsnet.fukt.Mandos")):
785
new_dbusfunc = (dbus.service.method
787
old_dbusobj._dbus_in_signature,
788
old_dbusobj._dbus_out_signature)
790
(old_dbusobj.func_code,
791
old_dbusobj.func_globals,
792
old_dbusobj.func_name,
793
old_dbusobj.func_defaults,
794
old_dbusobj.func_closure)))
796
attr[attrname] = new_dbusfunc
797
elif (getattr(old_dbusobj, "_dbus_is_property", False)
798
and old_dbusobj._dbus_interface.startswith("se.bsnet.fukt.Mandos")):
799
new_dbusfunc = (dbus_service_property
801
old_dbusobj._dbus_signature,
802
old_dbusobj._dbus_access,
803
old_dbusobj._dbus_get_args_options["byte_arrays"])
805
(old_dbusobj.func_code,
806
old_dbusobj.func_globals,
807
old_dbusobj.func_name,
808
old_dbusobj.func_defaults,
809
old_dbusobj.func_closure)))
811
attr[attrname] = new_dbusfunc
841
# Go through all the base classes which could have D-Bus
842
# methods, signals, or properties in them
843
for base in (b for b in bases
844
if issubclass(b, dbus.service.Object)):
845
# Go though all attributes of the base class
846
for attrname, attribute in inspect.getmembers(base):
847
# Ignore non-D-Bus attributes, and D-Bus attributes
848
# with the wrong interface name
849
if (not hasattr(attribute, "_dbus_interface")
850
or not attribute._dbus_interface
851
.startswith("se.recompile.Mandos")):
853
# Create an alternate D-Bus interface name based on
855
alt_interface = (attribute._dbus_interface
856
.replace("se.recompile.Mandos",
857
"se.bsnet.fukt.Mandos"))
858
# Is this a D-Bus signal?
859
if getattr(attribute, "_dbus_is_signal", False):
860
# Extract the original non-method function by
862
nonmethod_func = (dict(
863
zip(attribute.func_code.co_freevars,
864
attribute.__closure__))["func"]
866
# Create a new, but exactly alike, function
867
# object, and decorate it to be a new D-Bus signal
868
# with the alternate D-Bus interface name
869
new_function = (dbus.service.signal
871
attribute._dbus_signature)
873
nonmethod_func.func_code,
874
nonmethod_func.func_globals,
875
nonmethod_func.func_name,
876
nonmethod_func.func_defaults,
877
nonmethod_func.func_closure)))
878
# Define a creator of a function to call both the
879
# old and new functions, so both the old and new
880
# signals gets sent when the function is called
881
def fixscope(func1, func2):
882
"""This function is a scope container to pass
883
func1 and func2 to the "call_both" function
884
outside of its arguments"""
885
def call_both(*args, **kwargs):
886
"""This function will emit two D-Bus
887
signals by calling func1 and func2"""
888
func1(*args, **kwargs)
889
func2(*args, **kwargs)
891
# Create the "call_both" function and add it to
893
attr[attrname] = fixscope(attribute,
895
# Is this a D-Bus method?
896
elif getattr(attribute, "_dbus_is_method", False):
897
# Create a new, but exactly alike, function
898
# object. Decorate it to be a new D-Bus method
899
# with the alternate D-Bus interface name. Add it
901
attr[attrname] = (dbus.service.method
903
attribute._dbus_in_signature,
904
attribute._dbus_out_signature)
906
(attribute.func_code,
907
attribute.func_globals,
909
attribute.func_defaults,
910
attribute.func_closure)))
911
# Is this a D-Bus property?
912
elif getattr(attribute, "_dbus_is_property", False):
913
# Create a new, but exactly alike, function
914
# object, and decorate it to be a new D-Bus
915
# property with the alternate D-Bus interface
916
# name. Add it to the class.
917
attr[attrname] = (dbus_service_property
919
attribute._dbus_signature,
920
attribute._dbus_access,
922
._dbus_get_args_options
925
(attribute.func_code,
926
attribute.func_globals,
928
attribute.func_defaults,
929
attribute.func_closure)))
812
930
return type.__new__(mcs, name, bases, attr)
814
932
class ClientDBus(Client, DBusObjectWithProperties):
841
960
def notifychangeproperty(transform_func,
842
961
dbus_name, type_func=lambda x: x,
843
962
variant_level=1):
844
""" Modify a variable so that its a property that announce its
846
transform_fun: Function that takes a value and transform it to
848
dbus_name: DBus name of the variable
963
""" Modify a variable so that it's a property which announces
966
transform_fun: Function that takes a value and a variant_level
967
and transforms it to a D-Bus type.
968
dbus_name: D-Bus name of the variable
849
969
type_func: Function that transform the value before sending it
851
variant_level: DBus variant level. default: 1
970
to the D-Bus. Default: no transform
971
variant_level: D-Bus variant level. Default: 1
973
attrname = "_{0}".format(dbus_name)
854
974
def setter(self, value):
855
old_value = real_value[0]
856
real_value[0] = value
857
975
if hasattr(self, "dbus_object_path"):
858
if type_func(old_value) != type_func(real_value[0]):
859
dbus_value = transform_func(type_func(real_value[0]),
976
if (not hasattr(self, attrname) or
977
type_func(getattr(self, attrname, None))
978
!= type_func(value)):
979
dbus_value = transform_func(type_func(value),
861
982
self.PropertyChanged(dbus.String(dbus_name),
984
setattr(self, attrname, value)
864
return property(lambda self: real_value[0], setter)
986
return property(lambda self: getattr(self, attrname), setter)
867
989
expires = notifychangeproperty(datetime_to_dbus, "Expires")
872
994
last_enabled = notifychangeproperty(datetime_to_dbus,
874
996
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
875
type_func = lambda checker: checker is not None)
997
type_func = lambda checker:
876
999
last_checked_ok = notifychangeproperty(datetime_to_dbus,
877
1000
"LastCheckedOK")
878
last_approval_request = notifychangeproperty(datetime_to_dbus,
879
"LastApprovalRequest")
1001
last_approval_request = notifychangeproperty(
1002
datetime_to_dbus, "LastApprovalRequest")
880
1003
approved_by_default = notifychangeproperty(dbus.Boolean,
881
1004
"ApprovedByDefault")
882
approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
883
type_func = _timedelta_to_milliseconds)
884
approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
885
type_func = _timedelta_to_milliseconds)
1005
approval_delay = notifychangeproperty(dbus.UInt16,
1008
_timedelta_to_milliseconds)
1009
approval_duration = notifychangeproperty(
1010
dbus.UInt16, "ApprovalDuration",
1011
type_func = _timedelta_to_milliseconds)
886
1012
host = notifychangeproperty(dbus.String, "Host")
887
1013
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
888
type_func = _timedelta_to_milliseconds)
889
extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
890
type_func = _timedelta_to_milliseconds)
891
interval = notifychangeproperty(dbus.UInt16, "Interval",
892
type_func = _timedelta_to_milliseconds)
1015
_timedelta_to_milliseconds)
1016
extended_timeout = notifychangeproperty(
1017
dbus.UInt16, "ExtendedTimeout",
1018
type_func = _timedelta_to_milliseconds)
1019
interval = notifychangeproperty(dbus.UInt16,
1022
_timedelta_to_milliseconds)
893
1023
checker_command = notifychangeproperty(dbus.String, "Checker")
895
1025
del notifychangeproperty
1616
1756
"dress: %s", fpr, address)
1617
1757
if self.use_dbus:
1618
1758
# Emit D-Bus signal
1619
mandos_dbus_service.ClientNotFound(fpr, address[0])
1759
mandos_dbus_service.ClientNotFound(fpr,
1620
1761
parent_pipe.send(False)
1623
1764
gobject.io_add_watch(parent_pipe.fileno(),
1624
1765
gobject.IO_IN | gobject.IO_HUP,
1625
1766
functools.partial(self.handle_ipc,
1626
parent_pipe = parent_pipe,
1627
client_object = client))
1628
1772
parent_pipe.send(True)
1629
# remove the old hook in favor of the new above hook on same fileno
1773
# remove the old hook in favor of the new above hook on
1631
1776
if command == 'funcall':
1632
1777
funcname = request[1]
1633
1778
args = request[2]
1634
1779
kwargs = request[3]
1636
parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1781
parent_pipe.send(('data', getattr(client_object,
1638
1785
if command == 'getattr':
1639
1786
attrname = request[1]
1640
1787
if callable(client_object.__getattribute__(attrname)):
1641
1788
parent_pipe.send(('function',))
1643
parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1790
parent_pipe.send(('data', client_object
1791
.__getattribute__(attrname)))
1645
1793
if command == 'setattr':
1646
1794
attrname = request[1]
1935
2086
# End of Avahi example code
1938
bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
1939
bus, do_not_queue=True)
1940
bus_name2 = dbus.service.BusName("se.recompile.Mandos",
1941
bus, do_not_queue=True)
2089
bus_name = dbus.service.BusName("se.recompile.Mandos",
2090
bus, do_not_queue=True)
2091
old_bus_name = (dbus.service.BusName
2092
("se.bsnet.fukt.Mandos", bus,
1942
2094
except dbus.exceptions.NameExistsException as e:
1943
2095
logger.error(unicode(e) + ", disabling D-Bus")
1944
2096
use_dbus = False
1945
2097
server_settings["use_dbus"] = False
1946
2098
tcp_server.use_dbus = False
1947
2099
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1948
service = AvahiService(name = server_settings["servicename"],
1949
servicetype = "_mandos._tcp",
1950
protocol = protocol, bus = bus)
2100
service = AvahiServiceToSyslog(name =
2101
server_settings["servicename"],
2102
servicetype = "_mandos._tcp",
2103
protocol = protocol, bus = bus)
1951
2104
if server_settings["interface"]:
1952
2105
service.interface = (if_nametoindex
1953
2106
(str(server_settings["interface"])))
1958
2111
client_class = Client
1960
client_class = functools.partial(ClientDBusTransitional, bus = bus)
1961
def client_config_items(config, section):
1962
special_settings = {
1963
"approved_by_default":
1964
lambda: config.getboolean(section,
1965
"approved_by_default"),
1967
for name, value in config.items(section):
2113
client_class = functools.partial(ClientDBusTransitional,
2116
special_settings = {
2117
# Some settings need to be accessd by special methods;
2118
# booleans need .getboolean(), etc. Here is a list of them:
2119
"approved_by_default":
2121
client_config.getboolean(section, "approved_by_default"),
2123
# Construct a new dict of client settings of this form:
2124
# { client_name: {setting_name: value, ...}, ...}
2125
# with exceptions for any special settings as defined above
2126
client_settings = dict((clientname,
2128
(value if setting not in special_settings
2129
else special_settings[setting](clientname)))
2130
for setting, value in client_config.items(clientname)))
2131
for clientname in client_config.sections())
2133
old_client_settings = {}
2136
# Get client data and settings from last running state.
2137
if server_settings["restore"]:
2139
with open(stored_state_path, "rb") as stored_state:
2140
clients_data, old_client_settings = pickle.load(stored_state)
2141
os.remove(stored_state_path)
2142
except IOError as e:
2143
logger.warning("Could not load persistant state: {0}".format(e))
2144
if e.errno != errno.ENOENT:
2147
for client in clients_data:
2148
client_name = client["name"]
2150
# Decide which value to use after restoring saved state.
2151
# We have three different values: Old config file,
2152
# new config file, and saved state.
2153
# New config value takes precedence if it differs from old
2154
# config value, otherwise use saved state.
2155
for name, value in client_settings[client_name].items():
1969
yield (name, special_settings[name]())
2157
# For each value in new config, check if it differs
2158
# from the old config value (Except for the "secret"
2160
if name != "secret" and value != old_client_settings[client_name][name]:
2161
setattr(client, name, value)
1970
2162
except KeyError:
2165
# Clients who has passed its expire date, can still be enabled if its
2166
# last checker was sucessful. Clients who checkers failed before we
2167
# stored it state is asumed to had failed checker during downtime.
2168
if client["enabled"] and client["last_checked_ok"]:
2169
if ((datetime.datetime.utcnow() - client["last_checked_ok"])
2170
> client["interval"]):
2171
if client["last_checker_status"] != 0:
2172
client["enabled"] = False
2174
client["expires"] = datetime.datetime.utcnow() + client["timeout"]
2176
client["changedstate"] = (multiprocessing_manager
2177
.Condition(multiprocessing_manager
2180
new_client = ClientDBusTransitional.__new__(ClientDBusTransitional)
2181
tcp_server.clients[client_name] = new_client
2182
new_client.bus = bus
2183
for name, value in client.iteritems():
2184
setattr(new_client, name, value)
2185
client_object_name = unicode(client_name).translate(
2186
{ord("."): ord("_"),
2187
ord("-"): ord("_")})
2188
new_client.dbus_object_path = (dbus.ObjectPath
2189
("/clients/" + client_object_name))
2190
DBusObjectWithProperties.__init__(new_client,
2192
new_client.dbus_object_path)
2194
tcp_server.clients[client_name] = Client.__new__(Client)
2195
for name, value in client.iteritems():
2196
setattr(tcp_server.clients[client_name], name, value)
2198
tcp_server.clients[client_name].decrypt_secret(
2199
client_settings[client_name]["secret"])
2201
# Create/remove clients based on new changes made to config
2202
for clientname in set(old_client_settings) - set(client_settings):
2203
del tcp_server.clients[clientname]
2204
for clientname in set(client_settings) - set(old_client_settings):
2205
tcp_server.clients[clientname] = (client_class(name = clientname,
1973
tcp_server.clients.update(set(
1974
client_class(name = section,
1975
config= dict(client_config_items(
1976
client_config, section)))
1977
for section in client_config.sections()))
1978
2211
if not tcp_server.clients:
1979
2212
logger.warning("No clients defined")
2053
2287
class MandosDBusServiceTransitional(MandosDBusService):
2054
__metaclass__ = transitional_dbus_metaclass
2288
__metaclass__ = AlternateDBusNamesMetaclass
2055
2289
mandos_dbus_service = MandosDBusServiceTransitional()
2058
2292
"Cleanup function; run on exit"
2059
2293
service.cleanup()
2295
multiprocessing.active_children()
2296
if not (tcp_server.clients or client_settings):
2299
# Store client before exiting. Secrets are encrypted with key based
2300
# on what config file has. If config file is removed/edited, old
2301
# secret will thus be unrecovable.
2303
for client in tcp_server.clients.itervalues():
2304
client.encrypt_secret(client_settings[client.name]["secret"])
2308
# A list of attributes that will not be stored when shuting down.
2309
exclude = set(("bus", "changedstate", "secret"))
2310
for name, typ in inspect.getmembers(dbus.service.Object):
2313
client_dict["encrypted_secret"] = client.encrypted_secret
2314
for attr in client.client_structure:
2315
if attr not in exclude:
2316
client_dict[attr] = getattr(client, attr)
2318
clients.append(client_dict)
2319
del client_settings[client.name]["secret"]
2322
with os.fdopen(os.open(stored_state_path, os.O_CREAT|os.O_WRONLY|os.O_TRUNC, 0600), "wb") as stored_state:
2323
pickle.dump((clients, client_settings), stored_state)
2324
except IOError as e:
2325
logger.warning("Could not save persistant state: {0}".format(e))
2326
if e.errno != errno.ENOENT:
2329
# Delete all clients, and settings from config
2061
2330
while tcp_server.clients:
2062
client = tcp_server.clients.pop()
2331
name, client = tcp_server.clients.popitem()
2064
2333
client.remove_from_connection()
2065
client.disable_hook = None
2066
2334
# Don't signal anything except ClientRemoved
2067
2335
client.disable(quiet=True)
2069
2337
# Emit D-Bus signal
2070
mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2338
mandos_dbus_service.ClientRemoved(client
2341
client_settings.clear()
2073
2343
atexit.register(cleanup)
2075
for client in tcp_server.clients:
2345
for client in tcp_server.clients.itervalues():
2077
2347
# Emit D-Bus signal
2078
2348
mandos_dbus_service.ClientAdded(client.dbus_object_path)
2349
# Need to initiate checking of clients
2351
client.init_checker()
2081
2354
tcp_server.enable()
2082
2355
tcp_server.server_activate()