88
82
except ImportError:
89
83
SO_BINDTODEVICE = None
92
stored_state_file = "clients.pickle"
94
logger = logging.getLogger()
88
#logger = logging.getLogger('mandos')
89
logger = logging.Logger('mandos')
95
90
syslogger = (logging.handlers.SysLogHandler
96
91
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
97
92
address = str("/dev/log")))
100
if_nametoindex = (ctypes.cdll.LoadLibrary
101
(ctypes.util.find_library("c"))
103
except (OSError, AttributeError):
104
def if_nametoindex(interface):
105
"Get an interface index the hard way, i.e. using fcntl()"
106
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
107
with contextlib.closing(socket.socket()) as s:
108
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
109
struct.pack(str("16s16x"),
111
interface_index = struct.unpack(str("I"),
113
return interface_index
116
def initlogger(debug, level=logging.WARNING):
117
"""init logger and add loglevel"""
119
syslogger.setFormatter(logging.Formatter
120
('Mandos [%(process)d]: %(levelname)s:'
122
logger.addHandler(syslogger)
125
console = logging.StreamHandler()
126
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
130
logger.addHandler(console)
131
logger.setLevel(level)
134
class PGPError(Exception):
135
"""Exception if encryption/decryption fails"""
139
class PGPEngine(object):
140
"""A simple class for OpenPGP symmetric encryption & decryption"""
142
self.gnupg = GnuPGInterface.GnuPG()
143
self.tempdir = tempfile.mkdtemp(prefix="mandos-")
144
self.gnupg = GnuPGInterface.GnuPG()
145
self.gnupg.options.meta_interactive = False
146
self.gnupg.options.homedir = self.tempdir
147
self.gnupg.options.extra_args.extend(['--force-mdc',
154
def __exit__(self, exc_type, exc_value, traceback):
162
if self.tempdir is not None:
163
# Delete contents of tempdir
164
for root, dirs, files in os.walk(self.tempdir,
166
for filename in files:
167
os.remove(os.path.join(root, filename))
169
os.rmdir(os.path.join(root, dirname))
171
os.rmdir(self.tempdir)
174
def password_encode(self, password):
175
# Passphrase can not be empty and can not contain newlines or
176
# NUL bytes. So we prefix it and hex encode it.
177
return b"mandos" + binascii.hexlify(password)
179
def encrypt(self, data, password):
180
self.gnupg.passphrase = self.password_encode(password)
181
with open(os.devnull, "w") as devnull:
183
proc = self.gnupg.run(['--symmetric'],
184
create_fhs=['stdin', 'stdout'],
185
attach_fhs={'stderr': devnull})
186
with contextlib.closing(proc.handles['stdin']) as f:
188
with contextlib.closing(proc.handles['stdout']) as f:
189
ciphertext = f.read()
193
self.gnupg.passphrase = None
196
def decrypt(self, data, password):
197
self.gnupg.passphrase = self.password_encode(password)
198
with open(os.devnull, "w") as devnull:
200
proc = self.gnupg.run(['--decrypt'],
201
create_fhs=['stdin', 'stdout'],
202
attach_fhs={'stderr': devnull})
203
with contextlib.closing(proc.handles['stdin']) as f:
205
with contextlib.closing(proc.handles['stdout']) as f:
206
decrypted_plaintext = f.read()
210
self.gnupg.passphrase = None
211
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)
214
104
class AvahiError(Exception):
215
105
def __init__(self, value, *args, **kwargs):
426
299
interval: datetime.timedelta(); How often to start a new checker
427
300
last_approval_request: datetime.datetime(); (UTC) or None
428
301
last_checked_ok: datetime.datetime(); (UTC) or None
429
last_checker_status: integer between 0 and 255 reflecting exit
430
status of last checker. -1 reflects crashed
431
checker, -2 means no checker completed yet.
432
last_enabled: datetime.datetime(); (UTC) or None
302
last_enabled: datetime.datetime(); (UTC)
433
303
name: string; from the config file, used in log messages and
434
304
D-Bus identifiers
435
305
secret: bytestring; sent verbatim (over TLS) to client
436
306
timeout: datetime.timedelta(); How long from last_checked_ok
437
307
until this client is disabled
438
extended_timeout: extra long timeout when secret has been sent
308
extended_timeout: extra long timeout when password has been sent
439
309
runtime_expansions: Allowed attributes for runtime expansion.
440
310
expires: datetime.datetime(); time (UTC) when a client will be
441
311
disabled, or None
444
314
runtime_expansions = ("approval_delay", "approval_duration",
445
"created", "enabled", "expires",
446
"fingerprint", "host", "interval",
447
"last_approval_request", "last_checked_ok",
315
"created", "enabled", "fingerprint",
316
"host", "interval", "last_checked_ok",
448
317
"last_enabled", "name", "timeout")
449
client_defaults = { "timeout": "5m",
450
"extended_timeout": "15m",
452
"checker": "fping -q -- %%(host)s",
454
"approval_delay": "0s",
455
"approval_duration": "1s",
456
"approved_by_default": "True",
460
319
def timeout_milliseconds(self):
461
320
"Return the 'timeout' attribute in milliseconds"
462
return timedelta_to_milliseconds(self.timeout)
321
return _timedelta_to_milliseconds(self.timeout)
464
323
def extended_timeout_milliseconds(self):
465
324
"Return the 'extended_timeout' attribute in milliseconds"
466
return timedelta_to_milliseconds(self.extended_timeout)
325
return _timedelta_to_milliseconds(self.extended_timeout)
468
327
def interval_milliseconds(self):
469
328
"Return the 'interval' attribute in milliseconds"
470
return timedelta_to_milliseconds(self.interval)
329
return _timedelta_to_milliseconds(self.interval)
472
331
def approval_delay_milliseconds(self):
473
return timedelta_to_milliseconds(self.approval_delay)
476
def config_parser(config):
477
"""Construct a new dict of client settings of this form:
478
{ client_name: {setting_name: value, ...}, ...}
479
with exceptions for any special settings as defined above.
480
NOTE: Must be a pure function. Must return the same result
481
value given the same arguments.
484
for client_name in config.sections():
485
section = dict(config.items(client_name))
486
client = settings[client_name] = {}
488
client["host"] = section["host"]
489
# Reformat values from string types to Python types
490
client["approved_by_default"] = config.getboolean(
491
client_name, "approved_by_default")
492
client["enabled"] = config.getboolean(client_name,
495
client["fingerprint"] = (section["fingerprint"].upper()
497
if "secret" in section:
498
client["secret"] = section["secret"].decode("base64")
499
elif "secfile" in section:
500
with open(os.path.expanduser(os.path.expandvars
501
(section["secfile"])),
503
client["secret"] = secfile.read()
505
raise TypeError("No secret or secfile for section {0}"
507
client["timeout"] = string_to_delta(section["timeout"])
508
client["extended_timeout"] = string_to_delta(
509
section["extended_timeout"])
510
client["interval"] = string_to_delta(section["interval"])
511
client["approval_delay"] = string_to_delta(
512
section["approval_delay"])
513
client["approval_duration"] = string_to_delta(
514
section["approval_duration"])
515
client["checker_command"] = section["checker"]
516
client["last_approval_request"] = None
517
client["last_checked_ok"] = None
518
client["last_checker_status"] = -2
522
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):
335
"""Note: the 'checker' key in 'config' sets the
336
'checker_command' attribute and *not* the 'checker'
524
# adding all client settings
525
for setting, value in settings.iteritems():
526
setattr(self, setting, value)
529
if not hasattr(self, "last_enabled"):
530
self.last_enabled = datetime.datetime.utcnow()
531
if not hasattr(self, "expires"):
532
self.expires = (datetime.datetime.utcnow()
535
self.last_enabled = None
538
341
logger.debug("Creating client %r", self.name)
539
342
# Uppercase and remove spaces from fingerprint for later
540
343
# comparison purposes with return value from the fingerprint()
345
self.fingerprint = (config["fingerprint"].upper()
542
347
logger.debug(" Fingerprint: %s", self.fingerprint)
543
self.created = settings.get("created",
544
datetime.datetime.utcnow())
546
# 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
547
369
self.checker = None
548
370
self.checker_initiator_tag = None
549
371
self.disable_initiator_tag = None
550
373
self.checker_callback_tag = None
374
self.checker_command = config["checker"]
551
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",
553
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"])
554
385
self.changedstate = (multiprocessing_manager
555
386
.Condition(multiprocessing_manager
557
self.client_structure = [attr for attr in
558
self.__dict__.iterkeys()
559
if not attr.startswith("_")]
560
self.client_structure.append("client_structure")
562
for name, t in inspect.getmembers(type(self),
566
if not name.startswith("_"):
567
self.client_structure.append(name)
569
# Send notice to process children that client state has changed
570
389
def send_changedstate(self):
571
with self.changedstate:
572
self.changedstate.notify_all()
390
self.changedstate.acquire()
391
self.changedstate.notify_all()
392
self.changedstate.release()
574
394
def enable(self):
575
395
"""Start this client's checker and timeout hooks"""
576
396
if getattr(self, "enabled", False):
577
397
# Already enabled
399
self.send_changedstate()
400
# Schedule a new checker to be started an 'interval' from now,
401
# and every interval from then on.
402
self.checker_initiator_tag = (gobject.timeout_add
403
(self.interval_milliseconds(),
405
# Schedule a disable() when 'timeout' has passed
579
406
self.expires = datetime.datetime.utcnow() + self.timeout
407
self.disable_initiator_tag = (gobject.timeout_add
408
(self.timeout_milliseconds(),
580
410
self.enabled = True
581
411
self.last_enabled = datetime.datetime.utcnow()
583
self.send_changedstate()
412
# Also start a new checker *right now*.
585
415
def disable(self, quiet=True):
586
416
"""Disable this client."""
587
417
if not getattr(self, "enabled", False):
420
self.send_changedstate()
590
422
logger.info("Disabling client %s", self.name)
591
if getattr(self, "disable_initiator_tag", None) is not None:
423
if getattr(self, "disable_initiator_tag", False):
592
424
gobject.source_remove(self.disable_initiator_tag)
593
425
self.disable_initiator_tag = None
594
426
self.expires = None
595
if getattr(self, "checker_initiator_tag", None) is not None:
427
if getattr(self, "checker_initiator_tag", False):
596
428
gobject.source_remove(self.checker_initiator_tag)
597
429
self.checker_initiator_tag = None
598
430
self.stop_checker()
431
if self.disable_hook:
432
self.disable_hook(self)
599
433
self.enabled = False
601
self.send_changedstate()
602
434
# Do not run this again if called by a gobject.timeout_add
605
437
def __del__(self):
438
self.disable_hook = None
608
def init_checker(self):
609
# Schedule a new checker to be started an 'interval' from now,
610
# and every interval from then on.
611
if self.checker_initiator_tag is not None:
612
gobject.source_remove(self.checker_initiator_tag)
613
self.checker_initiator_tag = (gobject.timeout_add
614
(self.interval_milliseconds(),
616
# Schedule a disable() when 'timeout' has passed
617
if self.disable_initiator_tag is not None:
618
gobject.source_remove(self.disable_initiator_tag)
619
self.disable_initiator_tag = (gobject.timeout_add
620
(self.timeout_milliseconds(),
622
# Also start a new checker *right now*.
625
441
def checker_callback(self, pid, condition, command):
626
442
"""The checker has completed, so take appropriate actions."""
627
443
self.checker_callback_tag = None
628
444
self.checker = None
629
445
if os.WIFEXITED(condition):
630
self.last_checker_status = os.WEXITSTATUS(condition)
631
if self.last_checker_status == 0:
446
exitstatus = os.WEXITSTATUS(condition)
632
448
logger.info("Checker for %(name)s succeeded",
634
450
self.checked_ok()
1012
750
except (AttributeError, xml.dom.DOMException,
1013
751
xml.parsers.expat.ExpatError) as error:
1014
752
logger.error("Failed to override Introspection method",
1016
754
return xmlstring
1019
def datetime_to_dbus(dt, variant_level=0):
757
def datetime_to_dbus (dt, variant_level=0):
1020
758
"""Convert a UTC datetime.datetime() to a D-Bus type."""
1022
760
return dbus.String("", variant_level = variant_level)
1023
761
return dbus.String(dt.isoformat(),
1024
762
variant_level=variant_level)
1027
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1028
"""A class decorator; applied to a subclass of
1029
dbus.service.Object, it will add alternate D-Bus attributes with
1030
interface names according to the "alt_interface_names" mapping.
1033
@alternate_dbus_interfaces({"org.example.Interface":
1034
"net.example.AlternateInterface"})
1035
class SampleDBusObject(dbus.service.Object):
1036
@dbus.service.method("org.example.Interface")
1037
def SampleDBusMethod():
1040
The above "SampleDBusMethod" on "SampleDBusObject" will be
1041
reachable via two interfaces: "org.example.Interface" and
1042
"net.example.AlternateInterface", the latter of which will have
1043
its D-Bus annotation "org.freedesktop.DBus.Deprecated" set to
1044
"true", unless "deprecate" is passed with a False value.
1046
This works for methods and signals, and also for D-Bus properties
1047
(from DBusObjectWithProperties) and interfaces (from the
1048
dbus_interface_annotations decorator).
764
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
766
"""Applied to an empty subclass of a D-Bus object, this metaclass
767
will add additional D-Bus attributes matching a certain pattern.
1051
for orig_interface_name, alt_interface_name in (
1052
alt_interface_names.iteritems()):
1054
interface_names = set()
1055
# Go though all attributes of the class
1056
for attrname, attribute in inspect.getmembers(cls):
769
def __new__(mcs, name, bases, attr):
770
# Go through all the base classes which could have D-Bus
771
# methods, signals, or properties in them
772
for base in (b for b in bases
773
if issubclass(b, dbus.service.Object)):
774
# Go though all attributes of the base class
775
for attrname, attribute in inspect.getmembers(base):
1057
776
# Ignore non-D-Bus attributes, and D-Bus attributes
1058
777
# with the wrong interface name
1059
778
if (not hasattr(attribute, "_dbus_interface")
1060
779
or not attribute._dbus_interface
1061
.startswith(orig_interface_name)):
780
.startswith("se.recompile.Mandos")):
1063
782
# Create an alternate D-Bus interface name based on
1064
783
# the current name
1065
784
alt_interface = (attribute._dbus_interface
1066
.replace(orig_interface_name,
1067
alt_interface_name))
1068
interface_names.add(alt_interface)
785
.replace("se.recompile.Mandos",
786
"se.bsnet.fukt.Mandos"))
1069
787
# Is this a D-Bus signal?
1070
788
if getattr(attribute, "_dbus_is_signal", False):
1071
789
# Extract the original non-method function by
2351
2035
client_class = Client
2353
client_class = functools.partial(ClientDBus, bus = bus)
2355
client_settings = Client.config_parser(client_config)
2356
old_client_settings = {}
2359
# Get client data and settings from last running state.
2360
if server_settings["restore"]:
2362
with open(stored_state_path, "rb") as stored_state:
2363
clients_data, old_client_settings = (pickle.load
2365
os.remove(stored_state_path)
2366
except IOError as e:
2367
if e.errno == errno.ENOENT:
2368
logger.warning("Could not load persistent state: {0}"
2369
.format(os.strerror(e.errno)))
2371
logger.critical("Could not load persistent state:",
2374
except EOFError as e:
2375
logger.warning("Could not load persistent state: "
2376
"EOFError:", exc_info=e)
2378
with PGPEngine() as pgp:
2379
for client_name, client in clients_data.iteritems():
2380
# Decide which value to use after restoring saved state.
2381
# We have three different values: Old config file,
2382
# new config file, and saved state.
2383
# New config value takes precedence if it differs from old
2384
# config value, otherwise use saved state.
2385
for name, value in client_settings[client_name].items():
2387
# For each value in new config, check if it
2388
# differs from the old config value (Except for
2389
# the "secret" attribute)
2390
if (name != "secret" and
2391
value != old_client_settings[client_name]
2393
client[name] = value
2397
# Clients who has passed its expire date can still be
2398
# enabled if its last checker was successful. Clients
2399
# whose checker succeeded before we stored its state is
2400
# assumed to have successfully run all checkers during
2402
if client["enabled"]:
2403
if datetime.datetime.utcnow() >= client["expires"]:
2404
if not client["last_checked_ok"]:
2406
"disabling client {0} - Client never "
2407
"performed a successful checker"
2408
.format(client_name))
2409
client["enabled"] = False
2410
elif client["last_checker_status"] != 0:
2412
"disabling client {0} - Client "
2413
"last checker failed with error code {1}"
2414
.format(client_name,
2415
client["last_checker_status"]))
2416
client["enabled"] = False
2418
client["expires"] = (datetime.datetime
2420
+ client["timeout"])
2421
logger.debug("Last checker succeeded,"
2422
" keeping {0} enabled"
2423
.format(client_name))
2037
client_class = functools.partial(ClientDBusTransitional,
2039
def client_config_items(config, section):
2040
special_settings = {
2041
"approved_by_default":
2042
lambda: config.getboolean(section,
2043
"approved_by_default"),
2045
for name, value in config.items(section):
2425
client["secret"] = (
2426
pgp.decrypt(client["encrypted_secret"],
2427
client_settings[client_name]
2430
# If decryption fails, we use secret from new settings
2431
logger.debug("Failed to decrypt {0} old secret"
2432
.format(client_name))
2433
client["secret"] = (
2434
client_settings[client_name]["secret"])
2436
# Add/remove clients based on new changes made to config
2437
for client_name in (set(old_client_settings)
2438
- set(client_settings)):
2439
del clients_data[client_name]
2440
for client_name in (set(client_settings)
2441
- set(old_client_settings)):
2442
clients_data[client_name] = client_settings[client_name]
2444
# Create all client objects
2445
for client_name, client in clients_data.iteritems():
2446
tcp_server.clients[client_name] = client_class(
2447
name = client_name, settings = client)
2047
yield (name, special_settings[name]())
2051
tcp_server.clients.update(set(
2052
client_class(name = section,
2053
config= dict(client_config_items(
2054
client_config, section)))
2055
for section in client_config.sections()))
2449
2056
if not tcp_server.clients:
2450
2057
logger.warning("No clients defined")
2531
mandos_dbus_service = MandosDBusService()
2131
class MandosDBusServiceTransitional(MandosDBusService):
2132
__metaclass__ = AlternateDBusNamesMetaclass
2133
mandos_dbus_service = MandosDBusServiceTransitional()
2534
2136
"Cleanup function; run on exit"
2535
2137
service.cleanup()
2537
2139
multiprocessing.active_children()
2538
if not (tcp_server.clients or client_settings):
2541
# Store client before exiting. Secrets are encrypted with key
2542
# based on what config file has. If config file is
2543
# removed/edited, old secret will thus be unrecovable.
2545
with PGPEngine() as pgp:
2546
for client in tcp_server.clients.itervalues():
2547
key = client_settings[client.name]["secret"]
2548
client.encrypted_secret = pgp.encrypt(client.secret,
2552
# A list of attributes that can not be pickled
2554
exclude = set(("bus", "changedstate", "secret",
2556
for name, typ in (inspect.getmembers
2557
(dbus.service.Object)):
2560
client_dict["encrypted_secret"] = (client
2562
for attr in client.client_structure:
2563
if attr not in exclude:
2564
client_dict[attr] = getattr(client, attr)
2566
clients[client.name] = client_dict
2567
del client_settings[client.name]["secret"]
2570
with (tempfile.NamedTemporaryFile
2571
(mode='wb', suffix=".pickle", prefix='clients-',
2572
dir=os.path.dirname(stored_state_path),
2573
delete=False)) as stored_state:
2574
pickle.dump((clients, client_settings), stored_state)
2575
tempname=stored_state.name
2576
os.rename(tempname, stored_state_path)
2577
except (IOError, OSError) as e:
2583
if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2584
logger.warning("Could not save persistent state: {0}"
2585
.format(os.strerror(e.errno)))
2587
logger.warning("Could not save persistent state:",
2591
# Delete all clients, and settings from config
2592
2140
while tcp_server.clients:
2593
name, client = tcp_server.clients.popitem()
2141
client = tcp_server.clients.pop()
2595
2143
client.remove_from_connection()
2144
client.disable_hook = None
2596
2145
# Don't signal anything except ClientRemoved
2597
2146
client.disable(quiet=True)