/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

merge

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
# and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008 Teddy Hogeborn & Björn Påhlsson
 
14
# Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
15
15
16
16
# This program is free software: you can redistribute it and/or modify
17
17
# it under the terms of the GNU General Public License as published by
24
24
#     GNU General Public License for more details.
25
25
26
26
# You should have received a copy of the GNU General Public License
27
 
# along with this program.  If not, see
28
 
# <http://www.gnu.org/licenses/>.
 
27
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
29
28
30
29
# Contact the authors at <mandos@fukt.bsnet.se>.
31
30
34
33
 
35
34
import SocketServer
36
35
import socket
 
36
import select
37
37
from optparse import OptionParser
38
38
import datetime
39
39
import errno
54
54
import stat
55
55
import logging
56
56
import logging.handlers
57
 
import pwd
58
57
 
59
58
import dbus
60
59
import gobject
61
60
import avahi
62
61
from dbus.mainloop.glib import DBusGMainLoop
63
62
import ctypes
64
 
import ctypes.util
65
63
 
66
64
version = "1.0"
67
65
 
73
71
                        ('Mandos: %(levelname)s: %(message)s'))
74
72
logger.addHandler(syslogger)
75
73
 
76
 
console = logging.StreamHandler()
77
 
console.setFormatter(logging.Formatter('%(name)s: %(levelname)s:'
78
 
                                       ' %(message)s'))
79
 
logger.addHandler(console)
80
74
 
81
75
class AvahiError(Exception):
82
76
    def __init__(self, value):
83
77
        self.value = value
84
 
        super(AvahiError, self).__init__()
85
78
    def __str__(self):
86
79
        return repr(self.value)
87
80
 
109
102
                  a sensible number of times
110
103
    """
111
104
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
112
 
                 servicetype = None, port = None, TXT = None, domain = "",
 
105
                 type = None, port = None, TXT = None, domain = "",
113
106
                 host = "", max_renames = 32768):
114
107
        self.interface = interface
115
108
        self.name = name
116
 
        self.type = servicetype
 
109
        self.type = type
117
110
        self.port = port
118
111
        if TXT is None:
119
112
            self.TXT = []
122
115
        self.domain = domain
123
116
        self.host = host
124
117
        self.rename_count = 0
125
 
        self.max_renames = max_renames
126
118
    def rename(self):
127
119
        """Derived from the Avahi example code"""
128
120
        if self.rename_count >= self.max_renames:
129
 
            logger.critical(u"No suitable Zeroconf service name found"
130
 
                            u" after %i retries, exiting.",
131
 
                            self.rename_count)
 
121
            logger.critical(u"No suitable service name found after %i"
 
122
                            u" retries, exiting.", rename_count)
132
123
            raise AvahiServiceError("Too many renames")
133
 
        self.name = server.GetAlternativeServiceName(self.name)
134
 
        logger.info(u"Changing Zeroconf service name to %r ...",
135
 
                    str(self.name))
 
124
        name = server.GetAlternativeServiceName(name)
 
125
        logger.error(u"Changing name to %r ...", name)
136
126
        syslogger.setFormatter(logging.Formatter\
137
127
                               ('Mandos (%s): %%(levelname)s:'
138
 
                               ' %%(message)s' % self.name))
 
128
                               ' %%(message)s' % name))
139
129
        self.remove()
140
130
        self.add()
141
131
        self.rename_count += 1
153
143
                     avahi.DBUS_INTERFACE_ENTRY_GROUP)
154
144
            group.connect_to_signal('StateChanged',
155
145
                                    entry_group_state_changed)
156
 
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
 
146
        logger.debug(u"Adding service '%s' of type '%s' ...",
157
147
                     service.name, service.type)
158
148
        group.AddService(
159
149
                self.interface,         # interface
223
213
    interval = property(lambda self: self._interval,
224
214
                        _set_interval)
225
215
    del _set_interval
226
 
    def __init__(self, name = None, stop_hook=None, config=None):
 
216
    def __init__(self, name = None, stop_hook=None, config={}):
227
217
        """Note: the 'checker' key in 'config' sets the
228
218
        'checker_command' attribute and *not* the 'checker'
229
219
        attribute."""
230
 
        if config is None:
231
 
            config = {}
232
220
        self.name = name
233
221
        logger.debug(u"Creating client %r", self.name)
234
222
        # Uppercase and remove spaces from fingerprint for later
240
228
        if "secret" in config:
241
229
            self.secret = config["secret"].decode(u"base64")
242
230
        elif "secfile" in config:
243
 
            secfile = open(config["secfile"])
244
 
            self.secret = secfile.read()
245
 
            secfile.close()
 
231
            sf = open(config["secfile"])
 
232
            self.secret = sf.read()
 
233
            sf.close()
246
234
        else:
247
235
            raise TypeError(u"No secret or secfile for client %s"
248
236
                            % self.name)
344
332
            try:
345
333
                logger.info(u"Starting checker %r for %s",
346
334
                            command, self.name)
347
 
                # We don't need to redirect stdout and stderr, since
348
 
                # in normal mode, that is already done by daemon(),
349
 
                # and in debug mode we don't want to.  (Stdin is
350
 
                # always replaced by /dev/null.)
351
335
                self.checker = subprocess.Popen(command,
352
336
                                                close_fds=True,
353
337
                                                shell=True, cwd="/")
354
338
                self.checker_callback_tag = gobject.child_watch_add\
355
339
                                            (self.checker.pid,
356
340
                                             self.checker_callback)
357
 
            except OSError, error:
 
341
            except subprocess.OSError, error:
358
342
                logger.error(u"Failed to start subprocess: %s",
359
343
                             error)
360
344
        # Re-run this periodically if run by gobject.timeout_add
417
401
    gnutls.library.functions.gnutls_openpgp_crt_import\
418
402
                    (crt, ctypes.byref(datum),
419
403
                     gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
420
 
    # Verify the self signature in the key
421
 
    crtverify = ctypes.c_uint()
422
 
    gnutls.library.functions.gnutls_openpgp_crt_verify_self\
423
 
        (crt, 0, ctypes.byref(crtverify))
424
 
    if crtverify.value != 0:
425
 
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
426
 
        raise gnutls.errors.CertificateSecurityError("Verify failed")
427
404
    # New buffer for the fingerprint
428
 
    buf = ctypes.create_string_buffer(20)
429
 
    buf_len = ctypes.c_size_t()
 
405
    buffer = ctypes.create_string_buffer(20)
 
406
    buffer_length = ctypes.c_size_t()
430
407
    # Get the fingerprint from the certificate into the buffer
431
408
    gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint\
432
 
        (crt, ctypes.byref(buf), ctypes.byref(buf_len))
 
409
        (crt, ctypes.byref(buffer), ctypes.byref(buffer_length))
433
410
    # Deinit the certificate
434
411
    gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
435
412
    # Convert the buffer to a Python bytestring
436
 
    fpr = ctypes.string_at(buf, buf_len.value)
 
413
    fpr = ctypes.string_at(buffer, buffer_length.value)
437
414
    # Convert the bytestring to hexadecimal notation
438
415
    hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
439
416
    return hex_fpr
440
417
 
441
418
 
442
 
class TCP_handler(SocketServer.BaseRequestHandler, object):
 
419
class tcp_handler(SocketServer.BaseRequestHandler, object):
443
420
    """A TCP request handler class.
444
421
    Instantiated by IPv6_TCPServer for each request to handle it.
445
422
    Note: This will run in its own forked process."""
472
449
        if self.server.settings["priority"]:
473
450
            priority = self.server.settings["priority"]
474
451
        gnutls.library.functions.gnutls_priority_set_direct\
475
 
            (session._c_object, priority, None)
 
452
            (session._c_object, priority, None);
476
453
        
477
454
        try:
478
455
            session.handshake()
521
498
    Attributes:
522
499
        settings:       Server settings
523
500
        clients:        Set() of Client objects
524
 
        enabled:        Boolean; whether this server is activated yet
525
501
    """
526
502
    address_family = socket.AF_INET6
527
503
    def __init__(self, *args, **kwargs):
531
507
        if "clients" in kwargs:
532
508
            self.clients = kwargs["clients"]
533
509
            del kwargs["clients"]
534
 
        self.enabled = False
535
 
        super(IPv6_TCPServer, self).__init__(*args, **kwargs)
 
510
        return super(type(self), self).__init__(*args, **kwargs)
536
511
    def server_bind(self):
537
512
        """This overrides the normal server_bind() function
538
513
        to bind to an interface if one was specified, and also NOT to
567
542
#                                            if_nametoindex
568
543
#                                            (self.settings
569
544
#                                             ["interface"]))
570
 
            return super(IPv6_TCPServer, self).server_bind()
571
 
    def server_activate(self):
572
 
        if self.enabled:
573
 
            return super(IPv6_TCPServer, self).server_activate()
574
 
    def enable(self):
575
 
        self.enabled = True
 
545
            return super(type(self), self).server_bind()
576
546
 
577
547
 
578
548
def string_to_delta(interval):
588
558
    datetime.timedelta(1)
589
559
    >>> string_to_delta(u'1w')
590
560
    datetime.timedelta(7)
591
 
    >>> string_to_delta('5m 30s')
592
 
    datetime.timedelta(0, 330)
593
561
    """
594
 
    timevalue = datetime.timedelta(0)
595
 
    for s in interval.split():
596
 
        try:
597
 
            suffix = unicode(s[-1])
598
 
            value = int(s[:-1])
599
 
            if suffix == u"d":
600
 
                delta = datetime.timedelta(value)
601
 
            elif suffix == u"s":
602
 
                delta = datetime.timedelta(0, value)
603
 
            elif suffix == u"m":
604
 
                delta = datetime.timedelta(0, 0, 0, 0, value)
605
 
            elif suffix == u"h":
606
 
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
607
 
            elif suffix == u"w":
608
 
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
609
 
            else:
610
 
                raise ValueError
611
 
        except (ValueError, IndexError):
 
562
    try:
 
563
        suffix=unicode(interval[-1])
 
564
        value=int(interval[:-1])
 
565
        if suffix == u"d":
 
566
            delta = datetime.timedelta(value)
 
567
        elif suffix == u"s":
 
568
            delta = datetime.timedelta(0, value)
 
569
        elif suffix == u"m":
 
570
            delta = datetime.timedelta(0, 0, 0, 0, value)
 
571
        elif suffix == u"h":
 
572
            delta = datetime.timedelta(0, 0, 0, 0, 0, value)
 
573
        elif suffix == u"w":
 
574
            delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
 
575
        else:
612
576
            raise ValueError
613
 
        timevalue += delta
614
 
    return timevalue
 
577
    except (ValueError, IndexError):
 
578
        raise ValueError
 
579
    return delta
615
580
 
616
581
 
617
582
def server_state_changed(state):
618
583
    """Derived from the Avahi example code"""
619
584
    if state == avahi.SERVER_COLLISION:
620
 
        logger.error(u"Zeroconf server name collision")
 
585
        logger.error(u"Server name collision")
621
586
        service.remove()
622
587
    elif state == avahi.SERVER_RUNNING:
623
588
        service.add()
625
590
 
626
591
def entry_group_state_changed(state, error):
627
592
    """Derived from the Avahi example code"""
628
 
    logger.debug(u"Avahi state change: %i", state)
 
593
    logger.debug(u"state change: %i", state)
629
594
    
630
595
    if state == avahi.ENTRY_GROUP_ESTABLISHED:
631
 
        logger.debug(u"Zeroconf service established.")
 
596
        logger.debug(u"Service established.")
632
597
    elif state == avahi.ENTRY_GROUP_COLLISION:
633
 
        logger.warning(u"Zeroconf service name collision.")
 
598
        logger.warning(u"Service name collision.")
634
599
        service.rename()
635
600
    elif state == avahi.ENTRY_GROUP_FAILURE:
636
 
        logger.critical(u"Avahi: Error in group state changed %s",
 
601
        logger.critical(u"Error in group state changed %s",
637
602
                        unicode(error))
638
603
        raise AvahiGroupError("State changed: %s", str(error))
639
604
 
641
606
    """Call the C function if_nametoindex(), or equivalent"""
642
607
    global if_nametoindex
643
608
    try:
 
609
        if "ctypes.util" not in sys.modules:
 
610
            import ctypes.util
644
611
        if_nametoindex = ctypes.cdll.LoadLibrary\
645
612
            (ctypes.util.find_library("c")).if_nametoindex
646
613
    except (OSError, AttributeError):
684
651
 
685
652
 
686
653
def main():
687
 
    parser = OptionParser(version = "%%prog %s" % version)
 
654
    global main_loop_started
 
655
    main_loop_started = False
 
656
    
 
657
    parser = OptionParser(version = "Mandos server %s" % version)
688
658
    parser.add_option("-i", "--interface", type="string",
689
659
                      metavar="IF", help="Bind to interface IF")
690
660
    parser.add_option("-a", "--address", type="string",
704
674
                      default="/etc/mandos", metavar="DIR",
705
675
                      help="Directory to search for configuration"
706
676
                      " files")
707
 
    options = parser.parse_args()[0]
 
677
    (options, args) = parser.parse_args()
708
678
    
709
679
    if options.check:
710
680
        import doctest
725
695
    server_config = ConfigParser.SafeConfigParser(server_defaults)
726
696
    del server_defaults
727
697
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
 
698
    server_section = "server"
728
699
    # Convert the SafeConfigParser object to a dict
729
 
    server_settings = server_config.defaults()
 
700
    server_settings = dict(server_config.items(server_section))
730
701
    # Use getboolean on the boolean config option
731
702
    server_settings["debug"] = server_config.getboolean\
732
 
                               ("DEFAULT", "debug")
 
703
                               (server_section, "debug")
733
704
    del server_config
734
705
    
735
706
    # Override the settings from the config file with command line
746
717
    
747
718
    if not debug:
748
719
        syslogger.setLevel(logging.WARNING)
749
 
        console.setLevel(logging.WARNING)
750
720
    
751
721
    if server_settings["servicename"] != "Mandos":
752
722
        syslogger.setFormatter(logging.Formatter\
757
727
    # Parse config file with clients
758
728
    client_defaults = { "timeout": "1h",
759
729
                        "interval": "5m",
760
 
                        "checker": "fping -q -- %(host)s",
761
 
                        "host": "",
 
730
                        "checker": "fping -q -- %%(host)s",
762
731
                        }
763
732
    client_config = ConfigParser.SafeConfigParser(client_defaults)
764
733
    client_config.read(os.path.join(server_settings["configdir"],
765
734
                                    "clients.conf"))
766
735
    
767
 
    clients = Set()
768
 
    tcp_server = IPv6_TCPServer((server_settings["address"],
769
 
                                 server_settings["port"]),
770
 
                                TCP_handler,
771
 
                                settings=server_settings,
772
 
                                clients=clients)
773
 
    pidfilename = "/var/run/mandos.pid"
774
 
    try:
775
 
        pidfile = open(pidfilename, "w")
776
 
    except IOError, error:
777
 
        logger.error("Could not open file %r", pidfilename)
778
 
    
779
 
    uid = 65534
780
 
    gid = 65534
781
 
    try:
782
 
        uid = pwd.getpwnam("mandos").pw_uid
783
 
    except KeyError:
784
 
        try:
785
 
            uid = pwd.getpwnam("nobody").pw_uid
786
 
        except KeyError:
787
 
            pass
788
 
    try:
789
 
        gid = pwd.getpwnam("mandos").pw_gid
790
 
    except KeyError:
791
 
        try:
792
 
            gid = pwd.getpwnam("nogroup").pw_gid
793
 
        except KeyError:
794
 
            pass
795
 
    try:
796
 
        os.setuid(uid)
797
 
        os.setgid(gid)
798
 
    except OSError, error:
799
 
        if error[0] != errno.EPERM:
800
 
            raise error
801
 
    
802
736
    global service
803
737
    service = AvahiService(name = server_settings["servicename"],
804
 
                           servicetype = "_mandos._tcp", )
 
738
                           type = "_mandos._tcp", );
805
739
    if server_settings["interface"]:
806
 
        service.interface = if_nametoindex\
807
 
                            (server_settings["interface"])
 
740
        service.interface = if_nametoindex(server_settings["interface"])
808
741
    
809
742
    global main_loop
810
743
    global bus
813
746
    DBusGMainLoop(set_as_default=True )
814
747
    main_loop = gobject.MainLoop()
815
748
    bus = dbus.SystemBus()
816
 
    server = dbus.Interface(bus.get_object(avahi.DBUS_NAME,
817
 
                                           avahi.DBUS_PATH_SERVER),
818
 
                            avahi.DBUS_INTERFACE_SERVER)
 
749
    server = dbus.Interface(
 
750
            bus.get_object( avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER ),
 
751
            avahi.DBUS_INTERFACE_SERVER )
819
752
    # End of Avahi example code
820
753
    
 
754
    if debug:
 
755
        console = logging.StreamHandler()
 
756
        # console.setLevel(logging.DEBUG)
 
757
        console.setFormatter(logging.Formatter\
 
758
                             ('%(levelname)s: %(message)s'))
 
759
        logger.addHandler(console)
 
760
        del console
 
761
    
 
762
    clients = Set()
821
763
    def remove_from_clients(client):
822
764
        clients.remove(client)
823
765
        if not clients:
833
775
        logger.critical(u"No clients defined")
834
776
        sys.exit(1)
835
777
    
836
 
    if debug:
837
 
        # Redirect stdin so all checkers get /dev/null
838
 
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
839
 
        os.dup2(null, sys.stdin.fileno())
840
 
        if null > 2:
841
 
            os.close(null)
842
 
    else:
843
 
        # No console logging
844
 
        logger.removeHandler(console)
845
 
        # Close all input and output, do double fork, etc.
 
778
    if not debug:
846
779
        daemon()
847
780
    
 
781
    pidfilename = "/var/run/mandos/mandos.pid"
 
782
    pid = os.getpid()
848
783
    try:
849
 
        pid = os.getpid()
 
784
        pidfile = open(pidfilename, "w")
850
785
        pidfile.write(str(pid) + "\n")
851
786
        pidfile.close()
852
787
        del pidfile
853
 
    except IOError:
854
 
        logger.error(u"Could not write to file %r with PID %d",
855
 
                     pidfilename, pid)
856
 
    except NameError:
857
 
        # "pidfile" was never created
858
 
        pass
859
 
    del pidfilename
 
788
    except IOError, err:
 
789
        logger.error(u"Could not write %s file with PID %d",
 
790
                     pidfilename, os.getpid())
860
791
    
861
792
    def cleanup():
862
793
        "Cleanup function; run on exit"
882
813
    for client in clients:
883
814
        client.start()
884
815
    
885
 
    tcp_server.enable()
886
 
    tcp_server.server_activate()
887
 
    
 
816
    tcp_server = IPv6_TCPServer((server_settings["address"],
 
817
                                 server_settings["port"]),
 
818
                                tcp_handler,
 
819
                                settings=server_settings,
 
820
                                clients=clients)
888
821
    # Find out what port we got
889
822
    service.port = tcp_server.socket.getsockname()[1]
890
823
    logger.info(u"Now listening on address %r, port %d, flowinfo %d,"
908
841
                             (*args[2:], **kwargs) or True)
909
842
        
910
843
        logger.debug(u"Starting main loop")
 
844
        main_loop_started = True
911
845
        main_loop.run()
912
846
    except AvahiError, error:
913
847
        logger.critical(u"AvahiError: %s" + unicode(error))