/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-11-09 06:40:29 UTC
  • mto: (24.1.113 mandos)
  • mto: This revision was merged to the branch mainline in revision 238.
  • Revision ID: teddy@fukt.bsnet.se-20081109064029-df71jpoce308cq3v
First steps of a D-Bus interface to the server.

* mandos: Also import "dbus.service".
  (Client): Inherit from "dbus.service.Object", which is a new-style
            class, so inheriting from "object" is no longer necessary.
  (Client.interface): New temporary variable which only exists during
                     class definition.

  (Client.getName, Client.getFingerprint): New D-Bus getter methods.
  (Client.setSecret): New D-Bus setter method.
  (Client._set_timeout): Emit D-Bus signal "TimeoutChanged".
  (Client.getTimeout): New D-Bus getter method.
  (Client.TimeoutChanged): New D-Bus signal.
  (Client._set_interval): Emit D-Bus signal "IntervalChanged".
  (Client.getInterval): New D-Bus getter method.
  (Client.intervalChanged): New D-Bus signal.
  (Client.__init__): Also call "dbus.service.Object.__init__".
  (Client.started): New boolean attribute.
  (Client.start, Client.stop): Update "self.started", and emit D-Bus
                               signal "StateChanged".
  (Client.StateChanged): New D-Bus signal.
  (Client.stop): Use "self.started" instead of misusing "self.secret".
                 Also simplify code by using "getattr" instead of
                 "hasattr".
  (Client.checker_callback): Emit D-Bus signal "CheckerCompleted".
  (Client.CheckerCompleted): New D-Bus signal.
  (Client.bumpTimeout): D-Bus method name for "bump_timeout".
  (Client.start_checker): Emit D-Bus signal "CheckerStarted".
  (Client.CheckerStarted): New D-Bus signal.
  (Client.checkerIsRunning): New D-Bus method.
  (Client.StopChecker): D-Bus method name for "stop_checker".
  (Client.still_valid): First check "self.started".
  (Client.stillValid): D-Bus method name for "still_valid".

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 © 2007-2008 Teddy Hogeborn & Björn Påhlsson
 
14
# Copyright © 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
30
30
# Contact the authors at <mandos@fukt.bsnet.se>.
31
31
32
32
 
33
 
from __future__ import division
 
33
from __future__ import division, with_statement, absolute_import
34
34
 
35
35
import SocketServer
36
36
import socket
37
 
import select
38
37
from optparse import OptionParser
39
38
import datetime
40
39
import errno
56
55
import logging
57
56
import logging.handlers
58
57
import pwd
 
58
from contextlib import closing
59
59
 
60
60
import dbus
 
61
import dbus.service
61
62
import gobject
62
63
import avahi
63
64
from dbus.mainloop.glib import DBusGMainLoop
64
65
import ctypes
 
66
import ctypes.util
65
67
 
66
 
version = "1.0"
 
68
version = "1.0.2"
67
69
 
68
70
logger = logging.Logger('mandos')
69
71
syslogger = logging.handlers.SysLogHandler\
81
83
class AvahiError(Exception):
82
84
    def __init__(self, value):
83
85
        self.value = value
 
86
        super(AvahiError, self).__init__()
84
87
    def __str__(self):
85
88
        return repr(self.value)
86
89
 
108
111
                  a sensible number of times
109
112
    """
110
113
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
111
 
                 type = None, port = None, TXT = None, domain = "",
 
114
                 servicetype = None, port = None, TXT = None, domain = "",
112
115
                 host = "", max_renames = 32768):
113
116
        self.interface = interface
114
117
        self.name = name
115
 
        self.type = type
 
118
        self.type = servicetype
116
119
        self.port = port
117
120
        if TXT is None:
118
121
            self.TXT = []
127
130
        if self.rename_count >= self.max_renames:
128
131
            logger.critical(u"No suitable Zeroconf service name found"
129
132
                            u" after %i retries, exiting.",
130
 
                            rename_count)
 
133
                            self.rename_count)
131
134
            raise AvahiServiceError("Too many renames")
132
135
        self.name = server.GetAlternativeServiceName(self.name)
133
136
        logger.info(u"Changing Zeroconf service name to %r ...",
169
172
# End of Avahi example code
170
173
 
171
174
 
172
 
class Client(object):
 
175
class Client(dbus.service.Object):
173
176
    """A representation of a client host served by this server.
174
177
    Attributes:
175
178
    name:      string; from the config file, used in log messages
178
181
    secret:    bytestring; sent verbatim (over TLS) to client
179
182
    host:      string; available for use by the checker command
180
183
    created:   datetime.datetime(); object creation, not client host
 
184
    started:   bool()
181
185
    last_checked_ok: datetime.datetime() or None if not yet checked OK
182
186
    timeout:   datetime.timedelta(); How long from last_checked_ok
183
187
                                     until this client is invalid
199
203
    _timeout_milliseconds: Used when calling gobject.timeout_add()
200
204
    _interval_milliseconds: - '' -
201
205
    """
 
206
    interface = u"org.mandos_system.Mandos.Clients"
 
207
    
 
208
    @dbus.service.method(interface, out_signature="s")
 
209
    def getName(self):
 
210
        "D-Bus getter method"
 
211
        return self.name
 
212
    
 
213
    @dbus.service.method(interface, out_signature="s")
 
214
    def getFingerprint(self):
 
215
        "D-Bus getter method"
 
216
        return self.fingerprint
 
217
    
 
218
    @dbus.service.method(interface, in_signature="ay",
 
219
                         byte_arrays=True)
 
220
    def setSecret(self, secret):
 
221
        "D-Bus setter method"
 
222
        self.secret = secret
 
223
    
202
224
    def _set_timeout(self, timeout):
203
 
        "Setter function for 'timeout' attribute"
 
225
        "Setter function for the 'timeout' attribute"
204
226
        self._timeout = timeout
205
227
        self._timeout_milliseconds = ((self.timeout.days
206
228
                                       * 24 * 60 * 60 * 1000)
207
229
                                      + (self.timeout.seconds * 1000)
208
230
                                      + (self.timeout.microseconds
209
231
                                         // 1000))
210
 
    timeout = property(lambda self: self._timeout,
211
 
                       _set_timeout)
 
232
        # Emit D-Bus signal
 
233
        self.TimeoutChanged(self._timeout_milliseconds)
 
234
    timeout = property(lambda self: self._timeout, _set_timeout)
212
235
    del _set_timeout
 
236
    
 
237
    @dbus.service.method(interface, out_signature="t")
 
238
    def getTimeout(self):
 
239
        "D-Bus getter method"
 
240
        return self._timeout_milliseconds
 
241
    
 
242
    @dbus.service.signal(interface, signature="t")
 
243
    def TimeoutChanged(self, t):
 
244
        "D-Bus signal"
 
245
        pass
 
246
    
213
247
    def _set_interval(self, interval):
214
 
        "Setter function for 'interval' attribute"
 
248
        "Setter function for the 'interval' attribute"
215
249
        self._interval = interval
216
250
        self._interval_milliseconds = ((self.interval.days
217
251
                                        * 24 * 60 * 60 * 1000)
219
253
                                          * 1000)
220
254
                                       + (self.interval.microseconds
221
255
                                          // 1000))
222
 
    interval = property(lambda self: self._interval,
223
 
                        _set_interval)
 
256
        # Emit D-Bus signal
 
257
        self.IntervalChanged(self._interval_milliseconds)
 
258
    interval = property(lambda self: self._interval, _set_interval)
224
259
    del _set_interval
225
 
    def __init__(self, name = None, stop_hook=None, config={}):
 
260
    
 
261
    @dbus.service.method(interface, out_signature="t")
 
262
    def getInterval(self):
 
263
        "D-Bus getter method"
 
264
        return self._interval_milliseconds
 
265
    
 
266
    @dbus.service.signal(interface, signature="t")
 
267
    def IntervalChanged(self, t):
 
268
        "D-Bus signal"
 
269
        pass
 
270
    
 
271
    def __init__(self, name = None, stop_hook=None, config=None):
226
272
        """Note: the 'checker' key in 'config' sets the
227
273
        'checker_command' attribute and *not* the 'checker'
228
274
        attribute."""
 
275
        dbus.service.Object.__init__(self, bus,
 
276
                                     "/Mandos/Clients/%s"
 
277
                                     % name.replace(".", "_"))
 
278
        if config is None:
 
279
            config = {}
229
280
        self.name = name
230
281
        logger.debug(u"Creating client %r", self.name)
231
282
        # Uppercase and remove spaces from fingerprint for later
237
288
        if "secret" in config:
238
289
            self.secret = config["secret"].decode(u"base64")
239
290
        elif "secfile" in config:
240
 
            sf = open(config["secfile"])
241
 
            self.secret = sf.read()
242
 
            sf.close()
 
291
            with closing(open(os.path.expanduser
 
292
                              (os.path.expandvars
 
293
                               (config["secfile"])))) \
 
294
                               as secfile:
 
295
                self.secret = secfile.read()
243
296
        else:
244
297
            raise TypeError(u"No secret or secfile for client %s"
245
298
                            % self.name)
246
299
        self.host = config.get("host", "")
247
300
        self.created = datetime.datetime.now()
 
301
        self.started = False
248
302
        self.last_checked_ok = None
249
303
        self.timeout = string_to_delta(config["timeout"])
250
304
        self.interval = string_to_delta(config["interval"])
254
308
        self.stop_initiator_tag = None
255
309
        self.checker_callback_tag = None
256
310
        self.check_command = config["checker"]
 
311
    
257
312
    def start(self):
258
313
        """Start this client's checker and timeout hooks"""
 
314
        self.started = True
259
315
        # Schedule a new checker to be started an 'interval' from now,
260
316
        # and every interval from then on.
261
317
        self.checker_initiator_tag = gobject.timeout_add\
267
323
        self.stop_initiator_tag = gobject.timeout_add\
268
324
                                  (self._timeout_milliseconds,
269
325
                                   self.stop)
 
326
        # Emit D-Bus signal
 
327
        self.StateChanged(True)
 
328
    
 
329
    @dbus.service.signal(interface, signature="b")
 
330
    def StateChanged(self, started):
 
331
        "D-Bus signal"
 
332
        pass
 
333
    
270
334
    def stop(self):
271
 
        """Stop this client.
272
 
        The possibility that a client might be restarted is left open,
273
 
        but not currently used."""
274
 
        # If this client doesn't have a secret, it is already stopped.
275
 
        if hasattr(self, "secret") and self.secret:
 
335
        """Stop this client."""
 
336
        if getattr(self, "started", False):
276
337
            logger.info(u"Stopping client %s", self.name)
277
 
            self.secret = None
278
338
        else:
279
339
            return False
280
340
        if getattr(self, "stop_initiator_tag", False):
286
346
        self.stop_checker()
287
347
        if self.stop_hook:
288
348
            self.stop_hook(self)
 
349
        # Emit D-Bus signal
 
350
        self.StateChanged(False)
289
351
        # Do not run this again if called by a gobject.timeout_add
290
352
        return False
 
353
    # D-Bus variant
 
354
    Stop = dbus.service.method(interface)(stop)
 
355
    
291
356
    def __del__(self):
292
357
        self.stop_hook = None
293
358
        self.stop()
 
359
    
294
360
    def checker_callback(self, pid, condition):
295
361
        """The checker has completed, so take appropriate actions."""
296
 
        now = datetime.datetime.now()
297
362
        self.checker_callback_tag = None
298
363
        self.checker = None
299
364
        if os.WIFEXITED(condition) \
300
365
               and (os.WEXITSTATUS(condition) == 0):
301
366
            logger.info(u"Checker for %(name)s succeeded",
302
367
                        vars(self))
303
 
            self.last_checked_ok = now
304
 
            gobject.source_remove(self.stop_initiator_tag)
305
 
            self.stop_initiator_tag = gobject.timeout_add\
306
 
                                      (self._timeout_milliseconds,
307
 
                                       self.stop)
 
368
            # Emit D-Bus signal
 
369
            self.CheckerCompleted(True)
 
370
            self.bump_timeout()
308
371
        elif not os.WIFEXITED(condition):
309
372
            logger.warning(u"Checker for %(name)s crashed?",
310
373
                           vars(self))
 
374
            # Emit D-Bus signal
 
375
            self.CheckerCompleted(False)
311
376
        else:
312
377
            logger.info(u"Checker for %(name)s failed",
313
378
                        vars(self))
 
379
            # Emit D-Bus signal
 
380
            self.CheckerCompleted(False)
 
381
    
 
382
    @dbus.service.signal(interface, signature="b")
 
383
    def CheckerCompleted(self, success):
 
384
        "D-Bus signal"
 
385
        pass
 
386
    
 
387
    def bump_timeout(self):
 
388
        """Bump up the timeout for this client.
 
389
        This should only be called when the client has been seen,
 
390
        alive and well.
 
391
        """
 
392
        self.last_checked_ok = datetime.datetime.now()
 
393
        gobject.source_remove(self.stop_initiator_tag)
 
394
        self.stop_initiator_tag = gobject.timeout_add\
 
395
            (self._timeout_milliseconds, self.stop)
 
396
    # D-Bus variant
 
397
    bumpTimeout = dbus.service.method(interface)(bump_timeout)
 
398
    
314
399
    def start_checker(self):
315
400
        """Start a new checker subprocess if one is not running.
316
401
        If a checker already exists, leave it running and do
351
436
                self.checker_callback_tag = gobject.child_watch_add\
352
437
                                            (self.checker.pid,
353
438
                                             self.checker_callback)
 
439
                # Emit D-Bus signal
 
440
                self.CheckerStarted(command)
354
441
            except OSError, error:
355
442
                logger.error(u"Failed to start subprocess: %s",
356
443
                             error)
357
444
        # Re-run this periodically if run by gobject.timeout_add
358
445
        return True
 
446
    
 
447
    @dbus.service.signal(interface, signature="s")
 
448
    def CheckerStarted(self, command):
 
449
        pass
 
450
    
 
451
    @dbus.service.method(interface, out_signature="b")
 
452
    def checkerIsRunning(self):
 
453
        "D-Bus getter method"
 
454
        return self.checker is not None
 
455
    
359
456
    def stop_checker(self):
360
457
        """Force the checker process, if any, to stop."""
361
458
        if self.checker_callback_tag:
373
470
            if error.errno != errno.ESRCH: # No such process
374
471
                raise
375
472
        self.checker = None
 
473
    # D-Bus variant
 
474
    StopChecker = dbus.service.method(interface)(stop_checker)
 
475
    
376
476
    def still_valid(self):
377
477
        """Has the timeout not yet passed for this client?"""
 
478
        if not self.started:
 
479
            return False
378
480
        now = datetime.datetime.now()
379
481
        if self.last_checked_ok is None:
380
482
            return now < (self.created + self.timeout)
381
483
        else:
382
484
            return now < (self.last_checked_ok + self.timeout)
 
485
    # D-Bus variant
 
486
    stillValid = dbus.service.method(interface, out_signature="b")\
 
487
        (still_valid)
 
488
    
 
489
    del interface
383
490
 
384
491
 
385
492
def peer_certificate(session):
415
522
                    (crt, ctypes.byref(datum),
416
523
                     gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
417
524
    # Verify the self signature in the key
418
 
    crtverify = ctypes.c_uint();
 
525
    crtverify = ctypes.c_uint()
419
526
    gnutls.library.functions.gnutls_openpgp_crt_verify_self\
420
527
        (crt, 0, ctypes.byref(crtverify))
421
528
    if crtverify.value != 0:
422
529
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
423
530
        raise gnutls.errors.CertificateSecurityError("Verify failed")
424
531
    # New buffer for the fingerprint
425
 
    buffer = ctypes.create_string_buffer(20)
426
 
    buffer_length = ctypes.c_size_t()
 
532
    buf = ctypes.create_string_buffer(20)
 
533
    buf_len = ctypes.c_size_t()
427
534
    # Get the fingerprint from the certificate into the buffer
428
535
    gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint\
429
 
        (crt, ctypes.byref(buffer), ctypes.byref(buffer_length))
 
536
        (crt, ctypes.byref(buf), ctypes.byref(buf_len))
430
537
    # Deinit the certificate
431
538
    gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
432
539
    # Convert the buffer to a Python bytestring
433
 
    fpr = ctypes.string_at(buffer, buffer_length.value)
 
540
    fpr = ctypes.string_at(buf, buf_len.value)
434
541
    # Convert the bytestring to hexadecimal notation
435
542
    hex_fpr = u''.join(u"%02X" % ord(char) for char in fpr)
436
543
    return hex_fpr
437
544
 
438
545
 
439
 
class tcp_handler(SocketServer.BaseRequestHandler, object):
 
546
class TCP_handler(SocketServer.BaseRequestHandler, object):
440
547
    """A TCP request handler class.
441
548
    Instantiated by IPv6_TCPServer for each request to handle it.
442
549
    Note: This will run in its own forked process."""
443
550
    
444
551
    def handle(self):
445
552
        logger.info(u"TCP connection from: %s",
446
 
                     unicode(self.client_address))
 
553
                    unicode(self.client_address))
447
554
        session = gnutls.connection.ClientSession\
448
555
                  (self.request, gnutls.connection.X509Credentials())
449
556
        
464
571
        #priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
465
572
        #                "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
466
573
        #                "+DHE-DSS"))
467
 
        priority = "NORMAL"             # Fallback default, since this
468
 
                                        # MUST be set.
469
 
        if self.server.settings["priority"]:
470
 
            priority = self.server.settings["priority"]
 
574
        # Use a fallback default, since this MUST be set.
 
575
        priority = self.server.settings.get("priority", "NORMAL")
471
576
        gnutls.library.functions.gnutls_priority_set_direct\
472
 
            (session._c_object, priority, None);
 
577
            (session._c_object, priority, None)
473
578
        
474
579
        try:
475
580
            session.handshake()
503
608
                           vars(client))
504
609
            session.bye()
505
610
            return
 
611
        ## This won't work here, since we're in a fork.
 
612
        # client.bump_timeout()
506
613
        sent_size = 0
507
614
        while sent_size < len(client.secret):
508
615
            sent = session.send(client.secret[sent_size:])
513
620
        session.bye()
514
621
 
515
622
 
516
 
class IPv6_TCPServer(SocketServer.ForkingTCPServer, object):
 
623
class IPv6_TCPServer(SocketServer.ForkingMixIn,
 
624
                     SocketServer.TCPServer, object):
517
625
    """IPv6 TCP server.  Accepts 'None' as address and/or port.
518
626
    Attributes:
519
627
        settings:       Server settings
529
637
            self.clients = kwargs["clients"]
530
638
            del kwargs["clients"]
531
639
        self.enabled = False
532
 
        return super(type(self), self).__init__(*args, **kwargs)
 
640
        super(IPv6_TCPServer, self).__init__(*args, **kwargs)
533
641
    def server_bind(self):
534
642
        """This overrides the normal server_bind() function
535
643
        to bind to an interface if one was specified, and also NOT to
564
672
#                                            if_nametoindex
565
673
#                                            (self.settings
566
674
#                                             ["interface"]))
567
 
            return super(type(self), self).server_bind()
 
675
            return super(IPv6_TCPServer, self).server_bind()
568
676
    def server_activate(self):
569
677
        if self.enabled:
570
 
            return super(type(self), self).server_activate()
 
678
            return super(IPv6_TCPServer, self).server_activate()
571
679
    def enable(self):
572
680
        self.enabled = True
573
681
 
591
699
    timevalue = datetime.timedelta(0)
592
700
    for s in interval.split():
593
701
        try:
594
 
            suffix=unicode(s[-1])
595
 
            value=int(s[:-1])
 
702
            suffix = unicode(s[-1])
 
703
            value = int(s[:-1])
596
704
            if suffix == u"d":
597
705
                delta = datetime.timedelta(value)
598
706
            elif suffix == u"s":
638
746
    """Call the C function if_nametoindex(), or equivalent"""
639
747
    global if_nametoindex
640
748
    try:
641
 
        if "ctypes.util" not in sys.modules:
642
 
            import ctypes.util
643
749
        if_nametoindex = ctypes.cdll.LoadLibrary\
644
750
            (ctypes.util.find_library("c")).if_nametoindex
645
751
    except (OSError, AttributeError):
650
756
        def if_nametoindex(interface):
651
757
            "Get an interface index the hard way, i.e. using fcntl()"
652
758
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
653
 
            s = socket.socket()
654
 
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
655
 
                                struct.pack("16s16x", interface))
656
 
            s.close()
 
759
            with closing(socket.socket()) as s:
 
760
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
 
761
                                    struct.pack("16s16x", interface))
657
762
            interface_index = struct.unpack("I", ifreq[16:20])[0]
658
763
            return interface_index
659
764
    return if_nametoindex(interface)
683
788
 
684
789
 
685
790
def main():
686
 
    global main_loop_started
687
 
    main_loop_started = False
688
 
    
689
791
    parser = OptionParser(version = "%%prog %s" % version)
690
792
    parser.add_option("-i", "--interface", type="string",
691
793
                      metavar="IF", help="Bind to interface IF")
706
808
                      default="/etc/mandos", metavar="DIR",
707
809
                      help="Directory to search for configuration"
708
810
                      " files")
709
 
    (options, args) = parser.parse_args()
 
811
    options = parser.parse_args()[0]
710
812
    
711
813
    if options.check:
712
814
        import doctest
769
871
    clients = Set()
770
872
    tcp_server = IPv6_TCPServer((server_settings["address"],
771
873
                                 server_settings["port"]),
772
 
                                tcp_handler,
 
874
                                TCP_handler,
773
875
                                settings=server_settings,
774
876
                                clients=clients)
775
877
    pidfilename = "/var/run/mandos.pid"
803
905
    
804
906
    global service
805
907
    service = AvahiService(name = server_settings["servicename"],
806
 
                           type = "_mandos._tcp", );
 
908
                           servicetype = "_mandos._tcp", )
807
909
    if server_settings["interface"]:
808
910
        service.interface = if_nametoindex\
809
911
                            (server_settings["interface"])
852
954
        pidfile.write(str(pid) + "\n")
853
955
        pidfile.close()
854
956
        del pidfile
855
 
    except IOError, err:
 
957
    except IOError:
856
958
        logger.error(u"Could not write to file %r with PID %d",
857
959
                     pidfilename, pid)
858
960
    except NameError:
910
1012
                             (*args[2:], **kwargs) or True)
911
1013
        
912
1014
        logger.debug(u"Starting main loop")
913
 
        main_loop_started = True
914
1015
        main_loop.run()
915
1016
    except AvahiError, error:
916
1017
        logger.critical(u"AvahiError: %s" + unicode(error))