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',
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
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)
212
104
class AvahiError(Exception):
213
105
def __init__(self, value, *args, **kwargs):
432
315
"created", "enabled", "fingerprint",
433
316
"host", "interval", "last_checked_ok",
434
317
"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
319
def timeout_milliseconds(self):
447
320
"Return the 'timeout' attribute in milliseconds"
448
return timedelta_to_milliseconds(self.timeout)
321
return _timedelta_to_milliseconds(self.timeout)
450
323
def extended_timeout_milliseconds(self):
451
324
"Return the 'extended_timeout' attribute in milliseconds"
452
return timedelta_to_milliseconds(self.extended_timeout)
325
return _timedelta_to_milliseconds(self.extended_timeout)
454
327
def interval_milliseconds(self):
455
328
"Return the 'interval' attribute in milliseconds"
456
return timedelta_to_milliseconds(self.interval)
329
return _timedelta_to_milliseconds(self.interval)
458
331
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, "enabled")
480
client["fingerprint"] = (section["fingerprint"].upper()
482
if "secret" in section:
483
client["secret"] = section["secret"].decode("base64")
484
elif "secfile" in section:
485
with open(os.path.expanduser(os.path.expandvars
486
(section["secfile"])),
488
client["secret"] = secfile.read()
490
raise TypeError("No secret or secfile for section %s"
492
client["timeout"] = string_to_delta(section["timeout"])
493
client["extended_timeout"] = string_to_delta(
494
section["extended_timeout"])
495
client["interval"] = string_to_delta(section["interval"])
496
client["approval_delay"] = string_to_delta(
497
section["approval_delay"])
498
client["approval_duration"] = string_to_delta(
499
section["approval_duration"])
500
client["checker_command"] = section["checker"]
501
client["last_approval_request"] = None
502
client["last_checked_ok"] = None
503
client["last_checker_status"] = None
508
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):
509
335
"""Note: the 'checker' key in 'config' sets the
510
336
'checker_command' attribute and *not* the 'checker'
513
# adding all client settings
514
for setting, value in settings.iteritems():
515
setattr(self, setting, value)
518
if not hasattr(self, "last_enabled"):
519
self.last_enabled = datetime.datetime.utcnow()
520
if not hasattr(self, "expires"):
521
self.expires = (datetime.datetime.utcnow()
524
self.last_enabled = None
527
341
logger.debug("Creating client %r", self.name)
528
342
# Uppercase and remove spaces from fingerprint for later
529
343
# comparison purposes with return value from the fingerprint()
345
self.fingerprint = (config["fingerprint"].upper()
531
347
logger.debug(" Fingerprint: %s", self.fingerprint)
532
self.created = settings.get("created", datetime.datetime.utcnow())
534
# 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
535
369
self.checker = None
536
370
self.checker_initiator_tag = None
537
371
self.disable_initiator_tag = None
538
373
self.checker_callback_tag = None
374
self.checker_command = config["checker"]
539
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",
541
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"])
542
385
self.changedstate = (multiprocessing_manager
543
386
.Condition(multiprocessing_manager
545
self.client_structure = [attr for attr in
546
self.__dict__.iterkeys()
547
if not attr.startswith("_")]
548
self.client_structure.append("client_structure")
550
for name, t in inspect.getmembers(type(self),
554
if not name.startswith("_"):
555
self.client_structure.append(name)
557
# Send notice to process children that client state has changed
558
389
def send_changedstate(self):
559
with self.changedstate:
560
self.changedstate.notify_all()
390
self.changedstate.acquire()
391
self.changedstate.notify_all()
392
self.changedstate.release()
562
394
def enable(self):
563
395
"""Start this client's checker and timeout hooks"""
586
428
gobject.source_remove(self.checker_initiator_tag)
587
429
self.checker_initiator_tag = None
588
430
self.stop_checker()
431
if self.disable_hook:
432
self.disable_hook(self)
589
433
self.enabled = False
590
434
# Do not run this again if called by a gobject.timeout_add
593
437
def __del__(self):
438
self.disable_hook = None
596
def init_checker(self):
597
# Schedule a new checker to be started an 'interval' from now,
598
# and every interval from then on.
599
self.checker_initiator_tag = (gobject.timeout_add
600
(self.interval_milliseconds(),
602
# Schedule a disable() when 'timeout' has passed
603
self.disable_initiator_tag = (gobject.timeout_add
604
(self.timeout_milliseconds(),
606
# Also start a new checker *right now*.
609
441
def checker_callback(self, pid, condition, command):
610
442
"""The checker has completed, so take appropriate actions."""
611
443
self.checker_callback_tag = None
612
444
self.checker = None
613
445
if os.WIFEXITED(condition):
614
self.last_checker_status = os.WEXITSTATUS(condition)
615
if self.last_checker_status == 0:
446
exitstatus = os.WEXITSTATUS(condition)
616
448
logger.info("Checker for %(name)s succeeded",
618
450
self.checked_ok()
1105
932
datetime_to_dbus, "LastApprovalRequest")
1106
933
approved_by_default = notifychangeproperty(dbus.Boolean,
1107
934
"ApprovedByDefault")
1108
approval_delay = notifychangeproperty(dbus.UInt64,
935
approval_delay = notifychangeproperty(dbus.UInt16,
1109
936
"ApprovalDelay",
1111
timedelta_to_milliseconds)
938
_timedelta_to_milliseconds)
1112
939
approval_duration = notifychangeproperty(
1113
dbus.UInt64, "ApprovalDuration",
1114
type_func = timedelta_to_milliseconds)
940
dbus.UInt16, "ApprovalDuration",
941
type_func = _timedelta_to_milliseconds)
1115
942
host = notifychangeproperty(dbus.String, "Host")
1116
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
943
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1118
timedelta_to_milliseconds)
945
_timedelta_to_milliseconds)
1119
946
extended_timeout = notifychangeproperty(
1120
dbus.UInt64, "ExtendedTimeout",
1121
type_func = timedelta_to_milliseconds)
1122
interval = notifychangeproperty(dbus.UInt64,
947
dbus.UInt16, "ExtendedTimeout",
948
type_func = _timedelta_to_milliseconds)
949
interval = notifychangeproperty(dbus.UInt16,
1125
timedelta_to_milliseconds)
952
_timedelta_to_milliseconds)
1126
953
checker_command = notifychangeproperty(dbus.String, "Checker")
1128
955
del notifychangeproperty
2207
2039
client_class = functools.partial(ClientDBusTransitional,
2210
client_settings = Client.config_parser(client_config)
2211
old_client_settings = {}
2214
# Get client data and settings from last running state.
2215
if server_settings["restore"]:
2217
with open(stored_state_path, "rb") as stored_state:
2218
clients_data, old_client_settings = (pickle.load
2220
os.remove(stored_state_path)
2221
except IOError as e:
2222
logger.warning("Could not load persistent state: {0}"
2224
if e.errno != errno.ENOENT:
2226
except EOFError as e:
2227
logger.warning("Could not load persistent state: "
2228
"EOFError: {0}".format(e))
2230
with PGPEngine() as pgp:
2231
for client_name, client in clients_data.iteritems():
2232
# Decide which value to use after restoring saved state.
2233
# We have three different values: Old config file,
2234
# new config file, and saved state.
2235
# New config value takes precedence if it differs from old
2236
# config value, otherwise use saved state.
2237
for name, value in client_settings[client_name].items():
2239
# For each value in new config, check if it
2240
# differs from the old config value (Except for
2241
# the "secret" attribute)
2242
if (name != "secret" and
2243
value != old_client_settings[client_name]
2245
client[name] = value
2249
# Clients who has passed its expire date can still be
2250
# enabled if its last checker was successful. Clients
2251
# whose checker failed before we stored its state is
2252
# assumed to have failed all checkers during downtime.
2253
if client["enabled"]:
2254
if datetime.datetime.utcnow() >= client["expires"]:
2255
if not client["last_checked_ok"]:
2257
"disabling client {0} - Client never "
2258
"performed a successfull checker"
2259
.format(client["name"]))
2260
client["enabled"] = False
2261
elif client["last_checker_status"] != 0:
2263
"disabling client {0} - Client "
2264
"last checker failed with error code {1}"
2265
.format(client["name"],
2266
client["last_checker_status"]))
2267
client["enabled"] = False
2269
client["expires"] = (datetime.datetime
2271
+ client["timeout"])
2272
logger.debug("Last checker succeeded,"
2273
" keeping {0} enabled"
2274
.format(client["name"]))
2041
def client_config_items(config, section):
2042
special_settings = {
2043
"approved_by_default":
2044
lambda: config.getboolean(section,
2045
"approved_by_default"),
2047
for name, value in config.items(section):
2276
client["secret"] = (
2277
pgp.decrypt(client["encrypted_secret"],
2278
client_settings[client_name]
2281
# If decryption fails, we use secret from new settings
2282
logger.debug("Failed to decrypt {0} old secret"
2283
.format(client_name))
2284
client["secret"] = (
2285
client_settings[client_name]["secret"])
2288
# Add/remove clients based on new changes made to config
2289
for client_name in set(old_client_settings) - set(client_settings):
2290
del clients_data[client_name]
2291
for client_name in set(client_settings) - set(old_client_settings):
2292
clients_data[client_name] = client_settings[client_name]
2294
# Create clients all clients
2295
for client_name, client in clients_data.iteritems():
2296
tcp_server.clients[client_name] = client_class(
2297
name = client_name, settings = client)
2049
yield (name, special_settings[name]())
2053
tcp_server.clients.update(set(
2054
client_class(name = section,
2055
config= dict(client_config_items(
2056
client_config, section)))
2057
for section in client_config.sections()))
2299
2058
if not tcp_server.clients:
2300
2059
logger.warning("No clients defined")
2380
2139
service.cleanup()
2382
2141
multiprocessing.active_children()
2383
if not (tcp_server.clients or client_settings):
2386
# Store client before exiting. Secrets are encrypted with key
2387
# based on what config file has. If config file is
2388
# removed/edited, old secret will thus be unrecovable.
2390
with PGPEngine() as pgp:
2391
for client in tcp_server.clients.itervalues():
2392
key = client_settings[client.name]["secret"]
2393
client.encrypted_secret = pgp.encrypt(client.secret,
2397
# A list of attributes that can not be pickled
2399
exclude = set(("bus", "changedstate", "secret",
2401
for name, typ in (inspect.getmembers
2402
(dbus.service.Object)):
2405
client_dict["encrypted_secret"] = (client
2407
for attr in client.client_structure:
2408
if attr not in exclude:
2409
client_dict[attr] = getattr(client, attr)
2411
clients[client.name] = client_dict
2412
del client_settings[client.name]["secret"]
2415
tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2418
(stored_state_path))
2419
with os.fdopen(tempfd, "wb") as stored_state:
2420
pickle.dump((clients, client_settings), stored_state)
2421
os.rename(tempname, stored_state_path)
2422
except (IOError, OSError) as e:
2423
logger.warning("Could not save persistent state: {0}"
2430
if e.errno not in set((errno.ENOENT, errno.EACCES,
2434
# Delete all clients, and settings from config
2435
2142
while tcp_server.clients:
2436
name, client = tcp_server.clients.popitem()
2143
client = tcp_server.clients.pop()
2438
2145
client.remove_from_connection()
2146
client.disable_hook = None
2439
2147
# Don't signal anything except ClientRemoved
2440
2148
client.disable(quiet=True)