85
82
except ImportError:
86
83
SO_BINDTODEVICE = None
89
stored_state_file = "clients.pickle"
91
logger = logging.getLogger()
88
#logger = logging.getLogger('mandos')
89
logger = logging.Logger('mandos')
92
90
syslogger = (logging.handlers.SysLogHandler
93
91
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
94
92
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',
150
def __exit__ (self, exc_type, exc_value, traceback):
158
if self.tempdir is not None:
159
# Delete contents of tempdir
160
for root, dirs, files in os.walk(self.tempdir,
162
for filename in files:
163
os.remove(os.path.join(root, filename))
165
os.rmdir(os.path.join(root, dirname))
167
os.rmdir(self.tempdir)
170
def password_encode(self, password):
171
# Passphrase can not be empty and can not contain newlines or
172
# NUL bytes. So we prefix it and hex encode it.
173
return b"mandos" + binascii.hexlify(password)
175
def encrypt(self, data, password):
176
self.gnupg.passphrase = self.password_encode(password)
177
with open(os.devnull) as devnull:
179
proc = self.gnupg.run(['--symmetric'],
180
create_fhs=['stdin', 'stdout'],
181
attach_fhs={'stderr': devnull})
182
with contextlib.closing(proc.handles['stdin']) as f:
184
with contextlib.closing(proc.handles['stdout']) as f:
185
ciphertext = f.read()
189
self.gnupg.passphrase = None
192
def decrypt(self, data, password):
193
self.gnupg.passphrase = self.password_encode(password)
194
with open(os.devnull) as devnull:
196
proc = self.gnupg.run(['--decrypt'],
197
create_fhs=['stdin', 'stdout'],
198
attach_fhs={'stderr': devnull})
199
with contextlib.closing(proc.handles['stdin'] ) as f:
201
with contextlib.closing(proc.handles['stdout']) as f:
202
decrypted_plaintext = f.read()
206
self.gnupg.passphrase = None
207
return decrypted_plaintext
93
syslogger.setFormatter(logging.Formatter
94
('Mandos [%(process)d]: %(levelname)s:'
96
logger.addHandler(syslogger)
98
console = logging.StreamHandler()
99
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
102
logger.addHandler(console)
211
104
class AvahiError(Exception):
212
105
def __init__(self, value, *args, **kwargs):
431
315
"created", "enabled", "fingerprint",
432
316
"host", "interval", "last_checked_ok",
433
317
"last_enabled", "name", "timeout")
434
client_defaults = { "timeout": "5m",
435
"extended_timeout": "15m",
437
"checker": "fping -q -- %%(host)s",
439
"approval_delay": "0s",
440
"approval_duration": "1s",
441
"approved_by_default": "True",
445
319
def timeout_milliseconds(self):
446
320
"Return the 'timeout' attribute in milliseconds"
447
return timedelta_to_milliseconds(self.timeout)
321
return _timedelta_to_milliseconds(self.timeout)
449
323
def extended_timeout_milliseconds(self):
450
324
"Return the 'extended_timeout' attribute in milliseconds"
451
return timedelta_to_milliseconds(self.extended_timeout)
325
return _timedelta_to_milliseconds(self.extended_timeout)
453
327
def interval_milliseconds(self):
454
328
"Return the 'interval' attribute in milliseconds"
455
return timedelta_to_milliseconds(self.interval)
329
return _timedelta_to_milliseconds(self.interval)
457
331
def approval_delay_milliseconds(self):
458
return timedelta_to_milliseconds(self.approval_delay)
461
def config_parser(config):
462
""" Construct a new dict of client settings of this form:
463
{ client_name: {setting_name: value, ...}, ...}
464
with exceptions for any special settings as defined above"""
466
for client_name in config.sections():
467
section = dict(config.items(client_name))
468
client = settings[client_name] = {}
470
client["host"] = section["host"]
471
# Reformat values from string types to Python types
472
client["approved_by_default"] = config.getboolean(
473
client_name, "approved_by_default")
474
client["enabled"] = config.getboolean(client_name, "enabled")
476
client["fingerprint"] = (section["fingerprint"].upper()
478
if "secret" in section:
479
client["secret"] = section["secret"].decode("base64")
480
elif "secfile" in section:
481
with open(os.path.expanduser(os.path.expandvars
482
(section["secfile"])),
484
client["secret"] = secfile.read()
486
raise TypeError("No secret or secfile for section %s"
488
client["timeout"] = string_to_delta(section["timeout"])
489
client["extended_timeout"] = string_to_delta(
490
section["extended_timeout"])
491
client["interval"] = string_to_delta(section["interval"])
492
client["approval_delay"] = string_to_delta(
493
section["approval_delay"])
494
client["approval_duration"] = string_to_delta(
495
section["approval_duration"])
496
client["checker_command"] = section["checker"]
497
client["last_approval_request"] = None
498
client["last_checked_ok"] = None
499
client["last_checker_status"] = None
500
if client["enabled"]:
501
client["last_enabled"] = datetime.datetime.utcnow()
502
client["expires"] = (datetime.datetime.utcnow()
505
client["last_enabled"] = None
506
client["expires"] = None
511
def __init__(self, settings, name = None):
332
return _timedelta_to_milliseconds(self.approval_delay)
334
def __init__(self, name = None, disable_hook=None, config=None):
512
335
"""Note: the 'checker' key in 'config' sets the
513
336
'checker_command' attribute and *not* the 'checker'
516
# adding all client settings
517
for setting, value in settings.iteritems():
518
setattr(self, setting, value)
520
341
logger.debug("Creating client %r", self.name)
521
342
# Uppercase and remove spaces from fingerprint for later
522
343
# comparison purposes with return value from the fingerprint()
345
self.fingerprint = (config["fingerprint"].upper()
524
347
logger.debug(" Fingerprint: %s", self.fingerprint)
525
self.created = settings.get("created", datetime.datetime.utcnow())
527
# attributes specific for this server instance
348
if "secret" in config:
349
self.secret = config["secret"].decode("base64")
350
elif "secfile" in config:
351
with open(os.path.expanduser(os.path.expandvars
352
(config["secfile"])),
354
self.secret = secfile.read()
356
raise TypeError("No secret or secfile for client %s"
358
self.host = config.get("host", "")
359
self.created = datetime.datetime.utcnow()
361
self.last_approval_request = None
362
self.last_enabled = None
363
self.last_checked_ok = None
364
self.timeout = string_to_delta(config["timeout"])
365
self.extended_timeout = string_to_delta(config
366
["extended_timeout"])
367
self.interval = string_to_delta(config["interval"])
368
self.disable_hook = disable_hook
528
369
self.checker = None
529
370
self.checker_initiator_tag = None
530
371
self.disable_initiator_tag = None
531
373
self.checker_callback_tag = None
374
self.checker_command = config["checker"]
532
375
self.current_checker_command = None
376
self.last_connect = None
377
self._approved = None
378
self.approved_by_default = config.get("approved_by_default",
534
380
self.approvals_pending = 0
381
self.approval_delay = string_to_delta(
382
config["approval_delay"])
383
self.approval_duration = string_to_delta(
384
config["approval_duration"])
535
385
self.changedstate = (multiprocessing_manager
536
386
.Condition(multiprocessing_manager
538
self.client_structure = [attr for attr in
539
self.__dict__.iterkeys()
540
if not attr.startswith("_")]
541
self.client_structure.append("client_structure")
543
for name, t in inspect.getmembers(type(self),
547
if not name.startswith("_"):
548
self.client_structure.append(name)
550
# Send notice to process children that client state has changed
551
389
def send_changedstate(self):
552
with self.changedstate:
553
self.changedstate.notify_all()
390
self.changedstate.acquire()
391
self.changedstate.notify_all()
392
self.changedstate.release()
555
394
def enable(self):
556
395
"""Start this client's checker and timeout hooks"""
579
428
gobject.source_remove(self.checker_initiator_tag)
580
429
self.checker_initiator_tag = None
581
430
self.stop_checker()
431
if self.disable_hook:
432
self.disable_hook(self)
582
433
self.enabled = False
583
434
# Do not run this again if called by a gobject.timeout_add
586
437
def __del__(self):
438
self.disable_hook = None
589
def init_checker(self):
590
# Schedule a new checker to be started an 'interval' from now,
591
# and every interval from then on.
592
self.checker_initiator_tag = (gobject.timeout_add
593
(self.interval_milliseconds(),
595
# Schedule a disable() when 'timeout' has passed
596
self.disable_initiator_tag = (gobject.timeout_add
597
(self.timeout_milliseconds(),
599
# Also start a new checker *right now*.
602
441
def checker_callback(self, pid, condition, command):
603
442
"""The checker has completed, so take appropriate actions."""
604
443
self.checker_callback_tag = None
605
444
self.checker = None
606
445
if os.WIFEXITED(condition):
607
self.last_checker_status = os.WEXITSTATUS(condition)
608
if self.last_checker_status == 0:
446
exitstatus = os.WEXITSTATUS(condition)
609
448
logger.info("Checker for %(name)s succeeded",
611
450
self.checked_ok()
1058
890
variant_level=1):
1059
891
""" Modify a variable so that it's a property which announces
1060
892
its changes to DBus.
1062
transform_fun: Function that takes a value and a variant_level
1063
and transforms it to a D-Bus type.
894
transform_fun: Function that takes a value and transforms it
1064
896
dbus_name: D-Bus name of the variable
1065
897
type_func: Function that transform the value before sending it
1066
898
to the D-Bus. Default: no transform
1067
899
variant_level: D-Bus variant level. Default: 1
1069
attrname = "_{0}".format(dbus_name)
1070
902
def setter(self, value):
903
old_value = real_value[0]
904
real_value[0] = value
1071
905
if hasattr(self, "dbus_object_path"):
1072
if (not hasattr(self, attrname) or
1073
type_func(getattr(self, attrname, None))
1074
!= type_func(value)):
1075
dbus_value = transform_func(type_func(value),
906
if type_func(old_value) != type_func(real_value[0]):
907
dbus_value = transform_func(type_func
1078
910
self.PropertyChanged(dbus.String(dbus_name),
1080
setattr(self, attrname, value)
1082
return property(lambda self: getattr(self, attrname), setter)
913
return property(lambda self: real_value[0], setter)
1085
916
expires = notifychangeproperty(datetime_to_dbus, "Expires")
1098
929
datetime_to_dbus, "LastApprovalRequest")
1099
930
approved_by_default = notifychangeproperty(dbus.Boolean,
1100
931
"ApprovedByDefault")
1101
approval_delay = notifychangeproperty(dbus.UInt64,
932
approval_delay = notifychangeproperty(dbus.UInt16,
1102
933
"ApprovalDelay",
1104
timedelta_to_milliseconds)
935
_timedelta_to_milliseconds)
1105
936
approval_duration = notifychangeproperty(
1106
dbus.UInt64, "ApprovalDuration",
1107
type_func = timedelta_to_milliseconds)
937
dbus.UInt16, "ApprovalDuration",
938
type_func = _timedelta_to_milliseconds)
1108
939
host = notifychangeproperty(dbus.String, "Host")
1109
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
940
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1111
timedelta_to_milliseconds)
942
_timedelta_to_milliseconds)
1112
943
extended_timeout = notifychangeproperty(
1113
dbus.UInt64, "ExtendedTimeout",
1114
type_func = timedelta_to_milliseconds)
1115
interval = notifychangeproperty(dbus.UInt64,
944
dbus.UInt16, "ExtendedTimeout",
945
type_func = _timedelta_to_milliseconds)
946
interval = notifychangeproperty(dbus.UInt16,
1118
timedelta_to_milliseconds)
949
_timedelta_to_milliseconds)
1119
950
checker_command = notifychangeproperty(dbus.String, "Checker")
1121
952
del notifychangeproperty
2200
2030
client_class = functools.partial(ClientDBusTransitional,
2203
client_settings = Client.config_parser(client_config)
2204
old_client_settings = {}
2207
# Get client data and settings from last running state.
2208
if server_settings["restore"]:
2210
with open(stored_state_path, "rb") as stored_state:
2211
clients_data, old_client_settings = (pickle.load
2213
os.remove(stored_state_path)
2214
except IOError as e:
2215
logger.warning("Could not load persistent state: {0}"
2217
if e.errno != errno.ENOENT:
2219
except EOFError as e:
2220
logger.warning("Could not load persistent state: "
2221
"EOFError: {0}".format(e))
2223
with PGPEngine() as pgp:
2224
for client_name, client in clients_data.iteritems():
2225
# Decide which value to use after restoring saved state.
2226
# We have three different values: Old config file,
2227
# new config file, and saved state.
2228
# New config value takes precedence if it differs from old
2229
# config value, otherwise use saved state.
2230
for name, value in client_settings[client_name].items():
2232
# For each value in new config, check if it
2233
# differs from the old config value (Except for
2234
# the "secret" attribute)
2235
if (name != "secret" and
2236
value != old_client_settings[client_name]
2238
client[name] = value
2242
# Clients who has passed its expire date can still be
2243
# enabled if its last checker was successful. Clients
2244
# whose checker failed before we stored its state is
2245
# assumed to have failed all checkers during downtime.
2246
if client["enabled"]:
2247
if datetime.datetime.utcnow() >= client["expires"]:
2248
if not client["last_checked_ok"]:
2250
"disabling client {0} - Client never "
2251
"performed a successfull checker"
2252
.format(client["name"]))
2253
client["enabled"] = False
2254
elif client["last_checker_status"] != 0:
2256
"disabling client {0} - Client "
2257
"last checker failed with error code {1}"
2258
.format(client["name"],
2259
client["last_checker_status"]))
2260
client["enabled"] = False
2262
client["expires"] = (datetime.datetime
2264
+ client["timeout"])
2032
def client_config_items(config, section):
2033
special_settings = {
2034
"approved_by_default":
2035
lambda: config.getboolean(section,
2036
"approved_by_default"),
2038
for name, value in config.items(section):
2267
client["secret"] = (
2268
pgp.decrypt(client["encrypted_secret"],
2269
client_settings[client_name]
2272
# If decryption fails, we use secret from new settings
2273
logger.debug("Failed to decrypt {0} old secret"
2274
.format(client_name))
2275
client["secret"] = (
2276
client_settings[client_name]["secret"])
2279
# Add/remove clients based on new changes made to config
2280
for client_name in set(old_client_settings) - set(client_settings):
2281
del clients_data[client_name]
2282
for client_name in set(client_settings) - set(old_client_settings):
2283
clients_data[client_name] = client_settings[client_name]
2285
# Create clients all clients
2286
for client_name, client in clients_data.iteritems():
2287
tcp_server.clients[client_name] = client_class(
2288
name = client_name, settings = client)
2040
yield (name, special_settings[name]())
2044
tcp_server.clients.update(set(
2045
client_class(name = section,
2046
config= dict(client_config_items(
2047
client_config, section)))
2048
for section in client_config.sections()))
2290
2049
if not tcp_server.clients:
2291
2050
logger.warning("No clients defined")
2370
2129
"Cleanup function; run on exit"
2371
2130
service.cleanup()
2373
multiprocessing.active_children()
2374
if not (tcp_server.clients or client_settings):
2377
# Store client before exiting. Secrets are encrypted with key
2378
# based on what config file has. If config file is
2379
# removed/edited, old secret will thus be unrecovable.
2381
with PGPEngine() as pgp:
2382
for client in tcp_server.clients.itervalues():
2383
key = client_settings[client.name]["secret"]
2384
client.encrypted_secret = pgp.encrypt(client.secret,
2388
# A list of attributes that can not be pickled
2390
exclude = set(("bus", "changedstate", "secret",
2392
for name, typ in (inspect.getmembers
2393
(dbus.service.Object)):
2396
client_dict["encrypted_secret"] = (client
2398
for attr in client.client_structure:
2399
if attr not in exclude:
2400
client_dict[attr] = getattr(client, attr)
2402
clients[client.name] = client_dict
2403
del client_settings[client.name]["secret"]
2406
tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2409
(stored_state_path))
2410
with os.fdopen(tempfd, "wb") as stored_state:
2411
pickle.dump((clients, client_settings), stored_state)
2412
os.rename(tempname, stored_state_path)
2413
except (IOError, OSError) as e:
2414
logger.warning("Could not save persistent state: {0}"
2421
if e.errno not in set((errno.ENOENT, errno.EACCES,
2425
# Delete all clients, and settings from config
2426
2132
while tcp_server.clients:
2427
name, client = tcp_server.clients.popitem()
2133
client = tcp_server.clients.pop()
2429
2135
client.remove_from_connection()
2136
client.disable_hook = None
2430
2137
# Don't signal anything except ClientRemoved
2431
2138
client.disable(quiet=True)