/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:
66
66
import ctypes
67
67
import ctypes.util
68
68
 
69
 
version = "1.0.5"
 
69
version = "1.0.8"
70
70
 
71
71
logger = logging.Logger('mandos')
72
72
syslogger = (logging.handlers.SysLogHandler
114
114
    """
115
115
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
116
116
                 servicetype = None, port = None, TXT = None,
117
 
                 domain = "", host = "", max_renames = 32768):
 
117
                 domain = "", host = "", max_renames = 32768,
 
118
                 protocol = avahi.PROTO_UNSPEC):
118
119
        self.interface = interface
119
120
        self.name = name
120
121
        self.type = servicetype
124
125
        self.host = host
125
126
        self.rename_count = 0
126
127
        self.max_renames = max_renames
 
128
        self.protocol = protocol
127
129
    def rename(self):
128
130
        """Derived from the Avahi example code"""
129
131
        if self.rename_count >= self.max_renames:
135
137
        logger.info(u"Changing Zeroconf service name to %r ...",
136
138
                    str(self.name))
137
139
        syslogger.setFormatter(logging.Formatter
138
 
                               ('Mandos (%s): %%(levelname)s:'
139
 
                                ' %%(message)s' % self.name))
 
140
                               ('Mandos (%s) [%%(process)d]:'
 
141
                                ' %%(levelname)s: %%(message)s'
 
142
                                % self.name))
140
143
        self.remove()
141
144
        self.add()
142
145
        self.rename_count += 1
158
161
                     service.name, service.type)
159
162
        group.AddService(
160
163
                self.interface,         # interface
161
 
                avahi.PROTO_INET6,      # protocol
 
164
                self.protocol,          # protocol
162
165
                dbus.UInt32(0),         # flags
163
166
                self.name, self.type,
164
167
                self.domain, self.host,
176
179
    return dbus.String(dt.isoformat(), variant_level=variant_level)
177
180
 
178
181
 
179
 
class Client(dbus.service.Object):
 
182
class Client(object):
180
183
    """A representation of a client host served by this server.
181
184
    Attributes:
182
185
    name:       string; from the config file, used in log messages and
203
206
                     client lives.  %() expansions are done at
204
207
                     runtime with vars(self) as dict, so that for
205
208
                     instance %(name)s can be used in the command.
206
 
    use_dbus: bool(); Whether to provide D-Bus interface and signals
207
 
    dbus_object_path: dbus.ObjectPath ; only set if self.use_dbus
 
209
    current_checker_command: string; current running checker_command
208
210
    """
209
211
    def timeout_milliseconds(self):
210
212
        "Return the 'timeout' attribute in milliseconds"
218
220
                + (self.interval.seconds * 1000)
219
221
                + (self.interval.microseconds // 1000))
220
222
    
221
 
    def __init__(self, name = None, disable_hook=None, config=None,
222
 
                 use_dbus=True):
 
223
    def __init__(self, name = None, disable_hook=None, config=None):
223
224
        """Note: the 'checker' key in 'config' sets the
224
225
        'checker_command' attribute and *not* the 'checker'
225
226
        attribute."""
227
228
        if config is None:
228
229
            config = {}
229
230
        logger.debug(u"Creating client %r", self.name)
230
 
        self.use_dbus = False   # During __init__
231
231
        # Uppercase and remove spaces from fingerprint for later
232
232
        # comparison purposes with return value from the fingerprint()
233
233
        # function
257
257
        self.disable_initiator_tag = None
258
258
        self.checker_callback_tag = None
259
259
        self.checker_command = config["checker"]
 
260
        self.current_checker_command = None
260
261
        self.last_connect = None
261
 
        # Only now, when this client is initialized, can it show up on
262
 
        # the D-Bus
263
 
        self.use_dbus = use_dbus
264
 
        if self.use_dbus:
265
 
            self.dbus_object_path = (dbus.ObjectPath
266
 
                                     ("/clients/"
267
 
                                      + self.name.replace(".", "_")))
268
 
            dbus.service.Object.__init__(self, bus,
269
 
                                         self.dbus_object_path)
270
262
    
271
263
    def enable(self):
272
264
        """Start this client's checker and timeout hooks"""
283
275
                                   (self.timeout_milliseconds(),
284
276
                                    self.disable))
285
277
        self.enabled = True
286
 
        if self.use_dbus:
287
 
            # Emit D-Bus signals
288
 
            self.PropertyChanged(dbus.String(u"enabled"),
289
 
                                 dbus.Boolean(True, variant_level=1))
290
 
            self.PropertyChanged(dbus.String(u"last_enabled"),
291
 
                                 (_datetime_to_dbus(self.last_enabled,
292
 
                                                    variant_level=1)))
293
278
    
294
279
    def disable(self):
295
280
        """Disable this client."""
306
291
        if self.disable_hook:
307
292
            self.disable_hook(self)
308
293
        self.enabled = False
309
 
        if self.use_dbus:
310
 
            # Emit D-Bus signal
311
 
            self.PropertyChanged(dbus.String(u"enabled"),
312
 
                                 dbus.Boolean(False, variant_level=1))
313
294
        # Do not run this again if called by a gobject.timeout_add
314
295
        return False
315
296
    
321
302
        """The checker has completed, so take appropriate actions."""
322
303
        self.checker_callback_tag = None
323
304
        self.checker = None
324
 
        if self.use_dbus:
325
 
            # Emit D-Bus signal
326
 
            self.PropertyChanged(dbus.String(u"checker_running"),
327
 
                                 dbus.Boolean(False, variant_level=1))
328
305
        if os.WIFEXITED(condition):
329
306
            exitstatus = os.WEXITSTATUS(condition)
330
307
            if exitstatus == 0:
334
311
            else:
335
312
                logger.info(u"Checker for %(name)s failed",
336
313
                            vars(self))
337
 
            if self.use_dbus:
338
 
                # Emit D-Bus signal
339
 
                self.CheckerCompleted(dbus.Int16(exitstatus),
340
 
                                      dbus.Int64(condition),
341
 
                                      dbus.String(command))
342
314
        else:
343
315
            logger.warning(u"Checker for %(name)s crashed?",
344
316
                           vars(self))
345
 
            if self.use_dbus:
346
 
                # Emit D-Bus signal
347
 
                self.CheckerCompleted(dbus.Int16(-1),
348
 
                                      dbus.Int64(condition),
349
 
                                      dbus.String(command))
350
317
    
351
318
    def checked_ok(self):
352
319
        """Bump up the timeout for this client.
358
325
        self.disable_initiator_tag = (gobject.timeout_add
359
326
                                      (self.timeout_milliseconds(),
360
327
                                       self.disable))
361
 
        if self.use_dbus:
362
 
            # Emit D-Bus signal
363
 
            self.PropertyChanged(
364
 
                dbus.String(u"last_checked_ok"),
365
 
                (_datetime_to_dbus(self.last_checked_ok,
366
 
                                   variant_level=1)))
367
328
    
368
329
    def start_checker(self):
369
330
        """Start a new checker subprocess if one is not running.
377
338
        # checkers alone, the checker would have to take more time
378
339
        # than 'timeout' for the client to be declared invalid, which
379
340
        # 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
380
351
        if self.checker is None:
381
352
            try:
382
353
                # In case checker_command has exactly one % operator
392
363
                    logger.error(u'Could not format string "%s":'
393
364
                                 u' %s', self.checker_command, error)
394
365
                    return True # Try again later
 
366
            self.current_checker_command = command
395
367
            try:
396
368
                logger.info(u"Starting checker %r for %s",
397
369
                            command, self.name)
402
374
                self.checker = subprocess.Popen(command,
403
375
                                                close_fds=True,
404
376
                                                shell=True, cwd="/")
405
 
                if self.use_dbus:
406
 
                    # Emit D-Bus signal
407
 
                    self.CheckerStarted(command)
408
 
                    self.PropertyChanged(
409
 
                        dbus.String("checker_running"),
410
 
                        dbus.Boolean(True, variant_level=1))
411
377
                self.checker_callback_tag = (gobject.child_watch_add
412
378
                                             (self.checker.pid,
413
379
                                              self.checker_callback,
414
380
                                              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)
415
387
            except OSError, error:
416
388
                logger.error(u"Failed to start subprocess: %s",
417
389
                             error)
435
407
            if error.errno != errno.ESRCH: # No such process
436
408
                raise
437
409
        self.checker = None
438
 
        if self.use_dbus:
439
 
            self.PropertyChanged(dbus.String(u"checker_running"),
440
 
                                 dbus.Boolean(False, variant_level=1))
441
410
    
442
411
    def still_valid(self):
443
412
        """Has the timeout not yet passed for this client?"""
448
417
            return now < (self.created + self.timeout)
449
418
        else:
450
419
            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
451
523
    
452
524
    ## D-Bus methods & signals
453
525
    _interface = u"se.bsnet.fukt.Mandos.Client"
511
583
                }, signature="sv")
512
584
    
513
585
    # IsStillValid - method
514
 
    IsStillValid = (dbus.service.method(_interface, out_signature="b")
515
 
                    (still_valid))
516
 
    IsStillValid.__name__ = "IsStillValid"
 
586
    @dbus.service.method(_interface, out_signature="b")
 
587
    def IsStillValid(self):
 
588
        return self.still_valid()
517
589
    
518
590
    # PropertyChanged - signal
519
591
    @dbus.service.signal(_interface, signature="sv")
521
593
        "D-Bus signal"
522
594
        pass
523
595
    
 
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
    
524
608
    # SetChecker - method
525
609
    @dbus.service.method(_interface, in_signature="s")
526
610
    def SetChecker(self, checker):
657
741
    def handle(self):
658
742
        logger.info(u"TCP connection from: %s",
659
743
                    unicode(self.client_address))
660
 
        session = (gnutls.connection
661
 
                   .ClientSession(self.request,
662
 
                                  gnutls.connection
663
 
                                  .X509Credentials()))
664
 
        
665
 
        line = self.request.makefile().readline()
666
 
        logger.debug(u"Protocol version: %r", line)
667
 
        try:
668
 
            if int(line.strip().split()[0]) > 1:
669
 
                raise RuntimeError
670
 
        except (ValueError, IndexError, RuntimeError), error:
671
 
            logger.error(u"Unknown protocol version: %s", error)
672
 
            return
673
 
        
674
 
        # Note: gnutls.connection.X509Credentials is really a generic
675
 
        # GnuTLS certificate credentials object so long as no X.509
676
 
        # keys are added to it.  Therefore, we can use it here despite
677
 
        # using OpenPGP certificates.
678
 
        
679
 
        #priority = ':'.join(("NONE", "+VERS-TLS1.1", "+AES-256-CBC",
680
 
        #                     "+SHA1", "+COMP-NULL", "+CTYPE-OPENPGP",
681
 
        #                     "+DHE-DSS"))
682
 
        # Use a fallback default, since this MUST be set.
683
 
        priority = self.server.settings.get("priority", "NORMAL")
684
 
        (gnutls.library.functions
685
 
         .gnutls_priority_set_direct(session._c_object,
686
 
                                     priority, None))
687
 
        
688
 
        try:
689
 
            session.handshake()
690
 
        except gnutls.errors.GNUTLSError, error:
691
 
            logger.warning(u"Handshake failed: %s", error)
692
 
            # Do not run session.bye() here: the session is not
693
 
            # established.  Just abandon the request.
694
 
            return
695
 
        logger.debug(u"Handshake succeeded")
696
 
        try:
697
 
            fpr = fingerprint(peer_certificate(session))
698
 
        except (TypeError, gnutls.errors.GNUTLSError), error:
699
 
            logger.warning(u"Bad certificate: %s", error)
700
 
            session.bye()
701
 
            return
702
 
        logger.debug(u"Fingerprint: %s", fpr)
703
 
        
704
 
        for c in self.server.clients:
705
 
            if c.fingerprint == fpr:
706
 
                client = c
707
 
                break
708
 
        else:
709
 
            logger.warning(u"Client not found for fingerprint: %s",
710
 
                           fpr)
711
 
            session.bye()
712
 
            return
713
 
        # Have to check if client.still_valid(), since it is possible
714
 
        # that the client timed out while establishing the GnuTLS
715
 
        # session.
716
 
        if not client.still_valid():
717
 
            logger.warning(u"Client %(name)s is invalid",
718
 
                           vars(client))
719
 
            session.bye()
720
 
            return
721
 
        ## This won't work here, since we're in a fork.
722
 
        # client.checked_ok()
723
 
        sent_size = 0
724
 
        while sent_size < len(client.secret):
725
 
            sent = session.send(client.secret[sent_size:])
726
 
            logger.debug(u"Sent: %d, remaining: %d",
727
 
                         sent, len(client.secret)
728
 
                         - (sent_size + sent))
729
 
            sent_size += sent
730
 
        session.bye()
731
 
 
732
 
 
733
 
class IPv6_TCPServer(SocketServer.ForkingMixIn,
 
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,
734
845
                     SocketServer.TCPServer, object):
735
 
    """IPv6 TCP server.  Accepts 'None' as address and/or port.
 
846
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
736
847
    Attributes:
737
848
        settings:       Server settings
738
849
        clients:        Set() of Client objects
746
857
        if "clients" in kwargs:
747
858
            self.clients = kwargs["clients"]
748
859
            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"]
749
864
        self.enabled = False
750
865
        super(IPv6_TCPServer, self).__init__(*args, **kwargs)
751
866
    def server_bind(self):
769
884
        # Only bind(2) the socket if we really need to.
770
885
        if self.server_address[0] or self.server_address[1]:
771
886
            if not self.server_address[0]:
772
 
                in6addr_any = "::"
773
 
                self.server_address = (in6addr_any,
 
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,
774
892
                                       self.server_address[1])
775
893
            elif not self.server_address[1]:
776
894
                self.server_address = (self.server_address[0],
788
906
            return super(IPv6_TCPServer, self).server_activate()
789
907
    def enable(self):
790
908
        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
791
969
 
792
970
 
793
971
def string_to_delta(interval):
899
1077
 
900
1078
 
901
1079
def main():
 
1080
    
 
1081
    ######################################################################
 
1082
    # Parsing of options, both command line and config file
 
1083
    
902
1084
    parser = optparse.OptionParser(version = "%%prog %s" % version)
903
1085
    parser.add_option("-i", "--interface", type="string",
904
1086
                      metavar="IF", help="Bind to interface IF")
923
1105
                      dest="use_dbus",
924
1106
                      help="Do not provide D-Bus system bus"
925
1107
                      " interface")
 
1108
    parser.add_option("--no-ipv6", action="store_false",
 
1109
                      dest="use_ipv6", help="Do not use IPv6")
926
1110
    options = parser.parse_args()[0]
927
1111
    
928
1112
    if options.check:
939
1123
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
940
1124
                        "servicename": "Mandos",
941
1125
                        "use_dbus": "True",
 
1126
                        "use_ipv6": "True",
942
1127
                        }
943
1128
    
944
1129
    # Parse config file for server-global settings
952
1137
                                                        "debug")
953
1138
    server_settings["use_dbus"] = server_config.getboolean("DEFAULT",
954
1139
                                                           "use_dbus")
 
1140
    server_settings["use_ipv6"] = server_config.getboolean("DEFAULT",
 
1141
                                                           "use_ipv6")
955
1142
    if server_settings["port"]:
956
1143
        server_settings["port"] = server_config.getint("DEFAULT",
957
1144
                                                       "port")
961
1148
    # options, if set.
962
1149
    for option in ("interface", "address", "port", "debug",
963
1150
                   "priority", "servicename", "configdir",
964
 
                   "use_dbus"):
 
1151
                   "use_dbus", "use_ipv6"):
965
1152
        value = getattr(options, option)
966
1153
        if value is not None:
967
1154
            server_settings[option] = value
968
1155
    del options
969
1156
    # Now we have our good server settings in "server_settings"
970
1157
    
 
1158
    ##################################################################
 
1159
    
971
1160
    # For convenience
972
1161
    debug = server_settings["debug"]
973
1162
    use_dbus = server_settings["use_dbus"]
 
1163
    use_ipv6 = server_settings["use_ipv6"]
974
1164
    
975
1165
    if not debug:
976
1166
        syslogger.setLevel(logging.WARNING)
978
1168
    
979
1169
    if server_settings["servicename"] != "Mandos":
980
1170
        syslogger.setFormatter(logging.Formatter
981
 
                               ('Mandos (%s): %%(levelname)s:'
982
 
                                ' %%(message)s'
 
1171
                               ('Mandos (%s) [%%(process)d]:'
 
1172
                                ' %%(levelname)s: %%(message)s'
983
1173
                                % server_settings["servicename"]))
984
1174
    
985
1175
    # Parse config file with clients
991
1181
    client_config = ConfigParser.SafeConfigParser(client_defaults)
992
1182
    client_config.read(os.path.join(server_settings["configdir"],
993
1183
                                    "clients.conf"))
 
1184
 
 
1185
    global mandos_dbus_service
 
1186
    mandos_dbus_service = None
994
1187
    
995
1188
    clients = Set()
996
1189
    tcp_server = IPv6_TCPServer((server_settings["address"],
997
1190
                                 server_settings["port"]),
998
1191
                                TCP_handler,
999
1192
                                settings=server_settings,
1000
 
                                clients=clients)
 
1193
                                clients=clients, use_ipv6=use_ipv6)
1001
1194
    pidfilename = "/var/run/mandos.pid"
1002
1195
    try:
1003
1196
        pidfile = open(pidfilename, "w")
1039
1232
         .gnutls_global_set_log_function(debug_gnutls))
1040
1233
    
1041
1234
    global service
 
1235
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1042
1236
    service = AvahiService(name = server_settings["servicename"],
1043
 
                           servicetype = "_mandos._tcp", )
 
1237
                           servicetype = "_mandos._tcp",
 
1238
                           protocol = protocol)
1044
1239
    if server_settings["interface"]:
1045
1240
        service.interface = (if_nametoindex
1046
1241
                             (server_settings["interface"]))
1059
1254
    if use_dbus:
1060
1255
        bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
1061
1256
    
1062
 
    clients.update(Set(Client(name = section,
1063
 
                              config
1064
 
                              = dict(client_config.items(section)),
1065
 
                              use_dbus = use_dbus)
1066
 
                       for section in client_config.sections()))
 
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()))
1067
1264
    if not clients:
1068
1265
        logger.warning(u"No clients defined")
1069
1266
    
1080
1277
        daemon()
1081
1278
    
1082
1279
    try:
1083
 
        pid = os.getpid()
1084
 
        pidfile.write(str(pid) + "\n")
1085
 
        pidfile.close()
 
1280
        with closing(pidfile):
 
1281
            pid = os.getpid()
 
1282
            pidfile.write(str(pid) + "\n")
1086
1283
        del pidfile
1087
1284
    except IOError:
1088
1285
        logger.error(u"Could not write to file %r with PID %d",
1114
1311
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1115
1312
    
1116
1313
    if use_dbus:
1117
 
        class MandosServer(dbus.service.Object):
 
1314
        class MandosDBusService(dbus.service.Object):
1118
1315
            """A D-Bus proxy object"""
1119
1316
            def __init__(self):
1120
1317
                dbus.service.Object.__init__(self, bus, "/")
1125
1322
                "D-Bus signal"
1126
1323
                pass
1127
1324
            
 
1325
            @dbus.service.signal(_interface, signature="s")
 
1326
            def ClientNotFound(self, fingerprint):
 
1327
                "D-Bus signal"
 
1328
                pass
 
1329
            
1128
1330
            @dbus.service.signal(_interface, signature="os")
1129
1331
            def ClientRemoved(self, objpath, name):
1130
1332
                "D-Bus signal"
1149
1351
                for c in clients:
1150
1352
                    if c.dbus_object_path == object_path:
1151
1353
                        clients.remove(c)
 
1354
                        c.remove_from_connection()
1152
1355
                        # Don't signal anything except ClientRemoved
1153
 
                        c.use_dbus = False
1154
 
                        c.disable()
 
1356
                        c.disable(signal=False)
1155
1357
                        # Emit D-Bus signal
1156
1358
                        self.ClientRemoved(object_path, c.name)
1157
1359
                        return
1159
1361
            
1160
1362
            del _interface
1161
1363
        
1162
 
        mandos_server = MandosServer()
 
1364
        mandos_dbus_service = MandosDBusService()
1163
1365
    
1164
1366
    for client in clients:
1165
1367
        if use_dbus:
1166
1368
            # Emit D-Bus signal
1167
 
            mandos_server.ClientAdded(client.dbus_object_path,
1168
 
                                      client.GetAllProperties())
 
1369
            mandos_dbus_service.ClientAdded(client.dbus_object_path,
 
1370
                                            client.GetAllProperties())
1169
1371
        client.enable()
1170
1372
    
1171
1373
    tcp_server.enable()
1173
1375
    
1174
1376
    # Find out what port we got
1175
1377
    service.port = tcp_server.socket.getsockname()[1]
1176
 
    logger.info(u"Now listening on address %r, port %d, flowinfo %d,"
1177
 
                u" scope_id %d" % tcp_server.socket.getsockname())
 
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())
1178
1385
    
1179
1386
    #service.interface = tcp_server.socket.getsockname()[3]
1180
1387