/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-16 03:29:08 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080816032908-ihw7c05r2mnyk389
Add feature to specify custom environment variables for plugins.

* plugin-runner.c (plugin): New members "environ" and "envc" to
                            contain possible custom environment.
  (getplugin): Return NULL on failure instead of doing exit(); all
               callers changed.
  (add_to_char_array): New helper function for "add_argument" and
                       "add_environment".
  (addargument): Renamed to "add_argument".  Return bool.  Call
                 "add_to_char_array" to actually do things.
  (add_environment): New; analogous to "add_argument".
  (addcustomargument): Renamed to "add_to_argv" to avoid confusion
                       with "add_argument".
  (main): New options "--global-envs" and "--envs-for" to specify
          custom environment for plugins.  Print environment for
          plugins in debug mode.  Use asprintf instead of strcpy and
          strcat.  Use execve() for plugins with custom environments.
          Free environment for plugin when freeing plugin list.

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)))
346
355
            self.checker_callback_tag = None
347
356
        if getattr(self, "checker", None) is None:
348
357
            return
349
 
        logger.debug("Stopping checker for %(name)s", vars(self))
 
358
        logger.debug(u"Stopping checker for %(name)s", vars(self))
350
359
        try:
351
360
            os.kill(self.checker.pid, signal.SIGTERM)
352
361
            #os.sleep(0.5)
650
659
    global main_loop_started
651
660
    main_loop_started = False
652
661
    
653
 
    parser = OptionParser()
 
662
    parser = OptionParser(version = "%%prog %s" % version)
654
663
    parser.add_option("-i", "--interface", type="string",
655
664
                      metavar="IF", help="Bind to interface IF")
656
665
    parser.add_option("-a", "--address", type="string",
709
718
    del options
710
719
    # Now we have our good server settings in "server_settings"
711
720
    
 
721
    debug = server_settings["debug"]
 
722
    
 
723
    if not debug:
 
724
        syslogger.setLevel(logging.WARNING)
 
725
        console.setLevel(logging.WARNING)
 
726
    
 
727
    if server_settings["servicename"] != "Mandos":
 
728
        syslogger.setFormatter(logging.Formatter\
 
729
                               ('Mandos (%s): %%(levelname)s:'
 
730
                                ' %%(message)s'
 
731
                                % server_settings["servicename"]))
 
732
    
712
733
    # Parse config file with clients
713
734
    client_defaults = { "timeout": "1h",
714
735
                        "interval": "5m",
715
 
                        "checker": "fping -q -- %%(fqdn)s",
 
736
                        "checker": "fping -q -- %%(host)s",
716
737
                        }
717
738
    client_config = ConfigParser.SafeConfigParser(client_defaults)
718
739
    client_config.read(os.path.join(server_settings["configdir"],
736
757
            avahi.DBUS_INTERFACE_SERVER )
737
758
    # End of Avahi example code
738
759
    
739
 
    debug = server_settings["debug"]
740
 
    
741
 
    if debug:
742
 
        console = logging.StreamHandler()
743
 
        # console.setLevel(logging.DEBUG)
744
 
        console.setFormatter(logging.Formatter\
745
 
                             ('%(levelname)s: %(message)s'))
746
 
        logger.addHandler(console)
747
 
        del console
748
 
    
749
760
    clients = Set()
750
761
    def remove_from_clients(client):
751
762
        clients.remove(client)
758
769
                              config
759
770
                              = dict(client_config.items(section)))
760
771
                       for section in client_config.sections()))
 
772
    if not clients:
 
773
        logger.critical(u"No clients defined")
 
774
        sys.exit(1)
761
775
    
762
776
    if not debug:
 
777
        logger.removeHandler(console)
763
778
        daemon()
764
 
 
 
779
    
765
780
    pidfilename = "/var/run/mandos/mandos.pid"
766
781
    pid = os.getpid()
767
782
    try:
770
785
        pidfile.close()
771
786
        del pidfile
772
787
    except IOError, err:
773
 
        logger.error("Could not write %s file with PID %d",
 
788
        logger.error(u"Could not write %s file with PID %d",
774
789
                     pidfilename, os.getpid())
775
790
    
776
791
    def cleanup():
824
839
                             tcp_server.handle_request\
825
840
                             (*args[2:], **kwargs) or True)
826
841
        
827
 
        logger.debug("Starting main loop")
 
842
        logger.debug(u"Starting main loop")
828
843
        main_loop_started = True
829
844
        main_loop.run()
830
845
    except AvahiError, error: