/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

Merge from trunk.  Notable changes:

 1. Server package now depends on "python-gobject".
 2. Permission fix for /lib64.
 3. Support for DEVICE setting from initramfs.conf, kernel parameters
    "ip=" and "mandos=connect".
 4. Fix for the bug where the server would stop responding, with a
    zombie checker process.
 5. Add support for disabling IPv6 in the server
 6. Fix for the bug which made the server, plugin-runner and
    mandos-client fail to change group ID.
 7. Add GnuTLS debugging to server debug output.
 8. Fix for the bug of the "--options-for" option of plugin-runner,
    where it would cut the value at the first colon character.
 9. Stop using sscanf() throughout, since it does not detect overflow.
10. Fix for the bug where plugin-runner would not go to the fallback
    if all plugins failed.
11. Fix for the bug where mandos-client would not clean up after a
    signal.
12. Added support for connecting to IPv4 addresses in mandos-client.
13. Added support for not using a specific network interface in
    mandos-client.
14. Kernel log level will be lowered by mandos-client while bringing
    up the network interface.
15. Add an option for the maximum time for mandos-client to wait for
    the network interface to come up.
16. Fix for the bug where mandos-client would not clean the temporary
    directory on some filesystems.

Show diffs side-by-side

added added

removed removed

Lines of Context:
73
73
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
74
74
              address = "/dev/log"))
75
75
syslogger.setFormatter(logging.Formatter
76
 
                       ('Mandos: %(levelname)s: %(message)s'))
 
76
                       ('Mandos [%(process)d]: %(levelname)s:'
 
77
                        ' %(message)s'))
77
78
logger.addHandler(syslogger)
78
79
 
79
80
console = logging.StreamHandler()
80
 
console.setFormatter(logging.Formatter('%(name)s: %(levelname)s:'
81
 
                                       ' %(message)s'))
 
81
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
 
82
                                       ' %(levelname)s: %(message)s'))
82
83
logger.addHandler(console)
83
84
 
84
85
class AvahiError(Exception):
113
114
    """
114
115
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
115
116
                 servicetype = None, port = None, TXT = None,
116
 
                 domain = "", host = "", max_renames = 32768):
 
117
                 domain = "", host = "", max_renames = 32768,
 
118
                 protocol = avahi.PROTO_UNSPEC):
117
119
        self.interface = interface
118
120
        self.name = name
119
121
        self.type = servicetype
123
125
        self.host = host
124
126
        self.rename_count = 0
125
127
        self.max_renames = max_renames
 
128
        self.protocol = protocol
126
129
    def rename(self):
127
130
        """Derived from the Avahi example code"""
128
131
        if self.rename_count >= self.max_renames:
157
160
                     service.name, service.type)
158
161
        group.AddService(
159
162
                self.interface,         # interface
160
 
                avahi.PROTO_INET6,      # protocol
 
163
                self.protocol,          # protocol
161
164
                dbus.UInt32(0),         # flags
162
165
                self.name, self.type,
163
166
                self.domain, self.host,
202
205
                     client lives.  %() expansions are done at
203
206
                     runtime with vars(self) as dict, so that for
204
207
                     instance %(name)s can be used in the command.
 
208
    current_checker_command: string; current running checker_command
205
209
    use_dbus: bool(); Whether to provide D-Bus interface and signals
206
210
    dbus_object_path: dbus.ObjectPath ; only set if self.use_dbus
207
211
    """
256
260
        self.disable_initiator_tag = None
257
261
        self.checker_callback_tag = None
258
262
        self.checker_command = config["checker"]
 
263
        self.current_checker_command = None
259
264
        self.last_connect = None
260
265
        # Only now, when this client is initialized, can it show up on
261
266
        # the D-Bus
376
381
        # checkers alone, the checker would have to take more time
377
382
        # than 'timeout' for the client to be declared invalid, which
378
383
        # is as it should be.
 
384
        
 
385
        # If a checker exists, make sure it is not a zombie
 
386
        if self.checker is not None:
 
387
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
388
            if pid:
 
389
                logger.warning("Checker was a zombie")
 
390
                gobject.source_remove(self.checker_callback_tag)
 
391
                self.checker_callback(pid, status,
 
392
                                      self.current_checker_command)
 
393
        # Start a new checker if needed
379
394
        if self.checker is None:
380
395
            try:
381
396
                # In case checker_command has exactly one % operator
391
406
                    logger.error(u'Could not format string "%s":'
392
407
                                 u' %s', self.checker_command, error)
393
408
                    return True # Try again later
 
409
                self.current_checker_command = command
394
410
            try:
395
411
                logger.info(u"Starting checker %r for %s",
396
412
                            command, self.name)
411
427
                                             (self.checker.pid,
412
428
                                              self.checker_callback,
413
429
                                              data=command))
 
430
                # The checker may have completed before the gobject
 
431
                # watch was added.  Check for this.
 
432
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
433
                if pid:
 
434
                    gobject.source_remove(self.checker_callback_tag)
 
435
                    self.checker_callback(pid, status, command)
414
436
            except OSError, error:
415
437
                logger.error(u"Failed to start subprocess: %s",
416
438
                             error)
595
617
        != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
596
618
        # ...do the normal thing
597
619
        return session.peer_certificate
598
 
    list_size = ctypes.c_uint()
 
620
    list_size = ctypes.c_uint(1)
599
621
    cert_list = (gnutls.library.functions
600
622
                 .gnutls_certificate_get_peers
601
623
                 (session._c_object, ctypes.byref(list_size)))
 
624
    if not bool(cert_list) and list_size.value != 0:
 
625
        raise gnutls.errors.GNUTLSError("error getting peer"
 
626
                                        " certificate")
602
627
    if list_size.value == 0:
603
628
        return None
604
629
    cert = cert_list[0]
673
698
        # using OpenPGP certificates.
674
699
        
675
700
        #priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
676
 
        #                "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
677
 
        #                "+DHE-DSS"))
 
701
        #                     "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
 
702
        #                     "+DHE-DSS"))
678
703
        # Use a fallback default, since this MUST be set.
679
704
        priority = self.server.settings.get("priority", "NORMAL")
680
705
        (gnutls.library.functions
688
713
            # Do not run session.bye() here: the session is not
689
714
            # established.  Just abandon the request.
690
715
            return
 
716
        logger.debug(u"Handshake succeeded")
691
717
        try:
692
718
            fpr = fingerprint(peer_certificate(session))
693
719
        except (TypeError, gnutls.errors.GNUTLSError), error:
695
721
            session.bye()
696
722
            return
697
723
        logger.debug(u"Fingerprint: %s", fpr)
 
724
        
698
725
        for c in self.server.clients:
699
726
            if c.fingerprint == fpr:
700
727
                client = c
726
753
 
727
754
class IPv6_TCPServer(SocketServer.ForkingMixIn,
728
755
                     SocketServer.TCPServer, object):
729
 
    """IPv6 TCP server.  Accepts 'None' as address and/or port.
 
756
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
730
757
    Attributes:
731
758
        settings:       Server settings
732
759
        clients:        Set() of Client objects
740
767
        if "clients" in kwargs:
741
768
            self.clients = kwargs["clients"]
742
769
            del kwargs["clients"]
 
770
        if "use_ipv6" in kwargs:
 
771
            if not kwargs["use_ipv6"]:
 
772
                self.address_family = socket.AF_INET
 
773
            del kwargs["use_ipv6"]
743
774
        self.enabled = False
744
775
        super(IPv6_TCPServer, self).__init__(*args, **kwargs)
745
776
    def server_bind(self):
759
790
                                 u" bind to interface %s",
760
791
                                 self.settings["interface"])
761
792
                else:
762
 
                    raise error
 
793
                    raise
763
794
        # Only bind(2) the socket if we really need to.
764
795
        if self.server_address[0] or self.server_address[1]:
765
796
            if not self.server_address[0]:
766
 
                in6addr_any = "::"
767
 
                self.server_address = (in6addr_any,
 
797
                if self.address_family == socket.AF_INET6:
 
798
                    any_address = "::" # in6addr_any
 
799
                else:
 
800
                    any_address = socket.INADDR_ANY
 
801
                self.server_address = (any_address,
768
802
                                       self.server_address[1])
769
803
            elif not self.server_address[1]:
770
804
                self.server_address = (self.server_address[0],
786
820
 
787
821
def string_to_delta(interval):
788
822
    """Parse a string and return a datetime.timedelta
789
 
 
 
823
    
790
824
    >>> string_to_delta('7d')
791
825
    datetime.timedelta(7)
792
826
    >>> string_to_delta('60s')
916
950
    parser.add_option("--no-dbus", action="store_false",
917
951
                      dest="use_dbus",
918
952
                      help=optparse.SUPPRESS_HELP) # XXX: Not done yet
 
953
    parser.add_option("--no-ipv6", action="store_false",
 
954
                      dest="use_ipv6", help="Do not use IPv6")
919
955
    options = parser.parse_args()[0]
920
956
    
921
957
    if options.check:
932
968
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
933
969
                        "servicename": "Mandos",
934
970
                        "use_dbus": "True",
 
971
                        "use_ipv6": "True",
935
972
                        }
936
973
    
937
974
    # Parse config file for server-global settings
940
977
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
941
978
    # Convert the SafeConfigParser object to a dict
942
979
    server_settings = server_config.defaults()
943
 
    # Use getboolean on the boolean config options
944
 
    server_settings["debug"] = (server_config.getboolean
945
 
                                ("DEFAULT", "debug"))
946
 
    server_settings["use_dbus"] = (server_config.getboolean
947
 
                                   ("DEFAULT", "use_dbus"))
 
980
    # Use the appropriate methods on the non-string config options
 
981
    server_settings["debug"] = server_config.getboolean("DEFAULT",
 
982
                                                        "debug")
 
983
    server_settings["use_dbus"] = server_config.getboolean("DEFAULT",
 
984
                                                           "use_dbus")
 
985
    server_settings["use_ipv6"] = server_config.getboolean("DEFAULT",
 
986
                                                           "use_ipv6")
 
987
    if server_settings["port"]:
 
988
        server_settings["port"] = server_config.getint("DEFAULT",
 
989
                                                       "port")
948
990
    del server_config
949
991
    
950
992
    # Override the settings from the config file with command line
951
993
    # options, if set.
952
994
    for option in ("interface", "address", "port", "debug",
953
995
                   "priority", "servicename", "configdir",
954
 
                   "use_dbus"):
 
996
                   "use_dbus", "use_ipv6"):
955
997
        value = getattr(options, option)
956
998
        if value is not None:
957
999
            server_settings[option] = value
962
1004
    debug = server_settings["debug"]
963
1005
    use_dbus = server_settings["use_dbus"]
964
1006
    use_dbus = False            # XXX: Not done yet
 
1007
    use_ipv6 = server_settings["use_ipv6"]
965
1008
    
966
1009
    if not debug:
967
1010
        syslogger.setLevel(logging.WARNING)
988
1031
                                 server_settings["port"]),
989
1032
                                TCP_handler,
990
1033
                                settings=server_settings,
991
 
                                clients=clients)
 
1034
                                clients=clients, use_ipv6=use_ipv6)
992
1035
    pidfilename = "/var/run/mandos.pid"
993
1036
    try:
994
1037
        pidfile = open(pidfilename, "w")
995
 
    except IOError, error:
 
1038
    except IOError:
996
1039
        logger.error("Could not open file %r", pidfilename)
997
1040
    
998
1041
    try:
1010
1053
                uid = 65534
1011
1054
                gid = 65534
1012
1055
    try:
 
1056
        os.setgid(gid)
1013
1057
        os.setuid(uid)
1014
 
        os.setgid(gid)
1015
1058
    except OSError, error:
1016
1059
        if error[0] != errno.EPERM:
1017
1060
            raise error
1018
1061
    
 
1062
    # Enable all possible GnuTLS debugging
 
1063
    if debug:
 
1064
        # "Use a log level over 10 to enable all debugging options."
 
1065
        # - GnuTLS manual
 
1066
        gnutls.library.functions.gnutls_global_set_log_level(11)
 
1067
        
 
1068
        @gnutls.library.types.gnutls_log_func
 
1069
        def debug_gnutls(level, string):
 
1070
            logger.debug("GnuTLS: %s", string[:-1])
 
1071
        
 
1072
        (gnutls.library.functions
 
1073
         .gnutls_global_set_log_function(debug_gnutls))
 
1074
    
1019
1075
    global service
 
1076
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1020
1077
    service = AvahiService(name = server_settings["servicename"],
1021
 
                           servicetype = "_mandos._tcp", )
 
1078
                           servicetype = "_mandos._tcp",
 
1079
                           protocol = protocol)
1022
1080
    if server_settings["interface"]:
1023
1081
        service.interface = (if_nametoindex
1024
1082
                             (server_settings["interface"]))
1110
1168
            
1111
1169
            @dbus.service.method(_interface, out_signature="ao")
1112
1170
            def GetAllClients(self):
 
1171
                "D-Bus method"
1113
1172
                return dbus.Array(c.dbus_object_path for c in clients)
1114
1173
            
1115
1174
            @dbus.service.method(_interface, out_signature="a{oa{sv}}")
1116
1175
            def GetAllClientsWithProperties(self):
 
1176
                "D-Bus method"
1117
1177
                return dbus.Dictionary(
1118
1178
                    ((c.dbus_object_path, c.GetAllProperties())
1119
1179
                     for c in clients),
1121
1181
            
1122
1182
            @dbus.service.method(_interface, in_signature="o")
1123
1183
            def RemoveClient(self, object_path):
 
1184
                "D-Bus method"
1124
1185
                for c in clients:
1125
1186
                    if c.dbus_object_path == object_path:
1126
1187
                        clients.remove(c)
1148
1209
    
1149
1210
    # Find out what port we got
1150
1211
    service.port = tcp_server.socket.getsockname()[1]
1151
 
    logger.info(u"Now listening on address %r, port %d, flowinfo %d,"
1152
 
                u" scope_id %d" % tcp_server.socket.getsockname())
 
1212
    if use_ipv6:
 
1213
        logger.info(u"Now listening on address %r, port %d,"
 
1214
                    " flowinfo %d, scope_id %d"
 
1215
                    % tcp_server.socket.getsockname())
 
1216
    else:                       # IPv4
 
1217
        logger.info(u"Now listening on address %r, port %d"
 
1218
                    % tcp_server.socket.getsockname())
1153
1219
    
1154
1220
    #service.interface = tcp_server.socket.getsockname()[3]
1155
1221
    
1175
1241
        sys.exit(1)
1176
1242
    except KeyboardInterrupt:
1177
1243
        if debug:
1178
 
            print
 
1244
            print >> sys.stderr
 
1245
        logger.debug("Server received KeyboardInterrupt")
 
1246
    logger.debug("Server exiting")
1179
1247
 
1180
1248
if __name__ == '__main__':
1181
1249
    main()