85
84
except ImportError:
86
85
SO_BINDTODEVICE = None
89
stored_state_file = "clients.pickle"
91
90
logger = logging.getLogger()
91
stored_state_path = "/var/lib/mandos/clients.pickle"
92
93
syslogger = (logging.handlers.SysLogHandler
93
94
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
94
95
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
96
syslogger.setFormatter(logging.Formatter
97
('Mandos [%(process)d]: %(levelname)s:'
99
logger.addHandler(syslogger)
101
console = logging.StreamHandler()
102
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
106
logger.addHandler(console)
211
109
class AvahiError(Exception):
431
329
"created", "enabled", "fingerprint",
432
330
"host", "interval", "last_checked_ok",
433
331
"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
333
def timeout_milliseconds(self):
446
334
"Return the 'timeout' attribute in milliseconds"
447
return timedelta_to_milliseconds(self.timeout)
335
return _timedelta_to_milliseconds(self.timeout)
449
337
def extended_timeout_milliseconds(self):
450
338
"Return the 'extended_timeout' attribute in milliseconds"
451
return timedelta_to_milliseconds(self.extended_timeout)
339
return _timedelta_to_milliseconds(self.extended_timeout)
453
341
def interval_milliseconds(self):
454
342
"Return the 'interval' attribute in milliseconds"
455
return timedelta_to_milliseconds(self.interval)
343
return _timedelta_to_milliseconds(self.interval)
457
345
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):
346
return _timedelta_to_milliseconds(self.approval_delay)
348
def __init__(self, name = None, config=None):
512
349
"""Note: the 'checker' key in 'config' sets the
513
350
'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
355
logger.debug("Creating client %r", self.name)
521
356
# Uppercase and remove spaces from fingerprint for later
522
357
# comparison purposes with return value from the fingerprint()
359
self.fingerprint = (config["fingerprint"].upper()
524
361
logger.debug(" Fingerprint: %s", self.fingerprint)
525
self.created = settings.get("created", datetime.datetime.utcnow())
527
# attributes specific for this server instance
362
if "secret" in config:
363
self.secret = config["secret"].decode("base64")
364
elif "secfile" in config:
365
with open(os.path.expanduser(os.path.expandvars
366
(config["secfile"])),
368
self.secret = secfile.read()
370
raise TypeError("No secret or secfile for client %s"
372
self.host = config.get("host", "")
373
self.created = datetime.datetime.utcnow()
375
self.last_approval_request = None
376
self.last_enabled = datetime.datetime.utcnow()
377
self.last_checked_ok = None
378
self.last_checker_status = None
379
self.timeout = string_to_delta(config["timeout"])
380
self.extended_timeout = string_to_delta(config
381
["extended_timeout"])
382
self.interval = string_to_delta(config["interval"])
528
383
self.checker = None
529
384
self.checker_initiator_tag = None
530
385
self.disable_initiator_tag = None
386
self.expires = datetime.datetime.utcnow() + self.timeout
531
387
self.checker_callback_tag = None
388
self.checker_command = config["checker"]
532
389
self.current_checker_command = None
390
self._approved = None
391
self.approved_by_default = config.get("approved_by_default",
534
393
self.approvals_pending = 0
394
self.approval_delay = string_to_delta(
395
config["approval_delay"])
396
self.approval_duration = string_to_delta(
397
config["approval_duration"])
535
398
self.changedstate = (multiprocessing_manager
536
399
.Condition(multiprocessing_manager
538
self.client_structure = [attr for attr in
539
self.__dict__.iterkeys()
540
if not attr.startswith("_")]
401
self.client_structure = [attr for attr in self.__dict__.iterkeys() if not attr.startswith("_")]
541
402
self.client_structure.append("client_structure")
543
405
for name, t in inspect.getmembers(type(self),
406
lambda obj: isinstance(obj, property)):
547
407
if not name.startswith("_"):
548
408
self.client_structure.append(name)
731
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
734
641
def dbus_service_property(dbus_interface, signature="v",
735
642
access="readwrite", byte_arrays=False):
1098
1002
datetime_to_dbus, "LastApprovalRequest")
1099
1003
approved_by_default = notifychangeproperty(dbus.Boolean,
1100
1004
"ApprovedByDefault")
1101
approval_delay = notifychangeproperty(dbus.UInt64,
1005
approval_delay = notifychangeproperty(dbus.UInt16,
1102
1006
"ApprovalDelay",
1104
timedelta_to_milliseconds)
1008
_timedelta_to_milliseconds)
1105
1009
approval_duration = notifychangeproperty(
1106
dbus.UInt64, "ApprovalDuration",
1107
type_func = timedelta_to_milliseconds)
1010
dbus.UInt16, "ApprovalDuration",
1011
type_func = _timedelta_to_milliseconds)
1108
1012
host = notifychangeproperty(dbus.String, "Host")
1109
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1013
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1111
timedelta_to_milliseconds)
1015
_timedelta_to_milliseconds)
1112
1016
extended_timeout = notifychangeproperty(
1113
dbus.UInt64, "ExtendedTimeout",
1114
type_func = timedelta_to_milliseconds)
1115
interval = notifychangeproperty(dbus.UInt64,
1017
dbus.UInt16, "ExtendedTimeout",
1018
type_func = _timedelta_to_milliseconds)
1019
interval = notifychangeproperty(dbus.UInt16,
1118
timedelta_to_milliseconds)
1022
_timedelta_to_milliseconds)
1119
1023
checker_command = notifychangeproperty(dbus.String, "Checker")
1121
1025
del notifychangeproperty
2200
2124
client_class = functools.partial(ClientDBusTransitional,
2203
client_settings = Client.config_parser(client_config)
2127
special_settings = {
2128
# Some settings need to be accessd by special methods;
2129
# booleans need .getboolean(), etc. Here is a list of them:
2130
"approved_by_default":
2132
client_config.getboolean(section, "approved_by_default"),
2134
# Construct a new dict of client settings of this form:
2135
# { client_name: {setting_name: value, ...}, ...}
2136
# with exceptions for any special settings as defined above
2137
client_settings = dict((clientname,
2139
(value if setting not in special_settings
2140
else special_settings[setting](clientname)))
2141
for setting, value in client_config.items(clientname)))
2142
for clientname in client_config.sections())
2204
2144
old_client_settings = {}
2207
# Get client data and settings from last running state.
2147
# Get client data and settings from last running state.
2208
2148
if server_settings["restore"]:
2210
2150
with open(stored_state_path, "rb") as stored_state:
2211
clients_data, old_client_settings = (pickle.load
2151
clients_data, old_client_settings = pickle.load(stored_state)
2213
2152
os.remove(stored_state_path)
2214
2153
except IOError as e:
2215
logger.warning("Could not load persistent state: {0}"
2154
logger.warning("Could not load persistant state: {0}".format(e))
2217
2155
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"])
2158
for client in clients_data:
2159
client_name = client["name"]
2161
# Decide which value to use after restoring saved state.
2162
# We have three different values: Old config file,
2163
# new config file, and saved state.
2164
# New config value takes precedence if it differs from old
2165
# config value, otherwise use saved state.
2166
for name, value in client_settings[client_name].items():
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)
2168
# For each value in new config, check if it differs
2169
# from the old config value (Except for the "secret"
2171
if name != "secret" and value != old_client_settings[client_name][name]:
2172
setattr(client, name, value)
2176
# Clients who has passed its expire date, can still be enabled if its
2177
# last checker was sucessful. Clients who checkers failed before we
2178
# stored it state is asumed to had failed checker during downtime.
2179
if client["enabled"] and client["last_checked_ok"]:
2180
if ((datetime.datetime.utcnow() - client["last_checked_ok"])
2181
> client["interval"]):
2182
if client["last_checker_status"] != 0:
2183
client["enabled"] = False
2185
client["expires"] = datetime.datetime.utcnow() + client["timeout"]
2187
client["changedstate"] = (multiprocessing_manager
2188
.Condition(multiprocessing_manager
2191
new_client = ClientDBusTransitional.__new__(ClientDBusTransitional)
2192
tcp_server.clients[client_name] = new_client
2193
new_client.bus = bus
2194
for name, value in client.iteritems():
2195
setattr(new_client, name, value)
2196
client_object_name = unicode(client_name).translate(
2197
{ord("."): ord("_"),
2198
ord("-"): ord("_")})
2199
new_client.dbus_object_path = (dbus.ObjectPath
2200
("/clients/" + client_object_name))
2201
DBusObjectWithProperties.__init__(new_client,
2203
new_client.dbus_object_path)
2205
tcp_server.clients[client_name] = Client.__new__(Client)
2206
for name, value in client.iteritems():
2207
setattr(tcp_server.clients[client_name], name, value)
2209
tcp_server.clients[client_name].decrypt_secret(
2210
client_settings[client_name]["secret"])
2212
# Create/remove clients based on new changes made to config
2213
for clientname in set(old_client_settings) - set(client_settings):
2214
del tcp_server.clients[clientname]
2215
for clientname in set(client_settings) - set(old_client_settings):
2216
tcp_server.clients[clientname] = (client_class(name = clientname,
2290
2222
if not tcp_server.clients:
2291
2223
logger.warning("No clients defined")
2373
2306
multiprocessing.active_children()
2374
2307
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"]
2310
# Store client before exiting. Secrets are encrypted with key based
2311
# on what config file has. If config file is removed/edited, old
2312
# secret will thus be unrecovable.
2314
for client in tcp_server.clients.itervalues():
2315
client.encrypt_secret(client_settings[client.name]["secret"])
2319
# A list of attributes that will not be stored when shuting down.
2320
exclude = set(("bus", "changedstate", "secret"))
2321
for name, typ in inspect.getmembers(dbus.service.Object):
2324
client_dict["encrypted_secret"] = client.encrypted_secret
2325
for attr in client.client_structure:
2326
if attr not in exclude:
2327
client_dict[attr] = getattr(client, attr)
2329
clients.append(client_dict)
2330
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:
2333
with os.fdopen(os.open(stored_state_path, os.O_CREAT|os.O_WRONLY|os.O_TRUNC, 0600), "wb") as stored_state:
2411
2334
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,
2335
except IOError as e:
2336
logger.warning("Could not save persistant state: {0}".format(e))
2337
if e.errno != errno.ENOENT:
2425
2340
# Delete all clients, and settings from config
2426
2341
while tcp_server.clients:
2427
2342
name, client = tcp_server.clients.popitem()