/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 Hogeborn
  • Date: 2014-07-14 21:41:08 UTC
  • Revision ID: teddy@recompile.se-20140714214108-awg7u6gaiy7d40dz
mandos-monitor: New "verbose" mode to see less important log messages.

* mandos-monitor (MandosClientWidget.__init__): Log client creation.
  (MandosClientWidget.checker_completed): Log a successful checker.
  (MandosClientWidget.checker_started): Log starting of a checker.
  (UserInterface.__init__): New optional "log_level" argument.
  (UserInterface.log_message, UserInterface.log_message_raw): Take
                                                              optional
                                                              "level"
                                                              arg.
  (UserInterface.toggle_log_display): Log visibility change.
  (UserInterface.change_log_display): Log wrap mode change.
  (UserInterface.process_input): Show new "v" key in help message and
                                 process "v" key if pressed.
* mandos-monitor.xml (KEYS): Document new "v" key.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python2.7
 
1
#!/usr/bin/python
2
2
# -*- mode: python; coding: utf-8 -*-
3
3
4
4
# Mandos server - give out binary blobs to connecting clients.
88
88
    except ImportError:
89
89
        SO_BINDTODEVICE = None
90
90
 
91
 
version = "1.6.7"
 
91
version = "1.6.6"
92
92
stored_state_file = "clients.pickle"
93
93
 
94
94
logger = logging.getLogger()
338
338
        elif state == avahi.ENTRY_GROUP_FAILURE:
339
339
            logger.critical("Avahi: Error in group state changed %s",
340
340
                            unicode(error))
341
 
            raise AvahiGroupError("State changed: {!s}"
 
341
            raise AvahiGroupError("State changed: {0!s}"
342
342
                                  .format(error))
343
343
    
344
344
    def cleanup(self):
395
395
        """Add the new name to the syslog messages"""
396
396
        ret = AvahiService.rename(self)
397
397
        syslogger.setFormatter(logging.Formatter
398
 
                               ('Mandos ({}) [%(process)d]:'
 
398
                               ('Mandos ({0}) [%(process)d]:'
399
399
                                ' %(levelname)s: %(message)s'
400
400
                                .format(self.name)))
401
401
        return ret
513
513
                          "rb") as secfile:
514
514
                    client["secret"] = secfile.read()
515
515
            else:
516
 
                raise TypeError("No secret or secfile for section {}"
 
516
                raise TypeError("No secret or secfile for section {0}"
517
517
                                .format(section))
518
518
            client["timeout"] = string_to_delta(section["timeout"])
519
519
            client["extended_timeout"] = string_to_delta(
536
536
            server_settings = {}
537
537
        self.server_settings = server_settings
538
538
        # adding all client settings
539
 
        for setting, value in settings.items():
 
539
        for setting, value in settings.iteritems():
540
540
            setattr(self, setting, value)
541
541
        
542
542
        if self.enabled:
707
707
        # Start a new checker if needed
708
708
        if self.checker is None:
709
709
            # Escape attributes for the shell
710
 
            escaped_attrs = { attr:
711
 
                                  re.escape(unicode(getattr(self,
712
 
                                                            attr)))
713
 
                              for attr in self.runtime_expansions }
 
710
            escaped_attrs = dict(
 
711
                (attr, re.escape(unicode(getattr(self, attr))))
 
712
                for attr in
 
713
                self.runtime_expansions)
714
714
            try:
715
715
                command = self.checker_command % escaped_attrs
716
716
            except TypeError as error:
797
797
    # "Set" method, so we fail early here:
798
798
    if byte_arrays and signature != "ay":
799
799
        raise ValueError("Byte arrays not supported for non-'ay'"
800
 
                         " signature {!r}".format(signature))
 
800
                         " signature {0!r}".format(signature))
801
801
    def decorator(func):
802
802
        func._dbus_is_property = True
803
803
        func._dbus_interface = dbus_interface
882
882
        If called like _is_dbus_thing("method") it returns a function
883
883
        suitable for use as predicate to inspect.getmembers().
884
884
        """
885
 
        return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
 
885
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
886
886
                                   False)
887
887
    
888
888
    def _get_all_dbus_things(self, thing):
938
938
            # signatures other than "ay".
939
939
            if prop._dbus_signature != "ay":
940
940
                raise ValueError("Byte arrays not supported for non-"
941
 
                                 "'ay' signature {!r}"
 
941
                                 "'ay' signature {0!r}"
942
942
                                 .format(prop._dbus_signature))
943
943
            value = dbus.ByteArray(b''.join(chr(byte)
944
944
                                            for byte in value))
1009
1009
                                              (prop,
1010
1010
                                               "_dbus_annotations",
1011
1011
                                               {}))
1012
 
                        for name, value in annots.items():
 
1012
                        for name, value in annots.iteritems():
1013
1013
                            ann_tag = document.createElement(
1014
1014
                                "annotation")
1015
1015
                            ann_tag.setAttribute("name", name)
1018
1018
                # Add interface annotation tags
1019
1019
                for annotation, value in dict(
1020
1020
                    itertools.chain.from_iterable(
1021
 
                        annotations().items()
 
1021
                        annotations().iteritems()
1022
1022
                        for name, annotations in
1023
1023
                        self._get_all_dbus_things("interface")
1024
1024
                        if name == if_tag.getAttribute("name")
1025
 
                        )).items():
 
1025
                        )).iteritems():
1026
1026
                    ann_tag = document.createElement("annotation")
1027
1027
                    ann_tag.setAttribute("name", annotation)
1028
1028
                    ann_tag.setAttribute("value", value)
1084
1084
    """
1085
1085
    def wrapper(cls):
1086
1086
        for orig_interface_name, alt_interface_name in (
1087
 
            alt_interface_names.items()):
 
1087
            alt_interface_names.iteritems()):
1088
1088
            attr = {}
1089
1089
            interface_names = set()
1090
1090
            # Go though all attributes of the class
1207
1207
                                        attribute.func_closure)))
1208
1208
            if deprecate:
1209
1209
                # Deprecate all alternate interfaces
1210
 
                iname="_AlternateDBusNames_interface_annotation{}"
 
1210
                iname="_AlternateDBusNames_interface_annotation{0}"
1211
1211
                for interface_name in interface_names:
1212
1212
                    @dbus_interface_annotations(interface_name)
1213
1213
                    def func(self):
1222
1222
            if interface_names:
1223
1223
                # Replace the class with a new subclass of it with
1224
1224
                # methods, signals, etc. as created above.
1225
 
                cls = type(b"{}Alternate".format(cls.__name__),
 
1225
                cls = type(b"{0}Alternate".format(cls.__name__),
1226
1226
                           (cls,), attr)
1227
1227
        return cls
1228
1228
    return wrapper
1269
1269
                   to the D-Bus.  Default: no transform
1270
1270
        variant_level: D-Bus variant level.  Default: 1
1271
1271
        """
1272
 
        attrname = "_{}".format(dbus_name)
 
1272
        attrname = "_{0}".format(dbus_name)
1273
1273
        def setter(self, value):
1274
1274
            if hasattr(self, "dbus_object_path"):
1275
1275
                if (not hasattr(self, attrname) or
2188
2188
    token_duration = Token(re.compile(r"P"), None,
2189
2189
                           frozenset((token_year, token_month,
2190
2190
                                      token_day, token_time,
2191
 
                                      token_week)))
 
2191
                                      token_week))),
2192
2192
    # Define starting values
2193
2193
    value = datetime.timedelta() # Value so far
2194
2194
    found_token = None
2195
 
    followers = frozenset((token_duration,)) # Following valid tokens
 
2195
    followers = frozenset(token_duration,) # Following valid tokens
2196
2196
    s = duration                # String left to parse
2197
2197
    # Loop until end token is found
2198
2198
    while found_token is not token_end:
2258
2258
            elif suffix == "w":
2259
2259
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2260
2260
            else:
2261
 
                raise ValueError("Unknown suffix {!r}"
 
2261
                raise ValueError("Unknown suffix {0!r}"
2262
2262
                                 .format(suffix))
2263
2263
        except IndexError as e:
2264
2264
            raise ValueError(*(e.args))
2281
2281
        # Close all standard open file descriptors
2282
2282
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2283
2283
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2284
 
            raise OSError(errno.ENODEV, "{} not a character device"
 
2284
            raise OSError(errno.ENODEV,
 
2285
                          "{0} not a character device"
2285
2286
                          .format(os.devnull))
2286
2287
        os.dup2(null, sys.stdin.fileno())
2287
2288
        os.dup2(null, sys.stdout.fileno())
2297
2298
    
2298
2299
    parser = argparse.ArgumentParser()
2299
2300
    parser.add_argument("-v", "--version", action="version",
2300
 
                        version = "%(prog)s {}".format(version),
 
2301
                        version = "%(prog)s {0}".format(version),
2301
2302
                        help="show version number and exit")
2302
2303
    parser.add_argument("-i", "--interface", metavar="IF",
2303
2304
                        help="Bind to interface IF")
2442
2443
    
2443
2444
    if server_settings["servicename"] != "Mandos":
2444
2445
        syslogger.setFormatter(logging.Formatter
2445
 
                               ('Mandos ({}) [%(process)d]:'
 
2446
                               ('Mandos ({0}) [%(process)d]:'
2446
2447
                                ' %(levelname)s: %(message)s'
2447
2448
                                .format(server_settings
2448
2449
                                        ["servicename"])))
2582
2583
            os.remove(stored_state_path)
2583
2584
        except IOError as e:
2584
2585
            if e.errno == errno.ENOENT:
2585
 
                logger.warning("Could not load persistent state: {}"
 
2586
                logger.warning("Could not load persistent state: {0}"
2586
2587
                                .format(os.strerror(e.errno)))
2587
2588
            else:
2588
2589
                logger.critical("Could not load persistent state:",
2593
2594
                           "EOFError:", exc_info=e)
2594
2595
    
2595
2596
    with PGPEngine() as pgp:
2596
 
        for client_name, client in clients_data.items():
 
2597
        for client_name, client in clients_data.iteritems():
2597
2598
            # Skip removed clients
2598
2599
            if client_name not in client_settings:
2599
2600
                continue
2624
2625
                if datetime.datetime.utcnow() >= client["expires"]:
2625
2626
                    if not client["last_checked_ok"]:
2626
2627
                        logger.warning(
2627
 
                            "disabling client {} - Client never "
 
2628
                            "disabling client {0} - Client never "
2628
2629
                            "performed a successful checker"
2629
2630
                            .format(client_name))
2630
2631
                        client["enabled"] = False
2631
2632
                    elif client["last_checker_status"] != 0:
2632
2633
                        logger.warning(
2633
 
                            "disabling client {} - Client last"
2634
 
                            " checker failed with error code {}"
 
2634
                            "disabling client {0} - Client "
 
2635
                            "last checker failed with error code {1}"
2635
2636
                            .format(client_name,
2636
2637
                                    client["last_checker_status"]))
2637
2638
                        client["enabled"] = False
2640
2641
                                             .utcnow()
2641
2642
                                             + client["timeout"])
2642
2643
                        logger.debug("Last checker succeeded,"
2643
 
                                     " keeping {} enabled"
 
2644
                                     " keeping {0} enabled"
2644
2645
                                     .format(client_name))
2645
2646
            try:
2646
2647
                client["secret"] = (
2649
2650
                                ["secret"]))
2650
2651
            except PGPError:
2651
2652
                # If decryption fails, we use secret from new settings
2652
 
                logger.debug("Failed to decrypt {} old secret"
 
2653
                logger.debug("Failed to decrypt {0} old secret"
2653
2654
                             .format(client_name))
2654
2655
                client["secret"] = (
2655
2656
                    client_settings[client_name]["secret"])
2663
2664
        clients_data[client_name] = client_settings[client_name]
2664
2665
    
2665
2666
    # Create all client objects
2666
 
    for client_name, client in clients_data.items():
 
2667
    for client_name, client in clients_data.iteritems():
2667
2668
        tcp_server.clients[client_name] = client_class(
2668
2669
            name = client_name, settings = client,
2669
2670
            server_settings = server_settings)
2773
2774
                
2774
2775
                # A list of attributes that can not be pickled
2775
2776
                # + secret.
2776
 
                exclude = { "bus", "changedstate", "secret",
2777
 
                            "checker", "server_settings" }
 
2777
                exclude = set(("bus", "changedstate", "secret",
 
2778
                               "checker", "server_settings"))
2778
2779
                for name, typ in (inspect.getmembers
2779
2780
                                  (dbus.service.Object)):
2780
2781
                    exclude.add(name)
2803
2804
                except NameError:
2804
2805
                    pass
2805
2806
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2806
 
                logger.warning("Could not save persistent state: {}"
 
2807
                logger.warning("Could not save persistent state: {0}"
2807
2808
                               .format(os.strerror(e.errno)))
2808
2809
            else:
2809
2810
                logger.warning("Could not save persistent state:",