/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to mandos

working new feature: network-hooks - Enables user-scripts to take up
                     interfaces during bootup

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008-2012 Teddy Hogeborn
15
 
# Copyright © 2008-2012 Björn Påhlsson
 
14
# Copyright © 2008-2011 Teddy Hogeborn
 
15
# Copyright © 2008-2011 Björn Påhlsson
16
16
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
65
65
import types
66
66
import binascii
67
67
import tempfile
68
 
import itertools
69
68
 
70
69
import dbus
71
70
import dbus.service
86
85
    except ImportError:
87
86
        SO_BINDTODEVICE = None
88
87
 
89
 
version = "1.5.3"
 
88
version = "1.4.1"
90
89
stored_state_file = "clients.pickle"
91
90
 
92
91
logger = logging.getLogger()
111
110
        return interface_index
112
111
 
113
112
 
114
 
def initlogger(debug, level=logging.WARNING):
 
113
def initlogger(level=logging.WARNING):
115
114
    """init logger and add loglevel"""
116
115
    
117
116
    syslogger.setFormatter(logging.Formatter
119
118
                            ' %(message)s'))
120
119
    logger.addHandler(syslogger)
121
120
    
122
 
    if debug:
123
 
        console = logging.StreamHandler()
124
 
        console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
125
 
                                               ' [%(process)d]:'
126
 
                                               ' %(levelname)s:'
127
 
                                               ' %(message)s'))
128
 
        logger.addHandler(console)
 
121
    console = logging.StreamHandler()
 
122
    console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
 
123
                                           ' [%(process)d]:'
 
124
                                           ' %(levelname)s:'
 
125
                                           ' %(message)s'))
 
126
    logger.addHandler(console)
129
127
    logger.setLevel(level)
130
128
 
131
129
 
143
141
        self.gnupg.options.meta_interactive = False
144
142
        self.gnupg.options.homedir = self.tempdir
145
143
        self.gnupg.options.extra_args.extend(['--force-mdc',
146
 
                                              '--quiet',
147
 
                                              '--no-use-agent'])
 
144
                                              '--quiet'])
148
145
    
149
146
    def __enter__(self):
150
147
        return self
176
173
    
177
174
    def encrypt(self, data, password):
178
175
        self.gnupg.passphrase = self.password_encode(password)
179
 
        with open(os.devnull, "w") as devnull:
 
176
        with open(os.devnull) as devnull:
180
177
            try:
181
178
                proc = self.gnupg.run(['--symmetric'],
182
179
                                      create_fhs=['stdin', 'stdout'],
193
190
    
194
191
    def decrypt(self, data, password):
195
192
        self.gnupg.passphrase = self.password_encode(password)
196
 
        with open(os.devnull, "w") as devnull:
 
193
        with open(os.devnull) as devnull:
197
194
            try:
198
195
                proc = self.gnupg.run(['--decrypt'],
199
196
                                      create_fhs=['stdin', 'stdout'],
200
197
                                      attach_fhs={'stderr': devnull})
201
 
                with contextlib.closing(proc.handles['stdin']) as f:
 
198
                with contextlib.closing(proc.handles['stdin'] ) as f:
202
199
                    f.write(data)
203
200
                with contextlib.closing(proc.handles['stdout']) as f:
204
201
                    decrypted_plaintext = f.read()
416
413
    last_checked_ok: datetime.datetime(); (UTC) or None
417
414
    last_checker_status: integer between 0 and 255 reflecting exit
418
415
                         status of last checker. -1 reflects crashed
419
 
                         checker, -2 means no checker completed yet.
 
416
                         checker, or None.
420
417
    last_enabled: datetime.datetime(); (UTC) or None
421
418
    name:       string; from the config file, used in log messages and
422
419
                        D-Bus identifiers
423
420
    secret:     bytestring; sent verbatim (over TLS) to client
424
421
    timeout:    datetime.timedelta(); How long from last_checked_ok
425
422
                                      until this client is disabled
426
 
    extended_timeout:   extra long timeout when secret has been sent
 
423
    extended_timeout:   extra long timeout when password has been sent
427
424
    runtime_expansions: Allowed attributes for runtime expansion.
428
425
    expires:    datetime.datetime(); time (UTC) when a client will be
429
426
                disabled, or None
461
458
 
462
459
    @staticmethod
463
460
    def config_parser(config):
464
 
        """Construct a new dict of client settings of this form:
 
461
        """ Construct a new dict of client settings of this form:
465
462
        { client_name: {setting_name: value, ...}, ...}
466
 
        with exceptions for any special settings as defined above.
467
 
        NOTE: Must be a pure function. Must return the same result
468
 
        value given the same arguments.
469
 
        """
 
463
        with exceptions for any special settings as defined above"""
470
464
        settings = {}
471
465
        for client_name in config.sections():
472
466
            section = dict(config.items(client_name))
476
470
            # Reformat values from string types to Python types
477
471
            client["approved_by_default"] = config.getboolean(
478
472
                client_name, "approved_by_default")
479
 
            client["enabled"] = config.getboolean(client_name,
480
 
                                                  "enabled")
 
473
            client["enabled"] = config.getboolean(client_name, "enabled")
481
474
            
482
475
            client["fingerprint"] = (section["fingerprint"].upper()
483
476
                                     .replace(" ", ""))
502
495
            client["checker_command"] = section["checker"]
503
496
            client["last_approval_request"] = None
504
497
            client["last_checked_ok"] = None
505
 
            client["last_checker_status"] = -2
506
 
        
 
498
            client["last_checker_status"] = None
 
499
            if client["enabled"]:
 
500
                client["last_enabled"] = datetime.datetime.utcnow()
 
501
                client["expires"] = (datetime.datetime.utcnow()
 
502
                                     + client["timeout"])
 
503
            else:
 
504
                client["last_enabled"] = None
 
505
                client["expires"] = None
 
506
 
507
507
        return settings
508
508
        
509
509
        
516
516
        for setting, value in settings.iteritems():
517
517
            setattr(self, setting, value)
518
518
        
519
 
        if self.enabled:
520
 
            if not hasattr(self, "last_enabled"):
521
 
                self.last_enabled = datetime.datetime.utcnow()
522
 
            if not hasattr(self, "expires"):
523
 
                self.expires = (datetime.datetime.utcnow()
524
 
                                + self.timeout)
525
 
        else:
526
 
            self.last_enabled = None
527
 
            self.expires = None
528
 
       
529
519
        logger.debug("Creating client %r", self.name)
530
520
        # Uppercase and remove spaces from fingerprint for later
531
521
        # comparison purposes with return value from the fingerprint()
532
522
        # function
533
523
        logger.debug("  Fingerprint: %s", self.fingerprint)
534
 
        self.created = settings.get("created",
535
 
                                    datetime.datetime.utcnow())
 
524
        self.created = settings.get("created", datetime.datetime.utcnow())
536
525
 
537
526
        # attributes specific for this server instance
538
527
        self.checker = None
627
616
            logger.warning("Checker for %(name)s crashed?",
628
617
                           vars(self))
629
618
    
630
 
    def checked_ok(self):
631
 
        """Assert that the client has been seen, alive and well."""
632
 
        self.last_checked_ok = datetime.datetime.utcnow()
633
 
        self.last_checker_status = 0
634
 
        self.bump_timeout()
635
 
    
636
 
    def bump_timeout(self, timeout=None):
637
 
        """Bump up the timeout for this client."""
 
619
    def checked_ok(self, timeout=None):
 
620
        """Bump up the timeout for this client.
 
621
        
 
622
        This should only be called when the client has been seen,
 
623
        alive and well.
 
624
        """
638
625
        if timeout is None:
639
626
            timeout = self.timeout
 
627
        self.last_checked_ok = datetime.datetime.utcnow()
640
628
        if self.disable_initiator_tag is not None:
641
629
            gobject.source_remove(self.disable_initiator_tag)
642
630
        if getattr(self, "enabled", False):
732
720
            return
733
721
        logger.debug("Stopping checker for %(name)s", vars(self))
734
722
        try:
735
 
            self.checker.terminate()
 
723
            os.kill(self.checker.pid, signal.SIGTERM)
736
724
            #time.sleep(0.5)
737
725
            #if self.checker.poll() is None:
738
 
            #    self.checker.kill()
 
726
            #    os.kill(self.checker.pid, signal.SIGKILL)
739
727
        except OSError as error:
740
728
            if error.errno != errno.ESRCH: # No such process
741
729
                raise
772
760
    return decorator
773
761
 
774
762
 
775
 
def dbus_interface_annotations(dbus_interface):
776
 
    """Decorator for marking functions returning interface annotations.
777
 
    
778
 
    Usage:
779
 
    
780
 
    @dbus_interface_annotations("org.example.Interface")
781
 
    def _foo(self):  # Function name does not matter
782
 
        return {"org.freedesktop.DBus.Deprecated": "true",
783
 
                "org.freedesktop.DBus.Property.EmitsChangedSignal":
784
 
                    "false"}
785
 
    """
786
 
    def decorator(func):
787
 
        func._dbus_is_interface = True
788
 
        func._dbus_interface = dbus_interface
789
 
        func._dbus_name = dbus_interface
790
 
        return func
791
 
    return decorator
792
 
 
793
 
 
794
 
def dbus_annotations(annotations):
795
 
    """Decorator to annotate D-Bus methods, signals or properties
796
 
    Usage:
797
 
    
798
 
    @dbus_service_property("org.example.Interface", signature="b",
799
 
                           access="r")
800
 
    @dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
801
 
                        "org.freedesktop.DBus.Property."
802
 
                        "EmitsChangedSignal": "false"})
803
 
    def Property_dbus_property(self):
804
 
        return dbus.Boolean(False)
805
 
    """
806
 
    def decorator(func):
807
 
        func._dbus_annotations = annotations
808
 
        return func
809
 
    return decorator
810
 
 
811
 
 
812
763
class DBusPropertyException(dbus.exceptions.DBusException):
813
764
    """A base class for D-Bus property-related exceptions
814
765
    """
837
788
    """
838
789
    
839
790
    @staticmethod
840
 
    def _is_dbus_thing(thing):
841
 
        """Returns a function testing if an attribute is a D-Bus thing
842
 
        
843
 
        If called like _is_dbus_thing("method") it returns a function
844
 
        suitable for use as predicate to inspect.getmembers().
845
 
        """
846
 
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
847
 
                                   False)
 
791
    def _is_dbus_property(obj):
 
792
        return getattr(obj, "_dbus_is_property", False)
848
793
    
849
 
    def _get_all_dbus_things(self, thing):
 
794
    def _get_all_dbus_properties(self):
850
795
        """Returns a generator of (name, attribute) pairs
851
796
        """
852
 
        return ((getattr(athing.__get__(self), "_dbus_name",
853
 
                         name),
854
 
                 athing.__get__(self))
 
797
        return ((prop.__get__(self)._dbus_name, prop.__get__(self))
855
798
                for cls in self.__class__.__mro__
856
 
                for name, athing in
857
 
                inspect.getmembers(cls,
858
 
                                   self._is_dbus_thing(thing)))
 
799
                for name, prop in
 
800
                inspect.getmembers(cls, self._is_dbus_property))
859
801
    
860
802
    def _get_dbus_property(self, interface_name, property_name):
861
803
        """Returns a bound method if one exists which is a D-Bus
863
805
        """
864
806
        for cls in  self.__class__.__mro__:
865
807
            for name, value in (inspect.getmembers
866
 
                                (cls,
867
 
                                 self._is_dbus_thing("property"))):
 
808
                                (cls, self._is_dbus_property)):
868
809
                if (value._dbus_name == property_name
869
810
                    and value._dbus_interface == interface_name):
870
811
                    return value.__get__(self)
899
840
            # signatures other than "ay".
900
841
            if prop._dbus_signature != "ay":
901
842
                raise ValueError
902
 
            value = dbus.ByteArray(b''.join(chr(byte)
903
 
                                            for byte in value))
 
843
            value = dbus.ByteArray(''.join(unichr(byte)
 
844
                                           for byte in value))
904
845
        prop(value)
905
846
    
906
847
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
912
853
        Note: Will not include properties with access="write".
913
854
        """
914
855
        properties = {}
915
 
        for name, prop in self._get_all_dbus_things("property"):
 
856
        for name, prop in self._get_all_dbus_properties():
916
857
            if (interface_name
917
858
                and interface_name != prop._dbus_interface):
918
859
                # Interface non-empty but did not match
933
874
                         path_keyword='object_path',
934
875
                         connection_keyword='connection')
935
876
    def Introspect(self, object_path, connection):
936
 
        """Overloading of standard D-Bus method.
937
 
        
938
 
        Inserts property tags and interface annotation tags.
 
877
        """Standard D-Bus method, overloaded to insert property tags.
939
878
        """
940
879
        xmlstring = dbus.service.Object.Introspect(self, object_path,
941
880
                                                   connection)
948
887
                e.setAttribute("access", prop._dbus_access)
949
888
                return e
950
889
            for if_tag in document.getElementsByTagName("interface"):
951
 
                # Add property tags
952
890
                for tag in (make_tag(document, name, prop)
953
891
                            for name, prop
954
 
                            in self._get_all_dbus_things("property")
 
892
                            in self._get_all_dbus_properties()
955
893
                            if prop._dbus_interface
956
894
                            == if_tag.getAttribute("name")):
957
895
                    if_tag.appendChild(tag)
958
 
                # Add annotation tags
959
 
                for typ in ("method", "signal", "property"):
960
 
                    for tag in if_tag.getElementsByTagName(typ):
961
 
                        annots = dict()
962
 
                        for name, prop in (self.
963
 
                                           _get_all_dbus_things(typ)):
964
 
                            if (name == tag.getAttribute("name")
965
 
                                and prop._dbus_interface
966
 
                                == if_tag.getAttribute("name")):
967
 
                                annots.update(getattr
968
 
                                              (prop,
969
 
                                               "_dbus_annotations",
970
 
                                               {}))
971
 
                        for name, value in annots.iteritems():
972
 
                            ann_tag = document.createElement(
973
 
                                "annotation")
974
 
                            ann_tag.setAttribute("name", name)
975
 
                            ann_tag.setAttribute("value", value)
976
 
                            tag.appendChild(ann_tag)
977
 
                # Add interface annotation tags
978
 
                for annotation, value in dict(
979
 
                    itertools.chain(
980
 
                        *(annotations().iteritems()
981
 
                          for name, annotations in
982
 
                          self._get_all_dbus_things("interface")
983
 
                          if name == if_tag.getAttribute("name")
984
 
                          ))).iteritems():
985
 
                    ann_tag = document.createElement("annotation")
986
 
                    ann_tag.setAttribute("name", annotation)
987
 
                    ann_tag.setAttribute("value", value)
988
 
                    if_tag.appendChild(ann_tag)
989
896
                # Add the names to the return values for the
990
897
                # "org.freedesktop.DBus.Properties" methods
991
898
                if (if_tag.getAttribute("name")
1026
933
    def __new__(mcs, name, bases, attr):
1027
934
        # Go through all the base classes which could have D-Bus
1028
935
        # methods, signals, or properties in them
1029
 
        old_interface_names = []
1030
936
        for base in (b for b in bases
1031
937
                     if issubclass(b, dbus.service.Object)):
1032
938
            # Go though all attributes of the base class
1042
948
                alt_interface = (attribute._dbus_interface
1043
949
                                 .replace("se.recompile.Mandos",
1044
950
                                          "se.bsnet.fukt.Mandos"))
1045
 
                if alt_interface != attribute._dbus_interface:
1046
 
                    old_interface_names.append(alt_interface)
1047
951
                # Is this a D-Bus signal?
1048
952
                if getattr(attribute, "_dbus_is_signal", False):
1049
953
                    # Extract the original non-method function by
1064
968
                                nonmethod_func.func_name,
1065
969
                                nonmethod_func.func_defaults,
1066
970
                                nonmethod_func.func_closure)))
1067
 
                    # Copy annotations, if any
1068
 
                    try:
1069
 
                        new_function._dbus_annotations = (
1070
 
                            dict(attribute._dbus_annotations))
1071
 
                    except AttributeError:
1072
 
                        pass
1073
971
                    # Define a creator of a function to call both the
1074
972
                    # old and new functions, so both the old and new
1075
973
                    # signals gets sent when the function is called
1103
1001
                                        attribute.func_name,
1104
1002
                                        attribute.func_defaults,
1105
1003
                                        attribute.func_closure)))
1106
 
                    # Copy annotations, if any
1107
 
                    try:
1108
 
                        attr[attrname]._dbus_annotations = (
1109
 
                            dict(attribute._dbus_annotations))
1110
 
                    except AttributeError:
1111
 
                        pass
1112
1004
                # Is this a D-Bus property?
1113
1005
                elif getattr(attribute, "_dbus_is_property", False):
1114
1006
                    # Create a new, but exactly alike, function
1128
1020
                                        attribute.func_name,
1129
1021
                                        attribute.func_defaults,
1130
1022
                                        attribute.func_closure)))
1131
 
                    # Copy annotations, if any
1132
 
                    try:
1133
 
                        attr[attrname]._dbus_annotations = (
1134
 
                            dict(attribute._dbus_annotations))
1135
 
                    except AttributeError:
1136
 
                        pass
1137
 
                # Is this a D-Bus interface?
1138
 
                elif getattr(attribute, "_dbus_is_interface", False):
1139
 
                    # Create a new, but exactly alike, function
1140
 
                    # object.  Decorate it to be a new D-Bus interface
1141
 
                    # with the alternate D-Bus interface name.  Add it
1142
 
                    # to the class.
1143
 
                    attr[attrname] = (dbus_interface_annotations
1144
 
                                      (alt_interface)
1145
 
                                      (types.FunctionType
1146
 
                                       (attribute.func_code,
1147
 
                                        attribute.func_globals,
1148
 
                                        attribute.func_name,
1149
 
                                        attribute.func_defaults,
1150
 
                                        attribute.func_closure)))
1151
 
        # Deprecate all old interfaces
1152
 
        basename="_AlternateDBusNamesMetaclass_interface_annotation{0}"
1153
 
        for old_interface_name in old_interface_names:
1154
 
            @dbus_interface_annotations(old_interface_name)
1155
 
            def func(self):
1156
 
                return { "org.freedesktop.DBus.Deprecated": "true" }
1157
 
            # Find an unused name
1158
 
            for aname in (basename.format(i) for i in
1159
 
                          itertools.count()):
1160
 
                if aname not in attr:
1161
 
                    attr[aname] = func
1162
 
                    break
1163
1023
        return type.__new__(mcs, name, bases, attr)
1164
1024
 
1165
1025
 
1179
1039
    def __init__(self, bus = None, *args, **kwargs):
1180
1040
        self.bus = bus
1181
1041
        Client.__init__(self, *args, **kwargs)
 
1042
        self._approvals_pending = 0
 
1043
        
 
1044
        self._approvals_pending = 0
1182
1045
        # Only now, when this client is initialized, can it show up on
1183
1046
        # the D-Bus
1184
1047
        client_object_name = unicode(self.name).translate(
1230
1093
                                       checker is not None)
1231
1094
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1232
1095
                                           "LastCheckedOK")
1233
 
    last_checker_status = notifychangeproperty(dbus.Int16,
1234
 
                                               "LastCheckerStatus")
1235
1096
    last_approval_request = notifychangeproperty(
1236
1097
        datetime_to_dbus, "LastApprovalRequest")
1237
1098
    approved_by_default = notifychangeproperty(dbus.Boolean,
1315
1176
    ## D-Bus methods, signals & properties
1316
1177
    _interface = "se.recompile.Mandos.Client"
1317
1178
    
1318
 
    ## Interfaces
1319
 
    
1320
 
    @dbus_interface_annotations(_interface)
1321
 
    def _foo(self):
1322
 
        return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
1323
 
                     "false"}
1324
 
    
1325
1179
    ## Signals
1326
1180
    
1327
1181
    # CheckerCompleted - signal
1363
1217
        "D-Bus signal"
1364
1218
        return self.need_approval()
1365
1219
    
 
1220
    # NeRwequest - signal
 
1221
    @dbus.service.signal(_interface, signature="s")
 
1222
    def NewRequest(self, ip):
 
1223
        """D-Bus signal
 
1224
        Is sent after a client request a password.
 
1225
        """
 
1226
        pass
 
1227
    
1366
1228
    ## Methods
1367
1229
    
1368
1230
    # Approve - method
1478
1340
            return
1479
1341
        return datetime_to_dbus(self.last_checked_ok)
1480
1342
    
1481
 
    # LastCheckerStatus - property
1482
 
    @dbus_service_property(_interface, signature="n",
1483
 
                           access="read")
1484
 
    def LastCheckerStatus_dbus_property(self):
1485
 
        return dbus.Int16(self.last_checker_status)
1486
 
    
1487
1343
    # Expires - property
1488
1344
    @dbus_service_property(_interface, signature="s", access="read")
1489
1345
    def Expires_dbus_property(self):
1501
1357
        if value is None:       # get
1502
1358
            return dbus.UInt64(self.timeout_milliseconds())
1503
1359
        self.timeout = datetime.timedelta(0, 0, 0, value)
 
1360
        if getattr(self, "disable_initiator_tag", None) is None:
 
1361
            return
1504
1362
        # Reschedule timeout
1505
 
        if self.enabled:
1506
 
            now = datetime.datetime.utcnow()
1507
 
            time_to_die = timedelta_to_milliseconds(
1508
 
                (self.last_checked_ok + self.timeout) - now)
1509
 
            if time_to_die <= 0:
1510
 
                # The timeout has passed
1511
 
                self.disable()
1512
 
            else:
1513
 
                self.expires = (now +
1514
 
                                datetime.timedelta(milliseconds =
1515
 
                                                   time_to_die))
1516
 
                if (getattr(self, "disable_initiator_tag", None)
1517
 
                    is None):
1518
 
                    return
1519
 
                gobject.source_remove(self.disable_initiator_tag)
1520
 
                self.disable_initiator_tag = (gobject.timeout_add
1521
 
                                              (time_to_die,
1522
 
                                               self.disable))
 
1363
        gobject.source_remove(self.disable_initiator_tag)
 
1364
        self.disable_initiator_tag = None
 
1365
        self.expires = None
 
1366
        time_to_die = timedelta_to_milliseconds((self
 
1367
                                                 .last_checked_ok
 
1368
                                                 + self.timeout)
 
1369
                                                - datetime.datetime
 
1370
                                                .utcnow())
 
1371
        if time_to_die <= 0:
 
1372
            # The timeout has passed
 
1373
            self.disable()
 
1374
        else:
 
1375
            self.expires = (datetime.datetime.utcnow()
 
1376
                            + datetime.timedelta(milliseconds =
 
1377
                                                 time_to_die))
 
1378
            self.disable_initiator_tag = (gobject.timeout_add
 
1379
                                          (time_to_die, self.disable))
1523
1380
    
1524
1381
    # ExtendedTimeout - property
1525
1382
    @dbus_service_property(_interface, signature="t",
1681
1538
                except KeyError:
1682
1539
                    return
1683
1540
                
 
1541
                if self.server.use_dbus:
 
1542
                    # Emit D-Bus signal
 
1543
                    client.NewRequest(str(self.client_address))
 
1544
                
1684
1545
                if client.approval_delay:
1685
1546
                    delay = client.approval_delay
1686
1547
                    client.approvals_pending += 1
1750
1611
                
1751
1612
                logger.info("Sending secret to %s", client.name)
1752
1613
                # bump the timeout using extended_timeout
1753
 
                client.bump_timeout(client.extended_timeout)
 
1614
                client.checked_ok(client.extended_timeout)
1754
1615
                if self.server.use_dbus:
1755
1616
                    # Emit D-Bus signal
1756
1617
                    client.GotSecret()
2099
1960
        sys.exit()
2100
1961
    if not noclose:
2101
1962
        # Close all standard open file descriptors
2102
 
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
 
1963
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
2103
1964
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2104
1965
            raise OSError(errno.ENODEV,
2105
1966
                          "%s not a character device"
2106
 
                          % os.devnull)
 
1967
                          % os.path.devnull)
2107
1968
        os.dup2(null, sys.stdin.fileno())
2108
1969
        os.dup2(null, sys.stdout.fileno())
2109
1970
        os.dup2(null, sys.stderr.fileno())
2217
2078
                                     stored_state_file)
2218
2079
    
2219
2080
    if debug:
2220
 
        initlogger(debug, logging.DEBUG)
 
2081
        initlogger(logging.DEBUG)
2221
2082
    else:
2222
2083
        if not debuglevel:
2223
 
            initlogger(debug)
 
2084
            initlogger()
2224
2085
        else:
2225
2086
            level = getattr(logging, debuglevel.upper())
2226
 
            initlogger(debug, level)
 
2087
            initlogger(level)
2227
2088
    
2228
2089
    if server_settings["servicename"] != "Mandos":
2229
2090
        syslogger.setFormatter(logging.Formatter
2232
2093
                                % server_settings["servicename"]))
2233
2094
    
2234
2095
    # Parse config file with clients
2235
 
    client_config = configparser.SafeConfigParser(Client
2236
 
                                                  .client_defaults)
 
2096
    client_config = configparser.SafeConfigParser(Client.client_defaults)
2237
2097
    client_config.read(os.path.join(server_settings["configdir"],
2238
2098
                                    "clients.conf"))
2239
2099
    
2292
2152
         .gnutls_global_set_log_function(debug_gnutls))
2293
2153
        
2294
2154
        # Redirect stdin so all checkers get /dev/null
2295
 
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
 
2155
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
2296
2156
        os.dup2(null, sys.stdin.fileno())
2297
2157
        if null > 2:
2298
2158
            os.close(null)
 
2159
    else:
 
2160
        # No console logging
 
2161
        logger.removeHandler(console)
2299
2162
    
2300
2163
    # Need to fork before connecting to D-Bus
2301
2164
    if not debug:
2302
2165
        # Close all input and output, do double fork, etc.
2303
2166
        daemon()
2304
2167
    
2305
 
    gobject.threads_init()
2306
 
    
2307
2168
    global main_loop
2308
2169
    # From the Avahi example code
2309
 
    DBusGMainLoop(set_as_default=True)
 
2170
    DBusGMainLoop(set_as_default=True )
2310
2171
    main_loop = gobject.MainLoop()
2311
2172
    bus = dbus.SystemBus()
2312
2173
    # End of Avahi example code
2355
2216
                           .format(e))
2356
2217
            if e.errno != errno.ENOENT:
2357
2218
                raise
2358
 
        except EOFError as e:
2359
 
            logger.warning("Could not load persistent state: "
2360
 
                           "EOFError: {0}".format(e))
2361
2219
    
2362
2220
    with PGPEngine() as pgp:
2363
2221
        for client_name, client in clients_data.iteritems():
2380
2238
            
2381
2239
            # Clients who has passed its expire date can still be
2382
2240
            # enabled if its last checker was successful.  Clients
2383
 
            # whose checker succeeded before we stored its state is
2384
 
            # assumed to have successfully run all checkers during
2385
 
            # downtime.
 
2241
            # whose checker failed before we stored its state is
 
2242
            # assumed to have failed all checkers during downtime.
2386
2243
            if client["enabled"]:
2387
2244
                if datetime.datetime.utcnow() >= client["expires"]:
2388
2245
                    if not client["last_checked_ok"]:
2389
2246
                        logger.warning(
2390
2247
                            "disabling client {0} - Client never "
2391
 
                            "performed a successful checker"
2392
 
                            .format(client_name))
 
2248
                            "performed a successfull checker"
 
2249
                            .format(client["name"]))
2393
2250
                        client["enabled"] = False
2394
2251
                    elif client["last_checker_status"] != 0:
2395
2252
                        logger.warning(
2396
2253
                            "disabling client {0} - Client "
2397
2254
                            "last checker failed with error code {1}"
2398
 
                            .format(client_name,
 
2255
                            .format(client["name"],
2399
2256
                                    client["last_checker_status"]))
2400
2257
                        client["enabled"] = False
2401
2258
                    else:
2402
2259
                        client["expires"] = (datetime.datetime
2403
2260
                                             .utcnow()
2404
2261
                                             + client["timeout"])
2405
 
                        logger.debug("Last checker succeeded,"
2406
 
                                     " keeping {0} enabled"
2407
 
                                     .format(client_name))
 
2262
                    
2408
2263
            try:
2409
2264
                client["secret"] = (
2410
2265
                    pgp.decrypt(client["encrypted_secret"],
2419
2274
 
2420
2275
    
2421
2276
    # Add/remove clients based on new changes made to config
2422
 
    for client_name in (set(old_client_settings)
2423
 
                        - set(client_settings)):
 
2277
    for client_name in set(old_client_settings) - set(client_settings):
2424
2278
        del clients_data[client_name]
2425
 
    for client_name in (set(client_settings)
2426
 
                        - set(old_client_settings)):
 
2279
    for client_name in set(client_settings) - set(old_client_settings):
2427
2280
        clients_data[client_name] = client_settings[client_name]
2428
2281
 
2429
 
    # Create all client objects
 
2282
    # Create clients all clients
2430
2283
    for client_name, client in clients_data.iteritems():
2431
2284
        tcp_server.clients[client_name] = client_class(
2432
2285
            name = client_name, settings = client)
2453
2306
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2454
2307
    
2455
2308
    if use_dbus:
2456
 
        class MandosDBusService(DBusObjectWithProperties):
 
2309
        class MandosDBusService(dbus.service.Object):
2457
2310
            """A D-Bus proxy object"""
2458
2311
            def __init__(self):
2459
2312
                dbus.service.Object.__init__(self, bus, "/")
2460
2313
            _interface = "se.recompile.Mandos"
2461
2314
            
2462
 
            @dbus_interface_annotations(_interface)
2463
 
            def _foo(self):
2464
 
                return { "org.freedesktop.DBus.Property"
2465
 
                         ".EmitsChangedSignal":
2466
 
                             "false"}
2467
 
            
2468
2315
            @dbus.service.signal(_interface, signature="o")
2469
2316
            def ClientAdded(self, objpath):
2470
2317
                "D-Bus signal"
2553
2400
                del client_settings[client.name]["secret"]
2554
2401
        
2555
2402
        try:
2556
 
            tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2557
 
                                                prefix="clients-",
2558
 
                                                dir=os.path.dirname
2559
 
                                                (stored_state_path))
2560
 
            with os.fdopen(tempfd, "wb") as stored_state:
 
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:
2561
2406
                pickle.dump((clients, client_settings), stored_state)
2562
 
            os.rename(tempname, stored_state_path)
2563
2407
        except (IOError, OSError) as e:
2564
2408
            logger.warning("Could not save persistent state: {0}"
2565
2409
                           .format(e))
2566
 
            if not debug:
2567
 
                try:
2568
 
                    os.remove(tempname)
2569
 
                except NameError:
2570
 
                    pass
2571
 
            if e.errno not in set((errno.ENOENT, errno.EACCES,
2572
 
                                   errno.EEXIST)):
2573
 
                raise e
 
2410
            if e.errno not in (errno.ENOENT, errno.EACCES):
 
2411
                raise
2574
2412
        
2575
2413
        # Delete all clients, and settings from config
2576
2414
        while tcp_server.clients: