/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

merge + fallback bugg

Show diffs side-by-side

added added

removed removed

Lines of Context:
61
61
from dbus.mainloop.glib import DBusGMainLoop
62
62
import ctypes
63
63
 
 
64
version = "1.0"
64
65
 
65
66
logger = logging.Logger('mandos')
66
67
syslogger = logging.handlers.SysLogHandler\
67
 
            (facility = logging.handlers.SysLogHandler.LOG_DAEMON)
 
68
            (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
69
             address = "/dev/log")
68
70
syslogger.setFormatter(logging.Formatter\
69
 
                        ('%(levelname)s: %(message)s'))
 
71
                        ('Mandos: %(levelname)s: %(message)s'))
70
72
logger.addHandler(syslogger)
71
 
del syslogger
72
73
 
 
74
console = logging.StreamHandler()
 
75
console.setFormatter(logging.Formatter('%(name)s: %(levelname)s:'
 
76
                                       ' %(message)s'))
 
77
logger.addHandler(console)
73
78
 
74
79
class AvahiError(Exception):
75
80
    def __init__(self, value):
102
107
    """
103
108
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
104
109
                 type = None, port = None, TXT = None, domain = "",
105
 
                 host = "", max_renames = 12):
 
110
                 host = "", max_renames = 32768):
106
111
        self.interface = interface
107
112
        self.name = name
108
113
        self.type = type
114
119
        self.domain = domain
115
120
        self.host = host
116
121
        self.rename_count = 0
 
122
        self.max_renames = max_renames
117
123
    def rename(self):
118
124
        """Derived from the Avahi example code"""
119
125
        if self.rename_count >= self.max_renames:
120
126
            logger.critical(u"No suitable service name found after %i"
121
127
                            u" retries, exiting.", rename_count)
122
128
            raise AvahiServiceError("Too many renames")
123
 
        name = server.GetAlternativeServiceName(name)
124
 
        logger.error(u"Changing name to %r ...", name)
 
129
        self.name = server.GetAlternativeServiceName(self.name)
 
130
        logger.info(u"Changing name to %r ...", str(self.name))
 
131
        syslogger.setFormatter(logging.Formatter\
 
132
                               ('Mandos (%s): %%(levelname)s:'
 
133
                               ' %%(message)s' % self.name))
125
134
        self.remove()
126
135
        self.add()
127
136
        self.rename_count += 1
163
172
    fingerprint: string (40 or 32 hexadecimal digits); used to
164
173
                 uniquely identify the client
165
174
    secret:    bytestring; sent verbatim (over TLS) to client
166
 
    fqdn:      string (FQDN); available for use by the checker command
 
175
    host:      string; available for use by the checker command
167
176
    created:   datetime.datetime(); object creation, not client host
168
177
    last_checked_ok: datetime.datetime() or None if not yet checked OK
169
178
    timeout:   datetime.timedelta(); How long from last_checked_ok
230
239
        else:
231
240
            raise TypeError(u"No secret or secfile for client %s"
232
241
                            % self.name)
233
 
        self.fqdn = config.get("fqdn", "")
 
242
        self.host = config.get("host", "")
234
243
        self.created = datetime.datetime.now()
235
244
        self.last_checked_ok = None
236
245
        self.timeout = string_to_delta(config["timeout"])
259
268
        The possibility that a client might be restarted is left open,
260
269
        but not currently used."""
261
270
        # If this client doesn't have a secret, it is already stopped.
262
 
        if self.secret:
 
271
        if hasattr(self, "secret") and self.secret:
263
272
            logger.info(u"Stopping client %s", self.name)
264
273
            self.secret = None
265
274
        else:
313
322
        if self.checker is None:
314
323
            try:
315
324
                # In case check_command has exactly one % operator
316
 
                command = self.check_command % self.fqdn
 
325
                command = self.check_command % self.host
317
326
            except TypeError:
318
327
                # Escape attributes for the shell
319
328
                escaped_attrs = dict((key, re.escape(str(val)))
328
337
            try:
329
338
                logger.info(u"Starting checker %r for %s",
330
339
                            command, self.name)
 
340
                # We don't need to redirect stdout and stderr, since
 
341
                # in normal mode, that is already done by daemon(),
 
342
                # and in debug mode we don't want to.  (Stdin is
 
343
                # always replaced by /dev/null.)
331
344
                self.checker = subprocess.Popen(command,
332
345
                                                close_fds=True,
333
346
                                                shell=True, cwd="/")
334
347
                self.checker_callback_tag = gobject.child_watch_add\
335
348
                                            (self.checker.pid,
336
349
                                             self.checker_callback)
337
 
            except subprocess.OSError, error:
 
350
            except OSError, error:
338
351
                logger.error(u"Failed to start subprocess: %s",
339
352
                             error)
340
353
        # Re-run this periodically if run by gobject.timeout_add
346
359
            self.checker_callback_tag = None
347
360
        if getattr(self, "checker", None) is None:
348
361
            return
349
 
        logger.debug("Stopping checker for %(name)s", vars(self))
 
362
        logger.debug(u"Stopping checker for %(name)s", vars(self))
350
363
        try:
351
364
            os.kill(self.checker.pid, signal.SIGTERM)
352
365
            #os.sleep(0.5)
397
410
    gnutls.library.functions.gnutls_openpgp_crt_import\
398
411
                    (crt, ctypes.byref(datum),
399
412
                     gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
 
413
    # Verify the self signature in the key
 
414
    crtverify = ctypes.c_uint();
 
415
    gnutls.library.functions.gnutls_openpgp_crt_verify_self\
 
416
        (crt, ctypes.c_uint(0), ctypes.byref(crtverify))
 
417
    if crtverify != 0:
 
418
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
 
419
        raise gnutls.errors.CertificateSecurityError("Verify failed")
400
420
    # New buffer for the fingerprint
401
421
    buffer = ctypes.create_string_buffer(20)
402
422
    buffer_length = ctypes.c_size_t()
528
548
                in6addr_any = "::"
529
549
                self.server_address = (in6addr_any,
530
550
                                       self.server_address[1])
531
 
            elif self.server_address[1] is None:
 
551
            elif not self.server_address[1]:
532
552
                self.server_address = (self.server_address[0],
533
553
                                       0)
 
554
#                 if self.settings["interface"]:
 
555
#                     self.server_address = (self.server_address[0],
 
556
#                                            0, # port
 
557
#                                            0, # flowinfo
 
558
#                                            if_nametoindex
 
559
#                                            (self.settings
 
560
#                                             ["interface"]))
534
561
            return super(type(self), self).server_bind()
535
562
 
536
563
 
547
574
    datetime.timedelta(1)
548
575
    >>> string_to_delta(u'1w')
549
576
    datetime.timedelta(7)
 
577
    >>> string_to_delta('5m 30s')
 
578
    datetime.timedelta(0, 330)
550
579
    """
551
 
    try:
552
 
        suffix=unicode(interval[-1])
553
 
        value=int(interval[:-1])
554
 
        if suffix == u"d":
555
 
            delta = datetime.timedelta(value)
556
 
        elif suffix == u"s":
557
 
            delta = datetime.timedelta(0, value)
558
 
        elif suffix == u"m":
559
 
            delta = datetime.timedelta(0, 0, 0, 0, value)
560
 
        elif suffix == u"h":
561
 
            delta = datetime.timedelta(0, 0, 0, 0, 0, value)
562
 
        elif suffix == u"w":
563
 
            delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
564
 
        else:
 
580
    timevalue = datetime.timedelta(0)
 
581
    for s in interval.split():
 
582
        try:
 
583
            suffix=unicode(s[-1])
 
584
            value=int(s[:-1])
 
585
            if suffix == u"d":
 
586
                delta = datetime.timedelta(value)
 
587
            elif suffix == u"s":
 
588
                delta = datetime.timedelta(0, value)
 
589
            elif suffix == u"m":
 
590
                delta = datetime.timedelta(0, 0, 0, 0, value)
 
591
            elif suffix == u"h":
 
592
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
 
593
            elif suffix == u"w":
 
594
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
 
595
            else:
 
596
                raise ValueError
 
597
        except (ValueError, IndexError):
565
598
            raise ValueError
566
 
    except (ValueError, IndexError):
567
 
        raise ValueError
568
 
    return delta
 
599
        timevalue += delta
 
600
    return timevalue
569
601
 
570
602
 
571
603
def server_state_changed(state):
643
675
    global main_loop_started
644
676
    main_loop_started = False
645
677
    
646
 
    parser = OptionParser()
 
678
    parser = OptionParser(version = "%%prog %s" % version)
647
679
    parser.add_option("-i", "--interface", type="string",
648
680
                      metavar="IF", help="Bind to interface IF")
649
681
    parser.add_option("-a", "--address", type="string",
652
684
                      help="Port number to receive requests on")
653
685
    parser.add_option("--check", action="store_true", default=False,
654
686
                      help="Run self-test")
655
 
    parser.add_option("--debug", action="store_true", default=False,
 
687
    parser.add_option("--debug", action="store_true",
656
688
                      help="Debug mode; run in foreground and log to"
657
689
                      " terminal")
658
690
    parser.add_option("--priority", type="string", help="GnuTLS"
684
716
    server_config = ConfigParser.SafeConfigParser(server_defaults)
685
717
    del server_defaults
686
718
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
687
 
    server_section = "server"
688
719
    # Convert the SafeConfigParser object to a dict
689
 
    server_settings = dict(server_config.items(server_section))
 
720
    server_settings = server_config.defaults()
690
721
    # Use getboolean on the boolean config option
691
722
    server_settings["debug"] = server_config.getboolean\
692
 
                               (server_section, "debug")
 
723
                               ("DEFAULT", "debug")
693
724
    del server_config
694
725
    
695
726
    # Override the settings from the config file with command line
702
733
    del options
703
734
    # Now we have our good server settings in "server_settings"
704
735
    
 
736
    debug = server_settings["debug"]
 
737
    
 
738
    if not debug:
 
739
        syslogger.setLevel(logging.WARNING)
 
740
        console.setLevel(logging.WARNING)
 
741
    
 
742
    if server_settings["servicename"] != "Mandos":
 
743
        syslogger.setFormatter(logging.Formatter\
 
744
                               ('Mandos (%s): %%(levelname)s:'
 
745
                                ' %%(message)s'
 
746
                                % server_settings["servicename"]))
 
747
    
705
748
    # Parse config file with clients
706
749
    client_defaults = { "timeout": "1h",
707
750
                        "interval": "5m",
708
 
                        "checker": "fping -q -- %%(fqdn)s",
 
751
                        "checker": "fping -q -- %(host)s",
 
752
                        "host": "",
709
753
                        }
710
754
    client_config = ConfigParser.SafeConfigParser(client_defaults)
711
755
    client_config.read(os.path.join(server_settings["configdir"],
729
773
            avahi.DBUS_INTERFACE_SERVER )
730
774
    # End of Avahi example code
731
775
    
732
 
    debug = server_settings["debug"]
733
 
    
734
 
    if debug:
735
 
        console = logging.StreamHandler()
736
 
        # console.setLevel(logging.DEBUG)
737
 
        console.setFormatter(logging.Formatter\
738
 
                             ('%(levelname)s: %(message)s'))
739
 
        logger.addHandler(console)
740
 
        del console
741
 
    
742
776
    clients = Set()
743
777
    def remove_from_clients(client):
744
778
        clients.remove(client)
751
785
                              config
752
786
                              = dict(client_config.items(section)))
753
787
                       for section in client_config.sections()))
 
788
    if not clients:
 
789
        logger.critical(u"No clients defined")
 
790
        sys.exit(1)
754
791
    
755
 
    if not debug:
 
792
    if debug:
 
793
        # Redirect stdin so all checkers get /dev/null
 
794
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
 
795
        os.dup2(null, sys.stdin.fileno())
 
796
        if null > 2:
 
797
            os.close(null)
 
798
    else:
 
799
        # No console logging
 
800
        logger.removeHandler(console)
 
801
        # Close all input and output, do double fork, etc.
756
802
        daemon()
757
803
    
 
804
    pidfilename = "/var/run/mandos/mandos.pid"
 
805
    pid = os.getpid()
 
806
    try:
 
807
        pidfile = open(pidfilename, "w")
 
808
        pidfile.write(str(pid) + "\n")
 
809
        pidfile.close()
 
810
        del pidfile
 
811
    except IOError, err:
 
812
        logger.error(u"Could not write %s file with PID %d",
 
813
                     pidfilename, os.getpid())
 
814
    
758
815
    def cleanup():
759
816
        "Cleanup function; run on exit"
760
817
        global group
806
863
                             tcp_server.handle_request\
807
864
                             (*args[2:], **kwargs) or True)
808
865
        
809
 
        logger.debug("Starting main loop")
 
866
        logger.debug(u"Starting main loop")
810
867
        main_loop_started = True
811
868
        main_loop.run()
812
869
    except AvahiError, error: