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(level=logging.WARNING):
114
"""init logger and add loglevel"""
116
syslogger.setFormatter(logging.Formatter
117
('Mandos [%(process)d]: %(levelname)s:'
119
logger.addHandler(syslogger)
121
console = logging.StreamHandler()
122
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
126
logger.addHandler(console)
127
logger.setLevel(level)
130
class PGPError(Exception):
131
"""Exception if encryption/decryption fails"""
135
class PGPEngine(object):
136
"""A simple class for OpenPGP symmetric encryption & decryption"""
138
self.gnupg = GnuPGInterface.GnuPG()
139
self.tempdir = tempfile.mkdtemp(prefix="mandos-")
140
self.gnupg = GnuPGInterface.GnuPG()
141
self.gnupg.options.meta_interactive = False
142
self.gnupg.options.homedir = self.tempdir
143
self.gnupg.options.extra_args.extend(['--force-mdc',
149
def __exit__ (self, exc_type, exc_value, traceback):
157
if self.tempdir is not None:
158
# Delete contents of tempdir
159
for root, dirs, files in os.walk(self.tempdir,
161
for filename in files:
162
os.remove(os.path.join(root, filename))
164
os.rmdir(os.path.join(root, dirname))
166
os.rmdir(self.tempdir)
169
def password_encode(self, password):
170
# Passphrase can not be empty and can not contain newlines or
171
# NUL bytes. So we prefix it and hex encode it.
172
return b"mandos" + binascii.hexlify(password)
174
def encrypt(self, data, password):
175
self.gnupg.passphrase = self.password_encode(password)
176
with open(os.devnull) as devnull:
178
proc = self.gnupg.run(['--symmetric'],
179
create_fhs=['stdin', 'stdout'],
180
attach_fhs={'stderr': devnull})
181
with contextlib.closing(proc.handles['stdin']) as f:
183
with contextlib.closing(proc.handles['stdout']) as f:
184
ciphertext = f.read()
188
self.gnupg.passphrase = None
191
def decrypt(self, data, password):
192
self.gnupg.passphrase = self.password_encode(password)
193
with open(os.devnull) as devnull:
195
proc = self.gnupg.run(['--decrypt'],
196
create_fhs=['stdin', 'stdout'],
197
attach_fhs={'stderr': devnull})
198
with contextlib.closing(proc.handles['stdin'] ) as f:
200
with contextlib.closing(proc.handles['stdout']) as f:
201
decrypted_plaintext = f.read()
205
self.gnupg.passphrase = None
206
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)
210
109
class AvahiError(Exception):
430
329
"created", "enabled", "fingerprint",
431
330
"host", "interval", "last_checked_ok",
432
331
"last_enabled", "name", "timeout")
433
client_defaults = { "timeout": "5m",
434
"extended_timeout": "15m",
436
"checker": "fping -q -- %%(host)s",
438
"approval_delay": "0s",
439
"approval_duration": "1s",
440
"approved_by_default": "True",
444
333
def timeout_milliseconds(self):
445
334
"Return the 'timeout' attribute in milliseconds"
446
return timedelta_to_milliseconds(self.timeout)
335
return _timedelta_to_milliseconds(self.timeout)
448
337
def extended_timeout_milliseconds(self):
449
338
"Return the 'extended_timeout' attribute in milliseconds"
450
return timedelta_to_milliseconds(self.extended_timeout)
339
return _timedelta_to_milliseconds(self.extended_timeout)
452
341
def interval_milliseconds(self):
453
342
"Return the 'interval' attribute in milliseconds"
454
return timedelta_to_milliseconds(self.interval)
343
return _timedelta_to_milliseconds(self.interval)
456
345
def approval_delay_milliseconds(self):
457
return timedelta_to_milliseconds(self.approval_delay)
460
def config_parser(config):
461
""" Construct a new dict of client settings of this form:
462
{ client_name: {setting_name: value, ...}, ...}
463
with exceptions for any special settings as defined above"""
465
for client_name in config.sections():
466
section = dict(config.items(client_name))
467
client = settings[client_name] = {}
469
client["host"] = section["host"]
470
# Reformat values from string types to Python types
471
client["approved_by_default"] = config.getboolean(
472
client_name, "approved_by_default")
473
client["enabled"] = config.getboolean(client_name, "enabled")
475
client["fingerprint"] = (section["fingerprint"].upper()
477
if "secret" in section:
478
client["secret"] = section["secret"].decode("base64")
479
elif "secfile" in section:
480
with open(os.path.expanduser(os.path.expandvars
481
(section["secfile"])),
483
client["secret"] = secfile.read()
485
raise TypeError("No secret or secfile for section %s"
487
client["timeout"] = string_to_delta(section["timeout"])
488
client["extended_timeout"] = string_to_delta(
489
section["extended_timeout"])
490
client["interval"] = string_to_delta(section["interval"])
491
client["approval_delay"] = string_to_delta(
492
section["approval_delay"])
493
client["approval_duration"] = string_to_delta(
494
section["approval_duration"])
495
client["checker_command"] = section["checker"]
496
client["last_approval_request"] = None
497
client["last_checked_ok"] = None
498
client["last_checker_status"] = None
499
if client["enabled"]:
500
client["last_enabled"] = datetime.datetime.utcnow()
501
client["expires"] = (datetime.datetime.utcnow()
504
client["last_enabled"] = None
505
client["expires"] = None
510
def __init__(self, settings, name = None):
346
return _timedelta_to_milliseconds(self.approval_delay)
348
def __init__(self, name = None, config=None):
511
349
"""Note: the 'checker' key in 'config' sets the
512
350
'checker_command' attribute and *not* the 'checker'
515
# adding all client settings
516
for setting, value in settings.iteritems():
517
setattr(self, setting, value)
519
355
logger.debug("Creating client %r", self.name)
520
356
# Uppercase and remove spaces from fingerprint for later
521
357
# comparison purposes with return value from the fingerprint()
359
self.fingerprint = (config["fingerprint"].upper()
523
361
logger.debug(" Fingerprint: %s", self.fingerprint)
524
self.created = settings.get("created", datetime.datetime.utcnow())
526
# 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"])
527
383
self.checker = None
528
384
self.checker_initiator_tag = None
529
385
self.disable_initiator_tag = None
386
self.expires = datetime.datetime.utcnow() + self.timeout
530
387
self.checker_callback_tag = None
388
self.checker_command = config["checker"]
531
389
self.current_checker_command = None
390
self._approved = None
391
self.approved_by_default = config.get("approved_by_default",
533
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"])
534
398
self.changedstate = (multiprocessing_manager
535
399
.Condition(multiprocessing_manager
537
self.client_structure = [attr for attr in
538
self.__dict__.iterkeys()
539
if not attr.startswith("_")]
401
self.client_structure = [attr for attr in self.__dict__.iterkeys() if not attr.startswith("_")]
540
402
self.client_structure.append("client_structure")
542
405
for name, t in inspect.getmembers(type(self),
406
lambda obj: isinstance(obj, property)):
546
407
if not name.startswith("_"):
547
408
self.client_structure.append(name)
730
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
733
641
def dbus_service_property(dbus_interface, signature="v",
734
642
access="readwrite", byte_arrays=False):
1097
1002
datetime_to_dbus, "LastApprovalRequest")
1098
1003
approved_by_default = notifychangeproperty(dbus.Boolean,
1099
1004
"ApprovedByDefault")
1100
approval_delay = notifychangeproperty(dbus.UInt64,
1005
approval_delay = notifychangeproperty(dbus.UInt16,
1101
1006
"ApprovalDelay",
1103
timedelta_to_milliseconds)
1008
_timedelta_to_milliseconds)
1104
1009
approval_duration = notifychangeproperty(
1105
dbus.UInt64, "ApprovalDuration",
1106
type_func = timedelta_to_milliseconds)
1010
dbus.UInt16, "ApprovalDuration",
1011
type_func = _timedelta_to_milliseconds)
1107
1012
host = notifychangeproperty(dbus.String, "Host")
1108
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1013
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1110
timedelta_to_milliseconds)
1015
_timedelta_to_milliseconds)
1111
1016
extended_timeout = notifychangeproperty(
1112
dbus.UInt64, "ExtendedTimeout",
1113
type_func = timedelta_to_milliseconds)
1114
interval = notifychangeproperty(dbus.UInt64,
1017
dbus.UInt16, "ExtendedTimeout",
1018
type_func = _timedelta_to_milliseconds)
1019
interval = notifychangeproperty(dbus.UInt16,
1117
timedelta_to_milliseconds)
1022
_timedelta_to_milliseconds)
1118
1023
checker_command = notifychangeproperty(dbus.String, "Checker")
1120
1025
del notifychangeproperty
2202
2113
client_class = functools.partial(ClientDBusTransitional,
2205
client_settings = Client.config_parser(client_config)
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())
2206
2133
old_client_settings = {}
2209
# Get client data and settings from last running state.
2136
# Get client data and settings from last running state.
2210
2137
if server_settings["restore"]:
2212
2139
with open(stored_state_path, "rb") as stored_state:
2213
clients_data, old_client_settings = (pickle.load
2140
clients_data, old_client_settings = pickle.load(stored_state)
2215
2141
os.remove(stored_state_path)
2216
2142
except IOError as e:
2217
logger.warning("Could not load persistent state: {0}"
2143
logger.warning("Could not load persistant state: {0}".format(e))
2219
2144
if e.errno != errno.ENOENT:
2221
except EOFError as e:
2222
logger.warning("Could not load persistent state: "
2223
"EOFError: {0}".format(e))
2225
with PGPEngine() as pgp:
2226
for client_name, client in clients_data.iteritems():
2227
# Decide which value to use after restoring saved state.
2228
# We have three different values: Old config file,
2229
# new config file, and saved state.
2230
# New config value takes precedence if it differs from old
2231
# config value, otherwise use saved state.
2232
for name, value in client_settings[client_name].items():
2234
# For each value in new config, check if it
2235
# differs from the old config value (Except for
2236
# the "secret" attribute)
2237
if (name != "secret" and
2238
value != old_client_settings[client_name]
2240
client[name] = value
2244
# Clients who has passed its expire date can still be
2245
# enabled if its last checker was successful. Clients
2246
# whose checker failed before we stored its state is
2247
# assumed to have failed all checkers during downtime.
2248
if client["enabled"]:
2249
if datetime.datetime.utcnow() >= client["expires"]:
2250
if not client["last_checked_ok"]:
2252
"disabling client {0} - Client never "
2253
"performed a successfull checker"
2254
.format(client["name"]))
2255
client["enabled"] = False
2256
elif client["last_checker_status"] != 0:
2258
"disabling client {0} - Client "
2259
"last checker failed with error code {1}"
2260
.format(client["name"],
2261
client["last_checker_status"]))
2262
client["enabled"] = False
2264
client["expires"] = (datetime.datetime
2266
+ client["timeout"])
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():
2269
client["secret"] = (
2270
pgp.decrypt(client["encrypted_secret"],
2271
client_settings[client_name]
2274
# If decryption fails, we use secret from new settings
2275
logger.debug("Failed to decrypt {0} old secret"
2276
.format(client_name))
2277
client["secret"] = (
2278
client_settings[client_name]["secret"])
2281
# Add/remove clients based on new changes made to config
2282
for client_name in set(old_client_settings) - set(client_settings):
2283
del clients_data[client_name]
2284
for client_name in set(client_settings) - set(old_client_settings):
2285
clients_data[client_name] = client_settings[client_name]
2287
# Create clients all clients
2288
for client_name, client in clients_data.iteritems():
2289
tcp_server.clients[client_name] = client_class(
2290
name = client_name, settings = client)
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)
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,
2292
2211
if not tcp_server.clients:
2293
2212
logger.warning("No clients defined")
2375
2295
multiprocessing.active_children()
2376
2296
if not (tcp_server.clients or client_settings):
2379
# Store client before exiting. Secrets are encrypted with key
2380
# based on what config file has. If config file is
2381
# removed/edited, old secret will thus be unrecovable.
2383
with PGPEngine() as pgp:
2384
for client in tcp_server.clients.itervalues():
2385
key = client_settings[client.name]["secret"]
2386
client.encrypted_secret = pgp.encrypt(client.secret,
2390
# A list of attributes that can not be pickled
2392
exclude = set(("bus", "changedstate", "secret",
2394
for name, typ in (inspect.getmembers
2395
(dbus.service.Object)):
2398
client_dict["encrypted_secret"] = (client
2400
for attr in client.client_structure:
2401
if attr not in exclude:
2402
client_dict[attr] = getattr(client, attr)
2404
clients[client.name] = client_dict
2405
del client_settings[client.name]["secret"]
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"]
2408
tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2411
(stored_state_path))
2412
with os.fdopen(tempfd, "wb") as stored_state:
2322
with os.fdopen(os.open(stored_state_path, os.O_CREAT|os.O_WRONLY|os.O_TRUNC, 0600), "wb") as stored_state:
2413
2323
pickle.dump((clients, client_settings), stored_state)
2414
os.rename(tempname, stored_state_path)
2415
except (IOError, OSError) as e:
2416
logger.warning("Could not save persistent state: {0}"
2418
if e.errno not in set((errno.ENOENT, errno.EACCES,
2324
except IOError as e:
2325
logger.warning("Could not save persistant state: {0}".format(e))
2326
if e.errno != errno.ENOENT:
2422
2329
# Delete all clients, and settings from config
2423
2330
while tcp_server.clients:
2424
2331
name, client = tcp_server.clients.popitem()