/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

  • Committer: teddy at recompile
  • Date: 2011-12-27 14:15:40 UTC
  • Revision ID: teddy@recompile.se-20111227141540-ajrabf33q59jfa7t
Reorder TODO entries

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()
143
142
        self.gnupg.options.meta_interactive = False
144
143
        self.gnupg.options.homedir = self.tempdir
145
144
        self.gnupg.options.extra_args.extend(['--force-mdc',
146
 
                                              '--quiet',
147
 
                                              '--no-use-agent'])
 
145
                                              '--quiet'])
148
146
    
149
147
    def __enter__(self):
150
148
        return self
176
174
    
177
175
    def encrypt(self, data, password):
178
176
        self.gnupg.passphrase = self.password_encode(password)
179
 
        with open(os.devnull, "w") as devnull:
 
177
        with open(os.devnull) as devnull:
180
178
            try:
181
179
                proc = self.gnupg.run(['--symmetric'],
182
180
                                      create_fhs=['stdin', 'stdout'],
193
191
    
194
192
    def decrypt(self, data, password):
195
193
        self.gnupg.passphrase = self.password_encode(password)
196
 
        with open(os.devnull, "w") as devnull:
 
194
        with open(os.devnull) as devnull:
197
195
            try:
198
196
                proc = self.gnupg.run(['--decrypt'],
199
197
                                      create_fhs=['stdin', 'stdout'],
200
198
                                      attach_fhs={'stderr': devnull})
201
 
                with contextlib.closing(proc.handles['stdin']) as f:
 
199
                with contextlib.closing(proc.handles['stdin'] ) as f:
202
200
                    f.write(data)
203
201
                with contextlib.closing(proc.handles['stdout']) as f:
204
202
                    decrypted_plaintext = f.read()
277
275
        try:
278
276
            self.add()
279
277
        except dbus.exceptions.DBusException as error:
280
 
            logger.critical("D-Bus Exception", exc_info=error)
 
278
            logger.critical("DBusException: %s", error)
281
279
            self.cleanup()
282
280
            os._exit(1)
283
281
        self.rename_count += 1
322
320
        elif state == avahi.ENTRY_GROUP_FAILURE:
323
321
            logger.critical("Avahi: Error in group state changed %s",
324
322
                            unicode(error))
325
 
            raise AvahiGroupError("State changed: {0!s}"
326
 
                                  .format(error))
 
323
            raise AvahiGroupError("State changed: %s"
 
324
                                  % unicode(error))
327
325
    def cleanup(self):
328
326
        """Derived from the Avahi example code"""
329
327
        if self.group is not None:
375
373
        """Add the new name to the syslog messages"""
376
374
        ret = AvahiService.rename(self)
377
375
        syslogger.setFormatter(logging.Formatter
378
 
                               ('Mandos ({0}) [%(process)d]:'
379
 
                                ' %(levelname)s: %(message)s'
380
 
                                .format(self.name)))
 
376
                               ('Mandos (%s) [%%(process)d]:'
 
377
                                ' %%(levelname)s: %%(message)s'
 
378
                                % self.name))
381
379
        return ret
382
380
 
383
381
def timedelta_to_milliseconds(td):
416
414
    last_checked_ok: datetime.datetime(); (UTC) or None
417
415
    last_checker_status: integer between 0 and 255 reflecting exit
418
416
                         status of last checker. -1 reflects crashed
419
 
                         checker, -2 means no checker completed yet.
 
417
                         checker, or None.
420
418
    last_enabled: datetime.datetime(); (UTC) or None
421
419
    name:       string; from the config file, used in log messages and
422
420
                        D-Bus identifiers
423
421
    secret:     bytestring; sent verbatim (over TLS) to client
424
422
    timeout:    datetime.timedelta(); How long from last_checked_ok
425
423
                                      until this client is disabled
426
 
    extended_timeout:   extra long timeout when secret has been sent
 
424
    extended_timeout:   extra long timeout when password has been sent
427
425
    runtime_expansions: Allowed attributes for runtime expansion.
428
426
    expires:    datetime.datetime(); time (UTC) when a client will be
429
427
                disabled, or None
461
459
 
462
460
    @staticmethod
463
461
    def config_parser(config):
464
 
        """Construct a new dict of client settings of this form:
 
462
        """ Construct a new dict of client settings of this form:
465
463
        { 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
 
        """
 
464
        with exceptions for any special settings as defined above"""
470
465
        settings = {}
471
466
        for client_name in config.sections():
472
467
            section = dict(config.items(client_name))
476
471
            # Reformat values from string types to Python types
477
472
            client["approved_by_default"] = config.getboolean(
478
473
                client_name, "approved_by_default")
479
 
            client["enabled"] = config.getboolean(client_name,
480
 
                                                  "enabled")
 
474
            client["enabled"] = config.getboolean(client_name, "enabled")
481
475
            
482
476
            client["fingerprint"] = (section["fingerprint"].upper()
483
477
                                     .replace(" ", ""))
489
483
                          "rb") as secfile:
490
484
                    client["secret"] = secfile.read()
491
485
            else:
492
 
                raise TypeError("No secret or secfile for section {0}"
493
 
                                .format(section))
 
486
                raise TypeError("No secret or secfile for section %s"
 
487
                                % section)
494
488
            client["timeout"] = string_to_delta(section["timeout"])
495
489
            client["extended_timeout"] = string_to_delta(
496
490
                section["extended_timeout"])
502
496
            client["checker_command"] = section["checker"]
503
497
            client["last_approval_request"] = None
504
498
            client["last_checked_ok"] = None
505
 
            client["last_checker_status"] = -2
506
 
        
 
499
            client["last_checker_status"] = None
 
500
            if client["enabled"]:
 
501
                client["last_enabled"] = datetime.datetime.utcnow()
 
502
                client["expires"] = (datetime.datetime.utcnow()
 
503
                                     + client["timeout"])
 
504
            else:
 
505
                client["last_enabled"] = None
 
506
                client["expires"] = None
 
507
 
507
508
        return settings
508
509
        
509
510
        
516
517
        for setting, value in settings.iteritems():
517
518
            setattr(self, setting, value)
518
519
        
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
520
        logger.debug("Creating client %r", self.name)
530
521
        # Uppercase and remove spaces from fingerprint for later
531
522
        # comparison purposes with return value from the fingerprint()
532
523
        # function
533
524
        logger.debug("  Fingerprint: %s", self.fingerprint)
534
 
        self.created = settings.get("created",
535
 
                                    datetime.datetime.utcnow())
 
525
        self.created = settings.get("created", datetime.datetime.utcnow())
536
526
 
537
527
        # attributes specific for this server instance
538
528
        self.checker = None
627
617
            logger.warning("Checker for %(name)s crashed?",
628
618
                           vars(self))
629
619
    
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."""
 
620
    def checked_ok(self, timeout=None):
 
621
        """Bump up the timeout for this client.
 
622
        
 
623
        This should only be called when the client has been seen,
 
624
        alive and well.
 
625
        """
638
626
        if timeout is None:
639
627
            timeout = self.timeout
 
628
        self.last_checked_ok = datetime.datetime.utcnow()
640
629
        if self.disable_initiator_tag is not None:
641
630
            gobject.source_remove(self.disable_initiator_tag)
642
631
        if getattr(self, "enabled", False):
693
682
                try:
694
683
                    command = self.checker_command % escaped_attrs
695
684
                except TypeError as error:
696
 
                    logger.error('Could not format string "%s"',
697
 
                                 self.checker_command, exc_info=error)
 
685
                    logger.error('Could not format string "%s":'
 
686
                                 ' %s', self.checker_command, error)
698
687
                    return True # Try again later
699
688
            self.current_checker_command = command
700
689
            try:
718
707
                    gobject.source_remove(self.checker_callback_tag)
719
708
                    self.checker_callback(pid, status, command)
720
709
            except OSError as error:
721
 
                logger.error("Failed to start subprocess",
722
 
                             exc_info=error)
 
710
                logger.error("Failed to start subprocess: %s",
 
711
                             error)
723
712
        # Re-run this periodically if run by gobject.timeout_add
724
713
        return True
725
714
    
732
721
            return
733
722
        logger.debug("Stopping checker for %(name)s", vars(self))
734
723
        try:
735
 
            self.checker.terminate()
 
724
            os.kill(self.checker.pid, signal.SIGTERM)
736
725
            #time.sleep(0.5)
737
726
            #if self.checker.poll() is None:
738
 
            #    self.checker.kill()
 
727
            #    os.kill(self.checker.pid, signal.SIGKILL)
739
728
        except OSError as error:
740
729
            if error.errno != errno.ESRCH: # No such process
741
730
                raise
758
747
    # "Set" method, so we fail early here:
759
748
    if byte_arrays and signature != "ay":
760
749
        raise ValueError("Byte arrays not supported for non-'ay'"
761
 
                         " signature {0!r}".format(signature))
 
750
                         " signature %r" % signature)
762
751
    def decorator(func):
763
752
        func._dbus_is_property = True
764
753
        func._dbus_interface = dbus_interface
772
761
    return decorator
773
762
 
774
763
 
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
764
class DBusPropertyException(dbus.exceptions.DBusException):
813
765
    """A base class for D-Bus property-related exceptions
814
766
    """
837
789
    """
838
790
    
839
791
    @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)
 
792
    def _is_dbus_property(obj):
 
793
        return getattr(obj, "_dbus_is_property", False)
848
794
    
849
 
    def _get_all_dbus_things(self, thing):
 
795
    def _get_all_dbus_properties(self):
850
796
        """Returns a generator of (name, attribute) pairs
851
797
        """
852
 
        return ((getattr(athing.__get__(self), "_dbus_name",
853
 
                         name),
854
 
                 athing.__get__(self))
 
798
        return ((prop.__get__(self)._dbus_name, prop.__get__(self))
855
799
                for cls in self.__class__.__mro__
856
 
                for name, athing in
857
 
                inspect.getmembers(cls,
858
 
                                   self._is_dbus_thing(thing)))
 
800
                for name, prop in
 
801
                inspect.getmembers(cls, self._is_dbus_property))
859
802
    
860
803
    def _get_dbus_property(self, interface_name, property_name):
861
804
        """Returns a bound method if one exists which is a D-Bus
863
806
        """
864
807
        for cls in  self.__class__.__mro__:
865
808
            for name, value in (inspect.getmembers
866
 
                                (cls,
867
 
                                 self._is_dbus_thing("property"))):
 
809
                                (cls, self._is_dbus_property)):
868
810
                if (value._dbus_name == property_name
869
811
                    and value._dbus_interface == interface_name):
870
812
                    return value.__get__(self)
899
841
            # signatures other than "ay".
900
842
            if prop._dbus_signature != "ay":
901
843
                raise ValueError
902
 
            value = dbus.ByteArray(b''.join(chr(byte)
903
 
                                            for byte in value))
 
844
            value = dbus.ByteArray(''.join(unichr(byte)
 
845
                                           for byte in value))
904
846
        prop(value)
905
847
    
906
848
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
912
854
        Note: Will not include properties with access="write".
913
855
        """
914
856
        properties = {}
915
 
        for name, prop in self._get_all_dbus_things("property"):
 
857
        for name, prop in self._get_all_dbus_properties():
916
858
            if (interface_name
917
859
                and interface_name != prop._dbus_interface):
918
860
                # Interface non-empty but did not match
933
875
                         path_keyword='object_path',
934
876
                         connection_keyword='connection')
935
877
    def Introspect(self, object_path, connection):
936
 
        """Overloading of standard D-Bus method.
937
 
        
938
 
        Inserts property tags and interface annotation tags.
 
878
        """Standard D-Bus method, overloaded to insert property tags.
939
879
        """
940
880
        xmlstring = dbus.service.Object.Introspect(self, object_path,
941
881
                                                   connection)
948
888
                e.setAttribute("access", prop._dbus_access)
949
889
                return e
950
890
            for if_tag in document.getElementsByTagName("interface"):
951
 
                # Add property tags
952
891
                for tag in (make_tag(document, name, prop)
953
892
                            for name, prop
954
 
                            in self._get_all_dbus_things("property")
 
893
                            in self._get_all_dbus_properties()
955
894
                            if prop._dbus_interface
956
895
                            == if_tag.getAttribute("name")):
957
896
                    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
897
                # Add the names to the return values for the
990
898
                # "org.freedesktop.DBus.Properties" methods
991
899
                if (if_tag.getAttribute("name")
1006
914
        except (AttributeError, xml.dom.DOMException,
1007
915
                xml.parsers.expat.ExpatError) as error:
1008
916
            logger.error("Failed to override Introspection method",
1009
 
                         exc_info=error)
 
917
                         error)
1010
918
        return xmlstring
1011
919
 
1012
920
 
1026
934
    def __new__(mcs, name, bases, attr):
1027
935
        # Go through all the base classes which could have D-Bus
1028
936
        # methods, signals, or properties in them
1029
 
        old_interface_names = []
1030
937
        for base in (b for b in bases
1031
938
                     if issubclass(b, dbus.service.Object)):
1032
939
            # Go though all attributes of the base class
1042
949
                alt_interface = (attribute._dbus_interface
1043
950
                                 .replace("se.recompile.Mandos",
1044
951
                                          "se.bsnet.fukt.Mandos"))
1045
 
                if alt_interface != attribute._dbus_interface:
1046
 
                    old_interface_names.append(alt_interface)
1047
952
                # Is this a D-Bus signal?
1048
953
                if getattr(attribute, "_dbus_is_signal", False):
1049
954
                    # Extract the original non-method function by
1064
969
                                nonmethod_func.func_name,
1065
970
                                nonmethod_func.func_defaults,
1066
971
                                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
972
                    # Define a creator of a function to call both the
1074
973
                    # old and new functions, so both the old and new
1075
974
                    # signals gets sent when the function is called
1103
1002
                                        attribute.func_name,
1104
1003
                                        attribute.func_defaults,
1105
1004
                                        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
1005
                # Is this a D-Bus property?
1113
1006
                elif getattr(attribute, "_dbus_is_property", False):
1114
1007
                    # Create a new, but exactly alike, function
1128
1021
                                        attribute.func_name,
1129
1022
                                        attribute.func_defaults,
1130
1023
                                        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
1024
        return type.__new__(mcs, name, bases, attr)
1164
1025
 
1165
1026
 
1179
1040
    def __init__(self, bus = None, *args, **kwargs):
1180
1041
        self.bus = bus
1181
1042
        Client.__init__(self, *args, **kwargs)
 
1043
        self._approvals_pending = 0
 
1044
        
 
1045
        self._approvals_pending = 0
1182
1046
        # Only now, when this client is initialized, can it show up on
1183
1047
        # the D-Bus
1184
1048
        client_object_name = unicode(self.name).translate(
1230
1094
                                       checker is not None)
1231
1095
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1232
1096
                                           "LastCheckedOK")
1233
 
    last_checker_status = notifychangeproperty(dbus.Int16,
1234
 
                                               "LastCheckerStatus")
1235
1097
    last_approval_request = notifychangeproperty(
1236
1098
        datetime_to_dbus, "LastApprovalRequest")
1237
1099
    approved_by_default = notifychangeproperty(dbus.Boolean,
1315
1177
    ## D-Bus methods, signals & properties
1316
1178
    _interface = "se.recompile.Mandos.Client"
1317
1179
    
1318
 
    ## Interfaces
1319
 
    
1320
 
    @dbus_interface_annotations(_interface)
1321
 
    def _foo(self):
1322
 
        return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
1323
 
                     "false"}
1324
 
    
1325
1180
    ## Signals
1326
1181
    
1327
1182
    # CheckerCompleted - signal
1363
1218
        "D-Bus signal"
1364
1219
        return self.need_approval()
1365
1220
    
 
1221
    # NeRwequest - signal
 
1222
    @dbus.service.signal(_interface, signature="s")
 
1223
    def NewRequest(self, ip):
 
1224
        """D-Bus signal
 
1225
        Is sent after a client request a password.
 
1226
        """
 
1227
        pass
 
1228
    
1366
1229
    ## Methods
1367
1230
    
1368
1231
    # Approve - method
1478
1341
            return
1479
1342
        return datetime_to_dbus(self.last_checked_ok)
1480
1343
    
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
1344
    # Expires - property
1488
1345
    @dbus_service_property(_interface, signature="s", access="read")
1489
1346
    def Expires_dbus_property(self):
1501
1358
        if value is None:       # get
1502
1359
            return dbus.UInt64(self.timeout_milliseconds())
1503
1360
        self.timeout = datetime.timedelta(0, 0, 0, value)
 
1361
        if getattr(self, "disable_initiator_tag", None) is None:
 
1362
            return
1504
1363
        # 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))
 
1364
        gobject.source_remove(self.disable_initiator_tag)
 
1365
        self.disable_initiator_tag = None
 
1366
        self.expires = None
 
1367
        time_to_die = timedelta_to_milliseconds((self
 
1368
                                                 .last_checked_ok
 
1369
                                                 + self.timeout)
 
1370
                                                - datetime.datetime
 
1371
                                                .utcnow())
 
1372
        if time_to_die <= 0:
 
1373
            # The timeout has passed
 
1374
            self.disable()
 
1375
        else:
 
1376
            self.expires = (datetime.datetime.utcnow()
 
1377
                            + datetime.timedelta(milliseconds =
 
1378
                                                 time_to_die))
 
1379
            self.disable_initiator_tag = (gobject.timeout_add
 
1380
                                          (time_to_die, self.disable))
1523
1381
    
1524
1382
    # ExtendedTimeout - property
1525
1383
    @dbus_service_property(_interface, signature="t",
1681
1539
                except KeyError:
1682
1540
                    return
1683
1541
                
 
1542
                if self.server.use_dbus:
 
1543
                    # Emit D-Bus signal
 
1544
                    client.NewRequest(str(self.client_address))
 
1545
                
1684
1546
                if client.approval_delay:
1685
1547
                    delay = client.approval_delay
1686
1548
                    client.approvals_pending += 1
1750
1612
                
1751
1613
                logger.info("Sending secret to %s", client.name)
1752
1614
                # bump the timeout using extended_timeout
1753
 
                client.bump_timeout(client.extended_timeout)
 
1615
                client.checked_ok(client.extended_timeout)
1754
1616
                if self.server.use_dbus:
1755
1617
                    # Emit D-Bus signal
1756
1618
                    client.GotSecret()
2079
1941
            elif suffix == "w":
2080
1942
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2081
1943
            else:
2082
 
                raise ValueError("Unknown suffix {0!r}"
2083
 
                                 .format(suffix))
 
1944
                raise ValueError("Unknown suffix %r" % suffix)
2084
1945
        except (ValueError, IndexError) as e:
2085
1946
            raise ValueError(*(e.args))
2086
1947
        timevalue += delta
2100
1961
        sys.exit()
2101
1962
    if not noclose:
2102
1963
        # Close all standard open file descriptors
2103
 
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
 
1964
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
2104
1965
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2105
1966
            raise OSError(errno.ENODEV,
2106
 
                          "{0} not a character device"
2107
 
                          .format(os.devnull))
 
1967
                          "%s not a character device"
 
1968
                          % os.path.devnull)
2108
1969
        os.dup2(null, sys.stdin.fileno())
2109
1970
        os.dup2(null, sys.stdout.fileno())
2110
1971
        os.dup2(null, sys.stderr.fileno())
2119
1980
    
2120
1981
    parser = argparse.ArgumentParser()
2121
1982
    parser.add_argument("-v", "--version", action="version",
2122
 
                        version = "%(prog)s {0}".format(version),
 
1983
                        version = "%%(prog)s %s" % version,
2123
1984
                        help="show version number and exit")
2124
1985
    parser.add_argument("-i", "--interface", metavar="IF",
2125
1986
                        help="Bind to interface IF")
2228
2089
    
2229
2090
    if server_settings["servicename"] != "Mandos":
2230
2091
        syslogger.setFormatter(logging.Formatter
2231
 
                               ('Mandos ({0}) [%(process)d]:'
2232
 
                                ' %(levelname)s: %(message)s'
2233
 
                                .format(server_settings
2234
 
                                        ["servicename"])))
 
2092
                               ('Mandos (%s) [%%(process)d]:'
 
2093
                                ' %%(levelname)s: %%(message)s'
 
2094
                                % server_settings["servicename"]))
2235
2095
    
2236
2096
    # Parse config file with clients
2237
 
    client_config = configparser.SafeConfigParser(Client
2238
 
                                                  .client_defaults)
 
2097
    client_config = configparser.SafeConfigParser(Client.client_defaults)
2239
2098
    client_config.read(os.path.join(server_settings["configdir"],
2240
2099
                                    "clients.conf"))
2241
2100
    
2258
2117
        except IOError:
2259
2118
            logger.error("Could not open file %r", pidfilename)
2260
2119
    
2261
 
    for name in ("_mandos", "mandos", "nobody"):
 
2120
    try:
 
2121
        uid = pwd.getpwnam("_mandos").pw_uid
 
2122
        gid = pwd.getpwnam("_mandos").pw_gid
 
2123
    except KeyError:
2262
2124
        try:
2263
 
            uid = pwd.getpwnam(name).pw_uid
2264
 
            gid = pwd.getpwnam(name).pw_gid
2265
 
            break
 
2125
            uid = pwd.getpwnam("mandos").pw_uid
 
2126
            gid = pwd.getpwnam("mandos").pw_gid
2266
2127
        except KeyError:
2267
 
            continue
2268
 
    else:
2269
 
        uid = 65534
2270
 
        gid = 65534
 
2128
            try:
 
2129
                uid = pwd.getpwnam("nobody").pw_uid
 
2130
                gid = pwd.getpwnam("nobody").pw_gid
 
2131
            except KeyError:
 
2132
                uid = 65534
 
2133
                gid = 65534
2271
2134
    try:
2272
2135
        os.setgid(gid)
2273
2136
        os.setuid(uid)
2290
2153
         .gnutls_global_set_log_function(debug_gnutls))
2291
2154
        
2292
2155
        # Redirect stdin so all checkers get /dev/null
2293
 
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
 
2156
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
2294
2157
        os.dup2(null, sys.stdin.fileno())
2295
2158
        if null > 2:
2296
2159
            os.close(null)
2304
2167
    
2305
2168
    global main_loop
2306
2169
    # From the Avahi example code
2307
 
    DBusGMainLoop(set_as_default=True)
 
2170
    DBusGMainLoop(set_as_default=True )
2308
2171
    main_loop = gobject.MainLoop()
2309
2172
    bus = dbus.SystemBus()
2310
2173
    # End of Avahi example code
2378
2241
            
2379
2242
            # Clients who has passed its expire date can still be
2380
2243
            # enabled if its last checker was successful.  Clients
2381
 
            # whose checker succeeded before we stored its state is
2382
 
            # assumed to have successfully run all checkers during
2383
 
            # downtime.
 
2244
            # whose checker failed before we stored its state is
 
2245
            # assumed to have failed all checkers during downtime.
2384
2246
            if client["enabled"]:
2385
2247
                if datetime.datetime.utcnow() >= client["expires"]:
2386
2248
                    if not client["last_checked_ok"]:
2387
2249
                        logger.warning(
2388
2250
                            "disabling client {0} - Client never "
2389
 
                            "performed a successful checker"
2390
 
                            .format(client_name))
 
2251
                            "performed a successfull checker"
 
2252
                            .format(client["name"]))
2391
2253
                        client["enabled"] = False
2392
2254
                    elif client["last_checker_status"] != 0:
2393
2255
                        logger.warning(
2394
2256
                            "disabling client {0} - Client "
2395
2257
                            "last checker failed with error code {1}"
2396
 
                            .format(client_name,
 
2258
                            .format(client["name"],
2397
2259
                                    client["last_checker_status"]))
2398
2260
                        client["enabled"] = False
2399
2261
                    else:
2400
2262
                        client["expires"] = (datetime.datetime
2401
2263
                                             .utcnow()
2402
2264
                                             + client["timeout"])
2403
 
                        logger.debug("Last checker succeeded,"
2404
 
                                     " keeping {0} enabled"
2405
 
                                     .format(client_name))
 
2265
                    
2406
2266
            try:
2407
2267
                client["secret"] = (
2408
2268
                    pgp.decrypt(client["encrypted_secret"],
2417
2277
 
2418
2278
    
2419
2279
    # Add/remove clients based on new changes made to config
2420
 
    for client_name in (set(old_client_settings)
2421
 
                        - set(client_settings)):
 
2280
    for client_name in set(old_client_settings) - set(client_settings):
2422
2281
        del clients_data[client_name]
2423
 
    for client_name in (set(client_settings)
2424
 
                        - set(old_client_settings)):
 
2282
    for client_name in set(client_settings) - set(old_client_settings):
2425
2283
        clients_data[client_name] = client_settings[client_name]
2426
2284
 
2427
 
    # Create all client objects
 
2285
    # Create clients all clients
2428
2286
    for client_name, client in clients_data.iteritems():
2429
2287
        tcp_server.clients[client_name] = client_class(
2430
2288
            name = client_name, settings = client)
2451
2309
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2452
2310
    
2453
2311
    if use_dbus:
2454
 
        class MandosDBusService(DBusObjectWithProperties):
 
2312
        class MandosDBusService(dbus.service.Object):
2455
2313
            """A D-Bus proxy object"""
2456
2314
            def __init__(self):
2457
2315
                dbus.service.Object.__init__(self, bus, "/")
2458
2316
            _interface = "se.recompile.Mandos"
2459
2317
            
2460
 
            @dbus_interface_annotations(_interface)
2461
 
            def _foo(self):
2462
 
                return { "org.freedesktop.DBus.Property"
2463
 
                         ".EmitsChangedSignal":
2464
 
                             "false"}
2465
 
            
2466
2318
            @dbus.service.signal(_interface, signature="o")
2467
2319
            def ClientAdded(self, objpath):
2468
2320
                "D-Bus signal"
2601
2453
    service.port = tcp_server.socket.getsockname()[1]
2602
2454
    if use_ipv6:
2603
2455
        logger.info("Now listening on address %r, port %d,"
2604
 
                    " flowinfo %d, scope_id %d",
2605
 
                    *tcp_server.socket.getsockname())
 
2456
                    " flowinfo %d, scope_id %d"
 
2457
                    % tcp_server.socket.getsockname())
2606
2458
    else:                       # IPv4
2607
 
        logger.info("Now listening on address %r, port %d",
2608
 
                    *tcp_server.socket.getsockname())
 
2459
        logger.info("Now listening on address %r, port %d"
 
2460
                    % tcp_server.socket.getsockname())
2609
2461
    
2610
2462
    #service.interface = tcp_server.socket.getsockname()[3]
2611
2463
    
2614
2466
        try:
2615
2467
            service.activate()
2616
2468
        except dbus.exceptions.DBusException as error:
2617
 
            logger.critical("D-Bus Exception", exc_info=error)
 
2469
            logger.critical("DBusException: %s", error)
2618
2470
            cleanup()
2619
2471
            sys.exit(1)
2620
2472
        # End of Avahi example code
2627
2479
        logger.debug("Starting main loop")
2628
2480
        main_loop.run()
2629
2481
    except AvahiError as error:
2630
 
        logger.critical("Avahi Error", exc_info=error)
 
2482
        logger.critical("AvahiError: %s", error)
2631
2483
        cleanup()
2632
2484
        sys.exit(1)
2633
2485
    except KeyboardInterrupt: