/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: 2008-08-09 15:56:13 UTC
  • mfrom: (24.1.29 mandos)
  • Revision ID: teddy@fukt.bsnet.se-20080809155613-pm1o10yh44nafc0g
Merge.

Show diffs side-by-side

added added

removed removed

Lines of Context:
6
6
# This program is partly derived from an example program for an Avahi
7
7
# service publisher, downloaded from
8
8
# <http://avahi.org/wiki/PythonPublishExample>.  This includes the
9
 
# following functions: "AvahiService.add", "AvahiService.remove",
10
 
# "server_state_changed", "entry_group_state_changed", and some lines
11
 
# in "main".
 
9
# methods "add" and "remove" in the "AvahiService" class, the
 
10
# "server_state_changed" and "entry_group_state_changed" functions,
 
11
# and some lines in "main".
12
12
13
13
# Everything else is
14
14
# Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
61
61
from dbus.mainloop.glib import DBusGMainLoop
62
62
import ctypes
63
63
 
64
 
# Brief description of the operation of this program:
65
 
66
 
# This server announces itself as a Zeroconf service.  Connecting
67
 
# clients use the TLS protocol, with the unusual quirk that this
68
 
# server program acts as a TLS "client" while a connecting client acts
69
 
# as a TLS "server".  The client (acting as a TLS "server") must
70
 
# supply an OpenPGP certificate, and the fingerprint of this
71
 
# certificate is used by this server to look up (in a list read from a
72
 
# file at start time) which binary blob to give the client.  No other
73
 
# authentication or authorization is done by this server.
74
 
 
75
64
 
76
65
logger = logging.Logger('mandos')
77
66
syslogger = logging.handlers.SysLogHandler\
78
 
            (facility = logging.handlers.SysLogHandler.LOG_DAEMON)
 
67
            (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
68
             address = "/dev/log")
79
69
syslogger.setFormatter(logging.Formatter\
80
 
                        ('%(levelname)s: %(message)s'))
 
70
                        ('Mandos: %(levelname)s: %(message)s'))
81
71
logger.addHandler(syslogger)
82
 
del syslogger
83
72
 
84
73
 
85
74
class AvahiError(Exception):
113
102
    """
114
103
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
115
104
                 type = None, port = None, TXT = None, domain = "",
116
 
                 host = "", max_renames = 12):
 
105
                 host = "", max_renames = 32768):
117
106
        self.interface = interface
118
107
        self.name = name
119
108
        self.type = type
133
122
            raise AvahiServiceError("Too many renames")
134
123
        name = server.GetAlternativeServiceName(name)
135
124
        logger.error(u"Changing name to %r ...", name)
 
125
        syslogger.setFormatter(logging.Formatter\
 
126
                               ('Mandos (%s): %%(levelname)s:'
 
127
                               ' %%(message)s' % name))
136
128
        self.remove()
137
129
        self.add()
138
130
        self.rename_count += 1
174
166
    fingerprint: string (40 or 32 hexadecimal digits); used to
175
167
                 uniquely identify the client
176
168
    secret:    bytestring; sent verbatim (over TLS) to client
177
 
    fqdn:      string (FQDN); available for use by the checker command
 
169
    host:      string; available for use by the checker command
178
170
    created:   datetime.datetime(); object creation, not client host
179
171
    last_checked_ok: datetime.datetime() or None if not yet checked OK
180
172
    timeout:   datetime.timedelta(); How long from last_checked_ok
241
233
        else:
242
234
            raise TypeError(u"No secret or secfile for client %s"
243
235
                            % self.name)
244
 
        self.fqdn = config.get("fqdn", "")
 
236
        self.host = config.get("host", "")
245
237
        self.created = datetime.datetime.now()
246
238
        self.last_checked_ok = None
247
239
        self.timeout = string_to_delta(config["timeout"])
270
262
        The possibility that a client might be restarted is left open,
271
263
        but not currently used."""
272
264
        # If this client doesn't have a secret, it is already stopped.
273
 
        if self.secret:
 
265
        if hasattr(self, "secret") and self.secret:
274
266
            logger.info(u"Stopping client %s", self.name)
275
267
            self.secret = None
276
268
        else:
324
316
        if self.checker is None:
325
317
            try:
326
318
                # In case check_command has exactly one % operator
327
 
                command = self.check_command % self.fqdn
 
319
                command = self.check_command % self.host
328
320
            except TypeError:
329
321
                # Escape attributes for the shell
330
322
                escaped_attrs = dict((key, re.escape(str(val)))
357
349
            self.checker_callback_tag = None
358
350
        if getattr(self, "checker", None) is None:
359
351
            return
360
 
        logger.debug("Stopping checker for %(name)s", vars(self))
 
352
        logger.debug(u"Stopping checker for %(name)s", vars(self))
361
353
        try:
362
354
            os.kill(self.checker.pid, signal.SIGTERM)
363
355
            #os.sleep(0.5)
539
531
                in6addr_any = "::"
540
532
                self.server_address = (in6addr_any,
541
533
                                       self.server_address[1])
542
 
            elif self.server_address[1] is None:
 
534
            elif not self.server_address[1]:
543
535
                self.server_address = (self.server_address[0],
544
536
                                       0)
 
537
#                 if self.settings["interface"]:
 
538
#                     self.server_address = (self.server_address[0],
 
539
#                                            0, # port
 
540
#                                            0, # flowinfo
 
541
#                                            if_nametoindex
 
542
#                                            (self.settings
 
543
#                                             ["interface"]))
545
544
            return super(type(self), self).server_bind()
546
545
 
547
546
 
627
626
    return if_nametoindex(interface)
628
627
 
629
628
 
630
 
def daemon(nochdir, noclose):
 
629
def daemon(nochdir = False, noclose = False):
631
630
    """See daemon(3).  Standard BSD Unix function.
632
631
    This should really exist as os.daemon, but it doesn't (yet)."""
633
632
    if os.fork():
635
634
    os.setsid()
636
635
    if not nochdir:
637
636
        os.chdir("/")
 
637
    if os.fork():
 
638
        sys.exit()
638
639
    if not noclose:
639
640
        # Close all standard open file descriptors
640
641
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
661
662
                      help="Port number to receive requests on")
662
663
    parser.add_option("--check", action="store_true", default=False,
663
664
                      help="Run self-test")
664
 
    parser.add_option("--debug", action="store_true", default=False,
 
665
    parser.add_option("--debug", action="store_true",
665
666
                      help="Debug mode; run in foreground and log to"
666
667
                      " terminal")
667
668
    parser.add_option("--priority", type="string", help="GnuTLS"
692
693
    # Parse config file for server-global settings
693
694
    server_config = ConfigParser.SafeConfigParser(server_defaults)
694
695
    del server_defaults
695
 
    server_config.read(os.path.join(options.configdir, "server.conf"))
 
696
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
696
697
    server_section = "server"
697
698
    # Convert the SafeConfigParser object to a dict
698
699
    server_settings = dict(server_config.items(server_section))
711
712
    del options
712
713
    # Now we have our good server settings in "server_settings"
713
714
    
 
715
    debug = server_settings["debug"]
 
716
    
 
717
    if not debug:
 
718
        syslogger.setLevel(logging.WARNING)
 
719
    
 
720
    if server_settings["servicename"] != "Mandos":
 
721
        syslogger.setFormatter(logging.Formatter\
 
722
                               ('Mandos (%s): %%(levelname)s:'
 
723
                                ' %%(message)s'
 
724
                                % server_settings["servicename"]))
 
725
    
714
726
    # Parse config file with clients
715
727
    client_defaults = { "timeout": "1h",
716
728
                        "interval": "5m",
717
 
                        "checker": "fping -q -- %%(fqdn)s",
 
729
                        "checker": "fping -q -- %%(host)s",
718
730
                        }
719
731
    client_config = ConfigParser.SafeConfigParser(client_defaults)
720
732
    client_config.read(os.path.join(server_settings["configdir"],
738
750
            avahi.DBUS_INTERFACE_SERVER )
739
751
    # End of Avahi example code
740
752
    
741
 
    debug = server_settings["debug"]
742
 
    
743
753
    if debug:
744
754
        console = logging.StreamHandler()
745
755
        # console.setLevel(logging.DEBUG)
760
770
                              config
761
771
                              = dict(client_config.items(section)))
762
772
                       for section in client_config.sections()))
 
773
    if not clients:
 
774
        logger.critical(u"No clients defined")
 
775
        sys.exit(1)
763
776
    
764
777
    if not debug:
765
 
        daemon(False, False)
 
778
        daemon()
 
779
    
 
780
    pidfilename = "/var/run/mandos/mandos.pid"
 
781
    pid = os.getpid()
 
782
    try:
 
783
        pidfile = open(pidfilename, "w")
 
784
        pidfile.write(str(pid) + "\n")
 
785
        pidfile.close()
 
786
        del pidfile
 
787
    except IOError, err:
 
788
        logger.error(u"Could not write %s file with PID %d",
 
789
                     pidfilename, os.getpid())
766
790
    
767
791
    def cleanup():
768
792
        "Cleanup function; run on exit"
815
839
                             tcp_server.handle_request\
816
840
                             (*args[2:], **kwargs) or True)
817
841
        
818
 
        logger.debug("Starting main loop")
 
842
        logger.debug(u"Starting main loop")
819
843
        main_loop_started = True
820
844
        main_loop.run()
821
845
    except AvahiError, error: