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(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
104
210
class AvahiError(Exception):
105
211
def __init__(self, value, *args, **kwargs):
315
430
"created", "enabled", "fingerprint",
316
431
"host", "interval", "last_checked_ok",
317
432
"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",
319
444
def timeout_milliseconds(self):
320
445
"Return the 'timeout' attribute in milliseconds"
321
return _timedelta_to_milliseconds(self.timeout)
446
return timedelta_to_milliseconds(self.timeout)
323
448
def extended_timeout_milliseconds(self):
324
449
"Return the 'extended_timeout' attribute in milliseconds"
325
return _timedelta_to_milliseconds(self.extended_timeout)
450
return timedelta_to_milliseconds(self.extended_timeout)
327
452
def interval_milliseconds(self):
328
453
"Return the 'interval' attribute in milliseconds"
329
return _timedelta_to_milliseconds(self.interval)
454
return timedelta_to_milliseconds(self.interval)
331
456
def approval_delay_milliseconds(self):
332
return _timedelta_to_milliseconds(self.approval_delay)
334
def __init__(self, name = None, disable_hook=None, config=None):
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):
335
511
"""Note: the 'checker' key in 'config' sets the
336
512
'checker_command' attribute and *not* the 'checker'
515
# adding all client settings
516
for setting, value in settings.iteritems():
517
setattr(self, setting, value)
341
519
logger.debug("Creating client %r", self.name)
342
520
# Uppercase and remove spaces from fingerprint for later
343
521
# comparison purposes with return value from the fingerprint()
345
self.fingerprint = (config["fingerprint"].upper()
347
523
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
524
self.created = settings.get("created", datetime.datetime.utcnow())
526
# attributes specific for this server instance
369
527
self.checker = None
370
528
self.checker_initiator_tag = None
371
529
self.disable_initiator_tag = None
373
530
self.checker_callback_tag = None
374
self.checker_command = config["checker"]
375
531
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
533
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
534
self.changedstate = (multiprocessing_manager
386
535
.Condition(multiprocessing_manager
537
self.client_structure = [attr for attr in
538
self.__dict__.iterkeys()
539
if not attr.startswith("_")]
540
self.client_structure.append("client_structure")
542
for name, t in inspect.getmembers(type(self),
546
if not name.startswith("_"):
547
self.client_structure.append(name)
549
# Send notice to process children that client state has changed
389
550
def send_changedstate(self):
390
self.changedstate.acquire()
391
self.changedstate.notify_all()
392
self.changedstate.release()
551
with self.changedstate:
552
self.changedstate.notify_all()
394
554
def enable(self):
395
555
"""Start this client's checker and timeout hooks"""
428
578
gobject.source_remove(self.checker_initiator_tag)
429
579
self.checker_initiator_tag = None
430
580
self.stop_checker()
431
if self.disable_hook:
432
self.disable_hook(self)
433
581
self.enabled = False
434
582
# Do not run this again if called by a gobject.timeout_add
437
585
def __del__(self):
438
self.disable_hook = None
588
def init_checker(self):
589
# Schedule a new checker to be started an 'interval' from now,
590
# and every interval from then on.
591
self.checker_initiator_tag = (gobject.timeout_add
592
(self.interval_milliseconds(),
594
# Schedule a disable() when 'timeout' has passed
595
self.disable_initiator_tag = (gobject.timeout_add
596
(self.timeout_milliseconds(),
598
# Also start a new checker *right now*.
441
601
def checker_callback(self, pid, condition, command):
442
602
"""The checker has completed, so take appropriate actions."""
443
603
self.checker_callback_tag = None
444
604
self.checker = None
445
605
if os.WIFEXITED(condition):
446
exitstatus = os.WEXITSTATUS(condition)
606
self.last_checker_status = os.WEXITSTATUS(condition)
607
if self.last_checker_status == 0:
448
608
logger.info("Checker for %(name)s succeeded",
450
610
self.checked_ok()
932
1097
datetime_to_dbus, "LastApprovalRequest")
933
1098
approved_by_default = notifychangeproperty(dbus.Boolean,
934
1099
"ApprovedByDefault")
935
approval_delay = notifychangeproperty(dbus.UInt16,
1100
approval_delay = notifychangeproperty(dbus.UInt64,
936
1101
"ApprovalDelay",
938
_timedelta_to_milliseconds)
1103
timedelta_to_milliseconds)
939
1104
approval_duration = notifychangeproperty(
940
dbus.UInt16, "ApprovalDuration",
941
type_func = _timedelta_to_milliseconds)
1105
dbus.UInt64, "ApprovalDuration",
1106
type_func = timedelta_to_milliseconds)
942
1107
host = notifychangeproperty(dbus.String, "Host")
943
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1108
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
945
_timedelta_to_milliseconds)
1110
timedelta_to_milliseconds)
946
1111
extended_timeout = notifychangeproperty(
947
dbus.UInt16, "ExtendedTimeout",
948
type_func = _timedelta_to_milliseconds)
949
interval = notifychangeproperty(dbus.UInt16,
1112
dbus.UInt64, "ExtendedTimeout",
1113
type_func = timedelta_to_milliseconds)
1114
interval = notifychangeproperty(dbus.UInt64,
952
_timedelta_to_milliseconds)
1117
timedelta_to_milliseconds)
953
1118
checker_command = notifychangeproperty(dbus.String, "Checker")
955
1120
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:
2220
with PGPEngine() as pgp:
2221
for client_name, client in clients_data.iteritems():
2222
# Decide which value to use after restoring saved state.
2223
# We have three different values: Old config file,
2224
# new config file, and saved state.
2225
# New config value takes precedence if it differs from old
2226
# config value, otherwise use saved state.
2227
for name, value in client_settings[client_name].items():
2229
# For each value in new config, check if it
2230
# differs from the old config value (Except for
2231
# the "secret" attribute)
2232
if (name != "secret" and
2233
value != old_client_settings[client_name]
2235
client[name] = value
2239
# Clients who has passed its expire date can still be
2240
# enabled if its last checker was successful. Clients
2241
# whose checker failed before we stored its state is
2242
# assumed to have failed all checkers during downtime.
2243
if client["enabled"]:
2244
if datetime.datetime.utcnow() >= client["expires"]:
2245
if not client["last_checked_ok"]:
2247
"disabling client {0} - Client never "
2248
"performed a successfull checker"
2249
.format(client["name"]))
2250
client["enabled"] = False
2251
elif client["last_checker_status"] != 0:
2253
"disabling client {0} - Client "
2254
"last checker failed with error code {1}"
2255
.format(client["name"],
2256
client["last_checker_status"]))
2257
client["enabled"] = False
2259
client["expires"] = (datetime.datetime
2261
+ 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()))
2264
client["secret"] = (
2265
pgp.decrypt(client["encrypted_secret"],
2266
client_settings[client_name]
2269
# If decryption fails, we use secret from new settings
2270
logger.debug("Failed to decrypt {0} old secret"
2271
.format(client_name))
2272
client["secret"] = (
2273
client_settings[client_name]["secret"])
2276
# Add/remove clients based on new changes made to config
2277
for client_name in set(old_client_settings) - set(client_settings):
2278
del clients_data[client_name]
2279
for client_name in set(client_settings) - set(old_client_settings):
2280
clients_data[client_name] = client_settings[client_name]
2282
# Create clients all clients
2283
for client_name, client in clients_data.iteritems():
2284
tcp_server.clients[client_name] = client_class(
2285
name = client_name, settings = client)
2058
2287
if not tcp_server.clients:
2059
2288
logger.warning("No clients defined")
2139
2368
service.cleanup()
2141
2370
multiprocessing.active_children()
2371
if not (tcp_server.clients or client_settings):
2374
# Store client before exiting. Secrets are encrypted with key
2375
# based on what config file has. If config file is
2376
# removed/edited, old secret will thus be unrecovable.
2378
with PGPEngine() as pgp:
2379
for client in tcp_server.clients.itervalues():
2380
key = client_settings[client.name]["secret"]
2381
client.encrypted_secret = pgp.encrypt(client.secret,
2385
# A list of attributes that can not be pickled
2387
exclude = set(("bus", "changedstate", "secret",
2389
for name, typ in (inspect.getmembers
2390
(dbus.service.Object)):
2393
client_dict["encrypted_secret"] = (client
2395
for attr in client.client_structure:
2396
if attr not in exclude:
2397
client_dict[attr] = getattr(client, attr)
2399
clients[client.name] = client_dict
2400
del client_settings[client.name]["secret"]
2403
with os.fdopen(os.open(stored_state_path,
2404
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2405
0600), "wb") as stored_state:
2406
pickle.dump((clients, client_settings), stored_state)
2407
except (IOError, OSError) as e:
2408
logger.warning("Could not save persistent state: {0}"
2410
if e.errno not in (errno.ENOENT, errno.EACCES):
2413
# Delete all clients, and settings from config
2142
2414
while tcp_server.clients:
2143
client = tcp_server.clients.pop()
2415
name, client = tcp_server.clients.popitem()
2145
2417
client.remove_from_connection()
2146
client.disable_hook = None
2147
2418
# Don't signal anything except ClientRemoved
2148
2419
client.disable(quiet=True)