85
81
except ImportError:
86
82
SO_BINDTODEVICE = None
89
stored_state_file = "clients.pickle"
91
logger = logging.getLogger()
87
#logger = logging.getLogger('mandos')
88
logger = logging.Logger('mandos')
92
89
syslogger = (logging.handlers.SysLogHandler
93
90
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
94
91
address = str("/dev/log")))
97
if_nametoindex = (ctypes.cdll.LoadLibrary
98
(ctypes.util.find_library("c"))
100
except (OSError, AttributeError):
101
def if_nametoindex(interface):
102
"Get an interface index the hard way, i.e. using fcntl()"
103
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
104
with contextlib.closing(socket.socket()) as s:
105
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
106
struct.pack(str("16s16x"),
108
interface_index = struct.unpack(str("I"),
110
return interface_index
113
def initlogger(debug, level=logging.WARNING):
114
"""init logger and add loglevel"""
116
syslogger.setFormatter(logging.Formatter
117
('Mandos [%(process)d]: %(levelname)s:'
119
logger.addHandler(syslogger)
122
console = logging.StreamHandler()
123
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
127
logger.addHandler(console)
128
logger.setLevel(level)
131
class PGPError(Exception):
132
"""Exception if encryption/decryption fails"""
136
class PGPEngine(object):
137
"""A simple class for OpenPGP symmetric encryption & decryption"""
139
self.gnupg = GnuPGInterface.GnuPG()
140
self.tempdir = tempfile.mkdtemp(prefix="mandos-")
141
self.gnupg = GnuPGInterface.GnuPG()
142
self.gnupg.options.meta_interactive = False
143
self.gnupg.options.homedir = self.tempdir
144
self.gnupg.options.extra_args.extend(['--force-mdc',
151
def __exit__ (self, exc_type, exc_value, traceback):
159
if self.tempdir is not None:
160
# Delete contents of tempdir
161
for root, dirs, files in os.walk(self.tempdir,
163
for filename in files:
164
os.remove(os.path.join(root, filename))
166
os.rmdir(os.path.join(root, dirname))
168
os.rmdir(self.tempdir)
171
def password_encode(self, password):
172
# Passphrase can not be empty and can not contain newlines or
173
# NUL bytes. So we prefix it and hex encode it.
174
return b"mandos" + binascii.hexlify(password)
176
def encrypt(self, data, password):
177
self.gnupg.passphrase = self.password_encode(password)
178
with open(os.devnull) as devnull:
180
proc = self.gnupg.run(['--symmetric'],
181
create_fhs=['stdin', 'stdout'],
182
attach_fhs={'stderr': devnull})
183
with contextlib.closing(proc.handles['stdin']) as f:
185
with contextlib.closing(proc.handles['stdout']) as f:
186
ciphertext = f.read()
190
self.gnupg.passphrase = None
193
def decrypt(self, data, password):
194
self.gnupg.passphrase = self.password_encode(password)
195
with open(os.devnull) as devnull:
197
proc = self.gnupg.run(['--decrypt'],
198
create_fhs=['stdin', 'stdout'],
199
attach_fhs={'stderr': devnull})
200
with contextlib.closing(proc.handles['stdin'] ) as f:
202
with contextlib.closing(proc.handles['stdout']) as f:
203
decrypted_plaintext = f.read()
207
self.gnupg.passphrase = None
208
return decrypted_plaintext
92
syslogger.setFormatter(logging.Formatter
93
('Mandos [%(process)d]: %(levelname)s:'
95
logger.addHandler(syslogger)
97
console = logging.StreamHandler()
98
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
101
logger.addHandler(console)
212
103
class AvahiError(Exception):
213
104
def __init__(self, value, *args, **kwargs):
432
313
"created", "enabled", "fingerprint",
433
314
"host", "interval", "last_checked_ok",
434
315
"last_enabled", "name", "timeout")
435
client_defaults = { "timeout": "5m",
436
"extended_timeout": "15m",
438
"checker": "fping -q -- %%(host)s",
440
"approval_delay": "0s",
441
"approval_duration": "1s",
442
"approved_by_default": "True",
446
317
def timeout_milliseconds(self):
447
318
"Return the 'timeout' attribute in milliseconds"
448
return timedelta_to_milliseconds(self.timeout)
319
return _timedelta_to_milliseconds(self.timeout)
450
321
def extended_timeout_milliseconds(self):
451
322
"Return the 'extended_timeout' attribute in milliseconds"
452
return timedelta_to_milliseconds(self.extended_timeout)
323
return _timedelta_to_milliseconds(self.extended_timeout)
454
325
def interval_milliseconds(self):
455
326
"Return the 'interval' attribute in milliseconds"
456
return timedelta_to_milliseconds(self.interval)
327
return _timedelta_to_milliseconds(self.interval)
458
329
def approval_delay_milliseconds(self):
459
return timedelta_to_milliseconds(self.approval_delay)
462
def config_parser(config):
463
"""Construct a new dict of client settings of this form:
464
{ client_name: {setting_name: value, ...}, ...}
465
with exceptions for any special settings as defined above.
466
NOTE: Must be a pure function. Must return the same result
467
value given the same arguments.
470
for client_name in config.sections():
471
section = dict(config.items(client_name))
472
client = settings[client_name] = {}
474
client["host"] = section["host"]
475
# Reformat values from string types to Python types
476
client["approved_by_default"] = config.getboolean(
477
client_name, "approved_by_default")
478
client["enabled"] = config.getboolean(client_name,
481
client["fingerprint"] = (section["fingerprint"].upper()
483
if "secret" in section:
484
client["secret"] = section["secret"].decode("base64")
485
elif "secfile" in section:
486
with open(os.path.expanduser(os.path.expandvars
487
(section["secfile"])),
489
client["secret"] = secfile.read()
491
raise TypeError("No secret or secfile for section %s"
493
client["timeout"] = string_to_delta(section["timeout"])
494
client["extended_timeout"] = string_to_delta(
495
section["extended_timeout"])
496
client["interval"] = string_to_delta(section["interval"])
497
client["approval_delay"] = string_to_delta(
498
section["approval_delay"])
499
client["approval_duration"] = string_to_delta(
500
section["approval_duration"])
501
client["checker_command"] = section["checker"]
502
client["last_approval_request"] = None
503
client["last_checked_ok"] = None
504
client["last_checker_status"] = None
509
def __init__(self, settings, name = None):
330
return _timedelta_to_milliseconds(self.approval_delay)
332
def __init__(self, name = None, disable_hook=None, config=None):
510
333
"""Note: the 'checker' key in 'config' sets the
511
334
'checker_command' attribute and *not* the 'checker'
514
# adding all client settings
515
for setting, value in settings.iteritems():
516
setattr(self, setting, value)
519
if not hasattr(self, "last_enabled"):
520
self.last_enabled = datetime.datetime.utcnow()
521
if not hasattr(self, "expires"):
522
self.expires = (datetime.datetime.utcnow()
525
self.last_enabled = None
528
339
logger.debug("Creating client %r", self.name)
529
340
# Uppercase and remove spaces from fingerprint for later
530
341
# comparison purposes with return value from the fingerprint()
343
self.fingerprint = (config["fingerprint"].upper()
532
345
logger.debug(" Fingerprint: %s", self.fingerprint)
533
self.created = settings.get("created",
534
datetime.datetime.utcnow())
536
# attributes specific for this server instance
346
if "secret" in config:
347
self.secret = config["secret"].decode("base64")
348
elif "secfile" in config:
349
with open(os.path.expanduser(os.path.expandvars
350
(config["secfile"])),
352
self.secret = secfile.read()
354
raise TypeError("No secret or secfile for client %s"
356
self.host = config.get("host", "")
357
self.created = datetime.datetime.utcnow()
359
self.last_approval_request = None
360
self.last_enabled = None
361
self.last_checked_ok = None
362
self.timeout = string_to_delta(config["timeout"])
363
self.extended_timeout = string_to_delta(config["extended_timeout"])
364
self.interval = string_to_delta(config["interval"])
365
self.disable_hook = disable_hook
537
366
self.checker = None
538
367
self.checker_initiator_tag = None
539
368
self.disable_initiator_tag = None
540
370
self.checker_callback_tag = None
371
self.checker_command = config["checker"]
541
372
self.current_checker_command = None
373
self.last_connect = None
374
self._approved = None
375
self.approved_by_default = config.get("approved_by_default",
543
377
self.approvals_pending = 0
544
self.changedstate = (multiprocessing_manager
545
.Condition(multiprocessing_manager
547
self.client_structure = [attr for attr in
548
self.__dict__.iterkeys()
549
if not attr.startswith("_")]
550
self.client_structure.append("client_structure")
552
for name, t in inspect.getmembers(type(self),
556
if not name.startswith("_"):
557
self.client_structure.append(name)
378
self.approval_delay = string_to_delta(
379
config["approval_delay"])
380
self.approval_duration = string_to_delta(
381
config["approval_duration"])
382
self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
559
# Send notice to process children that client state has changed
560
384
def send_changedstate(self):
561
with self.changedstate:
562
self.changedstate.notify_all()
385
self.changedstate.acquire()
386
self.changedstate.notify_all()
387
self.changedstate.release()
564
389
def enable(self):
565
390
"""Start this client's checker and timeout hooks"""
566
391
if getattr(self, "enabled", False):
567
392
# Already enabled
569
394
self.send_changedstate()
395
# Schedule a new checker to be started an 'interval' from now,
396
# and every interval from then on.
397
self.checker_initiator_tag = (gobject.timeout_add
398
(self.interval_milliseconds(),
400
# Schedule a disable() when 'timeout' has passed
570
401
self.expires = datetime.datetime.utcnow() + self.timeout
402
self.disable_initiator_tag = (gobject.timeout_add
403
(self.timeout_milliseconds(),
571
405
self.enabled = True
572
406
self.last_enabled = datetime.datetime.utcnow()
407
# Also start a new checker *right now*.
575
410
def disable(self, quiet=True):
576
411
"""Disable this client."""
804
626
def _get_all_dbus_properties(self):
805
627
"""Returns a generator of (name, attribute) pairs
807
return ((prop.__get__(self)._dbus_name, prop.__get__(self))
808
for cls in self.__class__.__mro__
629
return ((prop._dbus_name, prop)
809
630
for name, prop in
810
inspect.getmembers(cls, self._is_dbus_property))
631
inspect.getmembers(self, self._is_dbus_property))
812
633
def _get_dbus_property(self, interface_name, property_name):
813
634
"""Returns a bound method if one exists which is a D-Bus
814
635
property with the specified name and interface.
816
for cls in self.__class__.__mro__:
817
for name, value in (inspect.getmembers
818
(cls, self._is_dbus_property)):
819
if (value._dbus_name == property_name
820
and value._dbus_interface == interface_name):
821
return value.__get__(self)
637
for name in (property_name,
638
property_name + "_dbus_property"):
639
prop = getattr(self, name, None)
641
or not self._is_dbus_property(prop)
642
or prop._dbus_name != property_name
643
or (interface_name and prop._dbus_interface
644
and interface_name != prop._dbus_interface)):
823
647
# No such property
824
648
raise DBusPropertyNotFound(self.dbus_object_path + ":"
825
649
+ interface_name + "."
935
759
variant_level=variant_level)
938
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
940
"""Applied to an empty subclass of a D-Bus object, this metaclass
941
will add additional D-Bus attributes matching a certain pattern.
943
def __new__(mcs, name, bases, attr):
944
# Go through all the base classes which could have D-Bus
945
# methods, signals, or properties in them
946
for base in (b for b in bases
947
if issubclass(b, dbus.service.Object)):
948
# Go though all attributes of the base class
949
for attrname, attribute in inspect.getmembers(base):
950
# Ignore non-D-Bus attributes, and D-Bus attributes
951
# with the wrong interface name
952
if (not hasattr(attribute, "_dbus_interface")
953
or not attribute._dbus_interface
954
.startswith("se.recompile.Mandos")):
956
# Create an alternate D-Bus interface name based on
958
alt_interface = (attribute._dbus_interface
959
.replace("se.recompile.Mandos",
960
"se.bsnet.fukt.Mandos"))
961
# Is this a D-Bus signal?
962
if getattr(attribute, "_dbus_is_signal", False):
963
# Extract the original non-method function by
965
nonmethod_func = (dict(
966
zip(attribute.func_code.co_freevars,
967
attribute.__closure__))["func"]
969
# Create a new, but exactly alike, function
970
# object, and decorate it to be a new D-Bus signal
971
# with the alternate D-Bus interface name
972
new_function = (dbus.service.signal
974
attribute._dbus_signature)
976
nonmethod_func.func_code,
977
nonmethod_func.func_globals,
978
nonmethod_func.func_name,
979
nonmethod_func.func_defaults,
980
nonmethod_func.func_closure)))
981
# Define a creator of a function to call both the
982
# old and new functions, so both the old and new
983
# signals gets sent when the function is called
984
def fixscope(func1, func2):
985
"""This function is a scope container to pass
986
func1 and func2 to the "call_both" function
987
outside of its arguments"""
988
def call_both(*args, **kwargs):
989
"""This function will emit two D-Bus
990
signals by calling func1 and func2"""
991
func1(*args, **kwargs)
992
func2(*args, **kwargs)
994
# Create the "call_both" function and add it to
996
attr[attrname] = fixscope(attribute,
998
# Is this a D-Bus method?
999
elif getattr(attribute, "_dbus_is_method", False):
1000
# Create a new, but exactly alike, function
1001
# object. Decorate it to be a new D-Bus method
1002
# with the alternate D-Bus interface name. Add it
1004
attr[attrname] = (dbus.service.method
1006
attribute._dbus_in_signature,
1007
attribute._dbus_out_signature)
1009
(attribute.func_code,
1010
attribute.func_globals,
1011
attribute.func_name,
1012
attribute.func_defaults,
1013
attribute.func_closure)))
1014
# Is this a D-Bus property?
1015
elif getattr(attribute, "_dbus_is_property", False):
1016
# Create a new, but exactly alike, function
1017
# object, and decorate it to be a new D-Bus
1018
# property with the alternate D-Bus interface
1019
# name. Add it to the class.
1020
attr[attrname] = (dbus_service_property
1022
attribute._dbus_signature,
1023
attribute._dbus_access,
1025
._dbus_get_args_options
1028
(attribute.func_code,
1029
attribute.func_globals,
1030
attribute.func_name,
1031
attribute.func_defaults,
1032
attribute.func_closure)))
1033
return type.__new__(mcs, name, bases, attr)
1036
762
class ClientDBus(Client, DBusObjectWithProperties):
1037
763
"""A Client class using D-Bus
1065
789
def notifychangeproperty(transform_func,
1066
790
dbus_name, type_func=lambda x: x,
1067
791
variant_level=1):
1068
""" Modify a variable so that it's a property which announces
1069
its changes to DBus.
1071
transform_fun: Function that takes a value and a variant_level
1072
and transforms it to a D-Bus type.
1073
dbus_name: D-Bus name of the variable
792
""" Modify a variable so that its a property that announce its
794
transform_fun: Function that takes a value and transform it to
796
dbus_name: DBus name of the variable
1074
797
type_func: Function that transform the value before sending it
1075
to the D-Bus. Default: no transform
1076
variant_level: D-Bus variant level. Default: 1
799
variant_level: DBus variant level. default: 1
1078
attrname = "_{0}".format(dbus_name)
1079
802
def setter(self, value):
803
old_value = real_value[0]
804
real_value[0] = value
1080
805
if hasattr(self, "dbus_object_path"):
1081
if (not hasattr(self, attrname) or
1082
type_func(getattr(self, attrname, None))
1083
!= type_func(value)):
1084
dbus_value = transform_func(type_func(value),
806
if type_func(old_value) != type_func(real_value[0]):
807
dbus_value = transform_func(type_func(real_value[0]),
1087
809
self.PropertyChanged(dbus.String(dbus_name),
1089
setattr(self, attrname, value)
1091
return property(lambda self: getattr(self, attrname), setter)
812
return property(lambda self: real_value[0], setter)
1094
815
expires = notifychangeproperty(datetime_to_dbus, "Expires")
1099
820
last_enabled = notifychangeproperty(datetime_to_dbus,
1101
822
checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1102
type_func = lambda checker:
1103
checker is not None)
823
type_func = lambda checker: checker is not None)
1104
824
last_checked_ok = notifychangeproperty(datetime_to_dbus,
1105
825
"LastCheckedOK")
1106
last_approval_request = notifychangeproperty(
1107
datetime_to_dbus, "LastApprovalRequest")
826
last_approval_request = notifychangeproperty(datetime_to_dbus,
827
"LastApprovalRequest")
1108
828
approved_by_default = notifychangeproperty(dbus.Boolean,
1109
829
"ApprovedByDefault")
1110
approval_delay = notifychangeproperty(dbus.UInt64,
1113
timedelta_to_milliseconds)
1114
approval_duration = notifychangeproperty(
1115
dbus.UInt64, "ApprovalDuration",
1116
type_func = timedelta_to_milliseconds)
830
approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
831
type_func = _timedelta_to_milliseconds)
832
approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
833
type_func = _timedelta_to_milliseconds)
1117
834
host = notifychangeproperty(dbus.String, "Host")
1118
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1120
timedelta_to_milliseconds)
1121
extended_timeout = notifychangeproperty(
1122
dbus.UInt64, "ExtendedTimeout",
1123
type_func = timedelta_to_milliseconds)
1124
interval = notifychangeproperty(dbus.UInt64,
1127
timedelta_to_milliseconds)
835
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
836
type_func = _timedelta_to_milliseconds)
837
extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
838
type_func = _timedelta_to_milliseconds)
839
interval = notifychangeproperty(dbus.UInt16, "Interval",
840
type_func = _timedelta_to_milliseconds)
1128
841
checker_command = notifychangeproperty(dbus.String, "Checker")
1130
843
del notifychangeproperty
2207
1902
client_class = Client
2209
client_class = functools.partial(ClientDBusTransitional,
2212
client_settings = Client.config_parser(client_config)
2213
old_client_settings = {}
2216
# Get client data and settings from last running state.
2217
if server_settings["restore"]:
2219
with open(stored_state_path, "rb") as stored_state:
2220
clients_data, old_client_settings = (pickle.load
2222
os.remove(stored_state_path)
2223
except IOError as e:
2224
logger.warning("Could not load persistent state: {0}"
2226
if e.errno != errno.ENOENT:
2228
except EOFError as e:
2229
logger.warning("Could not load persistent state: "
2230
"EOFError: {0}".format(e))
2232
with PGPEngine() as pgp:
2233
for client_name, client in clients_data.iteritems():
2234
# Decide which value to use after restoring saved state.
2235
# We have three different values: Old config file,
2236
# new config file, and saved state.
2237
# New config value takes precedence if it differs from old
2238
# config value, otherwise use saved state.
2239
for name, value in client_settings[client_name].items():
2241
# For each value in new config, check if it
2242
# differs from the old config value (Except for
2243
# the "secret" attribute)
2244
if (name != "secret" and
2245
value != old_client_settings[client_name]
2247
client[name] = value
2251
# Clients who has passed its expire date can still be
2252
# enabled if its last checker was successful. Clients
2253
# whose checker failed before we stored its state is
2254
# assumed to have failed all checkers during downtime.
2255
if client["enabled"]:
2256
if datetime.datetime.utcnow() >= client["expires"]:
2257
if not client["last_checked_ok"]:
2259
"disabling client {0} - Client never "
2260
"performed a successfull checker"
2261
.format(client["name"]))
2262
client["enabled"] = False
2263
elif client["last_checker_status"] != 0:
2265
"disabling client {0} - Client "
2266
"last checker failed with error code {1}"
2267
.format(client["name"],
2268
client["last_checker_status"]))
2269
client["enabled"] = False
2271
client["expires"] = (datetime.datetime
2273
+ client["timeout"])
2274
logger.debug("Last checker succeeded,"
2275
" keeping {0} enabled"
2276
.format(client["name"]))
1904
client_class = functools.partial(ClientDBus, bus = bus)
1905
def client_config_items(config, section):
1906
special_settings = {
1907
"approved_by_default":
1908
lambda: config.getboolean(section,
1909
"approved_by_default"),
1911
for name, value in config.items(section):
2278
client["secret"] = (
2279
pgp.decrypt(client["encrypted_secret"],
2280
client_settings[client_name]
2283
# If decryption fails, we use secret from new settings
2284
logger.debug("Failed to decrypt {0} old secret"
2285
.format(client_name))
2286
client["secret"] = (
2287
client_settings[client_name]["secret"])
2290
# Add/remove clients based on new changes made to config
2291
for client_name in (set(old_client_settings)
2292
- set(client_settings)):
2293
del clients_data[client_name]
2294
for client_name in (set(client_settings)
2295
- set(old_client_settings)):
2296
clients_data[client_name] = client_settings[client_name]
2298
# Create clients all clients
2299
for client_name, client in clients_data.iteritems():
2300
tcp_server.clients[client_name] = client_class(
2301
name = client_name, settings = client)
1913
yield (name, special_settings[name]())
1917
tcp_server.clients.update(set(
1918
client_class(name = section,
1919
config= dict(client_config_items(
1920
client_config, section)))
1921
for section in client_config.sections()))
2303
1922
if not tcp_server.clients:
2304
1923
logger.warning("No clients defined")
2378
class MandosDBusServiceTransitional(MandosDBusService):
2379
__metaclass__ = AlternateDBusNamesMetaclass
2380
mandos_dbus_service = MandosDBusServiceTransitional()
1997
mandos_dbus_service = MandosDBusService()
2383
2000
"Cleanup function; run on exit"
2384
2001
service.cleanup()
2386
multiprocessing.active_children()
2387
if not (tcp_server.clients or client_settings):
2390
# Store client before exiting. Secrets are encrypted with key
2391
# based on what config file has. If config file is
2392
# removed/edited, old secret will thus be unrecovable.
2394
with PGPEngine() as pgp:
2395
for client in tcp_server.clients.itervalues():
2396
key = client_settings[client.name]["secret"]
2397
client.encrypted_secret = pgp.encrypt(client.secret,
2401
# A list of attributes that can not be pickled
2403
exclude = set(("bus", "changedstate", "secret",
2405
for name, typ in (inspect.getmembers
2406
(dbus.service.Object)):
2409
client_dict["encrypted_secret"] = (client
2411
for attr in client.client_structure:
2412
if attr not in exclude:
2413
client_dict[attr] = getattr(client, attr)
2415
clients[client.name] = client_dict
2416
del client_settings[client.name]["secret"]
2419
tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2422
(stored_state_path))
2423
with os.fdopen(tempfd, "wb") as stored_state:
2424
pickle.dump((clients, client_settings), stored_state)
2425
os.rename(tempname, stored_state_path)
2426
except (IOError, OSError) as e:
2427
logger.warning("Could not save persistent state: {0}"
2434
if e.errno not in set((errno.ENOENT, errno.EACCES,
2438
# Delete all clients, and settings from config
2439
2003
while tcp_server.clients:
2440
name, client = tcp_server.clients.popitem()
2004
client = tcp_server.clients.pop()
2442
2006
client.remove_from_connection()
2007
client.disable_hook = None
2443
2008
# Don't signal anything except ClientRemoved
2444
2009
client.disable(quiet=True)
2446
2011
# Emit D-Bus signal
2447
mandos_dbus_service.ClientRemoved(client
2012
mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2450
client_settings.clear()
2452
2015
atexit.register(cleanup)
2454
for client in tcp_server.clients.itervalues():
2017
for client in tcp_server.clients:
2456
2019
# Emit D-Bus signal
2457
2020
mandos_dbus_service.ClientAdded(client.dbus_object_path)
2458
# Need to initiate checking of clients
2460
client.init_checker()
2462
2023
tcp_server.enable()
2463
2024
tcp_server.server_activate()