/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2013-10-13 15:43:42 UTC
  • mto: (237.7.272 trunk)
  • mto: This revision was merged to the branch mainline in revision 303.
  • Revision ID: teddy@recompile.se-20131013154342-2ztabynqog6xuk0t
* initramfs-unpack: Bug fix: Made executable.

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-2012 Teddy Hogeborn
 
15
# Copyright © 2008-2012 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.7"
 
91
version = "1.6.0"
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'))
175
172
    def password_encode(self, password):
176
173
        # Passphrase can not be empty and can not contain newlines or
177
174
        # NUL bytes.  So we prefix it and hex encode it.
178
 
        encoded = b"mandos" + binascii.hexlify(password)
179
 
        if len(encoded) > 2048:
180
 
            # GnuPG can't handle long passwords, so encode differently
181
 
            encoded = (b"mandos" + password.replace(b"\\", b"\\\\")
182
 
                       .replace(b"\n", b"\\n")
183
 
                       .replace(b"\0", b"\\x00"))
184
 
        return encoded
 
175
        return b"mandos" + binascii.hexlify(password)
185
176
    
186
177
    def encrypt(self, data, password):
187
178
        passphrase = self.password_encode(password)
693
684
        # If a checker exists, make sure it is not a zombie
694
685
        try:
695
686
            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
 
687
        except (AttributeError, OSError) as error:
 
688
            if (isinstance(error, OSError)
 
689
                and error.errno != errno.ECHILD):
 
690
                raise error
701
691
        else:
702
692
            if pid:
703
693
                logger.warning("Checker was a zombie")
937
927
            # The byte_arrays option is not supported yet on
938
928
            # signatures other than "ay".
939
929
            if prop._dbus_signature != "ay":
940
 
                raise ValueError("Byte arrays not supported for non-"
941
 
                                 "'ay' signature {0!r}"
942
 
                                 .format(prop._dbus_signature))
 
930
                raise ValueError
943
931
            value = dbus.ByteArray(b''.join(chr(byte)
944
932
                                            for byte in value))
945
933
        prop(value)
1353
1341
                                       *args, **kwargs)
1354
1342
    
1355
1343
    def start_checker(self, *args, **kwargs):
1356
 
        old_checker_pid = getattr(self.checker, "pid", None)
 
1344
        old_checker = self.checker
 
1345
        if self.checker is not None:
 
1346
            old_checker_pid = self.checker.pid
 
1347
        else:
 
1348
            old_checker_pid = None
1357
1349
        r = Client.start_checker(self, *args, **kwargs)
1358
1350
        # Only if new checker process was started
1359
1351
        if (self.checker is not None
1704
1696
            logger.debug("Protocol version: %r", line)
1705
1697
            try:
1706
1698
                if int(line.strip().split()[0]) > 1:
1707
 
                    raise RuntimeError(line)
 
1699
                    raise RuntimeError
1708
1700
            except (ValueError, IndexError, RuntimeError) as error:
1709
1701
                logger.error("Unknown protocol version: %s", error)
1710
1702
                return
1917
1909
    
1918
1910
    def add_pipe(self, parent_pipe, proc):
1919
1911
        """Dummy function; override as necessary"""
1920
 
        raise NotImplementedError()
 
1912
        raise NotImplementedError
1921
1913
 
1922
1914
 
1923
1915
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
2188
2180
    token_duration = Token(re.compile(r"P"), None,
2189
2181
                           frozenset((token_year, token_month,
2190
2182
                                      token_day, token_time,
2191
 
                                      token_week)))
 
2183
                                      token_week))),
2192
2184
    # Define starting values
2193
2185
    value = datetime.timedelta() # Value so far
2194
2186
    found_token = None
2195
 
    followers = frozenset((token_duration,)) # Following valid tokens
 
2187
    followers = frozenset(token_duration,) # Following valid tokens
2196
2188
    s = duration                # String left to parse
2197
2189
    # Loop until end token is found
2198
2190
    while found_token is not token_end:
2260
2252
            else:
2261
2253
                raise ValueError("Unknown suffix {0!r}"
2262
2254
                                 .format(suffix))
2263
 
        except IndexError as e:
 
2255
        except (ValueError, IndexError) as e:
2264
2256
            raise ValueError(*(e.args))
2265
2257
        timevalue += delta
2266
2258
    return timevalue
2337
2329
                        help="Directory to save/restore state in")
2338
2330
    parser.add_argument("--foreground", action="store_true",
2339
2331
                        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
2332
    
2344
2333
    options = parser.parse_args()
2345
2334
    
2346
2335
    if options.check:
2347
2336
        import doctest
2348
 
        fail_count, test_count = doctest.testmod()
2349
 
        sys.exit(os.EX_OK if fail_count == 0 else 1)
 
2337
        doctest.testmod()
 
2338
        sys.exit()
2350
2339
    
2351
2340
    # Default values for config file for server-global settings
2352
2341
    server_defaults = { "interface": "",
2354
2343
                        "port": "",
2355
2344
                        "debug": "False",
2356
2345
                        "priority":
2357
 
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
 
2346
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:+SIGN-RSA-SHA224",
2358
2347
                        "servicename": "Mandos",
2359
2348
                        "use_dbus": "True",
2360
2349
                        "use_ipv6": "True",
2363
2352
                        "socket": "",
2364
2353
                        "statedir": "/var/lib/mandos",
2365
2354
                        "foreground": "False",
2366
 
                        "zeroconf": "True",
2367
2355
                        }
2368
2356
    
2369
2357
    # Parse config file for server-global settings
2396
2384
    for option in ("interface", "address", "port", "debug",
2397
2385
                   "priority", "servicename", "configdir",
2398
2386
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
2399
 
                   "statedir", "socket", "foreground", "zeroconf"):
 
2387
                   "statedir", "socket", "foreground"):
2400
2388
        value = getattr(options, option)
2401
2389
        if value is not None:
2402
2390
            server_settings[option] = value
2407
2395
            server_settings[option] = unicode(server_settings[option])
2408
2396
    # Force all boolean options to be boolean
2409
2397
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2410
 
                   "foreground", "zeroconf"):
 
2398
                   "foreground"):
2411
2399
        server_settings[option] = bool(server_settings[option])
2412
2400
    # Debug implies foreground
2413
2401
    if server_settings["debug"]:
2416
2404
    
2417
2405
    ##################################################################
2418
2406
    
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
2407
    # For convenience
2426
2408
    debug = server_settings["debug"]
2427
2409
    debuglevel = server_settings["debuglevel"]
2430
2412
    stored_state_path = os.path.join(server_settings["statedir"],
2431
2413
                                     stored_state_file)
2432
2414
    foreground = server_settings["foreground"]
2433
 
    zeroconf = server_settings["zeroconf"]
2434
2415
    
2435
2416
    if debug:
2436
2417
        initlogger(debug, logging.DEBUG)
2457
2438
    global mandos_dbus_service
2458
2439
    mandos_dbus_service = None
2459
2440
    
2460
 
    socketfd = None
2461
 
    if server_settings["socket"] != "":
2462
 
        socketfd = server_settings["socket"]
2463
2441
    tcp_server = MandosServer((server_settings["address"],
2464
2442
                               server_settings["port"]),
2465
2443
                              ClientHandler,
2469
2447
                              gnutls_priority=
2470
2448
                              server_settings["priority"],
2471
2449
                              use_dbus=use_dbus,
2472
 
                              socketfd=socketfd)
 
2450
                              socketfd=(server_settings["socket"]
 
2451
                                        or None))
2473
2452
    if not foreground:
2474
 
        pidfilename = "/run/mandos.pid"
2475
 
        if not os.path.isdir("/run/."):
2476
 
            pidfilename = "/var/run/mandos.pid"
 
2453
        pidfilename = "/var/run/mandos.pid"
2477
2454
        pidfile = None
2478
2455
        try:
2479
2456
            pidfile = open(pidfilename, "w")
2496
2473
        os.setuid(uid)
2497
2474
    except OSError as error:
2498
2475
        if error.errno != errno.EPERM:
2499
 
            raise
 
2476
            raise error
2500
2477
    
2501
2478
    if debug:
2502
2479
        # Enable all possible GnuTLS debugging
2545
2522
            use_dbus = False
2546
2523
            server_settings["use_dbus"] = False
2547
2524
            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"])))
 
2525
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
2526
    service = AvahiServiceToSyslog(name =
 
2527
                                   server_settings["servicename"],
 
2528
                                   servicetype = "_mandos._tcp",
 
2529
                                   protocol = protocol, bus = bus)
 
2530
    if server_settings["interface"]:
 
2531
        service.interface = (if_nametoindex
 
2532
                             (str(server_settings["interface"])))
2557
2533
    
2558
2534
    global multiprocessing_manager
2559
2535
    multiprocessing_manager = multiprocessing.Manager()
2753
2729
    
2754
2730
    def cleanup():
2755
2731
        "Cleanup function; run on exit"
2756
 
        if zeroconf:
2757
 
            service.cleanup()
 
2732
        service.cleanup()
2758
2733
        
2759
2734
        multiprocessing.active_children()
2760
2735
        wnull.close()
2809
2784
            else:
2810
2785
                logger.warning("Could not save persistent state:",
2811
2786
                               exc_info=e)
2812
 
                raise
 
2787
                raise e
2813
2788
        
2814
2789
        # Delete all clients, and settings from config
2815
2790
        while tcp_server.clients:
2839
2814
    tcp_server.server_activate()
2840
2815
    
2841
2816
    # Find out what port we got
2842
 
    if zeroconf:
2843
 
        service.port = tcp_server.socket.getsockname()[1]
 
2817
    service.port = tcp_server.socket.getsockname()[1]
2844
2818
    if use_ipv6:
2845
2819
        logger.info("Now listening on address %r, port %d,"
2846
2820
                    " flowinfo %d, scope_id %d",
2852
2826
    #service.interface = tcp_server.socket.getsockname()[3]
2853
2827
    
2854
2828
    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
 
2829
        # From the Avahi example code
 
2830
        try:
 
2831
            service.activate()
 
2832
        except dbus.exceptions.DBusException as error:
 
2833
            logger.critical("D-Bus Exception", exc_info=error)
 
2834
            cleanup()
 
2835
            sys.exit(1)
 
2836
        # End of Avahi example code
2864
2837
        
2865
2838
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2866
2839
                             lambda *args, **kwargs: