/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-17 08:26:17 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090417082617-eltetak5lzjyz55o
* initramfs-tools-hook: Bug fix: Add "--userid" and "--groupid" to
                        start of "plugin-runner.conf" file instead of
                        appending, to allow any preexisting options to
                        override.
* plugin-runner.conf: Improved wording.

Show diffs side-by-side

added added

removed removed

Lines of Context:
55
55
import logging
56
56
import logging.handlers
57
57
import pwd
58
 
import contextlib
 
58
from contextlib import closing
59
59
import struct
60
60
import fcntl
61
61
import functools
62
 
import cPickle as pickle
63
 
import multiprocessing
64
62
 
65
63
import dbus
66
64
import dbus.service
69
67
from dbus.mainloop.glib import DBusGMainLoop
70
68
import ctypes
71
69
import ctypes.util
72
 
import xml.dom.minidom
73
 
import inspect
74
70
 
75
71
try:
76
72
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
81
77
        SO_BINDTODEVICE = None
82
78
 
83
79
 
84
 
version = "1.0.14"
 
80
version = "1.0.8"
85
81
 
86
 
#logger = logging.getLogger(u'mandos')
87
82
logger = logging.Logger(u'mandos')
88
83
syslogger = (logging.handlers.SysLogHandler
89
84
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
157
152
                            u" after %i retries, exiting.",
158
153
                            self.rename_count)
159
154
            raise AvahiServiceError(u"Too many renames")
160
 
        self.name = unicode(self.server.GetAlternativeServiceName(self.name))
 
155
        self.name = self.server.GetAlternativeServiceName(self.name)
161
156
        logger.info(u"Changing Zeroconf service name to %r ...",
162
 
                    self.name)
 
157
                    unicode(self.name))
163
158
        syslogger.setFormatter(logging.Formatter
164
159
                               (u'Mandos (%s) [%%(process)d]:'
165
160
                                u' %%(levelname)s: %%(message)s'
179
174
                                    self.server.EntryGroupNew()),
180
175
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
181
176
            self.group.connect_to_signal('StateChanged',
182
 
                                         self
183
 
                                         .entry_group_state_changed)
 
177
                                         self.entry_group_state_changed)
184
178
        logger.debug(u"Adding Zeroconf service '%s' of type '%s' ...",
185
179
                     self.name, self.type)
186
180
        self.group.AddService(
245
239
    enabled:    bool()
246
240
    last_checked_ok: datetime.datetime(); (UTC) or None
247
241
    timeout:    datetime.timedelta(); How long from last_checked_ok
248
 
                                      until this client is disabled
 
242
                                      until this client is invalid
249
243
    interval:   datetime.timedelta(); How often to start a new checker
250
244
    disable_hook:  If set, called by disable() as disable_hook(self)
251
245
    checker:    subprocess.Popen(); a running checker process used
252
246
                                    to see if the client lives.
253
247
                                    'None' if no process is running.
254
248
    checker_initiator_tag: a gobject event source tag, or None
255
 
    disable_initiator_tag: - '' -
 
249
    disable_initiator_tag:    - '' -
256
250
    checker_callback_tag:  - '' -
257
251
    checker_command: string; External command which is run to check if
258
252
                     client lives.  %() expansions are done at
259
253
                     runtime with vars(self) as dict, so that for
260
254
                     instance %(name)s can be used in the command.
261
255
    current_checker_command: string; current running checker_command
262
 
    approved_delay: datetime.timedelta(); Time to wait for approval
263
 
    _approved:   bool(); 'None' if not yet approved/disapproved
264
 
    approved_duration: datetime.timedelta(); Duration of one approval
265
256
    """
266
257
    
267
258
    @staticmethod
268
 
    def _timedelta_to_milliseconds(td):
269
 
        "Convert a datetime.timedelta() to milliseconds"
270
 
        return ((td.days * 24 * 60 * 60 * 1000)
271
 
                + (td.seconds * 1000)
272
 
                + (td.microseconds // 1000))
 
259
    def _datetime_to_milliseconds(dt):
 
260
        "Convert a datetime.datetime() to milliseconds"
 
261
        return ((dt.days * 24 * 60 * 60 * 1000)
 
262
                + (dt.seconds * 1000)
 
263
                + (dt.microseconds // 1000))
273
264
    
274
265
    def timeout_milliseconds(self):
275
266
        "Return the 'timeout' attribute in milliseconds"
276
 
        return self._timedelta_to_milliseconds(self.timeout)
 
267
        return self._datetime_to_milliseconds(self.timeout)
277
268
    
278
269
    def interval_milliseconds(self):
279
270
        "Return the 'interval' attribute in milliseconds"
280
 
        return self._timedelta_to_milliseconds(self.interval)
281
 
 
282
 
    def approved_delay_milliseconds(self):
283
 
        return self._timedelta_to_milliseconds(self.approved_delay)
 
271
        return self._datetime_to_milliseconds(self.interval)
284
272
    
285
273
    def __init__(self, name = None, disable_hook=None, config=None):
286
274
        """Note: the 'checker' key in 'config' sets the
299
287
        if u"secret" in config:
300
288
            self.secret = config[u"secret"].decode(u"base64")
301
289
        elif u"secfile" in config:
302
 
            with open(os.path.expanduser(os.path.expandvars
303
 
                                         (config[u"secfile"])),
304
 
                      "rb") as secfile:
 
290
            with closing(open(os.path.expanduser
 
291
                              (os.path.expandvars
 
292
                               (config[u"secfile"])))) as secfile:
305
293
                self.secret = secfile.read()
306
294
        else:
307
295
            raise TypeError(u"No secret or secfile for client %s"
321
309
        self.checker_command = config[u"checker"]
322
310
        self.current_checker_command = None
323
311
        self.last_connect = None
324
 
        self._approved = None
325
 
        self.approved_by_default = config.get(u"approved_by_default",
326
 
                                              True)
327
 
        self.approvals_pending = 0
328
 
        self.approved_delay = string_to_delta(
329
 
            config[u"approved_delay"])
330
 
        self.approved_duration = string_to_delta(
331
 
            config[u"approved_duration"])
332
 
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
333
312
    
334
 
    def send_changedstate(self):
335
 
        self.changedstate.acquire()
336
 
        self.changedstate.notify_all()
337
 
        self.changedstate.release()
338
 
        
339
313
    def enable(self):
340
314
        """Start this client's checker and timeout hooks"""
341
315
        if getattr(self, u"enabled", False):
342
316
            # Already enabled
343
317
            return
344
 
        self.send_changedstate()
345
318
        self.last_enabled = datetime.datetime.utcnow()
346
319
        # Schedule a new checker to be started an 'interval' from now,
347
320
        # and every interval from then on.
348
321
        self.checker_initiator_tag = (gobject.timeout_add
349
322
                                      (self.interval_milliseconds(),
350
323
                                       self.start_checker))
 
324
        # Also start a new checker *right now*.
 
325
        self.start_checker()
351
326
        # Schedule a disable() when 'timeout' has passed
352
327
        self.disable_initiator_tag = (gobject.timeout_add
353
328
                                   (self.timeout_milliseconds(),
354
329
                                    self.disable))
355
330
        self.enabled = True
356
 
        # Also start a new checker *right now*.
357
 
        self.start_checker()
358
331
    
359
 
    def disable(self, quiet=True):
 
332
    def disable(self):
360
333
        """Disable this client."""
361
334
        if not getattr(self, "enabled", False):
362
335
            return False
363
 
        if not quiet:
364
 
            self.send_changedstate()
365
 
        if not quiet:
366
 
            logger.info(u"Disabling client %s", self.name)
 
336
        logger.info(u"Disabling client %s", self.name)
367
337
        if getattr(self, u"disable_initiator_tag", False):
368
338
            gobject.source_remove(self.disable_initiator_tag)
369
339
            self.disable_initiator_tag = None
421
391
        # client would inevitably timeout, since no checker would get
422
392
        # a chance to run to completion.  If we instead leave running
423
393
        # checkers alone, the checker would have to take more time
424
 
        # than 'timeout' for the client to be disabled, which is as it
425
 
        # should be.
 
394
        # than 'timeout' for the client to be declared invalid, which
 
395
        # is as it should be.
426
396
        
427
397
        # If a checker exists, make sure it is not a zombie
428
 
        try:
 
398
        if self.checker is not None:
429
399
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
430
 
        except (AttributeError, OSError), error:
431
 
            if (isinstance(error, OSError)
432
 
                and error.errno != errno.ECHILD):
433
 
                raise error
434
 
        else:
435
400
            if pid:
436
401
                logger.warning(u"Checker was a zombie")
437
402
                gobject.source_remove(self.checker_callback_tag)
493
458
        logger.debug(u"Stopping checker for %(name)s", vars(self))
494
459
        try:
495
460
            os.kill(self.checker.pid, signal.SIGTERM)
496
 
            #time.sleep(0.5)
 
461
            #os.sleep(0.5)
497
462
            #if self.checker.poll() is None:
498
463
            #    os.kill(self.checker.pid, signal.SIGKILL)
499
464
        except OSError, error:
500
465
            if error.errno != errno.ESRCH: # No such process
501
466
                raise
502
467
        self.checker = None
503
 
 
504
 
def dbus_service_property(dbus_interface, signature=u"v",
505
 
                          access=u"readwrite", byte_arrays=False):
506
 
    """Decorators for marking methods of a DBusObjectWithProperties to
507
 
    become properties on the D-Bus.
508
 
    
509
 
    The decorated method will be called with no arguments by "Get"
510
 
    and with one argument by "Set".
511
 
    
512
 
    The parameters, where they are supported, are the same as
513
 
    dbus.service.method, except there is only "signature", since the
514
 
    type from Get() and the type sent to Set() is the same.
515
 
    """
516
 
    # Encoding deeply encoded byte arrays is not supported yet by the
517
 
    # "Set" method, so we fail early here:
518
 
    if byte_arrays and signature != u"ay":
519
 
        raise ValueError(u"Byte arrays not supported for non-'ay'"
520
 
                         u" signature %r" % signature)
521
 
    def decorator(func):
522
 
        func._dbus_is_property = True
523
 
        func._dbus_interface = dbus_interface
524
 
        func._dbus_signature = signature
525
 
        func._dbus_access = access
526
 
        func._dbus_name = func.__name__
527
 
        if func._dbus_name.endswith(u"_dbus_property"):
528
 
            func._dbus_name = func._dbus_name[:-14]
529
 
        func._dbus_get_args_options = {u'byte_arrays': byte_arrays }
530
 
        return func
531
 
    return decorator
532
 
 
533
 
 
534
 
class DBusPropertyException(dbus.exceptions.DBusException):
535
 
    """A base class for D-Bus property-related exceptions
536
 
    """
537
 
    def __unicode__(self):
538
 
        return unicode(str(self))
539
 
 
540
 
 
541
 
class DBusPropertyAccessException(DBusPropertyException):
542
 
    """A property's access permissions disallows an operation.
543
 
    """
544
 
    pass
545
 
 
546
 
 
547
 
class DBusPropertyNotFound(DBusPropertyException):
548
 
    """An attempt was made to access a non-existing property.
549
 
    """
550
 
    pass
551
 
 
552
 
 
553
 
class DBusObjectWithProperties(dbus.service.Object):
554
 
    """A D-Bus object with properties.
555
 
 
556
 
    Classes inheriting from this can use the dbus_service_property
557
 
    decorator to expose methods as D-Bus properties.  It exposes the
558
 
    standard Get(), Set(), and GetAll() methods on the D-Bus.
559
 
    """
560
 
    
561
 
    @staticmethod
562
 
    def _is_dbus_property(obj):
563
 
        return getattr(obj, u"_dbus_is_property", False)
564
 
    
565
 
    def _get_all_dbus_properties(self):
566
 
        """Returns a generator of (name, attribute) pairs
567
 
        """
568
 
        return ((prop._dbus_name, prop)
569
 
                for name, prop in
570
 
                inspect.getmembers(self, self._is_dbus_property))
571
 
    
572
 
    def _get_dbus_property(self, interface_name, property_name):
573
 
        """Returns a bound method if one exists which is a D-Bus
574
 
        property with the specified name and interface.
575
 
        """
576
 
        for name in (property_name,
577
 
                     property_name + u"_dbus_property"):
578
 
            prop = getattr(self, name, None)
579
 
            if (prop is None
580
 
                or not self._is_dbus_property(prop)
581
 
                or prop._dbus_name != property_name
582
 
                or (interface_name and prop._dbus_interface
583
 
                    and interface_name != prop._dbus_interface)):
584
 
                continue
585
 
            return prop
586
 
        # No such property
587
 
        raise DBusPropertyNotFound(self.dbus_object_path + u":"
588
 
                                   + interface_name + u"."
589
 
                                   + property_name)
590
 
    
591
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ss",
592
 
                         out_signature=u"v")
593
 
    def Get(self, interface_name, property_name):
594
 
        """Standard D-Bus property Get() method, see D-Bus standard.
595
 
        """
596
 
        prop = self._get_dbus_property(interface_name, property_name)
597
 
        if prop._dbus_access == u"write":
598
 
            raise DBusPropertyAccessException(property_name)
599
 
        value = prop()
600
 
        if not hasattr(value, u"variant_level"):
601
 
            return value
602
 
        return type(value)(value, variant_level=value.variant_level+1)
603
 
    
604
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"ssv")
605
 
    def Set(self, interface_name, property_name, value):
606
 
        """Standard D-Bus property Set() method, see D-Bus standard.
607
 
        """
608
 
        prop = self._get_dbus_property(interface_name, property_name)
609
 
        if prop._dbus_access == u"read":
610
 
            raise DBusPropertyAccessException(property_name)
611
 
        if prop._dbus_get_args_options[u"byte_arrays"]:
612
 
            # The byte_arrays option is not supported yet on
613
 
            # signatures other than "ay".
614
 
            if prop._dbus_signature != u"ay":
615
 
                raise ValueError
616
 
            value = dbus.ByteArray(''.join(unichr(byte)
617
 
                                           for byte in value))
618
 
        prop(value)
619
 
    
620
 
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature=u"s",
621
 
                         out_signature=u"a{sv}")
622
 
    def GetAll(self, interface_name):
623
 
        """Standard D-Bus property GetAll() method, see D-Bus
624
 
        standard.
625
 
 
626
 
        Note: Will not include properties with access="write".
627
 
        """
628
 
        all = {}
629
 
        for name, prop in self._get_all_dbus_properties():
630
 
            if (interface_name
631
 
                and interface_name != prop._dbus_interface):
632
 
                # Interface non-empty but did not match
633
 
                continue
634
 
            # Ignore write-only properties
635
 
            if prop._dbus_access == u"write":
636
 
                continue
637
 
            value = prop()
638
 
            if not hasattr(value, u"variant_level"):
639
 
                all[name] = value
640
 
                continue
641
 
            all[name] = type(value)(value, variant_level=
642
 
                                    value.variant_level+1)
643
 
        return dbus.Dictionary(all, signature=u"sv")
644
 
    
645
 
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
646
 
                         out_signature=u"s",
647
 
                         path_keyword='object_path',
648
 
                         connection_keyword='connection')
649
 
    def Introspect(self, object_path, connection):
650
 
        """Standard D-Bus method, overloaded to insert property tags.
651
 
        """
652
 
        xmlstring = dbus.service.Object.Introspect(self, object_path,
653
 
                                                   connection)
654
 
        try:
655
 
            document = xml.dom.minidom.parseString(xmlstring)
656
 
            def make_tag(document, name, prop):
657
 
                e = document.createElement(u"property")
658
 
                e.setAttribute(u"name", name)
659
 
                e.setAttribute(u"type", prop._dbus_signature)
660
 
                e.setAttribute(u"access", prop._dbus_access)
661
 
                return e
662
 
            for if_tag in document.getElementsByTagName(u"interface"):
663
 
                for tag in (make_tag(document, name, prop)
664
 
                            for name, prop
665
 
                            in self._get_all_dbus_properties()
666
 
                            if prop._dbus_interface
667
 
                            == if_tag.getAttribute(u"name")):
668
 
                    if_tag.appendChild(tag)
669
 
                # Add the names to the return values for the
670
 
                # "org.freedesktop.DBus.Properties" methods
671
 
                if (if_tag.getAttribute(u"name")
672
 
                    == u"org.freedesktop.DBus.Properties"):
673
 
                    for cn in if_tag.getElementsByTagName(u"method"):
674
 
                        if cn.getAttribute(u"name") == u"Get":
675
 
                            for arg in cn.getElementsByTagName(u"arg"):
676
 
                                if (arg.getAttribute(u"direction")
677
 
                                    == u"out"):
678
 
                                    arg.setAttribute(u"name", u"value")
679
 
                        elif cn.getAttribute(u"name") == u"GetAll":
680
 
                            for arg in cn.getElementsByTagName(u"arg"):
681
 
                                if (arg.getAttribute(u"direction")
682
 
                                    == u"out"):
683
 
                                    arg.setAttribute(u"name", u"props")
684
 
            xmlstring = document.toxml(u"utf-8")
685
 
            document.unlink()
686
 
        except (AttributeError, xml.dom.DOMException,
687
 
                xml.parsers.expat.ExpatError), error:
688
 
            logger.error(u"Failed to override Introspection method",
689
 
                         error)
690
 
        return xmlstring
691
 
 
692
 
 
693
 
class ClientDBus(Client, DBusObjectWithProperties):
 
468
    
 
469
    def still_valid(self):
 
470
        """Has the timeout not yet passed for this client?"""
 
471
        if not getattr(self, u"enabled", False):
 
472
            return False
 
473
        now = datetime.datetime.utcnow()
 
474
        if self.last_checked_ok is None:
 
475
            return now < (self.created + self.timeout)
 
476
        else:
 
477
            return now < (self.last_checked_ok + self.timeout)
 
478
 
 
479
 
 
480
class ClientDBus(Client, dbus.service.Object):
694
481
    """A Client class using D-Bus
695
482
    
696
483
    Attributes:
700
487
    # dbus.service.Object doesn't use super(), so we can't either.
701
488
    
702
489
    def __init__(self, bus = None, *args, **kwargs):
703
 
        self._approvals_pending = 0
704
490
        self.bus = bus
705
491
        Client.__init__(self, *args, **kwargs)
706
492
        # Only now, when this client is initialized, can it show up on
708
494
        self.dbus_object_path = (dbus.ObjectPath
709
495
                                 (u"/clients/"
710
496
                                  + self.name.replace(u".", u"_")))
711
 
        DBusObjectWithProperties.__init__(self, self.bus,
712
 
                                          self.dbus_object_path)
713
 
 
714
 
    def _get_approvals_pending(self):
715
 
        return self._approvals_pending
716
 
    def _set_approvals_pending(self, value):
717
 
        old_value = self._approvals_pending
718
 
        self._approvals_pending = value
719
 
        bval = bool(value)
720
 
        if (hasattr(self, "dbus_object_path")
721
 
            and bval is not bool(old_value)):
722
 
            dbus_bool = dbus.Boolean(bval, variant_level=1)
723
 
            self.PropertyChanged(dbus.String(u"approved_pending"),
724
 
                                 dbus_bool)
725
 
 
726
 
    approvals_pending = property(_get_approvals_pending,
727
 
                                 _set_approvals_pending)
728
 
    del _get_approvals_pending, _set_approvals_pending
 
497
        dbus.service.Object.__init__(self, self.bus,
 
498
                                     self.dbus_object_path)
729
499
    
730
500
    @staticmethod
731
501
    def _datetime_to_dbus(dt, variant_level=0):
746
516
                                       variant_level=1))
747
517
        return r
748
518
    
749
 
    def disable(self, quiet = False):
 
519
    def disable(self, signal = True):
750
520
        oldstate = getattr(self, u"enabled", False)
751
 
        r = Client.disable(self, quiet=quiet)
752
 
        if not quiet and oldstate != self.enabled:
 
521
        r = Client.disable(self)
 
522
        if signal and oldstate != self.enabled:
753
523
            # Emit D-Bus signal
754
524
            self.PropertyChanged(dbus.String(u"enabled"),
755
525
                                 dbus.Boolean(False, variant_level=1))
760
530
            self.remove_from_connection()
761
531
        except LookupError:
762
532
            pass
763
 
        if hasattr(DBusObjectWithProperties, u"__del__"):
764
 
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
 
533
        if hasattr(dbus.service.Object, u"__del__"):
 
534
            dbus.service.Object.__del__(self, *args, **kwargs)
765
535
        Client.__del__(self, *args, **kwargs)
766
536
    
767
537
    def checker_callback(self, pid, condition, command,
820
590
            self.PropertyChanged(dbus.String(u"checker_running"),
821
591
                                 dbus.Boolean(False, variant_level=1))
822
592
        return r
823
 
 
824
 
    def _reset_approved(self):
825
 
        self._approved = None
826
 
        return False
827
 
    
828
 
    def approve(self, value=True):
829
 
        self.send_changedstate()
830
 
        self._approved = value
831
 
        gobject.timeout_add(self._timedelta_to_milliseconds(self.approved_duration),
832
 
                            self._reset_approved)
833
 
    
834
 
    
835
 
    ## D-Bus methods, signals & properties
 
593
    
 
594
    ## D-Bus methods & signals
836
595
    _interface = u"se.bsnet.fukt.Mandos.Client"
837
596
    
838
 
    ## Signals
 
597
    # CheckedOK - method
 
598
    @dbus.service.method(_interface)
 
599
    def CheckedOK(self):
 
600
        return self.checked_ok()
839
601
    
840
602
    # CheckerCompleted - signal
841
603
    @dbus.service.signal(_interface, signature=u"nxs")
849
611
        "D-Bus signal"
850
612
        pass
851
613
    
 
614
    # GetAllProperties - method
 
615
    @dbus.service.method(_interface, out_signature=u"a{sv}")
 
616
    def GetAllProperties(self):
 
617
        "D-Bus method"
 
618
        return dbus.Dictionary({
 
619
                dbus.String(u"name"):
 
620
                    dbus.String(self.name, variant_level=1),
 
621
                dbus.String(u"fingerprint"):
 
622
                    dbus.String(self.fingerprint, variant_level=1),
 
623
                dbus.String(u"host"):
 
624
                    dbus.String(self.host, variant_level=1),
 
625
                dbus.String(u"created"):
 
626
                    self._datetime_to_dbus(self.created,
 
627
                                           variant_level=1),
 
628
                dbus.String(u"last_enabled"):
 
629
                    (self._datetime_to_dbus(self.last_enabled,
 
630
                                            variant_level=1)
 
631
                     if self.last_enabled is not None
 
632
                     else dbus.Boolean(False, variant_level=1)),
 
633
                dbus.String(u"enabled"):
 
634
                    dbus.Boolean(self.enabled, variant_level=1),
 
635
                dbus.String(u"last_checked_ok"):
 
636
                    (self._datetime_to_dbus(self.last_checked_ok,
 
637
                                            variant_level=1)
 
638
                     if self.last_checked_ok is not None
 
639
                     else dbus.Boolean (False, variant_level=1)),
 
640
                dbus.String(u"timeout"):
 
641
                    dbus.UInt64(self.timeout_milliseconds(),
 
642
                                variant_level=1),
 
643
                dbus.String(u"interval"):
 
644
                    dbus.UInt64(self.interval_milliseconds(),
 
645
                                variant_level=1),
 
646
                dbus.String(u"checker"):
 
647
                    dbus.String(self.checker_command,
 
648
                                variant_level=1),
 
649
                dbus.String(u"checker_running"):
 
650
                    dbus.Boolean(self.checker is not None,
 
651
                                 variant_level=1),
 
652
                dbus.String(u"object_path"):
 
653
                    dbus.ObjectPath(self.dbus_object_path,
 
654
                                    variant_level=1)
 
655
                }, signature=u"sv")
 
656
    
 
657
    # IsStillValid - method
 
658
    @dbus.service.method(_interface, out_signature=u"b")
 
659
    def IsStillValid(self):
 
660
        return self.still_valid()
 
661
    
852
662
    # PropertyChanged - signal
853
663
    @dbus.service.signal(_interface, signature=u"sv")
854
664
    def PropertyChanged(self, property, value):
855
665
        "D-Bus signal"
856
666
        pass
857
667
    
858
 
    # GotSecret - signal
 
668
    # ReceivedSecret - signal
859
669
    @dbus.service.signal(_interface)
860
 
    def GotSecret(self):
861
 
        """D-Bus signal
862
 
        Is sent after a successful transfer of secret from the Mandos
863
 
        server to mandos-client
864
 
        """
 
670
    def ReceivedSecret(self):
 
671
        "D-Bus signal"
865
672
        pass
866
673
    
867
674
    # Rejected - signal
868
 
    @dbus.service.signal(_interface, signature=u"s")
869
 
    def Rejected(self, reason):
870
 
        "D-Bus signal"
871
 
        pass
872
 
    
873
 
    # NeedApproval - signal
874
 
    @dbus.service.signal(_interface, signature=u"db")
875
 
    def NeedApproval(self, timeout, default):
876
 
        "D-Bus signal"
877
 
        pass
878
 
    
879
 
    ## Methods
880
 
 
881
 
    # Approve - method
882
 
    @dbus.service.method(_interface, in_signature=u"b")
883
 
    def Approve(self, value):
884
 
        self.approve(value)
885
 
 
886
 
    # CheckedOK - method
887
 
    @dbus.service.method(_interface)
888
 
    def CheckedOK(self):
889
 
        return self.checked_ok()
 
675
    @dbus.service.signal(_interface)
 
676
    def Rejected(self):
 
677
        "D-Bus signal"
 
678
        pass
 
679
    
 
680
    # SetChecker - method
 
681
    @dbus.service.method(_interface, in_signature=u"s")
 
682
    def SetChecker(self, checker):
 
683
        "D-Bus setter method"
 
684
        self.checker_command = checker
 
685
        # Emit D-Bus signal
 
686
        self.PropertyChanged(dbus.String(u"checker"),
 
687
                             dbus.String(self.checker_command,
 
688
                                         variant_level=1))
 
689
    
 
690
    # SetHost - method
 
691
    @dbus.service.method(_interface, in_signature=u"s")
 
692
    def SetHost(self, host):
 
693
        "D-Bus setter method"
 
694
        self.host = host
 
695
        # Emit D-Bus signal
 
696
        self.PropertyChanged(dbus.String(u"host"),
 
697
                             dbus.String(self.host, variant_level=1))
 
698
    
 
699
    # SetInterval - method
 
700
    @dbus.service.method(_interface, in_signature=u"t")
 
701
    def SetInterval(self, milliseconds):
 
702
        self.interval = datetime.timedelta(0, 0, 0, milliseconds)
 
703
        # Emit D-Bus signal
 
704
        self.PropertyChanged(dbus.String(u"interval"),
 
705
                             (dbus.UInt64(self.interval_milliseconds(),
 
706
                                          variant_level=1)))
 
707
    
 
708
    # SetSecret - method
 
709
    @dbus.service.method(_interface, in_signature=u"ay",
 
710
                         byte_arrays=True)
 
711
    def SetSecret(self, secret):
 
712
        "D-Bus setter method"
 
713
        self.secret = str(secret)
 
714
    
 
715
    # SetTimeout - method
 
716
    @dbus.service.method(_interface, in_signature=u"t")
 
717
    def SetTimeout(self, milliseconds):
 
718
        self.timeout = datetime.timedelta(0, 0, 0, milliseconds)
 
719
        # Emit D-Bus signal
 
720
        self.PropertyChanged(dbus.String(u"timeout"),
 
721
                             (dbus.UInt64(self.timeout_milliseconds(),
 
722
                                          variant_level=1)))
890
723
    
891
724
    # Enable - method
892
725
    @dbus.service.method(_interface)
911
744
    def StopChecker(self):
912
745
        self.stop_checker()
913
746
    
914
 
    ## Properties
915
 
    
916
 
    # approved_pending - property
917
 
    @dbus_service_property(_interface, signature=u"b", access=u"read")
918
 
    def approved_pending_dbus_property(self):
919
 
        return dbus.Boolean(bool(self.approvals_pending))
920
 
    
921
 
    # approved_by_default - property
922
 
    @dbus_service_property(_interface, signature=u"b",
923
 
                           access=u"readwrite")
924
 
    def approved_by_default_dbus_property(self):
925
 
        return dbus.Boolean(self.approved_by_default)
926
 
    
927
 
    # approved_delay - property
928
 
    @dbus_service_property(_interface, signature=u"t",
929
 
                           access=u"readwrite")
930
 
    def approved_delay_dbus_property(self):
931
 
        return dbus.UInt64(self.approved_delay_milliseconds())
932
 
    
933
 
    # approved_duration - property
934
 
    @dbus_service_property(_interface, signature=u"t",
935
 
                           access=u"readwrite")
936
 
    def approved_duration_dbus_property(self):
937
 
        return dbus.UInt64(self._timedelta_to_milliseconds(
938
 
                self.approved_duration))
939
 
    
940
 
    # name - property
941
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
942
 
    def name_dbus_property(self):
943
 
        return dbus.String(self.name)
944
 
    
945
 
    # fingerprint - property
946
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
947
 
    def fingerprint_dbus_property(self):
948
 
        return dbus.String(self.fingerprint)
949
 
    
950
 
    # host - property
951
 
    @dbus_service_property(_interface, signature=u"s",
952
 
                           access=u"readwrite")
953
 
    def host_dbus_property(self, value=None):
954
 
        if value is None:       # get
955
 
            return dbus.String(self.host)
956
 
        self.host = value
957
 
        # Emit D-Bus signal
958
 
        self.PropertyChanged(dbus.String(u"host"),
959
 
                             dbus.String(value, variant_level=1))
960
 
    
961
 
    # created - property
962
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
963
 
    def created_dbus_property(self):
964
 
        return dbus.String(self._datetime_to_dbus(self.created))
965
 
    
966
 
    # last_enabled - property
967
 
    @dbus_service_property(_interface, signature=u"s", access=u"read")
968
 
    def last_enabled_dbus_property(self):
969
 
        if self.last_enabled is None:
970
 
            return dbus.String(u"")
971
 
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
972
 
    
973
 
    # enabled - property
974
 
    @dbus_service_property(_interface, signature=u"b",
975
 
                           access=u"readwrite")
976
 
    def enabled_dbus_property(self, value=None):
977
 
        if value is None:       # get
978
 
            return dbus.Boolean(self.enabled)
979
 
        if value:
980
 
            self.enable()
981
 
        else:
982
 
            self.disable()
983
 
    
984
 
    # last_checked_ok - property
985
 
    @dbus_service_property(_interface, signature=u"s",
986
 
                           access=u"readwrite")
987
 
    def last_checked_ok_dbus_property(self, value=None):
988
 
        if value is not None:
989
 
            self.checked_ok()
990
 
            return
991
 
        if self.last_checked_ok is None:
992
 
            return dbus.String(u"")
993
 
        return dbus.String(self._datetime_to_dbus(self
994
 
                                                  .last_checked_ok))
995
 
    
996
 
    # timeout - property
997
 
    @dbus_service_property(_interface, signature=u"t",
998
 
                           access=u"readwrite")
999
 
    def timeout_dbus_property(self, value=None):
1000
 
        if value is None:       # get
1001
 
            return dbus.UInt64(self.timeout_milliseconds())
1002
 
        self.timeout = datetime.timedelta(0, 0, 0, value)
1003
 
        # Emit D-Bus signal
1004
 
        self.PropertyChanged(dbus.String(u"timeout"),
1005
 
                             dbus.UInt64(value, variant_level=1))
1006
 
        if getattr(self, u"disable_initiator_tag", None) is None:
1007
 
            return
1008
 
        # Reschedule timeout
1009
 
        gobject.source_remove(self.disable_initiator_tag)
1010
 
        self.disable_initiator_tag = None
1011
 
        time_to_die = (self.
1012
 
                       _timedelta_to_milliseconds((self
1013
 
                                                   .last_checked_ok
1014
 
                                                   + self.timeout)
1015
 
                                                  - datetime.datetime
1016
 
                                                  .utcnow()))
1017
 
        if time_to_die <= 0:
1018
 
            # The timeout has passed
1019
 
            self.disable()
1020
 
        else:
1021
 
            self.disable_initiator_tag = (gobject.timeout_add
1022
 
                                          (time_to_die, self.disable))
1023
 
    
1024
 
    # interval - property
1025
 
    @dbus_service_property(_interface, signature=u"t",
1026
 
                           access=u"readwrite")
1027
 
    def interval_dbus_property(self, value=None):
1028
 
        if value is None:       # get
1029
 
            return dbus.UInt64(self.interval_milliseconds())
1030
 
        self.interval = datetime.timedelta(0, 0, 0, value)
1031
 
        # Emit D-Bus signal
1032
 
        self.PropertyChanged(dbus.String(u"interval"),
1033
 
                             dbus.UInt64(value, variant_level=1))
1034
 
        if getattr(self, u"checker_initiator_tag", None) is None:
1035
 
            return
1036
 
        # Reschedule checker run
1037
 
        gobject.source_remove(self.checker_initiator_tag)
1038
 
        self.checker_initiator_tag = (gobject.timeout_add
1039
 
                                      (value, self.start_checker))
1040
 
        self.start_checker()    # Start one now, too
1041
 
 
1042
 
    # checker - property
1043
 
    @dbus_service_property(_interface, signature=u"s",
1044
 
                           access=u"readwrite")
1045
 
    def checker_dbus_property(self, value=None):
1046
 
        if value is None:       # get
1047
 
            return dbus.String(self.checker_command)
1048
 
        self.checker_command = value
1049
 
        # Emit D-Bus signal
1050
 
        self.PropertyChanged(dbus.String(u"checker"),
1051
 
                             dbus.String(self.checker_command,
1052
 
                                         variant_level=1))
1053
 
    
1054
 
    # checker_running - property
1055
 
    @dbus_service_property(_interface, signature=u"b",
1056
 
                           access=u"readwrite")
1057
 
    def checker_running_dbus_property(self, value=None):
1058
 
        if value is None:       # get
1059
 
            return dbus.Boolean(self.checker is not None)
1060
 
        if value:
1061
 
            self.start_checker()
1062
 
        else:
1063
 
            self.stop_checker()
1064
 
    
1065
 
    # object_path - property
1066
 
    @dbus_service_property(_interface, signature=u"o", access=u"read")
1067
 
    def object_path_dbus_property(self):
1068
 
        return self.dbus_object_path # is already a dbus.ObjectPath
1069
 
    
1070
 
    # secret = property
1071
 
    @dbus_service_property(_interface, signature=u"ay",
1072
 
                           access=u"write", byte_arrays=True)
1073
 
    def secret_dbus_property(self, value):
1074
 
        self.secret = str(value)
1075
 
    
1076
747
    del _interface
1077
748
 
1078
749
 
1079
 
class ProxyClient(object):
1080
 
    def __init__(self, child_pipe, fpr, address):
1081
 
        self._pipe = child_pipe
1082
 
        self._pipe.send(('init', fpr, address))
1083
 
        if not self._pipe.recv():
1084
 
            raise KeyError()
1085
 
 
1086
 
    def __getattribute__(self, name):
1087
 
        if(name == '_pipe'):
1088
 
            return super(ProxyClient, self).__getattribute__(name)
1089
 
        self._pipe.send(('getattr', name))
1090
 
        data = self._pipe.recv()
1091
 
        if data[0] == 'data':
1092
 
            return data[1]
1093
 
        if data[0] == 'function':
1094
 
            def func(*args, **kwargs):
1095
 
                self._pipe.send(('funcall', name, args, kwargs))
1096
 
                return self._pipe.recv()[1]
1097
 
            return func
1098
 
 
1099
 
    def __setattr__(self, name, value):
1100
 
        if(name == '_pipe'):
1101
 
            return super(ProxyClient, self).__setattr__(name, value)
1102
 
        self._pipe.send(('setattr', name, value))
1103
 
 
1104
 
 
1105
750
class ClientHandler(socketserver.BaseRequestHandler, object):
1106
751
    """A class to handle client connections.
1107
752
    
1109
754
    Note: This will run in its own forked process."""
1110
755
    
1111
756
    def handle(self):
1112
 
        with contextlib.closing(self.server.child_pipe) as child_pipe:
1113
 
            logger.info(u"TCP connection from: %s",
1114
 
                        unicode(self.client_address))
1115
 
            logger.debug(u"Pipe FD: %d",
1116
 
                         self.server.child_pipe.fileno())
1117
 
 
 
757
        logger.info(u"TCP connection from: %s",
 
758
                    unicode(self.client_address))
 
759
        logger.debug(u"IPC Pipe FD: %d", self.server.pipe[1])
 
760
        # Open IPC pipe to parent process
 
761
        with closing(os.fdopen(self.server.pipe[1], u"w", 1)) as ipc:
1118
762
            session = (gnutls.connection
1119
763
                       .ClientSession(self.request,
1120
764
                                      gnutls.connection
1121
765
                                      .X509Credentials()))
1122
 
 
 
766
            
 
767
            line = self.request.makefile().readline()
 
768
            logger.debug(u"Protocol version: %r", line)
 
769
            try:
 
770
                if int(line.strip().split()[0]) > 1:
 
771
                    raise RuntimeError
 
772
            except (ValueError, IndexError, RuntimeError), error:
 
773
                logger.error(u"Unknown protocol version: %s", error)
 
774
                return
 
775
            
1123
776
            # Note: gnutls.connection.X509Credentials is really a
1124
777
            # generic GnuTLS certificate credentials object so long as
1125
778
            # no X.509 keys are added to it.  Therefore, we can use it
1126
779
            # here despite using OpenPGP certificates.
1127
 
 
 
780
            
1128
781
            #priority = u':'.join((u"NONE", u"+VERS-TLS1.1",
1129
782
            #                      u"+AES-256-CBC", u"+SHA1",
1130
783
            #                      u"+COMP-NULL", u"+CTYPE-OPENPGP",
1136
789
            (gnutls.library.functions
1137
790
             .gnutls_priority_set_direct(session._c_object,
1138
791
                                         priority, None))
1139
 
 
1140
 
            # Start communication using the Mandos protocol
1141
 
            # Get protocol number
1142
 
            line = self.request.makefile().readline()
1143
 
            logger.debug(u"Protocol version: %r", line)
1144
 
            try:
1145
 
                if int(line.strip().split()[0]) > 1:
1146
 
                    raise RuntimeError
1147
 
            except (ValueError, IndexError, RuntimeError), error:
1148
 
                logger.error(u"Unknown protocol version: %s", error)
1149
 
                return
1150
 
 
1151
 
            # Start GnuTLS connection
 
792
            
1152
793
            try:
1153
794
                session.handshake()
1154
795
            except gnutls.errors.GNUTLSError, error:
1157
798
                # established.  Just abandon the request.
1158
799
                return
1159
800
            logger.debug(u"Handshake succeeded")
1160
 
 
1161
 
            approval_required = False
1162
801
            try:
1163
 
                try:
1164
 
                    fpr = self.fingerprint(self.peer_certificate
1165
 
                                           (session))
1166
 
                except (TypeError, gnutls.errors.GNUTLSError), error:
1167
 
                    logger.warning(u"Bad certificate: %s", error)
1168
 
                    return
1169
 
                logger.debug(u"Fingerprint: %s", fpr)
1170
 
 
1171
 
                try:
1172
 
                    client = ProxyClient(child_pipe, fpr,
1173
 
                                         self.client_address)
1174
 
                except KeyError:
1175
 
                    return
1176
 
                
1177
 
                if client.approved_delay:
1178
 
                    delay = client.approved_delay
1179
 
                    client.approvals_pending += 1
1180
 
                    approval_required = True
1181
 
                
1182
 
                while True:
1183
 
                    if not client.enabled:
1184
 
                        logger.warning(u"Client %s is disabled",
1185
 
                                       client.name)
1186
 
                        if self.server.use_dbus:
1187
 
                            # Emit D-Bus signal
1188
 
                            client.Rejected("Disabled")                    
1189
 
                        return
1190
 
                    
1191
 
                    if client._approved or not client.approved_delay:
1192
 
                        #We are approved or approval is disabled
1193
 
                        break
1194
 
                    elif client._approved is None:
1195
 
                        logger.info(u"Client %s need approval",
1196
 
                                    client.name)
1197
 
                        if self.server.use_dbus:
1198
 
                            # Emit D-Bus signal
1199
 
                            client.NeedApproval(
1200
 
                                client.approved_delay_milliseconds(),
1201
 
                                client.approved_by_default)
1202
 
                    else:
1203
 
                        logger.warning(u"Client %s was not approved",
1204
 
                                       client.name)
1205
 
                        if self.server.use_dbus:
1206
 
                            # Emit D-Bus signal
1207
 
                            client.Rejected("Disapproved")
1208
 
                        return
1209
 
                    
1210
 
                    #wait until timeout or approved
1211
 
                    #x = float(client._timedelta_to_milliseconds(delay))
1212
 
                    time = datetime.datetime.now()
1213
 
                    client.changedstate.acquire()
1214
 
                    client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1215
 
                    client.changedstate.release()
1216
 
                    time2 = datetime.datetime.now()
1217
 
                    if (time2 - time) >= delay:
1218
 
                        if not client.approved_by_default:
1219
 
                            logger.warning("Client %s timed out while"
1220
 
                                           " waiting for approval",
1221
 
                                           client.name)
1222
 
                            if self.server.use_dbus:
1223
 
                                # Emit D-Bus signal
1224
 
                                client.Rejected("Time out")
1225
 
                            return
1226
 
                        else:
1227
 
                            break
1228
 
                    else:
1229
 
                        delay -= time2 - time
1230
 
                
1231
 
                sent_size = 0
1232
 
                while sent_size < len(client.secret):
1233
 
                    try:
1234
 
                        sent = session.send(client.secret[sent_size:])
1235
 
                    except (gnutls.errors.GNUTLSError), error:
1236
 
                        logger.warning("gnutls send failed")
1237
 
                        return
1238
 
                    logger.debug(u"Sent: %d, remaining: %d",
1239
 
                                 sent, len(client.secret)
1240
 
                                 - (sent_size + sent))
1241
 
                    sent_size += sent
1242
 
 
1243
 
                logger.info(u"Sending secret to %s", client.name)
1244
 
                # bump the timeout as if seen
1245
 
                client.checked_ok()
1246
 
                if self.server.use_dbus:
1247
 
                    # Emit D-Bus signal
1248
 
                    client.GotSecret()
 
802
                fpr = self.fingerprint(self.peer_certificate(session))
 
803
            except (TypeError, gnutls.errors.GNUTLSError), error:
 
804
                logger.warning(u"Bad certificate: %s", error)
 
805
                session.bye()
 
806
                return
 
807
            logger.debug(u"Fingerprint: %s", fpr)
1249
808
            
1250
 
            finally:
1251
 
                if approval_required:
1252
 
                    client.approvals_pending -= 1
1253
 
                try:
1254
 
                    session.bye()
1255
 
                except (gnutls.errors.GNUTLSError), error:
1256
 
                    logger.warning("gnutls bye failed")
 
809
            for c in self.server.clients:
 
810
                if c.fingerprint == fpr:
 
811
                    client = c
 
812
                    break
 
813
            else:
 
814
                ipc.write(u"NOTFOUND %s\n" % fpr)
 
815
                session.bye()
 
816
                return
 
817
            # Have to check if client.still_valid(), since it is
 
818
            # possible that the client timed out while establishing
 
819
            # the GnuTLS session.
 
820
            if not client.still_valid():
 
821
                ipc.write(u"INVALID %s\n" % client.name)
 
822
                session.bye()
 
823
                return
 
824
            ipc.write(u"SENDING %s\n" % client.name)
 
825
            sent_size = 0
 
826
            while sent_size < len(client.secret):
 
827
                sent = session.send(client.secret[sent_size:])
 
828
                logger.debug(u"Sent: %d, remaining: %d",
 
829
                             sent, len(client.secret)
 
830
                             - (sent_size + sent))
 
831
                sent_size += sent
 
832
            session.bye()
1257
833
    
1258
834
    @staticmethod
1259
835
    def peer_certificate(session):
1319
895
        return hex_fpr
1320
896
 
1321
897
 
1322
 
class MultiprocessingMixIn(object):
1323
 
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
1324
 
    def sub_process_main(self, request, address):
1325
 
        try:
1326
 
            self.finish_request(request, address)
1327
 
        except:
1328
 
            self.handle_error(request, address)
1329
 
        self.close_request(request)
1330
 
            
1331
 
    def process_request(self, request, address):
1332
 
        """Start a new process to process the request."""
1333
 
        multiprocessing.Process(target = self.sub_process_main,
1334
 
                                args = (request, address)).start()
1335
 
 
1336
 
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1337
 
    """ adds a pipe to the MixIn """
 
898
class ForkingMixInWithPipe(socketserver.ForkingMixIn, object):
 
899
    """Like socketserver.ForkingMixIn, but also pass a pipe."""
1338
900
    def process_request(self, request, client_address):
1339
901
        """Overrides and wraps the original process_request().
1340
902
        
1341
 
        This function creates a new pipe in self.pipe
 
903
        This function creates a new pipe in self.pipe 
1342
904
        """
1343
 
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1344
 
 
1345
 
        super(MultiprocessingMixInWithPipe,
 
905
        self.pipe = os.pipe()
 
906
        super(ForkingMixInWithPipe,
1346
907
              self).process_request(request, client_address)
1347
 
        self.child_pipe.close()
1348
 
        self.add_pipe(parent_pipe)
1349
 
 
1350
 
    def add_pipe(self, parent_pipe):
 
908
        os.close(self.pipe[1])  # close write end
 
909
        self.add_pipe(self.pipe[0])
 
910
    def add_pipe(self, pipe):
1351
911
        """Dummy function; override as necessary"""
1352
 
        pass
1353
 
 
1354
 
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
 
912
        os.close(pipe)
 
913
 
 
914
 
 
915
class IPv6_TCPServer(ForkingMixInWithPipe,
1355
916
                     socketserver.TCPServer, object):
1356
917
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1357
918
    
1421
982
        clients:        set of Client objects
1422
983
        gnutls_priority GnuTLS priority string
1423
984
        use_dbus:       Boolean; to emit D-Bus signals or not
 
985
        clients:        set of Client objects
 
986
        gnutls_priority GnuTLS priority string
 
987
        use_dbus:       Boolean; to emit D-Bus signals or not
1424
988
    
1425
989
    Assumes a gobject.MainLoop event loop.
1426
990
    """
1442
1006
            return socketserver.TCPServer.server_activate(self)
1443
1007
    def enable(self):
1444
1008
        self.enabled = True
1445
 
    def add_pipe(self, parent_pipe):
 
1009
    def add_pipe(self, pipe):
1446
1010
        # Call "handle_ipc" for both data and EOF events
1447
 
        gobject.io_add_watch(parent_pipe.fileno(),
1448
 
                             gobject.IO_IN | gobject.IO_HUP,
1449
 
                             functools.partial(self.handle_ipc,
1450
 
                                               parent_pipe = parent_pipe))
1451
 
        
1452
 
    def handle_ipc(self, source, condition, parent_pipe=None,
1453
 
                   client_object=None):
 
1011
        gobject.io_add_watch(pipe, gobject.IO_IN | gobject.IO_HUP,
 
1012
                             self.handle_ipc)
 
1013
    def handle_ipc(self, source, condition, file_objects={}):
1454
1014
        condition_names = {
1455
1015
            gobject.IO_IN: u"IN",   # There is data to read.
1456
1016
            gobject.IO_OUT: u"OUT", # Data can be written (without
1467
1027
                                       if cond & condition)
1468
1028
        logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
1469
1029
                     conditions_string)
1470
 
 
1471
 
        # error or the other end of multiprocessing.Pipe has closed
1472
 
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
1473
 
            return False
1474
 
        
1475
 
        # Read a request from the child
1476
 
        request = parent_pipe.recv()
1477
 
        logger.debug(u"IPC request: %s", repr(request))
1478
 
        command = request[0]
1479
 
        
1480
 
        if command == 'init':
1481
 
            fpr = request[1]
1482
 
            address = request[2]
1483
 
            
1484
 
            for c in self.clients:
1485
 
                if c.fingerprint == fpr:
1486
 
                    client = c
1487
 
                    break
1488
 
            else:
1489
 
                logger.warning(u"Client not found for fingerprint: %s, ad"
1490
 
                               u"dress: %s", fpr, address)
1491
 
                if self.use_dbus:
1492
 
                    # Emit D-Bus signal
1493
 
                    mandos_dbus_service.ClientNotFound(fpr, address)
1494
 
                parent_pipe.send(False)
1495
 
                return False
1496
 
            
1497
 
            gobject.io_add_watch(parent_pipe.fileno(),
1498
 
                                 gobject.IO_IN | gobject.IO_HUP,
1499
 
                                 functools.partial(self.handle_ipc,
1500
 
                                                   parent_pipe = parent_pipe,
1501
 
                                                   client_object = client))
1502
 
            parent_pipe.send(True)
1503
 
            # remove the old hook in favor of the new above hook on same fileno
1504
 
            return False
1505
 
        if command == 'funcall':
1506
 
            funcname = request[1]
1507
 
            args = request[2]
1508
 
            kwargs = request[3]
1509
 
            
1510
 
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1511
 
 
1512
 
        if command == 'getattr':
1513
 
            attrname = request[1]
1514
 
            if callable(client_object.__getattribute__(attrname)):
1515
 
                parent_pipe.send(('function',))
1516
 
            else:
1517
 
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1518
 
        
1519
 
        if command == 'setattr':
1520
 
            attrname = request[1]
1521
 
            value = request[2]
1522
 
            setattr(client_object, attrname, value)
1523
 
 
 
1030
        
 
1031
        # Turn the pipe file descriptor into a Python file object
 
1032
        if source not in file_objects:
 
1033
            file_objects[source] = os.fdopen(source, u"r", 1)
 
1034
        
 
1035
        # Read a line from the file object
 
1036
        cmdline = file_objects[source].readline()
 
1037
        if not cmdline:             # Empty line means end of file
 
1038
            # close the IPC pipe
 
1039
            file_objects[source].close()
 
1040
            del file_objects[source]
 
1041
            
 
1042
            # Stop calling this function
 
1043
            return False
 
1044
        
 
1045
        logger.debug(u"IPC command: %r", cmdline)
 
1046
        
 
1047
        # Parse and act on command
 
1048
        cmd, args = cmdline.rstrip(u"\r\n").split(None, 1)
 
1049
        
 
1050
        if cmd == u"NOTFOUND":
 
1051
            logger.warning(u"Client not found for fingerprint: %s",
 
1052
                           args)
 
1053
            if self.use_dbus:
 
1054
                # Emit D-Bus signal
 
1055
                mandos_dbus_service.ClientNotFound(args)
 
1056
        elif cmd == u"INVALID":
 
1057
            for client in self.clients:
 
1058
                if client.name == args:
 
1059
                    logger.warning(u"Client %s is invalid", args)
 
1060
                    if self.use_dbus:
 
1061
                        # Emit D-Bus signal
 
1062
                        client.Rejected()
 
1063
                    break
 
1064
            else:
 
1065
                logger.error(u"Unknown client %s is invalid", args)
 
1066
        elif cmd == u"SENDING":
 
1067
            for client in self.clients:
 
1068
                if client.name == args:
 
1069
                    logger.info(u"Sending secret to %s", client.name)
 
1070
                    client.checked_ok()
 
1071
                    if self.use_dbus:
 
1072
                        # Emit D-Bus signal
 
1073
                        client.ReceivedSecret()
 
1074
                    break
 
1075
            else:
 
1076
                logger.error(u"Sending secret to unknown client %s",
 
1077
                             args)
 
1078
        else:
 
1079
            logger.error(u"Unknown IPC command: %r", cmdline)
 
1080
        
 
1081
        # Keep calling this function
1524
1082
        return True
1525
1083
 
1526
1084
 
1556
1114
            elif suffix == u"w":
1557
1115
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1558
1116
            else:
1559
 
                raise ValueError(u"Unknown suffix %r" % suffix)
1560
 
        except (ValueError, IndexError), e:
1561
 
            raise ValueError(e.message)
 
1117
                raise ValueError
 
1118
        except (ValueError, IndexError):
 
1119
            raise ValueError
1562
1120
        timevalue += delta
1563
1121
    return timevalue
1564
1122
 
1577
1135
        def if_nametoindex(interface):
1578
1136
            "Get an interface index the hard way, i.e. using fcntl()"
1579
1137
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
1580
 
            with contextlib.closing(socket.socket()) as s:
 
1138
            with closing(socket.socket()) as s:
1581
1139
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1582
1140
                                    struct.pack(str(u"16s16x"),
1583
1141
                                                interface))
1603
1161
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1604
1162
        if not stat.S_ISCHR(os.fstat(null).st_mode):
1605
1163
            raise OSError(errno.ENODEV,
1606
 
                          u"%s not a character device"
1607
 
                          % os.path.devnull)
 
1164
                          u"/dev/null not a character device")
1608
1165
        os.dup2(null, sys.stdin.fileno())
1609
1166
        os.dup2(null, sys.stdout.fileno())
1610
1167
        os.dup2(null, sys.stderr.fileno())
1614
1171
 
1615
1172
def main():
1616
1173
    
1617
 
    ##################################################################
 
1174
    ######################################################################
1618
1175
    # Parsing of options, both command line and config file
1619
1176
    
1620
1177
    parser = optparse.OptionParser(version = "%%prog %s" % version)
1629
1186
    parser.add_option("--debug", action=u"store_true",
1630
1187
                      help=u"Debug mode; run in foreground and log to"
1631
1188
                      u" terminal")
1632
 
    parser.add_option("--debuglevel", type=u"string", metavar="Level",
1633
 
                      help=u"Debug level for stdout output")
1634
1189
    parser.add_option("--priority", type=u"string", help=u"GnuTLS"
1635
1190
                      u" priority string (see GnuTLS documentation)")
1636
1191
    parser.add_option("--servicename", type=u"string",
1661
1216
                        u"servicename": u"Mandos",
1662
1217
                        u"use_dbus": u"True",
1663
1218
                        u"use_ipv6": u"True",
1664
 
                        u"debuglevel": u"",
1665
1219
                        }
1666
1220
    
1667
1221
    # Parse config file for server-global settings
1684
1238
    # options, if set.
1685
1239
    for option in (u"interface", u"address", u"port", u"debug",
1686
1240
                   u"priority", u"servicename", u"configdir",
1687
 
                   u"use_dbus", u"use_ipv6", u"debuglevel"):
 
1241
                   u"use_dbus", u"use_ipv6"):
1688
1242
        value = getattr(options, option)
1689
1243
        if value is not None:
1690
1244
            server_settings[option] = value
1699
1253
    
1700
1254
    # For convenience
1701
1255
    debug = server_settings[u"debug"]
1702
 
    debuglevel = server_settings[u"debuglevel"]
1703
1256
    use_dbus = server_settings[u"use_dbus"]
1704
1257
    use_ipv6 = server_settings[u"use_ipv6"]
1705
 
 
 
1258
    
 
1259
    if not debug:
 
1260
        syslogger.setLevel(logging.WARNING)
 
1261
        console.setLevel(logging.WARNING)
 
1262
    
1706
1263
    if server_settings[u"servicename"] != u"Mandos":
1707
1264
        syslogger.setFormatter(logging.Formatter
1708
1265
                               (u'Mandos (%s) [%%(process)d]:'
1714
1271
                        u"interval": u"5m",
1715
1272
                        u"checker": u"fping -q -- %%(host)s",
1716
1273
                        u"host": u"",
1717
 
                        u"approved_delay": u"0s",
1718
 
                        u"approved_duration": u"1s",
1719
1274
                        }
1720
1275
    client_config = configparser.SafeConfigParser(client_defaults)
1721
1276
    client_config.read(os.path.join(server_settings[u"configdir"],
1760
1315
            raise error
1761
1316
    
1762
1317
    # Enable all possible GnuTLS debugging
1763
 
 
1764
 
 
1765
 
    if not debug and not debuglevel:
1766
 
        syslogger.setLevel(logging.WARNING)
1767
 
        console.setLevel(logging.WARNING)
1768
 
    if debuglevel:
1769
 
        level = getattr(logging, debuglevel.upper())
1770
 
        syslogger.setLevel(level)
1771
 
        console.setLevel(level)
1772
 
 
1773
1318
    if debug:
1774
1319
        # "Use a log level over 10 to enable all debugging options."
1775
1320
        # - GnuTLS manual
1781
1326
        
1782
1327
        (gnutls.library.functions
1783
1328
         .gnutls_global_set_log_function(debug_gnutls))
1784
 
 
1785
 
        # Redirect stdin so all checkers get /dev/null
1786
 
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1787
 
        os.dup2(null, sys.stdin.fileno())
1788
 
        if null > 2:
1789
 
            os.close(null)
1790
 
    else:
1791
 
        # No console logging
1792
 
        logger.removeHandler(console)
1793
 
 
1794
1329
    
1795
1330
    global main_loop
1796
1331
    # From the Avahi example code
1799
1334
    bus = dbus.SystemBus()
1800
1335
    # End of Avahi example code
1801
1336
    if use_dbus:
1802
 
        try:
1803
 
            bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos",
1804
 
                                            bus, do_not_queue=True)
1805
 
        except dbus.exceptions.NameExistsException, e:
1806
 
            logger.error(unicode(e) + u", disabling D-Bus")
1807
 
            use_dbus = False
1808
 
            server_settings[u"use_dbus"] = False
1809
 
            tcp_server.use_dbus = False
 
1337
        bus_name = dbus.service.BusName(u"se.bsnet.fukt.Mandos", bus)
1810
1338
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
1811
1339
    service = AvahiService(name = server_settings[u"servicename"],
1812
1340
                           servicetype = u"_mandos._tcp",
1814
1342
    if server_settings["interface"]:
1815
1343
        service.interface = (if_nametoindex
1816
1344
                             (str(server_settings[u"interface"])))
1817
 
 
1818
 
    if not debug:
1819
 
        # Close all input and output, do double fork, etc.
1820
 
        daemon()
1821
 
        
1822
 
    global multiprocessing_manager
1823
 
    multiprocessing_manager = multiprocessing.Manager()
1824
1345
    
1825
1346
    client_class = Client
1826
1347
    if use_dbus:
1827
1348
        client_class = functools.partial(ClientDBus, bus = bus)
1828
 
    def client_config_items(config, section):
1829
 
        special_settings = {
1830
 
            "approved_by_default":
1831
 
                lambda: config.getboolean(section,
1832
 
                                          "approved_by_default"),
1833
 
            }
1834
 
        for name, value in config.items(section):
1835
 
            try:
1836
 
                yield (name, special_settings[name]())
1837
 
            except KeyError:
1838
 
                yield (name, value)
1839
 
    
1840
1349
    tcp_server.clients.update(set(
1841
1350
            client_class(name = section,
1842
 
                         config= dict(client_config_items(
1843
 
                        client_config, section)))
 
1351
                         config= dict(client_config.items(section)))
1844
1352
            for section in client_config.sections()))
1845
1353
    if not tcp_server.clients:
1846
1354
        logger.warning(u"No clients defined")
1847
 
        
 
1355
    
 
1356
    if debug:
 
1357
        # Redirect stdin so all checkers get /dev/null
 
1358
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
 
1359
        os.dup2(null, sys.stdin.fileno())
 
1360
        if null > 2:
 
1361
            os.close(null)
 
1362
    else:
 
1363
        # No console logging
 
1364
        logger.removeHandler(console)
 
1365
        # Close all input and output, do double fork, etc.
 
1366
        daemon()
 
1367
    
1848
1368
    try:
1849
 
        with pidfile:
 
1369
        with closing(pidfile):
1850
1370
            pid = os.getpid()
1851
1371
            pidfile.write(str(pid) + "\n")
1852
1372
        del pidfile
1858
1378
        pass
1859
1379
    del pidfilename
1860
1380
    
 
1381
    def cleanup():
 
1382
        "Cleanup function; run on exit"
 
1383
        service.cleanup()
 
1384
        
 
1385
        while tcp_server.clients:
 
1386
            client = tcp_server.clients.pop()
 
1387
            client.disable_hook = None
 
1388
            client.disable()
 
1389
    
 
1390
    atexit.register(cleanup)
 
1391
    
1861
1392
    if not debug:
1862
1393
        signal.signal(signal.SIGINT, signal.SIG_IGN)
1863
1394
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1870
1401
                dbus.service.Object.__init__(self, bus, u"/")
1871
1402
            _interface = u"se.bsnet.fukt.Mandos"
1872
1403
            
1873
 
            @dbus.service.signal(_interface, signature=u"o")
1874
 
            def ClientAdded(self, objpath):
 
1404
            @dbus.service.signal(_interface, signature=u"oa{sv}")
 
1405
            def ClientAdded(self, objpath, properties):
1875
1406
                "D-Bus signal"
1876
1407
                pass
1877
1408
            
1878
 
            @dbus.service.signal(_interface, signature=u"ss")
1879
 
            def ClientNotFound(self, fingerprint, address):
 
1409
            @dbus.service.signal(_interface, signature=u"s")
 
1410
            def ClientNotFound(self, fingerprint):
1880
1411
                "D-Bus signal"
1881
1412
                pass
1882
1413
            
1896
1427
            def GetAllClientsWithProperties(self):
1897
1428
                "D-Bus method"
1898
1429
                return dbus.Dictionary(
1899
 
                    ((c.dbus_object_path, c.GetAll(u""))
 
1430
                    ((c.dbus_object_path, c.GetAllProperties())
1900
1431
                     for c in tcp_server.clients),
1901
1432
                    signature=u"oa{sv}")
1902
1433
            
1908
1439
                        tcp_server.clients.remove(c)
1909
1440
                        c.remove_from_connection()
1910
1441
                        # Don't signal anything except ClientRemoved
1911
 
                        c.disable(quiet=True)
 
1442
                        c.disable(signal=False)
1912
1443
                        # Emit D-Bus signal
1913
1444
                        self.ClientRemoved(object_path, c.name)
1914
1445
                        return
1915
 
                raise KeyError(object_path)
 
1446
                raise KeyError
1916
1447
            
1917
1448
            del _interface
1918
1449
        
1919
1450
        mandos_dbus_service = MandosDBusService()
1920
1451
    
1921
 
    def cleanup():
1922
 
        "Cleanup function; run on exit"
1923
 
        service.cleanup()
1924
 
        
1925
 
        while tcp_server.clients:
1926
 
            client = tcp_server.clients.pop()
1927
 
            if use_dbus:
1928
 
                client.remove_from_connection()
1929
 
            client.disable_hook = None
1930
 
            # Don't signal anything except ClientRemoved
1931
 
            client.disable(quiet=True)
1932
 
            if use_dbus:
1933
 
                # Emit D-Bus signal
1934
 
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
1935
 
                                                  client.name)
1936
 
    
1937
 
    atexit.register(cleanup)
1938
 
    
1939
1452
    for client in tcp_server.clients:
1940
1453
        if use_dbus:
1941
1454
            # Emit D-Bus signal
1942
 
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
 
1455
            mandos_dbus_service.ClientAdded(client.dbus_object_path,
 
1456
                                            client.GetAllProperties())
1943
1457
        client.enable()
1944
1458
    
1945
1459
    tcp_server.enable()
1963
1477
            service.activate()
1964
1478
        except dbus.exceptions.DBusException, error:
1965
1479
            logger.critical(u"DBusException: %s", error)
1966
 
            cleanup()
1967
1480
            sys.exit(1)
1968
1481
        # End of Avahi example code
1969
1482
        
1976
1489
        main_loop.run()
1977
1490
    except AvahiError, error:
1978
1491
        logger.critical(u"AvahiError: %s", error)
1979
 
        cleanup()
1980
1492
        sys.exit(1)
1981
1493
    except KeyboardInterrupt:
1982
1494
        if debug:
1983
1495
            print >> sys.stderr
1984
1496
        logger.debug(u"Server received KeyboardInterrupt")
1985
1497
    logger.debug(u"Server exiting")
1986
 
    # Must run before the D-Bus bus name gets deregistered
1987
 
    cleanup()
1988
1498
 
1989
1499
if __name__ == '__main__':
1990
1500
    main()