/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: 2009-01-10 06:00:50 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090110060050-6v5y342fit0233pg
* plugins.d/askpass-fifo.c: Fix name in header.
* plugins.d/mandos-client.c: - '' -
* plugins.d/password-prompt.c: - '' -
* plugins.d/splashy.c: - '' -
* plugins.d/usplash.c: - '' -

Show diffs side-by-side

added added

removed removed

Lines of Context:
35
35
 
36
36
import SocketServer
37
37
import socket
38
 
import optparse
 
38
from optparse import OptionParser
39
39
import datetime
40
40
import errno
41
41
import gnutls.crypto
66
66
import ctypes
67
67
import ctypes.util
68
68
 
69
 
version = "1.0.8"
 
69
version = "1.0.3"
70
70
 
71
71
logger = logging.Logger('mandos')
72
72
syslogger = (logging.handlers.SysLogHandler
73
73
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
74
74
              address = "/dev/log"))
75
75
syslogger.setFormatter(logging.Formatter
76
 
                       ('Mandos [%(process)d]: %(levelname)s:'
77
 
                        ' %(message)s'))
 
76
                       ('Mandos: %(levelname)s: %(message)s'))
78
77
logger.addHandler(syslogger)
79
78
 
80
79
console = logging.StreamHandler()
81
 
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
82
 
                                       ' %(levelname)s: %(message)s'))
 
80
console.setFormatter(logging.Formatter('%(name)s: %(levelname)s:'
 
81
                                       ' %(message)s'))
83
82
logger.addHandler(console)
84
83
 
85
84
class AvahiError(Exception):
114
113
    """
115
114
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
116
115
                 servicetype = None, port = None, TXT = None,
117
 
                 domain = "", host = "", max_renames = 32768,
118
 
                 protocol = avahi.PROTO_UNSPEC):
 
116
                 domain = "", host = "", max_renames = 32768):
119
117
        self.interface = interface
120
118
        self.name = name
121
119
        self.type = servicetype
125
123
        self.host = host
126
124
        self.rename_count = 0
127
125
        self.max_renames = max_renames
128
 
        self.protocol = protocol
129
126
    def rename(self):
130
127
        """Derived from the Avahi example code"""
131
128
        if self.rename_count >= self.max_renames:
137
134
        logger.info(u"Changing Zeroconf service name to %r ...",
138
135
                    str(self.name))
139
136
        syslogger.setFormatter(logging.Formatter
140
 
                               ('Mandos (%s) [%%(process)d]:'
141
 
                                ' %%(levelname)s: %%(message)s'
142
 
                                % self.name))
 
137
                               ('Mandos (%s): %%(levelname)s:'
 
138
                                ' %%(message)s' % self.name))
143
139
        self.remove()
144
140
        self.add()
145
141
        self.rename_count += 1
161
157
                     service.name, service.type)
162
158
        group.AddService(
163
159
                self.interface,         # interface
164
 
                self.protocol,          # protocol
 
160
                avahi.PROTO_INET6,      # protocol
165
161
                dbus.UInt32(0),         # flags
166
162
                self.name, self.type,
167
163
                self.domain, self.host,
179
175
    return dbus.String(dt.isoformat(), variant_level=variant_level)
180
176
 
181
177
 
182
 
class Client(object):
 
178
class Client(dbus.service.Object):
183
179
    """A representation of a client host served by this server.
184
180
    Attributes:
185
 
    name:       string; from the config file, used in log messages and
186
 
                        D-Bus identifiers
 
181
    name:       string; from the config file, used in log messages
187
182
    fingerprint: string (40 or 32 hexadecimal digits); used to
188
183
                 uniquely identify the client
189
184
    secret:     bytestring; sent verbatim (over TLS) to client
206
201
                     client lives.  %() expansions are done at
207
202
                     runtime with vars(self) as dict, so that for
208
203
                     instance %(name)s can be used in the command.
209
 
    current_checker_command: string; current running checker_command
 
204
    use_dbus: bool(); Whether to provide D-Bus interface and signals
 
205
    dbus_object_path: dbus.ObjectPath ; only set if self.use_dbus
210
206
    """
211
207
    def timeout_milliseconds(self):
212
208
        "Return the 'timeout' attribute in milliseconds"
220
216
                + (self.interval.seconds * 1000)
221
217
                + (self.interval.microseconds // 1000))
222
218
    
223
 
    def __init__(self, name = None, disable_hook=None, config=None):
 
219
    def __init__(self, name = None, disable_hook=None, config=None,
 
220
                 use_dbus=True):
224
221
        """Note: the 'checker' key in 'config' sets the
225
222
        'checker_command' attribute and *not* the 'checker'
226
223
        attribute."""
228
225
        if config is None:
229
226
            config = {}
230
227
        logger.debug(u"Creating client %r", self.name)
 
228
        self.use_dbus = use_dbus
 
229
        if self.use_dbus:
 
230
            self.dbus_object_path = (dbus.ObjectPath
 
231
                                     ("/Mandos/clients/"
 
232
                                      + self.name.replace(".", "_")))
 
233
            dbus.service.Object.__init__(self, bus,
 
234
                                         self.dbus_object_path)
231
235
        # Uppercase and remove spaces from fingerprint for later
232
236
        # comparison purposes with return value from the fingerprint()
233
237
        # function
257
261
        self.disable_initiator_tag = None
258
262
        self.checker_callback_tag = None
259
263
        self.checker_command = config["checker"]
260
 
        self.current_checker_command = None
261
 
        self.last_connect = None
262
264
    
263
265
    def enable(self):
264
266
        """Start this client's checker and timeout hooks"""
275
277
                                   (self.timeout_milliseconds(),
276
278
                                    self.disable))
277
279
        self.enabled = True
 
280
        if self.use_dbus:
 
281
            # Emit D-Bus signals
 
282
            self.PropertyChanged(dbus.String(u"enabled"),
 
283
                                 dbus.Boolean(True, variant_level=1))
 
284
            self.PropertyChanged(dbus.String(u"last_enabled"),
 
285
                                 (_datetime_to_dbus(self.last_enabled,
 
286
                                                    variant_level=1)))
278
287
    
279
288
    def disable(self):
280
289
        """Disable this client."""
291
300
        if self.disable_hook:
292
301
            self.disable_hook(self)
293
302
        self.enabled = False
 
303
        if self.use_dbus:
 
304
            # Emit D-Bus signal
 
305
            self.PropertyChanged(dbus.String(u"enabled"),
 
306
                                 dbus.Boolean(False, variant_level=1))
294
307
        # Do not run this again if called by a gobject.timeout_add
295
308
        return False
296
309
    
302
315
        """The checker has completed, so take appropriate actions."""
303
316
        self.checker_callback_tag = None
304
317
        self.checker = None
305
 
        if os.WIFEXITED(condition):
306
 
            exitstatus = os.WEXITSTATUS(condition)
307
 
            if exitstatus == 0:
308
 
                logger.info(u"Checker for %(name)s succeeded",
309
 
                            vars(self))
310
 
                self.checked_ok()
311
 
            else:
312
 
                logger.info(u"Checker for %(name)s failed",
313
 
                            vars(self))
314
 
        else:
 
318
        if self.use_dbus:
 
319
            # Emit D-Bus signal
 
320
            self.PropertyChanged(dbus.String(u"checker_running"),
 
321
                                 dbus.Boolean(False, variant_level=1))
 
322
        if (os.WIFEXITED(condition)
 
323
            and (os.WEXITSTATUS(condition) == 0)):
 
324
            logger.info(u"Checker for %(name)s succeeded",
 
325
                        vars(self))
 
326
            if self.use_dbus:
 
327
                # Emit D-Bus signal
 
328
                self.CheckerCompleted(dbus.Boolean(True),
 
329
                                      dbus.UInt16(condition),
 
330
                                      dbus.String(command))
 
331
            self.bump_timeout()
 
332
        elif not os.WIFEXITED(condition):
315
333
            logger.warning(u"Checker for %(name)s crashed?",
316
334
                           vars(self))
 
335
            if self.use_dbus:
 
336
                # Emit D-Bus signal
 
337
                self.CheckerCompleted(dbus.Boolean(False),
 
338
                                      dbus.UInt16(condition),
 
339
                                      dbus.String(command))
 
340
        else:
 
341
            logger.info(u"Checker for %(name)s failed",
 
342
                        vars(self))
 
343
            if self.use_dbus:
 
344
                # Emit D-Bus signal
 
345
                self.CheckerCompleted(dbus.Boolean(False),
 
346
                                      dbus.UInt16(condition),
 
347
                                      dbus.String(command))
317
348
    
318
 
    def checked_ok(self):
 
349
    def bump_timeout(self):
319
350
        """Bump up the timeout for this client.
320
351
        This should only be called when the client has been seen,
321
352
        alive and well.
325
356
        self.disable_initiator_tag = (gobject.timeout_add
326
357
                                      (self.timeout_milliseconds(),
327
358
                                       self.disable))
 
359
        if self.use_dbus:
 
360
            # Emit D-Bus signal
 
361
            self.PropertyChanged(
 
362
                dbus.String(u"last_checked_ok"),
 
363
                (_datetime_to_dbus(self.last_checked_ok,
 
364
                                   variant_level=1)))
328
365
    
329
366
    def start_checker(self):
330
367
        """Start a new checker subprocess if one is not running.
338
375
        # checkers alone, the checker would have to take more time
339
376
        # than 'timeout' for the client to be declared invalid, which
340
377
        # is as it should be.
341
 
        
342
 
        # If a checker exists, make sure it is not a zombie
343
 
        if self.checker is not None:
344
 
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
345
 
            if pid:
346
 
                logger.warning("Checker was a zombie")
347
 
                gobject.source_remove(self.checker_callback_tag)
348
 
                self.checker_callback(pid, status,
349
 
                                      self.current_checker_command)
350
 
        # Start a new checker if needed
351
378
        if self.checker is None:
352
379
            try:
353
380
                # In case checker_command has exactly one % operator
363
390
                    logger.error(u'Could not format string "%s":'
364
391
                                 u' %s', self.checker_command, error)
365
392
                    return True # Try again later
366
 
            self.current_checker_command = command
367
393
            try:
368
394
                logger.info(u"Starting checker %r for %s",
369
395
                            command, self.name)
374
400
                self.checker = subprocess.Popen(command,
375
401
                                                close_fds=True,
376
402
                                                shell=True, cwd="/")
 
403
                if self.use_dbus:
 
404
                    # Emit D-Bus signal
 
405
                    self.CheckerStarted(command)
 
406
                    self.PropertyChanged(
 
407
                        dbus.String("checker_running"),
 
408
                        dbus.Boolean(True, variant_level=1))
377
409
                self.checker_callback_tag = (gobject.child_watch_add
378
410
                                             (self.checker.pid,
379
411
                                              self.checker_callback,
380
412
                                              data=command))
381
 
                # The checker may have completed before the gobject
382
 
                # watch was added.  Check for this.
383
 
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
384
 
                if pid:
385
 
                    gobject.source_remove(self.checker_callback_tag)
386
 
                    self.checker_callback(pid, status, command)
387
413
            except OSError, error:
388
414
                logger.error(u"Failed to start subprocess: %s",
389
415
                             error)
407
433
            if error.errno != errno.ESRCH: # No such process
408
434
                raise
409
435
        self.checker = None
 
436
        if self.use_dbus:
 
437
            self.PropertyChanged(dbus.String(u"checker_running"),
 
438
                                 dbus.Boolean(False, variant_level=1))
410
439
    
411
440
    def still_valid(self):
412
441
        """Has the timeout not yet passed for this client?"""
417
446
            return now < (self.created + self.timeout)
418
447
        else:
419
448
            return now < (self.last_checked_ok + self.timeout)
420
 
 
421
 
 
422
 
class ClientDBus(Client, dbus.service.Object):
423
 
    """A Client class using D-Bus
424
 
    Attributes:
425
 
    dbus_object_path: dbus.ObjectPath ; only set if self.use_dbus
426
 
    """
427
 
    # dbus.service.Object doesn't use super(), so we can't either.
428
 
    
429
 
    def __init__(self, *args, **kwargs):
430
 
        Client.__init__(self, *args, **kwargs)
431
 
        # Only now, when this client is initialized, can it show up on
432
 
        # the D-Bus
433
 
        self.dbus_object_path = (dbus.ObjectPath
434
 
                                 ("/clients/"
435
 
                                  + self.name.replace(".", "_")))
436
 
        dbus.service.Object.__init__(self, bus,
437
 
                                     self.dbus_object_path)
438
 
    def enable(self):
439
 
        oldstate = getattr(self, "enabled", False)
440
 
        r = Client.enable(self)
441
 
        if oldstate != self.enabled:
442
 
            # Emit D-Bus signals
443
 
            self.PropertyChanged(dbus.String(u"enabled"),
444
 
                                 dbus.Boolean(True, variant_level=1))
445
 
            self.PropertyChanged(dbus.String(u"last_enabled"),
446
 
                                 (_datetime_to_dbus(self.last_enabled,
447
 
                                                    variant_level=1)))
448
 
        return r
449
 
    
450
 
    def disable(self, signal = True):
451
 
        oldstate = getattr(self, "enabled", False)
452
 
        r = Client.disable(self)
453
 
        if signal and oldstate != self.enabled:
454
 
            # Emit D-Bus signal
455
 
            self.PropertyChanged(dbus.String(u"enabled"),
456
 
                                 dbus.Boolean(False, variant_level=1))
457
 
        return r
458
 
    
459
 
    def __del__(self, *args, **kwargs):
460
 
        try:
461
 
            self.remove_from_connection()
462
 
        except org.freedesktop.DBus.Python.LookupError:
463
 
            pass
464
 
        dbus.service.Object.__del__(self, *args, **kwargs)
465
 
        Client.__del__(self, *args, **kwargs)
466
 
    
467
 
    def checker_callback(self, pid, condition, command,
468
 
                         *args, **kwargs):
469
 
        self.checker_callback_tag = None
470
 
        self.checker = None
471
 
        # Emit D-Bus signal
472
 
        self.PropertyChanged(dbus.String(u"checker_running"),
473
 
                             dbus.Boolean(False, variant_level=1))
474
 
        if os.WIFEXITED(condition):
475
 
            exitstatus = os.WEXITSTATUS(condition)
476
 
            # Emit D-Bus signal
477
 
            self.CheckerCompleted(dbus.Int16(exitstatus),
478
 
                                  dbus.Int64(condition),
479
 
                                  dbus.String(command))
480
 
        else:
481
 
            # Emit D-Bus signal
482
 
            self.CheckerCompleted(dbus.Int16(-1),
483
 
                                  dbus.Int64(condition),
484
 
                                  dbus.String(command))
485
 
        
486
 
        return Client.checker_callback(self, pid, condition, command,
487
 
                                       *args, **kwargs)
488
 
    
489
 
    def checked_ok(self, *args, **kwargs):
490
 
        r = Client.checked_ok(self, *args, **kwargs)
491
 
        # Emit D-Bus signal
492
 
        self.PropertyChanged(
493
 
            dbus.String(u"last_checked_ok"),
494
 
            (_datetime_to_dbus(self.last_checked_ok,
495
 
                               variant_level=1)))
496
 
        return r
497
 
    
498
 
    def start_checker(self, *args, **kwargs):
499
 
        old_checker = self.checker
500
 
        if self.checker is not None:
501
 
            old_checker_pid = self.checker.pid
502
 
        else:
503
 
            old_checker_pid = None
504
 
        r = Client.start_checker(self, *args, **kwargs)
505
 
        # Only emit D-Bus signal if new checker process was started
506
 
        if ((self.checker is not None)
507
 
            and not (old_checker is not None
508
 
                     and old_checker_pid == self.checker.pid)):
509
 
            self.CheckerStarted(self.current_checker_command)
510
 
            self.PropertyChanged(
511
 
                dbus.String("checker_running"),
512
 
                dbus.Boolean(True, variant_level=1))
513
 
        return r
514
 
    
515
 
    def stop_checker(self, *args, **kwargs):
516
 
        old_checker = getattr(self, "checker", None)
517
 
        r = Client.stop_checker(self, *args, **kwargs)
518
 
        if (old_checker is not None
519
 
            and getattr(self, "checker", None) is None):
520
 
            self.PropertyChanged(dbus.String(u"checker_running"),
521
 
                                 dbus.Boolean(False, variant_level=1))
522
 
        return r
523
449
    
524
450
    ## D-Bus methods & signals
525
 
    _interface = u"se.bsnet.fukt.Mandos.Client"
 
451
    _interface = u"org.mandos_system.Mandos.Client"
526
452
    
527
 
    # CheckedOK - method
528
 
    CheckedOK = dbus.service.method(_interface)(checked_ok)
529
 
    CheckedOK.__name__ = "CheckedOK"
 
453
    # BumpTimeout - method
 
454
    BumpTimeout = dbus.service.method(_interface)(bump_timeout)
 
455
    BumpTimeout.__name__ = "BumpTimeout"
530
456
    
531
457
    # CheckerCompleted - signal
532
 
    @dbus.service.signal(_interface, signature="nxs")
533
 
    def CheckerCompleted(self, exitcode, waitstatus, command):
 
458
    @dbus.service.signal(_interface, signature="bqs")
 
459
    def CheckerCompleted(self, success, condition, command):
534
460
        "D-Bus signal"
535
461
        pass
536
462
    
577
503
                dbus.String("checker_running"):
578
504
                    dbus.Boolean(self.checker is not None,
579
505
                                 variant_level=1),
580
 
                dbus.String("object_path"):
581
 
                    dbus.ObjectPath(self.dbus_object_path,
582
 
                                    variant_level=1)
583
506
                }, signature="sv")
584
507
    
585
508
    # IsStillValid - method
586
 
    @dbus.service.method(_interface, out_signature="b")
587
 
    def IsStillValid(self):
588
 
        return self.still_valid()
 
509
    IsStillValid = (dbus.service.method(_interface, out_signature="b")
 
510
                    (still_valid))
 
511
    IsStillValid.__name__ = "IsStillValid"
589
512
    
590
513
    # PropertyChanged - signal
591
514
    @dbus.service.signal(_interface, signature="sv")
593
516
        "D-Bus signal"
594
517
        pass
595
518
    
596
 
    # ReceivedSecret - signal
597
 
    @dbus.service.signal(_interface)
598
 
    def ReceivedSecret(self):
599
 
        "D-Bus signal"
600
 
        pass
601
 
    
602
 
    # Rejected - signal
603
 
    @dbus.service.signal(_interface)
604
 
    def Rejected(self):
605
 
        "D-Bus signal"
606
 
        pass
607
 
    
608
519
    # SetChecker - method
609
520
    @dbus.service.method(_interface, in_signature="s")
610
521
    def SetChecker(self, checker):
680
591
        != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
681
592
        # ...do the normal thing
682
593
        return session.peer_certificate
683
 
    list_size = ctypes.c_uint(1)
 
594
    list_size = ctypes.c_uint()
684
595
    cert_list = (gnutls.library.functions
685
596
                 .gnutls_certificate_get_peers
686
597
                 (session._c_object, ctypes.byref(list_size)))
687
 
    if not bool(cert_list) and list_size.value != 0:
688
 
        raise gnutls.errors.GNUTLSError("error getting peer"
689
 
                                        " certificate")
690
598
    if list_size.value == 0:
691
599
        return None
692
600
    cert = cert_list[0]
741
649
    def handle(self):
742
650
        logger.info(u"TCP connection from: %s",
743
651
                    unicode(self.client_address))
744
 
        logger.debug(u"IPC Pipe FD: %d", self.server.pipe[1])
745
 
        # Open IPC pipe to parent process
746
 
        with closing(os.fdopen(self.server.pipe[1], "w", 1)) as ipc:
747
 
            session = (gnutls.connection
748
 
                       .ClientSession(self.request,
749
 
                                      gnutls.connection
750
 
                                      .X509Credentials()))
751
 
            
752
 
            line = self.request.makefile().readline()
753
 
            logger.debug(u"Protocol version: %r", line)
754
 
            try:
755
 
                if int(line.strip().split()[0]) > 1:
756
 
                    raise RuntimeError
757
 
            except (ValueError, IndexError, RuntimeError), error:
758
 
                logger.error(u"Unknown protocol version: %s", error)
759
 
                return
760
 
            
761
 
            # Note: gnutls.connection.X509Credentials is really a
762
 
            # generic GnuTLS certificate credentials object so long as
763
 
            # no X.509 keys are added to it.  Therefore, we can use it
764
 
            # here despite using OpenPGP certificates.
765
 
            
766
 
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
767
 
            #                     "+AES-256-CBC", "+SHA1",
768
 
            #                     "+COMP-NULL", "+CTYPE-OPENPGP",
769
 
            #                     "+DHE-DSS"))
770
 
            # Use a fallback default, since this MUST be set.
771
 
            priority = self.server.settings.get("priority", "NORMAL")
772
 
            (gnutls.library.functions
773
 
             .gnutls_priority_set_direct(session._c_object,
774
 
                                         priority, None))
775
 
            
776
 
            try:
777
 
                session.handshake()
778
 
            except gnutls.errors.GNUTLSError, error:
779
 
                logger.warning(u"Handshake failed: %s", error)
780
 
                # Do not run session.bye() here: the session is not
781
 
                # established.  Just abandon the request.
782
 
                return
783
 
            logger.debug(u"Handshake succeeded")
784
 
            try:
785
 
                fpr = fingerprint(peer_certificate(session))
786
 
            except (TypeError, gnutls.errors.GNUTLSError), error:
787
 
                logger.warning(u"Bad certificate: %s", error)
788
 
                session.bye()
789
 
                return
790
 
            logger.debug(u"Fingerprint: %s", fpr)
791
 
            
792
 
            for c in self.server.clients:
793
 
                if c.fingerprint == fpr:
794
 
                    client = c
795
 
                    break
796
 
            else:
797
 
                logger.warning(u"Client not found for fingerprint: %s",
798
 
                               fpr)
799
 
                ipc.write("NOTFOUND %s\n" % fpr)
800
 
                session.bye()
801
 
                return
802
 
            # Have to check if client.still_valid(), since it is
803
 
            # possible that the client timed out while establishing
804
 
            # the GnuTLS session.
805
 
            if not client.still_valid():
806
 
                logger.warning(u"Client %(name)s is invalid",
807
 
                               vars(client))
808
 
                ipc.write("INVALID %s\n" % client.name)
809
 
                session.bye()
810
 
                return
811
 
            ipc.write("SENDING %s\n" % client.name)
812
 
            sent_size = 0
813
 
            while sent_size < len(client.secret):
814
 
                sent = session.send(client.secret[sent_size:])
815
 
                logger.debug(u"Sent: %d, remaining: %d",
816
 
                             sent, len(client.secret)
817
 
                             - (sent_size + sent))
818
 
                sent_size += sent
819
 
            session.bye()
820
 
 
821
 
 
822
 
class ForkingMixInWithPipe(SocketServer.ForkingMixIn, object):
823
 
    """Like SocketServer.ForkingMixIn, but also pass a pipe.
824
 
    Assumes a gobject.MainLoop event loop.
825
 
    """
826
 
    def process_request(self, request, client_address):
827
 
        """This overrides and wraps the original process_request().
828
 
        This function creates a new pipe in self.pipe 
829
 
        """
830
 
        self.pipe = os.pipe()
831
 
        super(ForkingMixInWithPipe,
832
 
              self).process_request(request, client_address)
833
 
        os.close(self.pipe[1])  # close write end
834
 
        # Call "handle_ipc" for both data and EOF events
835
 
        gobject.io_add_watch(self.pipe[0],
836
 
                             gobject.IO_IN | gobject.IO_HUP,
837
 
                             self.handle_ipc)
838
 
    def handle_ipc(source, condition):
839
 
        """Dummy function; override as necessary"""
840
 
        os.close(source)
841
 
        return False
842
 
 
843
 
 
844
 
class IPv6_TCPServer(ForkingMixInWithPipe,
 
652
        session = (gnutls.connection
 
653
                   .ClientSession(self.request,
 
654
                                  gnutls.connection
 
655
                                  .X509Credentials()))
 
656
        
 
657
        line = self.request.makefile().readline()
 
658
        logger.debug(u"Protocol version: %r", line)
 
659
        try:
 
660
            if int(line.strip().split()[0]) > 1:
 
661
                raise RuntimeError
 
662
        except (ValueError, IndexError, RuntimeError), error:
 
663
            logger.error(u"Unknown protocol version: %s", error)
 
664
            return
 
665
        
 
666
        # Note: gnutls.connection.X509Credentials is really a generic
 
667
        # GnuTLS certificate credentials object so long as no X.509
 
668
        # keys are added to it.  Therefore, we can use it here despite
 
669
        # using OpenPGP certificates.
 
670
        
 
671
        #priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
 
672
        #                "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
 
673
        #                "+DHE-DSS"))
 
674
        # Use a fallback default, since this MUST be set.
 
675
        priority = self.server.settings.get("priority", "NORMAL")
 
676
        (gnutls.library.functions
 
677
         .gnutls_priority_set_direct(session._c_object,
 
678
                                     priority, None))
 
679
        
 
680
        try:
 
681
            session.handshake()
 
682
        except gnutls.errors.GNUTLSError, error:
 
683
            logger.warning(u"Handshake failed: %s", error)
 
684
            # Do not run session.bye() here: the session is not
 
685
            # established.  Just abandon the request.
 
686
            return
 
687
        try:
 
688
            fpr = fingerprint(peer_certificate(session))
 
689
        except (TypeError, gnutls.errors.GNUTLSError), error:
 
690
            logger.warning(u"Bad certificate: %s", error)
 
691
            session.bye()
 
692
            return
 
693
        logger.debug(u"Fingerprint: %s", fpr)
 
694
        for c in self.server.clients:
 
695
            if c.fingerprint == fpr:
 
696
                client = c
 
697
                break
 
698
        else:
 
699
            logger.warning(u"Client not found for fingerprint: %s",
 
700
                           fpr)
 
701
            session.bye()
 
702
            return
 
703
        # Have to check if client.still_valid(), since it is possible
 
704
        # that the client timed out while establishing the GnuTLS
 
705
        # session.
 
706
        if not client.still_valid():
 
707
            logger.warning(u"Client %(name)s is invalid",
 
708
                           vars(client))
 
709
            session.bye()
 
710
            return
 
711
        ## This won't work here, since we're in a fork.
 
712
        # client.bump_timeout()
 
713
        sent_size = 0
 
714
        while sent_size < len(client.secret):
 
715
            sent = session.send(client.secret[sent_size:])
 
716
            logger.debug(u"Sent: %d, remaining: %d",
 
717
                         sent, len(client.secret)
 
718
                         - (sent_size + sent))
 
719
            sent_size += sent
 
720
        session.bye()
 
721
 
 
722
 
 
723
class IPv6_TCPServer(SocketServer.ForkingMixIn,
845
724
                     SocketServer.TCPServer, object):
846
 
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
 
725
    """IPv6 TCP server.  Accepts 'None' as address and/or port.
847
726
    Attributes:
848
727
        settings:       Server settings
849
728
        clients:        Set() of Client objects
857
736
        if "clients" in kwargs:
858
737
            self.clients = kwargs["clients"]
859
738
            del kwargs["clients"]
860
 
        if "use_ipv6" in kwargs:
861
 
            if not kwargs["use_ipv6"]:
862
 
                self.address_family = socket.AF_INET
863
 
            del kwargs["use_ipv6"]
864
739
        self.enabled = False
865
740
        super(IPv6_TCPServer, self).__init__(*args, **kwargs)
866
741
    def server_bind(self):
880
755
                                 u" bind to interface %s",
881
756
                                 self.settings["interface"])
882
757
                else:
883
 
                    raise
 
758
                    raise error
884
759
        # Only bind(2) the socket if we really need to.
885
760
        if self.server_address[0] or self.server_address[1]:
886
761
            if not self.server_address[0]:
887
 
                if self.address_family == socket.AF_INET6:
888
 
                    any_address = "::" # in6addr_any
889
 
                else:
890
 
                    any_address = socket.INADDR_ANY
891
 
                self.server_address = (any_address,
 
762
                in6addr_any = "::"
 
763
                self.server_address = (in6addr_any,
892
764
                                       self.server_address[1])
893
765
            elif not self.server_address[1]:
894
766
                self.server_address = (self.server_address[0],
906
778
            return super(IPv6_TCPServer, self).server_activate()
907
779
    def enable(self):
908
780
        self.enabled = True
909
 
    def handle_ipc(self, source, condition, file_objects={}):
910
 
        condition_names = {
911
 
            gobject.IO_IN: "IN", # There is data to read.
912
 
            gobject.IO_OUT: "OUT", # Data can be written (without
913
 
                                   # blocking).
914
 
            gobject.IO_PRI: "PRI", # There is urgent data to read.
915
 
            gobject.IO_ERR: "ERR", # Error condition.
916
 
            gobject.IO_HUP: "HUP"  # Hung up (the connection has been
917
 
                                   # broken, usually for pipes and
918
 
                                   # sockets).
919
 
            }
920
 
        conditions_string = ' | '.join(name
921
 
                                       for cond, name in
922
 
                                       condition_names.iteritems()
923
 
                                       if cond & condition)
924
 
        logger.debug("Handling IPC: FD = %d, condition = %s", source,
925
 
                     conditions_string)
926
 
        
927
 
        # Turn the pipe file descriptor into a Python file object
928
 
        if source not in file_objects:
929
 
            file_objects[source] = os.fdopen(source, "r", 1)
930
 
        
931
 
        # Read a line from the file object
932
 
        cmdline = file_objects[source].readline()
933
 
        if not cmdline:             # Empty line means end of file
934
 
            # close the IPC pipe
935
 
            file_objects[source].close()
936
 
            del file_objects[source]
937
 
            
938
 
            # Stop calling this function
939
 
            return False
940
 
        
941
 
        logger.debug("IPC command: %r\n" % cmdline)
942
 
        
943
 
        # Parse and act on command
944
 
        cmd, args = cmdline.split(None, 1)
945
 
        if cmd == "NOTFOUND":
946
 
            if self.settings["use_dbus"]:
947
 
                # Emit D-Bus signal
948
 
                mandos_dbus_service.ClientNotFound(args)
949
 
        elif cmd == "INVALID":
950
 
            if self.settings["use_dbus"]:
951
 
                for client in self.clients:
952
 
                    if client.name == args:
953
 
                        # Emit D-Bus signal
954
 
                        client.Rejected()
955
 
                        break
956
 
        elif cmd == "SENDING":
957
 
            for client in self.clients:
958
 
                if client.name == args:
959
 
                    client.checked_ok()
960
 
                    if self.settings["use_dbus"]:
961
 
                        # Emit D-Bus signal
962
 
                        client.ReceivedSecret()
963
 
                    break
964
 
        else:
965
 
            logger.error("Unknown IPC command: %r", cmdline)
966
 
        
967
 
        # Keep calling this function
968
 
        return True
969
781
 
970
782
 
971
783
def string_to_delta(interval):
972
784
    """Parse a string and return a datetime.timedelta
973
 
    
 
785
 
974
786
    >>> string_to_delta('7d')
975
787
    datetime.timedelta(7)
976
788
    >>> string_to_delta('60s')
1077
889
 
1078
890
 
1079
891
def main():
1080
 
    
1081
 
    ######################################################################
1082
 
    # Parsing of options, both command line and config file
1083
 
    
1084
 
    parser = optparse.OptionParser(version = "%%prog %s" % version)
 
892
    parser = OptionParser(version = "%%prog %s" % version)
1085
893
    parser.add_option("-i", "--interface", type="string",
1086
894
                      metavar="IF", help="Bind to interface IF")
1087
895
    parser.add_option("-a", "--address", type="string",
1105
913
                      dest="use_dbus",
1106
914
                      help="Do not provide D-Bus system bus"
1107
915
                      " interface")
1108
 
    parser.add_option("--no-ipv6", action="store_false",
1109
 
                      dest="use_ipv6", help="Do not use IPv6")
1110
916
    options = parser.parse_args()[0]
1111
917
    
1112
918
    if options.check:
1123
929
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
1124
930
                        "servicename": "Mandos",
1125
931
                        "use_dbus": "True",
1126
 
                        "use_ipv6": "True",
1127
932
                        }
1128
933
    
1129
934
    # Parse config file for server-global settings
1132
937
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
1133
938
    # Convert the SafeConfigParser object to a dict
1134
939
    server_settings = server_config.defaults()
1135
 
    # Use the appropriate methods on the non-string config options
1136
 
    server_settings["debug"] = server_config.getboolean("DEFAULT",
1137
 
                                                        "debug")
1138
 
    server_settings["use_dbus"] = server_config.getboolean("DEFAULT",
1139
 
                                                           "use_dbus")
1140
 
    server_settings["use_ipv6"] = server_config.getboolean("DEFAULT",
1141
 
                                                           "use_ipv6")
1142
 
    if server_settings["port"]:
1143
 
        server_settings["port"] = server_config.getint("DEFAULT",
1144
 
                                                       "port")
 
940
    # Use getboolean on the boolean config options
 
941
    server_settings["debug"] = (server_config.getboolean
 
942
                                ("DEFAULT", "debug"))
 
943
    server_settings["use_dbus"] = (server_config.getboolean
 
944
                                   ("DEFAULT", "use_dbus"))
1145
945
    del server_config
1146
946
    
1147
947
    # Override the settings from the config file with command line
1148
948
    # options, if set.
1149
949
    for option in ("interface", "address", "port", "debug",
1150
950
                   "priority", "servicename", "configdir",
1151
 
                   "use_dbus", "use_ipv6"):
 
951
                   "use_dbus"):
1152
952
        value = getattr(options, option)
1153
953
        if value is not None:
1154
954
            server_settings[option] = value
1155
955
    del options
1156
956
    # Now we have our good server settings in "server_settings"
1157
957
    
1158
 
    ##################################################################
1159
 
    
1160
958
    # For convenience
1161
959
    debug = server_settings["debug"]
1162
960
    use_dbus = server_settings["use_dbus"]
1163
 
    use_ipv6 = server_settings["use_ipv6"]
1164
961
    
1165
962
    if not debug:
1166
963
        syslogger.setLevel(logging.WARNING)
1168
965
    
1169
966
    if server_settings["servicename"] != "Mandos":
1170
967
        syslogger.setFormatter(logging.Formatter
1171
 
                               ('Mandos (%s) [%%(process)d]:'
1172
 
                                ' %%(levelname)s: %%(message)s'
 
968
                               ('Mandos (%s): %%(levelname)s:'
 
969
                                ' %%(message)s'
1173
970
                                % server_settings["servicename"]))
1174
971
    
1175
972
    # Parse config file with clients
1181
978
    client_config = ConfigParser.SafeConfigParser(client_defaults)
1182
979
    client_config.read(os.path.join(server_settings["configdir"],
1183
980
                                    "clients.conf"))
1184
 
 
1185
 
    global mandos_dbus_service
1186
 
    mandos_dbus_service = None
1187
981
    
1188
982
    clients = Set()
1189
983
    tcp_server = IPv6_TCPServer((server_settings["address"],
1190
984
                                 server_settings["port"]),
1191
985
                                TCP_handler,
1192
986
                                settings=server_settings,
1193
 
                                clients=clients, use_ipv6=use_ipv6)
 
987
                                clients=clients)
1194
988
    pidfilename = "/var/run/mandos.pid"
1195
989
    try:
1196
990
        pidfile = open(pidfilename, "w")
1197
 
    except IOError:
 
991
    except IOError, error:
1198
992
        logger.error("Could not open file %r", pidfilename)
1199
993
    
1200
994
    try:
1212
1006
                uid = 65534
1213
1007
                gid = 65534
1214
1008
    try:
 
1009
        os.setuid(uid)
1215
1010
        os.setgid(gid)
1216
 
        os.setuid(uid)
1217
1011
    except OSError, error:
1218
1012
        if error[0] != errno.EPERM:
1219
1013
            raise error
1220
1014
    
1221
 
    # Enable all possible GnuTLS debugging
1222
 
    if debug:
1223
 
        # "Use a log level over 10 to enable all debugging options."
1224
 
        # - GnuTLS manual
1225
 
        gnutls.library.functions.gnutls_global_set_log_level(11)
1226
 
        
1227
 
        @gnutls.library.types.gnutls_log_func
1228
 
        def debug_gnutls(level, string):
1229
 
            logger.debug("GnuTLS: %s", string[:-1])
1230
 
        
1231
 
        (gnutls.library.functions
1232
 
         .gnutls_global_set_log_function(debug_gnutls))
1233
 
    
1234
1015
    global service
1235
 
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1236
1016
    service = AvahiService(name = server_settings["servicename"],
1237
 
                           servicetype = "_mandos._tcp",
1238
 
                           protocol = protocol)
 
1017
                           servicetype = "_mandos._tcp", )
1239
1018
    if server_settings["interface"]:
1240
1019
        service.interface = (if_nametoindex
1241
1020
                             (server_settings["interface"]))
1252
1031
                            avahi.DBUS_INTERFACE_SERVER)
1253
1032
    # End of Avahi example code
1254
1033
    if use_dbus:
1255
 
        bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
 
1034
        bus_name = dbus.service.BusName(u"org.mandos-system.Mandos",
 
1035
                                        bus)
1256
1036
    
1257
 
    client_class = Client
1258
 
    if use_dbus:
1259
 
        client_class = ClientDBus
1260
 
    clients.update(Set(
1261
 
            client_class(name = section,
1262
 
                         config= dict(client_config.items(section)))
1263
 
            for section in client_config.sections()))
 
1037
    clients.update(Set(Client(name = section,
 
1038
                              config
 
1039
                              = dict(client_config.items(section)),
 
1040
                              use_dbus = use_dbus)
 
1041
                       for section in client_config.sections()))
1264
1042
    if not clients:
1265
1043
        logger.warning(u"No clients defined")
1266
1044
    
1277
1055
        daemon()
1278
1056
    
1279
1057
    try:
1280
 
        with closing(pidfile):
1281
 
            pid = os.getpid()
1282
 
            pidfile.write(str(pid) + "\n")
 
1058
        pid = os.getpid()
 
1059
        pidfile.write(str(pid) + "\n")
 
1060
        pidfile.close()
1283
1061
        del pidfile
1284
1062
    except IOError:
1285
1063
        logger.error(u"Could not write to file %r with PID %d",
1311
1089
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1312
1090
    
1313
1091
    if use_dbus:
1314
 
        class MandosDBusService(dbus.service.Object):
 
1092
        class MandosServer(dbus.service.Object):
1315
1093
            """A D-Bus proxy object"""
1316
1094
            def __init__(self):
1317
 
                dbus.service.Object.__init__(self, bus, "/")
1318
 
            _interface = u"se.bsnet.fukt.Mandos"
1319
 
            
 
1095
                dbus.service.Object.__init__(self, bus,
 
1096
                                             "/Mandos")
 
1097
            _interface = u"org.mandos_system.Mandos"
 
1098
 
1320
1099
            @dbus.service.signal(_interface, signature="oa{sv}")
1321
1100
            def ClientAdded(self, objpath, properties):
1322
1101
                "D-Bus signal"
1323
1102
                pass
1324
 
            
1325
 
            @dbus.service.signal(_interface, signature="s")
1326
 
            def ClientNotFound(self, fingerprint):
1327
 
                "D-Bus signal"
1328
 
                pass
1329
 
            
1330
 
            @dbus.service.signal(_interface, signature="os")
1331
 
            def ClientRemoved(self, objpath, name):
1332
 
                "D-Bus signal"
1333
 
                pass
1334
 
            
 
1103
 
 
1104
            @dbus.service.signal(_interface, signature="o")
 
1105
            def ClientRemoved(self, objpath):
 
1106
                "D-Bus signal"
 
1107
                pass
 
1108
 
1335
1109
            @dbus.service.method(_interface, out_signature="ao")
1336
1110
            def GetAllClients(self):
1337
 
                "D-Bus method"
1338
1111
                return dbus.Array(c.dbus_object_path for c in clients)
1339
 
            
 
1112
 
1340
1113
            @dbus.service.method(_interface, out_signature="a{oa{sv}}")
1341
1114
            def GetAllClientsWithProperties(self):
1342
 
                "D-Bus method"
1343
1115
                return dbus.Dictionary(
1344
1116
                    ((c.dbus_object_path, c.GetAllProperties())
1345
1117
                     for c in clients),
1346
1118
                    signature="oa{sv}")
1347
 
            
 
1119
 
1348
1120
            @dbus.service.method(_interface, in_signature="o")
1349
1121
            def RemoveClient(self, object_path):
1350
 
                "D-Bus method"
1351
1122
                for c in clients:
1352
1123
                    if c.dbus_object_path == object_path:
1353
1124
                        clients.remove(c)
1354
 
                        c.remove_from_connection()
1355
1125
                        # Don't signal anything except ClientRemoved
1356
 
                        c.disable(signal=False)
 
1126
                        c.use_dbus = False
 
1127
                        c.disable()
1357
1128
                        # Emit D-Bus signal
1358
 
                        self.ClientRemoved(object_path, c.name)
 
1129
                        self.ClientRemoved(object_path)
1359
1130
                        return
1360
1131
                raise KeyError
1361
 
            
 
1132
            @dbus.service.method(_interface)
 
1133
            def Quit(self):
 
1134
                main_loop.quit()
 
1135
 
1362
1136
            del _interface
1363
 
        
1364
 
        mandos_dbus_service = MandosDBusService()
 
1137
    
 
1138
        mandos_server = MandosServer()
1365
1139
    
1366
1140
    for client in clients:
1367
1141
        if use_dbus:
1368
1142
            # Emit D-Bus signal
1369
 
            mandos_dbus_service.ClientAdded(client.dbus_object_path,
1370
 
                                            client.GetAllProperties())
 
1143
            mandos_server.ClientAdded(client.dbus_object_path,
 
1144
                                      client.GetAllProperties())
1371
1145
        client.enable()
1372
1146
    
1373
1147
    tcp_server.enable()
1375
1149
    
1376
1150
    # Find out what port we got
1377
1151
    service.port = tcp_server.socket.getsockname()[1]
1378
 
    if use_ipv6:
1379
 
        logger.info(u"Now listening on address %r, port %d,"
1380
 
                    " flowinfo %d, scope_id %d"
1381
 
                    % tcp_server.socket.getsockname())
1382
 
    else:                       # IPv4
1383
 
        logger.info(u"Now listening on address %r, port %d"
1384
 
                    % tcp_server.socket.getsockname())
 
1152
    logger.info(u"Now listening on address %r, port %d, flowinfo %d,"
 
1153
                u" scope_id %d" % tcp_server.socket.getsockname())
1385
1154
    
1386
1155
    #service.interface = tcp_server.socket.getsockname()[3]
1387
1156
    
1407
1176
        sys.exit(1)
1408
1177
    except KeyboardInterrupt:
1409
1178
        if debug:
1410
 
            print >> sys.stderr
1411
 
        logger.debug("Server received KeyboardInterrupt")
1412
 
    logger.debug("Server exiting")
 
1179
            print
1413
1180
 
1414
1181
if __name__ == '__main__':
1415
1182
    main()