85
81
    except ImportError:
 
86
82
        SO_BINDTODEVICE = None
 
89
 
stored_state_file = "clients.pickle"
 
91
 
logger = logging.getLogger()
 
 
87
#logger = logging.getLogger('mandos')
 
 
88
logger = logging.Logger('mandos')
 
92
89
syslogger = (logging.handlers.SysLogHandler
 
93
90
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
94
91
              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
 
 
92
syslogger.setFormatter(logging.Formatter
 
 
93
                       ('Mandos [%(process)d]: %(levelname)s:'
 
 
95
logger.addHandler(syslogger)
 
 
97
console = logging.StreamHandler()
 
 
98
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
 
 
101
logger.addHandler(console)
 
212
103
class AvahiError(Exception):
 
213
104
    def __init__(self, value, *args, **kwargs):
 
 
413
283
    interval:   datetime.timedelta(); How often to start a new checker
 
414
284
    last_approval_request: datetime.datetime(); (UTC) or None
 
415
285
    last_checked_ok: datetime.datetime(); (UTC) or None
 
416
 
    last_checker_status: integer between 0 and 255 reflecting exit
 
417
 
                         status of last checker. -1 reflects crashed
 
419
 
    last_enabled: datetime.datetime(); (UTC) or None
 
 
286
    last_enabled: datetime.datetime(); (UTC)
 
420
287
    name:       string; from the config file, used in log messages and
 
421
288
                        D-Bus identifiers
 
422
289
    secret:     bytestring; sent verbatim (over TLS) to client
 
423
290
    timeout:    datetime.timedelta(); How long from last_checked_ok
 
424
291
                                      until this client is disabled
 
425
 
    extended_timeout:   extra long timeout when secret has been sent
 
426
292
    runtime_expansions: Allowed attributes for runtime expansion.
 
427
 
    expires:    datetime.datetime(); time (UTC) when a client will be
 
431
295
    runtime_expansions = ("approval_delay", "approval_duration",
 
432
296
                          "created", "enabled", "fingerprint",
 
433
297
                          "host", "interval", "last_checked_ok",
 
434
298
                          "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",
 
 
301
    def _timedelta_to_milliseconds(td):
 
 
302
        "Convert a datetime.timedelta() to milliseconds"
 
 
303
        return ((td.days * 24 * 60 * 60 * 1000)
 
 
304
                + (td.seconds * 1000)
 
 
305
                + (td.microseconds // 1000))
 
446
307
    def timeout_milliseconds(self):
 
447
308
        "Return the 'timeout' attribute in milliseconds"
 
448
 
        return timedelta_to_milliseconds(self.timeout)
 
450
 
    def extended_timeout_milliseconds(self):
 
451
 
        "Return the 'extended_timeout' attribute in milliseconds"
 
452
 
        return timedelta_to_milliseconds(self.extended_timeout)
 
 
309
        return self._timedelta_to_milliseconds(self.timeout)
 
454
311
    def interval_milliseconds(self):
 
455
312
        "Return the 'interval' attribute in milliseconds"
 
456
 
        return timedelta_to_milliseconds(self.interval)
 
 
313
        return self._timedelta_to_milliseconds(self.interval)
 
458
315
    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,
 
481
 
            client["fingerprint"] = (section["fingerprint"].upper()
 
483
 
            if "secret" in section:
 
484
 
                client["secret"] = section["secret"].decode("base64")
 
485
 
            elif "secfile" in section:
 
486
 
                with open(os.path.expanduser(os.path.expandvars
 
487
 
                                             (section["secfile"])),
 
489
 
                    client["secret"] = secfile.read()
 
491
 
                raise TypeError("No secret or secfile for section %s"
 
493
 
            client["timeout"] = string_to_delta(section["timeout"])
 
494
 
            client["extended_timeout"] = string_to_delta(
 
495
 
                section["extended_timeout"])
 
496
 
            client["interval"] = string_to_delta(section["interval"])
 
497
 
            client["approval_delay"] = string_to_delta(
 
498
 
                section["approval_delay"])
 
499
 
            client["approval_duration"] = string_to_delta(
 
500
 
                section["approval_duration"])
 
501
 
            client["checker_command"] = section["checker"]
 
502
 
            client["last_approval_request"] = None
 
503
 
            client["last_checked_ok"] = None
 
504
 
            client["last_checker_status"] = None
 
509
 
    def __init__(self, settings, name = None):
 
 
316
        return self._timedelta_to_milliseconds(self.approval_delay)
 
 
318
    def __init__(self, name = None, disable_hook=None, config=None):
 
510
319
        """Note: the 'checker' key in 'config' sets the
 
511
320
        'checker_command' attribute and *not* the 'checker'
 
514
 
        # adding all client settings
 
515
 
        for setting, value in settings.iteritems():
 
516
 
            setattr(self, setting, value)
 
519
 
            if not hasattr(self, "last_enabled"):
 
520
 
                self.last_enabled = datetime.datetime.utcnow()
 
521
 
            if not hasattr(self, "expires"):
 
522
 
                self.expires = (datetime.datetime.utcnow()
 
525
 
            self.last_enabled = None
 
528
325
        logger.debug("Creating client %r", self.name)
 
529
326
        # Uppercase and remove spaces from fingerprint for later
 
530
327
        # comparison purposes with return value from the fingerprint()
 
 
329
        self.fingerprint = (config["fingerprint"].upper()
 
532
331
        logger.debug("  Fingerprint: %s", self.fingerprint)
 
533
 
        self.created = settings.get("created",
 
534
 
                                    datetime.datetime.utcnow())
 
536
 
        # attributes specific for this server instance
 
 
332
        if "secret" in config:
 
 
333
            self.secret = config["secret"].decode("base64")
 
 
334
        elif "secfile" in config:
 
 
335
            with open(os.path.expanduser(os.path.expandvars
 
 
336
                                         (config["secfile"])),
 
 
338
                self.secret = secfile.read()
 
 
340
            raise TypeError("No secret or secfile for client %s"
 
 
342
        self.host = config.get("host", "")
 
 
343
        self.created = datetime.datetime.utcnow()
 
 
345
        self.last_approval_request = None
 
 
346
        self.last_enabled = None
 
 
347
        self.last_checked_ok = None
 
 
348
        self.timeout = string_to_delta(config["timeout"])
 
 
349
        self.interval = string_to_delta(config["interval"])
 
 
350
        self.disable_hook = disable_hook
 
537
351
        self.checker = None
 
538
352
        self.checker_initiator_tag = None
 
539
353
        self.disable_initiator_tag = None
 
540
354
        self.checker_callback_tag = None
 
 
355
        self.checker_command = config["checker"]
 
541
356
        self.current_checker_command = None
 
 
357
        self.last_connect = None
 
 
358
        self._approved = None
 
 
359
        self.approved_by_default = config.get("approved_by_default",
 
543
361
        self.approvals_pending = 0
 
544
 
        self.changedstate = (multiprocessing_manager
 
545
 
                             .Condition(multiprocessing_manager
 
547
 
        self.client_structure = [attr for attr in
 
548
 
                                 self.__dict__.iterkeys()
 
549
 
                                 if not attr.startswith("_")]
 
550
 
        self.client_structure.append("client_structure")
 
552
 
        for name, t in inspect.getmembers(type(self),
 
556
 
            if not name.startswith("_"):
 
557
 
                self.client_structure.append(name)
 
 
362
        self.approval_delay = string_to_delta(
 
 
363
            config["approval_delay"])
 
 
364
        self.approval_duration = string_to_delta(
 
 
365
            config["approval_duration"])
 
 
366
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
 
559
 
    # Send notice to process children that client state has changed
 
560
368
    def send_changedstate(self):
 
561
 
        with self.changedstate:
 
562
 
            self.changedstate.notify_all()
 
 
369
        self.changedstate.acquire()
 
 
370
        self.changedstate.notify_all()
 
 
371
        self.changedstate.release()
 
564
373
    def enable(self):
 
565
374
        """Start this client's checker and timeout hooks"""
 
566
375
        if getattr(self, "enabled", False):
 
567
376
            # Already enabled
 
569
378
        self.send_changedstate()
 
570
 
        self.expires = datetime.datetime.utcnow() + self.timeout
 
572
379
        self.last_enabled = datetime.datetime.utcnow()
 
 
380
        # Schedule a new checker to be started an 'interval' from now,
 
 
381
        # and every interval from then on.
 
 
382
        self.checker_initiator_tag = (gobject.timeout_add
 
 
383
                                      (self.interval_milliseconds(),
 
 
385
        # Schedule a disable() when 'timeout' has passed
 
 
386
        self.disable_initiator_tag = (gobject.timeout_add
 
 
387
                                   (self.timeout_milliseconds(),
 
 
390
        # Also start a new checker *right now*.
 
575
393
    def disable(self, quiet=True):
 
576
394
        """Disable this client."""
 
 
930
 
def datetime_to_dbus (dt, variant_level=0):
 
931
 
    """Convert a UTC datetime.datetime() to a D-Bus type."""
 
933
 
        return dbus.String("", variant_level = variant_level)
 
934
 
    return dbus.String(dt.isoformat(),
 
935
 
                       variant_level=variant_level)
 
938
 
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
 
940
 
    """Applied to an empty subclass of a D-Bus object, this metaclass
 
941
 
    will add additional D-Bus attributes matching a certain pattern.
 
943
 
    def __new__(mcs, name, bases, attr):
 
944
 
        # Go through all the base classes which could have D-Bus
 
945
 
        # methods, signals, or properties in them
 
946
 
        for base in (b for b in bases
 
947
 
                     if issubclass(b, dbus.service.Object)):
 
948
 
            # Go though all attributes of the base class
 
949
 
            for attrname, attribute in inspect.getmembers(base):
 
950
 
                # Ignore non-D-Bus attributes, and D-Bus attributes
 
951
 
                # with the wrong interface name
 
952
 
                if (not hasattr(attribute, "_dbus_interface")
 
953
 
                    or not attribute._dbus_interface
 
954
 
                    .startswith("se.recompile.Mandos")):
 
956
 
                # Create an alternate D-Bus interface name based on
 
958
 
                alt_interface = (attribute._dbus_interface
 
959
 
                                 .replace("se.recompile.Mandos",
 
960
 
                                          "se.bsnet.fukt.Mandos"))
 
961
 
                # Is this a D-Bus signal?
 
962
 
                if getattr(attribute, "_dbus_is_signal", False):
 
963
 
                    # Extract the original non-method function by
 
965
 
                    nonmethod_func = (dict(
 
966
 
                            zip(attribute.func_code.co_freevars,
 
967
 
                                attribute.__closure__))["func"]
 
969
 
                    # Create a new, but exactly alike, function
 
970
 
                    # object, and decorate it to be a new D-Bus signal
 
971
 
                    # with the alternate D-Bus interface name
 
972
 
                    new_function = (dbus.service.signal
 
974
 
                                     attribute._dbus_signature)
 
976
 
                                nonmethod_func.func_code,
 
977
 
                                nonmethod_func.func_globals,
 
978
 
                                nonmethod_func.func_name,
 
979
 
                                nonmethod_func.func_defaults,
 
980
 
                                nonmethod_func.func_closure)))
 
981
 
                    # Define a creator of a function to call both the
 
982
 
                    # old and new functions, so both the old and new
 
983
 
                    # signals gets sent when the function is called
 
984
 
                    def fixscope(func1, func2):
 
985
 
                        """This function is a scope container to pass
 
986
 
                        func1 and func2 to the "call_both" function
 
987
 
                        outside of its arguments"""
 
988
 
                        def call_both(*args, **kwargs):
 
989
 
                            """This function will emit two D-Bus
 
990
 
                            signals by calling func1 and func2"""
 
991
 
                            func1(*args, **kwargs)
 
992
 
                            func2(*args, **kwargs)
 
994
 
                    # Create the "call_both" function and add it to
 
996
 
                    attr[attrname] = fixscope(attribute,
 
998
 
                # Is this a D-Bus method?
 
999
 
                elif getattr(attribute, "_dbus_is_method", False):
 
1000
 
                    # Create a new, but exactly alike, function
 
1001
 
                    # object.  Decorate it to be a new D-Bus method
 
1002
 
                    # with the alternate D-Bus interface name.  Add it
 
1004
 
                    attr[attrname] = (dbus.service.method
 
1006
 
                                       attribute._dbus_in_signature,
 
1007
 
                                       attribute._dbus_out_signature)
 
1009
 
                                       (attribute.func_code,
 
1010
 
                                        attribute.func_globals,
 
1011
 
                                        attribute.func_name,
 
1012
 
                                        attribute.func_defaults,
 
1013
 
                                        attribute.func_closure)))
 
1014
 
                # Is this a D-Bus property?
 
1015
 
                elif getattr(attribute, "_dbus_is_property", False):
 
1016
 
                    # Create a new, but exactly alike, function
 
1017
 
                    # object, and decorate it to be a new D-Bus
 
1018
 
                    # property with the alternate D-Bus interface
 
1019
 
                    # name.  Add it to the class.
 
1020
 
                    attr[attrname] = (dbus_service_property
 
1022
 
                                       attribute._dbus_signature,
 
1023
 
                                       attribute._dbus_access,
 
1025
 
                                       ._dbus_get_args_options
 
1028
 
                                       (attribute.func_code,
 
1029
 
                                        attribute.func_globals,
 
1030
 
                                        attribute.func_name,
 
1031
 
                                        attribute.func_defaults,
 
1032
 
                                        attribute.func_closure)))
 
1033
 
        return type.__new__(mcs, name, bases, attr)
 
1036
732
class ClientDBus(Client, DBusObjectWithProperties):
 
1037
733
    """A Client class using D-Bus
 
 
1059
756
        DBusObjectWithProperties.__init__(self, self.bus,
 
1060
757
                                          self.dbus_object_path)
 
1062
 
    def notifychangeproperty(transform_func,
 
1063
 
                             dbus_name, type_func=lambda x: x,
 
1065
 
        """ Modify a variable so that it's a property which announces
 
1066
 
        its changes to DBus.
 
1068
 
        transform_fun: Function that takes a value and a variant_level
 
1069
 
                       and transforms it to a D-Bus type.
 
1070
 
        dbus_name: D-Bus name of the variable
 
1071
 
        type_func: Function that transform the value before sending it
 
1072
 
                   to the D-Bus.  Default: no transform
 
1073
 
        variant_level: D-Bus variant level.  Default: 1
 
1075
 
        attrname = "_{0}".format(dbus_name)
 
1076
 
        def setter(self, value):
 
1077
 
            if hasattr(self, "dbus_object_path"):
 
1078
 
                if (not hasattr(self, attrname) or
 
1079
 
                    type_func(getattr(self, attrname, None))
 
1080
 
                    != type_func(value)):
 
1081
 
                    dbus_value = transform_func(type_func(value),
 
1084
 
                    self.PropertyChanged(dbus.String(dbus_name),
 
1086
 
            setattr(self, attrname, value)
 
1088
 
        return property(lambda self: getattr(self, attrname), setter)
 
1091
 
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
 
1092
 
    approvals_pending = notifychangeproperty(dbus.Boolean,
 
1095
 
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
 
1096
 
    last_enabled = notifychangeproperty(datetime_to_dbus,
 
1098
 
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
 
1099
 
                                   type_func = lambda checker:
 
1100
 
                                       checker is not None)
 
1101
 
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
 
1103
 
    last_approval_request = notifychangeproperty(
 
1104
 
        datetime_to_dbus, "LastApprovalRequest")
 
1105
 
    approved_by_default = notifychangeproperty(dbus.Boolean,
 
1106
 
                                               "ApprovedByDefault")
 
1107
 
    approval_delay = notifychangeproperty(dbus.UInt64,
 
1110
 
                                          timedelta_to_milliseconds)
 
1111
 
    approval_duration = notifychangeproperty(
 
1112
 
        dbus.UInt64, "ApprovalDuration",
 
1113
 
        type_func = timedelta_to_milliseconds)
 
1114
 
    host = notifychangeproperty(dbus.String, "Host")
 
1115
 
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
 
1117
 
                                   timedelta_to_milliseconds)
 
1118
 
    extended_timeout = notifychangeproperty(
 
1119
 
        dbus.UInt64, "ExtendedTimeout",
 
1120
 
        type_func = timedelta_to_milliseconds)
 
1121
 
    interval = notifychangeproperty(dbus.UInt64,
 
1124
 
                                    timedelta_to_milliseconds)
 
1125
 
    checker_command = notifychangeproperty(dbus.String, "Checker")
 
1127
 
    del notifychangeproperty
 
 
759
    def _get_approvals_pending(self):
 
 
760
        return self._approvals_pending
 
 
761
    def _set_approvals_pending(self, value):
 
 
762
        old_value = self._approvals_pending
 
 
763
        self._approvals_pending = value
 
 
765
        if (hasattr(self, "dbus_object_path")
 
 
766
            and bval is not bool(old_value)):
 
 
767
            dbus_bool = dbus.Boolean(bval, variant_level=1)
 
 
768
            self.PropertyChanged(dbus.String("ApprovalPending"),
 
 
771
    approvals_pending = property(_get_approvals_pending,
 
 
772
                                 _set_approvals_pending)
 
 
773
    del _get_approvals_pending, _set_approvals_pending
 
 
776
    def _datetime_to_dbus(dt, variant_level=0):
 
 
777
        """Convert a UTC datetime.datetime() to a D-Bus type."""
 
 
778
        return dbus.String(dt.isoformat(),
 
 
779
                           variant_level=variant_level)
 
 
782
        oldstate = getattr(self, "enabled", False)
 
 
783
        r = Client.enable(self)
 
 
784
        if oldstate != self.enabled:
 
 
786
            self.PropertyChanged(dbus.String("Enabled"),
 
 
787
                                 dbus.Boolean(True, variant_level=1))
 
 
788
            self.PropertyChanged(
 
 
789
                dbus.String("LastEnabled"),
 
 
790
                self._datetime_to_dbus(self.last_enabled,
 
 
794
    def disable(self, quiet = False):
 
 
795
        oldstate = getattr(self, "enabled", False)
 
 
796
        r = Client.disable(self, quiet=quiet)
 
 
797
        if not quiet and oldstate != self.enabled:
 
 
799
            self.PropertyChanged(dbus.String("Enabled"),
 
 
800
                                 dbus.Boolean(False, variant_level=1))
 
1129
803
    def __del__(self, *args, **kwargs):
 
 
1364
1078
        if value is None:       # get
 
1365
1079
            return dbus.UInt64(self.timeout_milliseconds())
 
1366
1080
        self.timeout = datetime.timedelta(0, 0, 0, value)
 
 
1082
        self.PropertyChanged(dbus.String("Timeout"),
 
 
1083
                             dbus.UInt64(value, variant_level=1))
 
 
1084
        if getattr(self, "disable_initiator_tag", None) is None:
 
1367
1086
        # Reschedule timeout
 
1369
 
            now = datetime.datetime.utcnow()
 
1370
 
            time_to_die = timedelta_to_milliseconds(
 
1371
 
                (self.last_checked_ok + self.timeout) - now)
 
1372
 
            if time_to_die <= 0:
 
1373
 
                # The timeout has passed
 
1376
 
                self.expires = (now +
 
1377
 
                                datetime.timedelta(milliseconds =
 
1379
 
                if (getattr(self, "disable_initiator_tag", None)
 
1382
 
                gobject.source_remove(self.disable_initiator_tag)
 
1383
 
                self.disable_initiator_tag = (gobject.timeout_add
 
1387
 
    # ExtendedTimeout - property
 
1388
 
    @dbus_service_property(_interface, signature="t",
 
1390
 
    def ExtendedTimeout_dbus_property(self, value=None):
 
1391
 
        if value is None:       # get
 
1392
 
            return dbus.UInt64(self.extended_timeout_milliseconds())
 
1393
 
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
 
 
1087
        gobject.source_remove(self.disable_initiator_tag)
 
 
1088
        self.disable_initiator_tag = None
 
 
1089
        time_to_die = (self.
 
 
1090
                       _timedelta_to_milliseconds((self
 
 
1095
        if time_to_die <= 0:
 
 
1096
            # The timeout has passed
 
 
1099
            self.disable_initiator_tag = (gobject.timeout_add
 
 
1100
                                          (time_to_die, self.disable))
 
1395
1102
    # Interval - property
 
1396
1103
    @dbus_service_property(_interface, signature="t",
 
 
1399
1106
        if value is None:       # get
 
1400
1107
            return dbus.UInt64(self.interval_milliseconds())
 
1401
1108
        self.interval = datetime.timedelta(0, 0, 0, value)
 
 
1110
        self.PropertyChanged(dbus.String("Interval"),
 
 
1111
                             dbus.UInt64(value, variant_level=1))
 
1402
1112
        if getattr(self, "checker_initiator_tag", None) is None:
 
1405
 
            # Reschedule checker run
 
1406
 
            gobject.source_remove(self.checker_initiator_tag)
 
1407
 
            self.checker_initiator_tag = (gobject.timeout_add
 
1408
 
                                          (value, self.start_checker))
 
1409
 
            self.start_checker()    # Start one now, too
 
 
1114
        # Reschedule checker run
 
 
1115
        gobject.source_remove(self.checker_initiator_tag)
 
 
1116
        self.checker_initiator_tag = (gobject.timeout_add
 
 
1117
                                      (value, self.start_checker))
 
 
1118
        self.start_checker()    # Start one now, too
 
1411
1120
    # Checker - property
 
1412
1121
    @dbus_service_property(_interface, signature="s",
 
1413
1122
                           access="readwrite")
 
1414
1123
    def Checker_dbus_property(self, value=None):
 
1415
1124
        if value is None:       # get
 
1416
1125
            return dbus.String(self.checker_command)
 
1417
 
        self.checker_command = unicode(value)
 
 
1126
        self.checker_command = value
 
 
1128
        self.PropertyChanged(dbus.String("Checker"),
 
 
1129
                             dbus.String(self.checker_command,
 
1419
1132
    # CheckerRunning - property
 
1420
1133
    @dbus_service_property(_interface, signature="b",
 
 
1863
1556
            fpr = request[1]
 
1864
1557
            address = request[2]
 
1866
 
            for c in self.clients.itervalues():
 
 
1559
            for c in self.clients:
 
1867
1560
                if c.fingerprint == fpr:
 
1871
 
                logger.info("Client not found for fingerprint: %s, ad"
 
1872
 
                            "dress: %s", fpr, address)
 
 
1564
                logger.warning("Client not found for fingerprint: %s, ad"
 
 
1565
                               "dress: %s", fpr, address)
 
1873
1566
                if self.use_dbus:
 
1874
1567
                    # Emit D-Bus signal
 
1875
 
                    mandos_dbus_service.ClientNotFound(fpr,
 
 
1568
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
 
1877
1569
                parent_pipe.send(False)
 
1880
1572
            gobject.io_add_watch(parent_pipe.fileno(),
 
1881
1573
                                 gobject.IO_IN | gobject.IO_HUP,
 
1882
1574
                                 functools.partial(self.handle_ipc,
 
 
1575
                                                   parent_pipe = parent_pipe,
 
 
1576
                                                   client_object = client))
 
1888
1577
            parent_pipe.send(True)
 
1889
 
            # remove the old hook in favor of the new above hook on
 
 
1578
            # remove the old hook in favor of the new above hook on same fileno
 
1892
1580
        if command == 'funcall':
 
1893
1581
            funcname = request[1]
 
1894
1582
            args = request[2]
 
1895
1583
            kwargs = request[3]
 
1897
 
            parent_pipe.send(('data', getattr(client_object,
 
 
1585
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
 
1901
1587
        if command == 'getattr':
 
1902
1588
            attrname = request[1]
 
1903
1589
            if callable(client_object.__getattribute__(attrname)):
 
1904
1590
                parent_pipe.send(('function',))
 
1906
 
                parent_pipe.send(('data', client_object
 
1907
 
                                  .__getattribute__(attrname)))
 
 
1592
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
 
1909
1594
        if command == 'setattr':
 
1910
1595
            attrname = request[1]
 
1911
1596
            value = request[2]
 
1912
1597
            setattr(client_object, attrname, value)
 
 
2204
1904
    client_class = Client
 
2206
 
        client_class = functools.partial(ClientDBusTransitional,
 
2209
 
    client_settings = Client.config_parser(client_config)
 
2210
 
    old_client_settings = {}
 
2213
 
    # Get client data and settings from last running state.
 
2214
 
    if server_settings["restore"]:
 
2216
 
            with open(stored_state_path, "rb") as stored_state:
 
2217
 
                clients_data, old_client_settings = (pickle.load
 
2219
 
            os.remove(stored_state_path)
 
2220
 
        except IOError as e:
 
2221
 
            logger.warning("Could not load persistent state: {0}"
 
2223
 
            if e.errno != errno.ENOENT:
 
2225
 
        except EOFError as e:
 
2226
 
            logger.warning("Could not load persistent state: "
 
2227
 
                           "EOFError: {0}".format(e))
 
2229
 
    with PGPEngine() as pgp:
 
2230
 
        for client_name, client in clients_data.iteritems():
 
2231
 
            # Decide which value to use after restoring saved state.
 
2232
 
            # We have three different values: Old config file,
 
2233
 
            # new config file, and saved state.
 
2234
 
            # New config value takes precedence if it differs from old
 
2235
 
            # config value, otherwise use saved state.
 
2236
 
            for name, value in client_settings[client_name].items():
 
2238
 
                    # For each value in new config, check if it
 
2239
 
                    # differs from the old config value (Except for
 
2240
 
                    # the "secret" attribute)
 
2241
 
                    if (name != "secret" and
 
2242
 
                        value != old_client_settings[client_name]
 
2244
 
                        client[name] = value
 
2248
 
            # Clients who has passed its expire date can still be
 
2249
 
            # enabled if its last checker was successful.  Clients
 
2250
 
            # whose checker succeeded before we stored its state is
 
2251
 
            # assumed to have successfully run all checkers during
 
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 successful 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))
 
 
1906
        client_class = functools.partial(ClientDBus, bus = bus)
 
 
1907
    def client_config_items(config, section):
 
 
1908
        special_settings = {
 
 
1909
            "approved_by_default":
 
 
1910
                lambda: config.getboolean(section,
 
 
1911
                                          "approved_by_default"),
 
 
1913
        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)
 
2290
 
                        - set(client_settings)):
 
2291
 
        del clients_data[client_name]
 
2292
 
    for client_name in (set(client_settings)
 
2293
 
                        - set(old_client_settings)):
 
2294
 
        clients_data[client_name] = client_settings[client_name]
 
2296
 
    # Create all client objects
 
2297
 
    for client_name, client in clients_data.iteritems():
 
2298
 
        tcp_server.clients[client_name] = client_class(
 
2299
 
            name = client_name, settings = client)
 
 
1915
                yield (name, special_settings[name]())
 
 
1919
    tcp_server.clients.update(set(
 
 
1920
            client_class(name = section,
 
 
1921
                         config= dict(client_config_items(
 
 
1922
                        client_config, section)))
 
 
1923
            for section in client_config.sections()))
 
2301
1924
    if not tcp_server.clients:
 
2302
1925
        logger.warning("No clients defined")
 
 
2376
 
        class MandosDBusServiceTransitional(MandosDBusService):
 
2377
 
            __metaclass__ = AlternateDBusNamesMetaclass
 
2378
 
        mandos_dbus_service = MandosDBusServiceTransitional()
 
 
1999
        mandos_dbus_service = MandosDBusService()
 
2381
2002
        "Cleanup function; run on exit"
 
2382
2003
        service.cleanup()
 
2384
 
        multiprocessing.active_children()
 
2385
 
        if not (tcp_server.clients or client_settings):
 
2388
 
        # Store client before exiting. Secrets are encrypted with key
 
2389
 
        # based on what config file has. If config file is
 
2390
 
        # removed/edited, old secret will thus be unrecovable.
 
2392
 
        with PGPEngine() as pgp:
 
2393
 
            for client in tcp_server.clients.itervalues():
 
2394
 
                key = client_settings[client.name]["secret"]
 
2395
 
                client.encrypted_secret = pgp.encrypt(client.secret,
 
2399
 
                # A list of attributes that can not be pickled
 
2401
 
                exclude = set(("bus", "changedstate", "secret",
 
2403
 
                for name, typ in (inspect.getmembers
 
2404
 
                                  (dbus.service.Object)):
 
2407
 
                client_dict["encrypted_secret"] = (client
 
2409
 
                for attr in client.client_structure:
 
2410
 
                    if attr not in exclude:
 
2411
 
                        client_dict[attr] = getattr(client, attr)
 
2413
 
                clients[client.name] = client_dict
 
2414
 
                del client_settings[client.name]["secret"]
 
2417
 
            tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
 
2420
 
                                                (stored_state_path))
 
2421
 
            with os.fdopen(tempfd, "wb") as stored_state:
 
2422
 
                pickle.dump((clients, client_settings), stored_state)
 
2423
 
            os.rename(tempname, stored_state_path)
 
2424
 
        except (IOError, OSError) as e:
 
2425
 
            logger.warning("Could not save persistent state: {0}"
 
2432
 
            if e.errno not in set((errno.ENOENT, errno.EACCES,
 
2436
 
        # Delete all clients, and settings from config
 
2437
2005
        while tcp_server.clients:
 
2438
 
            name, client = tcp_server.clients.popitem()
 
 
2006
            client = tcp_server.clients.pop()
 
2440
2008
                client.remove_from_connection()
 
 
2009
            client.disable_hook = None
 
2441
2010
            # Don't signal anything except ClientRemoved
 
2442
2011
            client.disable(quiet=True)
 
2444
2013
                # Emit D-Bus signal
 
2445
 
                mandos_dbus_service.ClientRemoved(client
 
 
2014
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
 
2448
 
        client_settings.clear()
 
2450
2017
    atexit.register(cleanup)
 
2452
 
    for client in tcp_server.clients.itervalues():
 
 
2019
    for client in tcp_server.clients:
 
2454
2021
            # Emit D-Bus signal
 
2455
2022
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
 
2456
 
        # Need to initiate checking of clients
 
2458
 
            client.init_checker()
 
2460
2025
    tcp_server.enable()
 
2461
2026
    tcp_server.server_activate()