82
85
except ImportError:
83
86
SO_BINDTODEVICE = None
89
stored_state_file = "clients.pickle"
88
#logger = logging.getLogger('mandos')
89
logger = logging.Logger('mandos')
91
logger = logging.getLogger()
90
92
syslogger = (logging.handlers.SysLogHandler
91
93
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
92
94
address = str("/dev/log")))
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)
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
104
211
class AvahiError(Exception):
105
212
def __init__(self, value, *args, **kwargs):
315
431
"created", "enabled", "fingerprint",
316
432
"host", "interval", "last_checked_ok",
317
433
"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",
319
445
def timeout_milliseconds(self):
320
446
"Return the 'timeout' attribute in milliseconds"
321
return _timedelta_to_milliseconds(self.timeout)
447
return timedelta_to_milliseconds(self.timeout)
323
449
def extended_timeout_milliseconds(self):
324
450
"Return the 'extended_timeout' attribute in milliseconds"
325
return _timedelta_to_milliseconds(self.extended_timeout)
451
return timedelta_to_milliseconds(self.extended_timeout)
327
453
def interval_milliseconds(self):
328
454
"Return the 'interval' attribute in milliseconds"
329
return _timedelta_to_milliseconds(self.interval)
455
return timedelta_to_milliseconds(self.interval)
331
457
def approval_delay_milliseconds(self):
332
return _timedelta_to_milliseconds(self.approval_delay)
334
def __init__(self, name = None, disable_hook=None, config=None):
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):
335
512
"""Note: the 'checker' key in 'config' sets the
336
513
'checker_command' attribute and *not* the 'checker'
516
# adding all client settings
517
for setting, value in settings.iteritems():
518
setattr(self, setting, value)
341
520
logger.debug("Creating client %r", self.name)
342
521
# Uppercase and remove spaces from fingerprint for later
343
522
# comparison purposes with return value from the fingerprint()
345
self.fingerprint = (config["fingerprint"].upper()
347
524
logger.debug(" Fingerprint: %s", self.fingerprint)
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
525
self.created = settings.get("created", datetime.datetime.utcnow())
527
# attributes specific for this server instance
369
528
self.checker = None
370
529
self.checker_initiator_tag = None
371
530
self.disable_initiator_tag = None
373
531
self.checker_callback_tag = None
374
self.checker_command = config["checker"]
375
532
self.current_checker_command = None
376
self.last_connect = None
377
self._approved = None
378
self.approved_by_default = config.get("approved_by_default",
380
534
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"])
385
535
self.changedstate = (multiprocessing_manager
386
536
.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
389
551
def send_changedstate(self):
390
self.changedstate.acquire()
391
self.changedstate.notify_all()
392
self.changedstate.release()
552
with self.changedstate:
553
self.changedstate.notify_all()
394
555
def enable(self):
395
556
"""Start this client's checker and timeout hooks"""
428
579
gobject.source_remove(self.checker_initiator_tag)
429
580
self.checker_initiator_tag = None
430
581
self.stop_checker()
431
if self.disable_hook:
432
self.disable_hook(self)
433
582
self.enabled = False
434
583
# Do not run this again if called by a gobject.timeout_add
437
586
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*.
441
602
def checker_callback(self, pid, condition, command):
442
603
"""The checker has completed, so take appropriate actions."""
443
604
self.checker_callback_tag = None
444
605
self.checker = None
445
606
if os.WIFEXITED(condition):
446
exitstatus = os.WEXITSTATUS(condition)
607
self.last_checker_status = os.WEXITSTATUS(condition)
608
if self.last_checker_status == 0:
448
609
logger.info("Checker for %(name)s succeeded",
450
611
self.checked_ok()
932
1098
datetime_to_dbus, "LastApprovalRequest")
933
1099
approved_by_default = notifychangeproperty(dbus.Boolean,
934
1100
"ApprovedByDefault")
935
approval_delay = notifychangeproperty(dbus.UInt16,
1101
approval_delay = notifychangeproperty(dbus.UInt64,
936
1102
"ApprovalDelay",
938
_timedelta_to_milliseconds)
1104
timedelta_to_milliseconds)
939
1105
approval_duration = notifychangeproperty(
940
dbus.UInt16, "ApprovalDuration",
941
type_func = _timedelta_to_milliseconds)
1106
dbus.UInt64, "ApprovalDuration",
1107
type_func = timedelta_to_milliseconds)
942
1108
host = notifychangeproperty(dbus.String, "Host")
943
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1109
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
945
_timedelta_to_milliseconds)
1111
timedelta_to_milliseconds)
946
1112
extended_timeout = notifychangeproperty(
947
dbus.UInt16, "ExtendedTimeout",
948
type_func = _timedelta_to_milliseconds)
949
interval = notifychangeproperty(dbus.UInt16,
1113
dbus.UInt64, "ExtendedTimeout",
1114
type_func = timedelta_to_milliseconds)
1115
interval = notifychangeproperty(dbus.UInt64,
952
_timedelta_to_milliseconds)
1118
timedelta_to_milliseconds)
953
1119
checker_command = notifychangeproperty(dbus.String, "Checker")
955
1121
del notifychangeproperty
2039
2200
client_class = functools.partial(ClientDBusTransitional,
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):
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"])
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()))
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)
2058
2290
if not tcp_server.clients:
2059
2291
logger.warning("No clients defined")
2139
2371
service.cleanup()
2141
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
2142
2426
while tcp_server.clients:
2143
client = tcp_server.clients.pop()
2427
name, client = tcp_server.clients.popitem()
2145
2429
client.remove_from_connection()
2146
client.disable_hook = None
2147
2430
# Don't signal anything except ClientRemoved
2148
2431
client.disable(quiet=True)