/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: 2013-10-24 20:21:45 UTC
  • Revision ID: teddy@recompile.se-20131024202145-456a9y6x910a2vhb
* debian/control (Build-Depends): Changed debhelper version to (>= 9)
                                  to match debian/compat.
* mandos-options.xml (priority): Changed back to normal priority.
  (priority_compat): New option; for the server which needs to a
                     priority string compatible with old keys.
* mandos-conf.xml (OPTIONS/priority): Include "priority_compat".
* mandos.xml (OPTIONS/priority): - '' -

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-2014 Teddy Hogeborn
15
 
# Copyright © 2008-2014 Björn Påhlsson
 
14
# Copyright © 2008-2013 Teddy Hogeborn
 
15
# Copyright © 2008-2013 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
88
88
    except ImportError:
89
89
        SO_BINDTODEVICE = None
90
90
 
91
 
version = "1.6.5"
 
91
version = "1.6.1"
92
92
stored_state_file = "clients.pickle"
93
93
 
94
94
logger = logging.getLogger()
95
 
syslogger = None
 
95
syslogger = (logging.handlers.SysLogHandler
 
96
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
97
              address = str("/dev/log")))
96
98
 
97
99
try:
98
100
    if_nametoindex = (ctypes.cdll.LoadLibrary
114
116
def initlogger(debug, level=logging.WARNING):
115
117
    """init logger and add loglevel"""
116
118
    
117
 
    global syslogger
118
 
    syslogger = (logging.handlers.SysLogHandler
119
 
                 (facility =
120
 
                  logging.handlers.SysLogHandler.LOG_DAEMON,
121
 
                  address = str("/dev/log")))
122
119
    syslogger.setFormatter(logging.Formatter
123
120
                           ('Mandos [%(process)d]: %(levelname)s:'
124
121
                            ' %(message)s'))
693
690
        # If a checker exists, make sure it is not a zombie
694
691
        try:
695
692
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
696
 
        except AttributeError:
697
 
            pass
698
 
        except OSError as error:
699
 
            if error.errno != errno.ECHILD:
700
 
                raise
 
693
        except (AttributeError, OSError) as error:
 
694
            if (isinstance(error, OSError)
 
695
                and error.errno != errno.ECHILD):
 
696
                raise error
701
697
        else:
702
698
            if pid:
703
699
                logger.warning("Checker was a zombie")
937
933
            # The byte_arrays option is not supported yet on
938
934
            # signatures other than "ay".
939
935
            if prop._dbus_signature != "ay":
940
 
                raise ValueError("Byte arrays not supported for non-"
941
 
                                 "'ay' signature {0!r}"
942
 
                                 .format(prop._dbus_signature))
 
936
                raise ValueError
943
937
            value = dbus.ByteArray(b''.join(chr(byte)
944
938
                                            for byte in value))
945
939
        prop(value)
1353
1347
                                       *args, **kwargs)
1354
1348
    
1355
1349
    def start_checker(self, *args, **kwargs):
1356
 
        old_checker_pid = getattr(self.checker, "pid", None)
 
1350
        old_checker = self.checker
 
1351
        if self.checker is not None:
 
1352
            old_checker_pid = self.checker.pid
 
1353
        else:
 
1354
            old_checker_pid = None
1357
1355
        r = Client.start_checker(self, *args, **kwargs)
1358
1356
        # Only if new checker process was started
1359
1357
        if (self.checker is not None
1704
1702
            logger.debug("Protocol version: %r", line)
1705
1703
            try:
1706
1704
                if int(line.strip().split()[0]) > 1:
1707
 
                    raise RuntimeError(line)
 
1705
                    raise RuntimeError
1708
1706
            except (ValueError, IndexError, RuntimeError) as error:
1709
1707
                logger.error("Unknown protocol version: %s", error)
1710
1708
                return
1917
1915
    
1918
1916
    def add_pipe(self, parent_pipe, proc):
1919
1917
        """Dummy function; override as necessary"""
1920
 
        raise NotImplementedError()
 
1918
        raise NotImplementedError
1921
1919
 
1922
1920
 
1923
1921
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
2260
2258
            else:
2261
2259
                raise ValueError("Unknown suffix {0!r}"
2262
2260
                                 .format(suffix))
2263
 
        except IndexError as e:
 
2261
        except (ValueError, IndexError) as e:
2264
2262
            raise ValueError(*(e.args))
2265
2263
        timevalue += delta
2266
2264
    return timevalue
2337
2335
                        help="Directory to save/restore state in")
2338
2336
    parser.add_argument("--foreground", action="store_true",
2339
2337
                        help="Run in foreground", default=None)
2340
 
    parser.add_argument("--no-zeroconf", action="store_false",
2341
 
                        dest="zeroconf", help="Do not use Zeroconf",
2342
 
                        default=None)
2343
2338
    
2344
2339
    options = parser.parse_args()
2345
2340
    
2346
2341
    if options.check:
2347
2342
        import doctest
2348
 
        fail_count, test_count = doctest.testmod()
2349
 
        sys.exit(os.EX_OK if fail_count == 0 else 1)
 
2343
        doctest.testmod()
 
2344
        sys.exit()
2350
2345
    
2351
2346
    # Default values for config file for server-global settings
2352
2347
    server_defaults = { "interface": "",
2363
2358
                        "socket": "",
2364
2359
                        "statedir": "/var/lib/mandos",
2365
2360
                        "foreground": "False",
2366
 
                        "zeroconf": "True",
2367
2361
                        }
2368
2362
    
2369
2363
    # Parse config file for server-global settings
2396
2390
    for option in ("interface", "address", "port", "debug",
2397
2391
                   "priority", "servicename", "configdir",
2398
2392
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
2399
 
                   "statedir", "socket", "foreground", "zeroconf"):
 
2393
                   "statedir", "socket", "foreground"):
2400
2394
        value = getattr(options, option)
2401
2395
        if value is not None:
2402
2396
            server_settings[option] = value
2407
2401
            server_settings[option] = unicode(server_settings[option])
2408
2402
    # Force all boolean options to be boolean
2409
2403
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2410
 
                   "foreground", "zeroconf"):
 
2404
                   "foreground"):
2411
2405
        server_settings[option] = bool(server_settings[option])
2412
2406
    # Debug implies foreground
2413
2407
    if server_settings["debug"]:
2416
2410
    
2417
2411
    ##################################################################
2418
2412
    
2419
 
    if (not server_settings["zeroconf"] and
2420
 
        not (server_settings["port"]
2421
 
             or server_settings["socket"] != "")):
2422
 
            parser.error("Needs port or socket to work without"
2423
 
                         " Zeroconf")
2424
 
    
2425
2413
    # For convenience
2426
2414
    debug = server_settings["debug"]
2427
2415
    debuglevel = server_settings["debuglevel"]
2430
2418
    stored_state_path = os.path.join(server_settings["statedir"],
2431
2419
                                     stored_state_file)
2432
2420
    foreground = server_settings["foreground"]
2433
 
    zeroconf = server_settings["zeroconf"]
2434
2421
    
2435
2422
    if debug:
2436
2423
        initlogger(debug, logging.DEBUG)
2457
2444
    global mandos_dbus_service
2458
2445
    mandos_dbus_service = None
2459
2446
    
2460
 
    socketfd = None
2461
 
    if server_settings["socket"] != "":
2462
 
        socketfd = server_settings["socket"]
2463
2447
    tcp_server = MandosServer((server_settings["address"],
2464
2448
                               server_settings["port"]),
2465
2449
                              ClientHandler,
2469
2453
                              gnutls_priority=
2470
2454
                              server_settings["priority"],
2471
2455
                              use_dbus=use_dbus,
2472
 
                              socketfd=socketfd)
 
2456
                              socketfd=(server_settings["socket"]
 
2457
                                        or None))
2473
2458
    if not foreground:
2474
2459
        pidfilename = "/run/mandos.pid"
2475
 
        if not os.path.isdir("/run/."):
2476
 
            pidfilename = "/var/run/mandos.pid"
2477
2460
        pidfile = None
2478
2461
        try:
2479
2462
            pidfile = open(pidfilename, "w")
2496
2479
        os.setuid(uid)
2497
2480
    except OSError as error:
2498
2481
        if error.errno != errno.EPERM:
2499
 
            raise
 
2482
            raise error
2500
2483
    
2501
2484
    if debug:
2502
2485
        # Enable all possible GnuTLS debugging
2545
2528
            use_dbus = False
2546
2529
            server_settings["use_dbus"] = False
2547
2530
            tcp_server.use_dbus = False
2548
 
    if zeroconf:
2549
 
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2550
 
        service = AvahiServiceToSyslog(name =
2551
 
                                       server_settings["servicename"],
2552
 
                                       servicetype = "_mandos._tcp",
2553
 
                                       protocol = protocol, bus = bus)
2554
 
        if server_settings["interface"]:
2555
 
            service.interface = (if_nametoindex
2556
 
                                 (str(server_settings["interface"])))
 
2531
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
2532
    service = AvahiServiceToSyslog(name =
 
2533
                                   server_settings["servicename"],
 
2534
                                   servicetype = "_mandos._tcp",
 
2535
                                   protocol = protocol, bus = bus)
 
2536
    if server_settings["interface"]:
 
2537
        service.interface = (if_nametoindex
 
2538
                             (str(server_settings["interface"])))
2557
2539
    
2558
2540
    global multiprocessing_manager
2559
2541
    multiprocessing_manager = multiprocessing.Manager()
2753
2735
    
2754
2736
    def cleanup():
2755
2737
        "Cleanup function; run on exit"
2756
 
        if zeroconf:
2757
 
            service.cleanup()
 
2738
        service.cleanup()
2758
2739
        
2759
2740
        multiprocessing.active_children()
2760
2741
        wnull.close()
2809
2790
            else:
2810
2791
                logger.warning("Could not save persistent state:",
2811
2792
                               exc_info=e)
2812
 
                raise
 
2793
                raise e
2813
2794
        
2814
2795
        # Delete all clients, and settings from config
2815
2796
        while tcp_server.clients:
2839
2820
    tcp_server.server_activate()
2840
2821
    
2841
2822
    # Find out what port we got
2842
 
    if zeroconf:
2843
 
        service.port = tcp_server.socket.getsockname()[1]
 
2823
    service.port = tcp_server.socket.getsockname()[1]
2844
2824
    if use_ipv6:
2845
2825
        logger.info("Now listening on address %r, port %d,"
2846
2826
                    " flowinfo %d, scope_id %d",
2852
2832
    #service.interface = tcp_server.socket.getsockname()[3]
2853
2833
    
2854
2834
    try:
2855
 
        if zeroconf:
2856
 
            # From the Avahi example code
2857
 
            try:
2858
 
                service.activate()
2859
 
            except dbus.exceptions.DBusException as error:
2860
 
                logger.critical("D-Bus Exception", exc_info=error)
2861
 
                cleanup()
2862
 
                sys.exit(1)
2863
 
            # End of Avahi example code
 
2835
        # From the Avahi example code
 
2836
        try:
 
2837
            service.activate()
 
2838
        except dbus.exceptions.DBusException as error:
 
2839
            logger.critical("D-Bus Exception", exc_info=error)
 
2840
            cleanup()
 
2841
            sys.exit(1)
 
2842
        # End of Avahi example code
2864
2843
        
2865
2844
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2866
2845
                             lambda *args, **kwargs: