/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-04-01 03:37:45 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090401033745-c89k6bij5opdm1rk
* mandos (ClientDBus.__del__): Bug fix: Correct mispasted code, and do
                               not try to call
                               dbus.service.Object.__del__() if it
                               does not exist.
  (ClientDBus.start_checker): Simplify logic.

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 LookupError:
 
463
            pass
 
464
        if hasattr(dbus.service.Object, "__del__"):
 
465
            dbus.service.Object.__del__(self, *args, **kwargs)
 
466
        Client.__del__(self, *args, **kwargs)
 
467
    
 
468
    def checker_callback(self, pid, condition, command,
 
469
                         *args, **kwargs):
 
470
        self.checker_callback_tag = None
 
471
        self.checker = None
 
472
        # Emit D-Bus signal
 
473
        self.PropertyChanged(dbus.String(u"checker_running"),
 
474
                             dbus.Boolean(False, variant_level=1))
 
475
        if os.WIFEXITED(condition):
 
476
            exitstatus = os.WEXITSTATUS(condition)
 
477
            # Emit D-Bus signal
 
478
            self.CheckerCompleted(dbus.Int16(exitstatus),
 
479
                                  dbus.Int64(condition),
 
480
                                  dbus.String(command))
 
481
        else:
 
482
            # Emit D-Bus signal
 
483
            self.CheckerCompleted(dbus.Int16(-1),
 
484
                                  dbus.Int64(condition),
 
485
                                  dbus.String(command))
 
486
        
 
487
        return Client.checker_callback(self, pid, condition, command,
 
488
                                       *args, **kwargs)
 
489
    
 
490
    def checked_ok(self, *args, **kwargs):
 
491
        r = Client.checked_ok(self, *args, **kwargs)
 
492
        # Emit D-Bus signal
 
493
        self.PropertyChanged(
 
494
            dbus.String(u"last_checked_ok"),
 
495
            (_datetime_to_dbus(self.last_checked_ok,
 
496
                               variant_level=1)))
 
497
        return r
 
498
    
 
499
    def start_checker(self, *args, **kwargs):
 
500
        old_checker = self.checker
 
501
        if self.checker is not None:
 
502
            old_checker_pid = self.checker.pid
 
503
        else:
 
504
            old_checker_pid = None
 
505
        r = Client.start_checker(self, *args, **kwargs)
 
506
        # Only if new checker process was started
 
507
        if (self.checker is not None
 
508
            and old_checker_pid != self.checker.pid):
 
509
            # Emit D-Bus signal
 
510
            self.CheckerStarted(self.current_checker_command)
 
511
            self.PropertyChanged(
 
512
                dbus.String("checker_running"),
 
513
                dbus.Boolean(True, variant_level=1))
 
514
        return r
 
515
    
 
516
    def stop_checker(self, *args, **kwargs):
 
517
        old_checker = getattr(self, "checker", None)
 
518
        r = Client.stop_checker(self, *args, **kwargs)
 
519
        if (old_checker is not None
 
520
            and getattr(self, "checker", None) is None):
 
521
            self.PropertyChanged(dbus.String(u"checker_running"),
 
522
                                 dbus.Boolean(False, variant_level=1))
 
523
        return r
451
524
    
452
525
    ## D-Bus methods & signals
453
526
    _interface = u"se.bsnet.fukt.Mandos.Client"
511
584
                }, signature="sv")
512
585
    
513
586
    # IsStillValid - method
514
 
    IsStillValid = (dbus.service.method(_interface, out_signature="b")
515
 
                    (still_valid))
516
 
    IsStillValid.__name__ = "IsStillValid"
 
587
    @dbus.service.method(_interface, out_signature="b")
 
588
    def IsStillValid(self):
 
589
        return self.still_valid()
517
590
    
518
591
    # PropertyChanged - signal
519
592
    @dbus.service.signal(_interface, signature="sv")
521
594
        "D-Bus signal"
522
595
        pass
523
596
    
 
597
    # ReceivedSecret - signal
 
598
    @dbus.service.signal(_interface)
 
599
    def ReceivedSecret(self):
 
600
        "D-Bus signal"
 
601
        pass
 
602
    
 
603
    # Rejected - signal
 
604
    @dbus.service.signal(_interface)
 
605
    def Rejected(self):
 
606
        "D-Bus signal"
 
607
        pass
 
608
    
524
609
    # SetChecker - method
525
610
    @dbus.service.method(_interface, in_signature="s")
526
611
    def SetChecker(self, checker):
657
742
    def handle(self):
658
743
        logger.info(u"TCP connection from: %s",
659
744
                    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,
 
745
        logger.debug(u"IPC Pipe FD: %d", self.server.pipe[1])
 
746
        # Open IPC pipe to parent process
 
747
        with closing(os.fdopen(self.server.pipe[1], "w", 1)) as ipc:
 
748
            session = (gnutls.connection
 
749
                       .ClientSession(self.request,
 
750
                                      gnutls.connection
 
751
                                      .X509Credentials()))
 
752
            
 
753
            line = self.request.makefile().readline()
 
754
            logger.debug(u"Protocol version: %r", line)
 
755
            try:
 
756
                if int(line.strip().split()[0]) > 1:
 
757
                    raise RuntimeError
 
758
            except (ValueError, IndexError, RuntimeError), error:
 
759
                logger.error(u"Unknown protocol version: %s", error)
 
760
                return
 
761
            
 
762
            # Note: gnutls.connection.X509Credentials is really a
 
763
            # generic GnuTLS certificate credentials object so long as
 
764
            # no X.509 keys are added to it.  Therefore, we can use it
 
765
            # here despite using OpenPGP certificates.
 
766
            
 
767
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
 
768
            #                     "+AES-256-CBC", "+SHA1",
 
769
            #                     "+COMP-NULL", "+CTYPE-OPENPGP",
 
770
            #                     "+DHE-DSS"))
 
771
            # Use a fallback default, since this MUST be set.
 
772
            priority = self.server.settings.get("priority", "NORMAL")
 
773
            (gnutls.library.functions
 
774
             .gnutls_priority_set_direct(session._c_object,
 
775
                                         priority, None))
 
776
            
 
777
            try:
 
778
                session.handshake()
 
779
            except gnutls.errors.GNUTLSError, error:
 
780
                logger.warning(u"Handshake failed: %s", error)
 
781
                # Do not run session.bye() here: the session is not
 
782
                # established.  Just abandon the request.
 
783
                return
 
784
            logger.debug(u"Handshake succeeded")
 
785
            try:
 
786
                fpr = fingerprint(peer_certificate(session))
 
787
            except (TypeError, gnutls.errors.GNUTLSError), error:
 
788
                logger.warning(u"Bad certificate: %s", error)
 
789
                session.bye()
 
790
                return
 
791
            logger.debug(u"Fingerprint: %s", fpr)
 
792
            
 
793
            for c in self.server.clients:
 
794
                if c.fingerprint == fpr:
 
795
                    client = c
 
796
                    break
 
797
            else:
 
798
                logger.warning(u"Client not found for fingerprint: %s",
 
799
                               fpr)
 
800
                ipc.write("NOTFOUND %s\n" % fpr)
 
801
                session.bye()
 
802
                return
 
803
            # Have to check if client.still_valid(), since it is
 
804
            # possible that the client timed out while establishing
 
805
            # the GnuTLS session.
 
806
            if not client.still_valid():
 
807
                logger.warning(u"Client %(name)s is invalid",
 
808
                               vars(client))
 
809
                ipc.write("INVALID %s\n" % client.name)
 
810
                session.bye()
 
811
                return
 
812
            ipc.write("SENDING %s\n" % client.name)
 
813
            sent_size = 0
 
814
            while sent_size < len(client.secret):
 
815
                sent = session.send(client.secret[sent_size:])
 
816
                logger.debug(u"Sent: %d, remaining: %d",
 
817
                             sent, len(client.secret)
 
818
                             - (sent_size + sent))
 
819
                sent_size += sent
 
820
            session.bye()
 
821
 
 
822
 
 
823
class ForkingMixInWithPipe(SocketServer.ForkingMixIn, object):
 
824
    """Like SocketServer.ForkingMixIn, but also pass a pipe.
 
825
    Assumes a gobject.MainLoop event loop.
 
826
    """
 
827
    def process_request(self, request, client_address):
 
828
        """This overrides and wraps the original process_request().
 
829
        This function creates a new pipe in self.pipe 
 
830
        """
 
831
        self.pipe = os.pipe()
 
832
        super(ForkingMixInWithPipe,
 
833
              self).process_request(request, client_address)
 
834
        os.close(self.pipe[1])  # close write end
 
835
        # Call "handle_ipc" for both data and EOF events
 
836
        gobject.io_add_watch(self.pipe[0],
 
837
                             gobject.IO_IN | gobject.IO_HUP,
 
838
                             self.handle_ipc)
 
839
    def handle_ipc(source, condition):
 
840
        """Dummy function; override as necessary"""
 
841
        os.close(source)
 
842
        return False
 
843
 
 
844
 
 
845
class IPv6_TCPServer(ForkingMixInWithPipe,
734
846
                     SocketServer.TCPServer, object):
735
 
    """IPv6 TCP server.  Accepts 'None' as address and/or port.
 
847
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
736
848
    Attributes:
737
849
        settings:       Server settings
738
850
        clients:        Set() of Client objects
746
858
        if "clients" in kwargs:
747
859
            self.clients = kwargs["clients"]
748
860
            del kwargs["clients"]
 
861
        if "use_ipv6" in kwargs:
 
862
            if not kwargs["use_ipv6"]:
 
863
                self.address_family = socket.AF_INET
 
864
            del kwargs["use_ipv6"]
749
865
        self.enabled = False
750
866
        super(IPv6_TCPServer, self).__init__(*args, **kwargs)
751
867
    def server_bind(self):
769
885
        # Only bind(2) the socket if we really need to.
770
886
        if self.server_address[0] or self.server_address[1]:
771
887
            if not self.server_address[0]:
772
 
                in6addr_any = "::"
773
 
                self.server_address = (in6addr_any,
 
888
                if self.address_family == socket.AF_INET6:
 
889
                    any_address = "::" # in6addr_any
 
890
                else:
 
891
                    any_address = socket.INADDR_ANY
 
892
                self.server_address = (any_address,
774
893
                                       self.server_address[1])
775
894
            elif not self.server_address[1]:
776
895
                self.server_address = (self.server_address[0],
788
907
            return super(IPv6_TCPServer, self).server_activate()
789
908
    def enable(self):
790
909
        self.enabled = True
 
910
    def handle_ipc(self, source, condition, file_objects={}):
 
911
        condition_names = {
 
912
            gobject.IO_IN: "IN", # There is data to read.
 
913
            gobject.IO_OUT: "OUT", # Data can be written (without
 
914
                                   # blocking).
 
915
            gobject.IO_PRI: "PRI", # There is urgent data to read.
 
916
            gobject.IO_ERR: "ERR", # Error condition.
 
917
            gobject.IO_HUP: "HUP"  # Hung up (the connection has been
 
918
                                   # broken, usually for pipes and
 
919
                                   # sockets).
 
920
            }
 
921
        conditions_string = ' | '.join(name
 
922
                                       for cond, name in
 
923
                                       condition_names.iteritems()
 
924
                                       if cond & condition)
 
925
        logger.debug("Handling IPC: FD = %d, condition = %s", source,
 
926
                     conditions_string)
 
927
        
 
928
        # Turn the pipe file descriptor into a Python file object
 
929
        if source not in file_objects:
 
930
            file_objects[source] = os.fdopen(source, "r", 1)
 
931
        
 
932
        # Read a line from the file object
 
933
        cmdline = file_objects[source].readline()
 
934
        if not cmdline:             # Empty line means end of file
 
935
            # close the IPC pipe
 
936
            file_objects[source].close()
 
937
            del file_objects[source]
 
938
            
 
939
            # Stop calling this function
 
940
            return False
 
941
        
 
942
        logger.debug("IPC command: %r\n" % cmdline)
 
943
        
 
944
        # Parse and act on command
 
945
        cmd, args = cmdline.split(None, 1)
 
946
        if cmd == "NOTFOUND":
 
947
            if self.settings["use_dbus"]:
 
948
                # Emit D-Bus signal
 
949
                mandos_dbus_service.ClientNotFound(args)
 
950
        elif cmd == "INVALID":
 
951
            if self.settings["use_dbus"]:
 
952
                for client in self.clients:
 
953
                    if client.name == args:
 
954
                        # Emit D-Bus signal
 
955
                        client.Rejected()
 
956
                        break
 
957
        elif cmd == "SENDING":
 
958
            for client in self.clients:
 
959
                if client.name == args:
 
960
                    client.checked_ok()
 
961
                    if self.settings["use_dbus"]:
 
962
                        # Emit D-Bus signal
 
963
                        client.ReceivedSecret()
 
964
                    break
 
965
        else:
 
966
            logger.error("Unknown IPC command: %r", cmdline)
 
967
        
 
968
        # Keep calling this function
 
969
        return True
791
970
 
792
971
 
793
972
def string_to_delta(interval):
899
1078
 
900
1079
 
901
1080
def main():
 
1081
    
 
1082
    ######################################################################
 
1083
    # Parsing of options, both command line and config file
 
1084
    
902
1085
    parser = optparse.OptionParser(version = "%%prog %s" % version)
903
1086
    parser.add_option("-i", "--interface", type="string",
904
1087
                      metavar="IF", help="Bind to interface IF")
923
1106
                      dest="use_dbus",
924
1107
                      help="Do not provide D-Bus system bus"
925
1108
                      " interface")
 
1109
    parser.add_option("--no-ipv6", action="store_false",
 
1110
                      dest="use_ipv6", help="Do not use IPv6")
926
1111
    options = parser.parse_args()[0]
927
1112
    
928
1113
    if options.check:
939
1124
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP",
940
1125
                        "servicename": "Mandos",
941
1126
                        "use_dbus": "True",
 
1127
                        "use_ipv6": "True",
942
1128
                        }
943
1129
    
944
1130
    # Parse config file for server-global settings
952
1138
                                                        "debug")
953
1139
    server_settings["use_dbus"] = server_config.getboolean("DEFAULT",
954
1140
                                                           "use_dbus")
 
1141
    server_settings["use_ipv6"] = server_config.getboolean("DEFAULT",
 
1142
                                                           "use_ipv6")
955
1143
    if server_settings["port"]:
956
1144
        server_settings["port"] = server_config.getint("DEFAULT",
957
1145
                                                       "port")
961
1149
    # options, if set.
962
1150
    for option in ("interface", "address", "port", "debug",
963
1151
                   "priority", "servicename", "configdir",
964
 
                   "use_dbus"):
 
1152
                   "use_dbus", "use_ipv6"):
965
1153
        value = getattr(options, option)
966
1154
        if value is not None:
967
1155
            server_settings[option] = value
968
1156
    del options
969
1157
    # Now we have our good server settings in "server_settings"
970
1158
    
 
1159
    ##################################################################
 
1160
    
971
1161
    # For convenience
972
1162
    debug = server_settings["debug"]
973
1163
    use_dbus = server_settings["use_dbus"]
 
1164
    use_ipv6 = server_settings["use_ipv6"]
974
1165
    
975
1166
    if not debug:
976
1167
        syslogger.setLevel(logging.WARNING)
978
1169
    
979
1170
    if server_settings["servicename"] != "Mandos":
980
1171
        syslogger.setFormatter(logging.Formatter
981
 
                               ('Mandos (%s): %%(levelname)s:'
982
 
                                ' %%(message)s'
 
1172
                               ('Mandos (%s) [%%(process)d]:'
 
1173
                                ' %%(levelname)s: %%(message)s'
983
1174
                                % server_settings["servicename"]))
984
1175
    
985
1176
    # Parse config file with clients
991
1182
    client_config = ConfigParser.SafeConfigParser(client_defaults)
992
1183
    client_config.read(os.path.join(server_settings["configdir"],
993
1184
                                    "clients.conf"))
 
1185
 
 
1186
    global mandos_dbus_service
 
1187
    mandos_dbus_service = None
994
1188
    
995
1189
    clients = Set()
996
1190
    tcp_server = IPv6_TCPServer((server_settings["address"],
997
1191
                                 server_settings["port"]),
998
1192
                                TCP_handler,
999
1193
                                settings=server_settings,
1000
 
                                clients=clients)
 
1194
                                clients=clients, use_ipv6=use_ipv6)
1001
1195
    pidfilename = "/var/run/mandos.pid"
1002
1196
    try:
1003
1197
        pidfile = open(pidfilename, "w")
1039
1233
         .gnutls_global_set_log_function(debug_gnutls))
1040
1234
    
1041
1235
    global service
 
1236
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1042
1237
    service = AvahiService(name = server_settings["servicename"],
1043
 
                           servicetype = "_mandos._tcp", )
 
1238
                           servicetype = "_mandos._tcp",
 
1239
                           protocol = protocol)
1044
1240
    if server_settings["interface"]:
1045
1241
        service.interface = (if_nametoindex
1046
1242
                             (server_settings["interface"]))
1059
1255
    if use_dbus:
1060
1256
        bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
1061
1257
    
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()))
 
1258
    client_class = Client
 
1259
    if use_dbus:
 
1260
        client_class = ClientDBus
 
1261
    clients.update(Set(
 
1262
            client_class(name = section,
 
1263
                         config= dict(client_config.items(section)))
 
1264
            for section in client_config.sections()))
1067
1265
    if not clients:
1068
1266
        logger.warning(u"No clients defined")
1069
1267
    
1080
1278
        daemon()
1081
1279
    
1082
1280
    try:
1083
 
        pid = os.getpid()
1084
 
        pidfile.write(str(pid) + "\n")
1085
 
        pidfile.close()
 
1281
        with closing(pidfile):
 
1282
            pid = os.getpid()
 
1283
            pidfile.write(str(pid) + "\n")
1086
1284
        del pidfile
1087
1285
    except IOError:
1088
1286
        logger.error(u"Could not write to file %r with PID %d",
1114
1312
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1115
1313
    
1116
1314
    if use_dbus:
1117
 
        class MandosServer(dbus.service.Object):
 
1315
        class MandosDBusService(dbus.service.Object):
1118
1316
            """A D-Bus proxy object"""
1119
1317
            def __init__(self):
1120
1318
                dbus.service.Object.__init__(self, bus, "/")
1125
1323
                "D-Bus signal"
1126
1324
                pass
1127
1325
            
 
1326
            @dbus.service.signal(_interface, signature="s")
 
1327
            def ClientNotFound(self, fingerprint):
 
1328
                "D-Bus signal"
 
1329
                pass
 
1330
            
1128
1331
            @dbus.service.signal(_interface, signature="os")
1129
1332
            def ClientRemoved(self, objpath, name):
1130
1333
                "D-Bus signal"
1149
1352
                for c in clients:
1150
1353
                    if c.dbus_object_path == object_path:
1151
1354
                        clients.remove(c)
 
1355
                        c.remove_from_connection()
1152
1356
                        # Don't signal anything except ClientRemoved
1153
 
                        c.use_dbus = False
1154
 
                        c.disable()
 
1357
                        c.disable(signal=False)
1155
1358
                        # Emit D-Bus signal
1156
1359
                        self.ClientRemoved(object_path, c.name)
1157
1360
                        return
1159
1362
            
1160
1363
            del _interface
1161
1364
        
1162
 
        mandos_server = MandosServer()
 
1365
        mandos_dbus_service = MandosDBusService()
1163
1366
    
1164
1367
    for client in clients:
1165
1368
        if use_dbus:
1166
1369
            # Emit D-Bus signal
1167
 
            mandos_server.ClientAdded(client.dbus_object_path,
1168
 
                                      client.GetAllProperties())
 
1370
            mandos_dbus_service.ClientAdded(client.dbus_object_path,
 
1371
                                            client.GetAllProperties())
1169
1372
        client.enable()
1170
1373
    
1171
1374
    tcp_server.enable()
1173
1376
    
1174
1377
    # Find out what port we got
1175
1378
    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())
 
1379
    if use_ipv6:
 
1380
        logger.info(u"Now listening on address %r, port %d,"
 
1381
                    " flowinfo %d, scope_id %d"
 
1382
                    % tcp_server.socket.getsockname())
 
1383
    else:                       # IPv4
 
1384
        logger.info(u"Now listening on address %r, port %d"
 
1385
                    % tcp_server.socket.getsockname())
1178
1386
    
1179
1387
    #service.interface = tcp_server.socket.getsockname()[3]
1180
1388