/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to mandos

* mandos-clients.conf.xml (OPTIONS): Moved up "extended_timeout" to
                                     order options alphabetically.
* clients.conf: Language change in comment.

Show diffs side-by-side

added added

removed removed

Lines of Context:
28
28
# along with this program.  If not, see
29
29
# <http://www.gnu.org/licenses/>.
30
30
31
 
# Contact the authors at <mandos@recompile.se>.
 
31
# Contact the authors at <mandos@fukt.bsnet.se>.
32
32
33
33
 
34
34
from __future__ import (division, absolute_import, print_function,
62
62
import functools
63
63
import cPickle as pickle
64
64
import multiprocessing
65
 
import types
66
65
 
67
66
import dbus
68
67
import dbus.service
160
159
                            " after %i retries, exiting.",
161
160
                            self.rename_count)
162
161
            raise AvahiServiceError("Too many renames")
163
 
        self.name = unicode(self.server
164
 
                            .GetAlternativeServiceName(self.name))
 
162
        self.name = unicode(self.server.GetAlternativeServiceName(self.name))
165
163
        logger.info("Changing Zeroconf service name to %r ...",
166
164
                    self.name)
167
165
        syslogger.setFormatter(logging.Formatter
266
264
        self.server_state_changed(self.server.GetState())
267
265
 
268
266
 
269
 
def _timedelta_to_milliseconds(td):
270
 
    "Convert a datetime.timedelta() to milliseconds"
271
 
    return ((td.days * 24 * 60 * 60 * 1000)
272
 
            + (td.seconds * 1000)
273
 
            + (td.microseconds // 1000))
274
 
        
275
267
class Client(object):
276
268
    """A representation of a client host served by this server.
277
269
    
316
308
                          "host", "interval", "last_checked_ok",
317
309
                          "last_enabled", "name", "timeout")
318
310
    
 
311
    @staticmethod
 
312
    def _timedelta_to_milliseconds(td):
 
313
        "Convert a datetime.timedelta() to milliseconds"
 
314
        return ((td.days * 24 * 60 * 60 * 1000)
 
315
                + (td.seconds * 1000)
 
316
                + (td.microseconds // 1000))
 
317
    
319
318
    def timeout_milliseconds(self):
320
319
        "Return the 'timeout' attribute in milliseconds"
321
 
        return _timedelta_to_milliseconds(self.timeout)
322
 
    
 
320
        return self._timedelta_to_milliseconds(self.timeout)
 
321
 
323
322
    def extended_timeout_milliseconds(self):
324
323
        "Return the 'extended_timeout' attribute in milliseconds"
325
 
        return _timedelta_to_milliseconds(self.extended_timeout)
 
324
        return self._timedelta_to_milliseconds(self.extended_timeout)    
326
325
    
327
326
    def interval_milliseconds(self):
328
327
        "Return the 'interval' attribute in milliseconds"
329
 
        return _timedelta_to_milliseconds(self.interval)
330
 
    
 
328
        return self._timedelta_to_milliseconds(self.interval)
 
329
 
331
330
    def approval_delay_milliseconds(self):
332
 
        return _timedelta_to_milliseconds(self.approval_delay)
 
331
        return self._timedelta_to_milliseconds(self.approval_delay)
333
332
    
334
333
    def __init__(self, name = None, disable_hook=None, config=None):
335
334
        """Note: the 'checker' key in 'config' sets the
362
361
        self.last_enabled = None
363
362
        self.last_checked_ok = None
364
363
        self.timeout = string_to_delta(config["timeout"])
365
 
        self.extended_timeout = string_to_delta(config
366
 
                                                ["extended_timeout"])
 
364
        self.extended_timeout = string_to_delta(config["extended_timeout"])
367
365
        self.interval = string_to_delta(config["interval"])
368
366
        self.disable_hook = disable_hook
369
367
        self.checker = None
382
380
            config["approval_delay"])
383
381
        self.approval_duration = string_to_delta(
384
382
            config["approval_duration"])
385
 
        self.changedstate = (multiprocessing_manager
386
 
                             .Condition(multiprocessing_manager
387
 
                                        .Lock()))
 
383
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
388
384
    
389
385
    def send_changedstate(self):
390
386
        self.changedstate.acquire()
391
387
        self.changedstate.notify_all()
392
388
        self.changedstate.release()
393
 
    
 
389
        
394
390
    def enable(self):
395
391
        """Start this client's checker and timeout hooks"""
396
392
        if getattr(self, "enabled", False):
397
393
            # Already enabled
398
394
            return
399
395
        self.send_changedstate()
 
396
        self.last_enabled = datetime.datetime.utcnow()
400
397
        # Schedule a new checker to be started an 'interval' from now,
401
398
        # and every interval from then on.
402
399
        self.checker_initiator_tag = (gobject.timeout_add
408
405
                                   (self.timeout_milliseconds(),
409
406
                                    self.disable))
410
407
        self.enabled = True
411
 
        self.last_enabled = datetime.datetime.utcnow()
412
408
        # Also start a new checker *right now*.
413
409
        self.start_checker()
414
410
    
467
463
        gobject.source_remove(self.disable_initiator_tag)
468
464
        self.expires = datetime.datetime.utcnow() + timeout
469
465
        self.disable_initiator_tag = (gobject.timeout_add
470
 
                                      (_timedelta_to_milliseconds
471
 
                                       (timeout), self.disable))
 
466
                                      (self._timedelta_to_milliseconds(timeout),
 
467
                                       self.disable))
472
468
    
473
469
    def need_approval(self):
474
470
        self.last_approval_request = datetime.datetime.utcnow()
514
510
                                       'replace')))
515
511
                    for attr in
516
512
                    self.runtime_expansions)
517
 
                
 
513
 
518
514
                try:
519
515
                    command = self.checker_command % escaped_attrs
520
516
                except TypeError as error:
566
562
                raise
567
563
        self.checker = None
568
564
 
569
 
 
570
565
def dbus_service_property(dbus_interface, signature="v",
571
566
                          access="readwrite", byte_arrays=False):
572
567
    """Decorators for marking methods of a DBusObjectWithProperties to
618
613
 
619
614
class DBusObjectWithProperties(dbus.service.Object):
620
615
    """A D-Bus object with properties.
621
 
    
 
616
 
622
617
    Classes inheriting from this can use the dbus_service_property
623
618
    decorator to expose methods as D-Bus properties.  It exposes the
624
619
    standard Get(), Set(), and GetAll() methods on the D-Bus.
631
626
    def _get_all_dbus_properties(self):
632
627
        """Returns a generator of (name, attribute) pairs
633
628
        """
634
 
        return ((prop.__get__(self)._dbus_name, prop.__get__(self))
635
 
                for cls in self.__class__.__mro__
 
629
        return ((prop._dbus_name, prop)
636
630
                for name, prop in
637
 
                inspect.getmembers(cls, self._is_dbus_property))
 
631
                inspect.getmembers(self, self._is_dbus_property))
638
632
    
639
633
    def _get_dbus_property(self, interface_name, property_name):
640
634
        """Returns a bound method if one exists which is a D-Bus
641
635
        property with the specified name and interface.
642
636
        """
643
 
        for cls in  self.__class__.__mro__:
644
 
            for name, value in (inspect.getmembers
645
 
                                (cls, self._is_dbus_property)):
646
 
                if (value._dbus_name == property_name
647
 
                    and value._dbus_interface == interface_name):
648
 
                    return value.__get__(self)
649
 
        
 
637
        for name in (property_name,
 
638
                     property_name + "_dbus_property"):
 
639
            prop = getattr(self, name, None)
 
640
            if (prop is None
 
641
                or not self._is_dbus_property(prop)
 
642
                or prop._dbus_name != property_name
 
643
                or (interface_name and prop._dbus_interface
 
644
                    and interface_name != prop._dbus_interface)):
 
645
                continue
 
646
            return prop
650
647
        # No such property
651
648
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
652
649
                                   + interface_name + "."
686
683
    def GetAll(self, interface_name):
687
684
        """Standard D-Bus property GetAll() method, see D-Bus
688
685
        standard.
689
 
        
 
686
 
690
687
        Note: Will not include properties with access="write".
691
688
        """
692
689
        all = {}
754
751
        return xmlstring
755
752
 
756
753
 
757
 
def datetime_to_dbus (dt, variant_level=0):
758
 
    """Convert a UTC datetime.datetime() to a D-Bus type."""
759
 
    if dt is None:
760
 
        return dbus.String("", variant_level = variant_level)
761
 
    return dbus.String(dt.isoformat(),
762
 
                       variant_level=variant_level)
763
 
 
764
 
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
765
 
                                  .__metaclass__):
766
 
    """Applied to an empty subclass of a D-Bus object, this metaclass
767
 
    will add additional D-Bus attributes matching a certain pattern.
768
 
    """
769
 
    def __new__(mcs, name, bases, attr):
770
 
        # Go through all the base classes which could have D-Bus
771
 
        # methods, signals, or properties in them
772
 
        for base in (b for b in bases
773
 
                     if issubclass(b, dbus.service.Object)):
774
 
            # Go though all attributes of the base class
775
 
            for attrname, attribute in inspect.getmembers(base):
776
 
                # Ignore non-D-Bus attributes, and D-Bus attributes
777
 
                # with the wrong interface name
778
 
                if (not hasattr(attribute, "_dbus_interface")
779
 
                    or not attribute._dbus_interface
780
 
                    .startswith("se.recompile.Mandos")):
781
 
                    continue
782
 
                # Create an alternate D-Bus interface name based on
783
 
                # the current name
784
 
                alt_interface = (attribute._dbus_interface
785
 
                                 .replace("se.recompile.Mandos",
786
 
                                          "se.bsnet.fukt.Mandos"))
787
 
                # Is this a D-Bus signal?
788
 
                if getattr(attribute, "_dbus_is_signal", False):
789
 
                    # Extract the original non-method function by
790
 
                    # black magic
791
 
                    nonmethod_func = (dict(
792
 
                            zip(attribute.func_code.co_freevars,
793
 
                                attribute.__closure__))["func"]
794
 
                                      .cell_contents)
795
 
                    # Create a new, but exactly alike, function
796
 
                    # object, and decorate it to be a new D-Bus signal
797
 
                    # with the alternate D-Bus interface name
798
 
                    new_function = (dbus.service.signal
799
 
                                    (alt_interface,
800
 
                                     attribute._dbus_signature)
801
 
                                    (types.FunctionType(
802
 
                                nonmethod_func.func_code,
803
 
                                nonmethod_func.func_globals,
804
 
                                nonmethod_func.func_name,
805
 
                                nonmethod_func.func_defaults,
806
 
                                nonmethod_func.func_closure)))
807
 
                    # Define a creator of a function to call both the
808
 
                    # old and new functions, so both the old and new
809
 
                    # signals gets sent when the function is called
810
 
                    def fixscope(func1, func2):
811
 
                        """This function is a scope container to pass
812
 
                        func1 and func2 to the "call_both" function
813
 
                        outside of its arguments"""
814
 
                        def call_both(*args, **kwargs):
815
 
                            """This function will emit two D-Bus
816
 
                            signals by calling func1 and func2"""
817
 
                            func1(*args, **kwargs)
818
 
                            func2(*args, **kwargs)
819
 
                        return call_both
820
 
                    # Create the "call_both" function and add it to
821
 
                    # the class
822
 
                    attr[attrname] = fixscope(attribute,
823
 
                                              new_function)
824
 
                # Is this a D-Bus method?
825
 
                elif getattr(attribute, "_dbus_is_method", False):
826
 
                    # Create a new, but exactly alike, function
827
 
                    # object.  Decorate it to be a new D-Bus method
828
 
                    # with the alternate D-Bus interface name.  Add it
829
 
                    # to the class.
830
 
                    attr[attrname] = (dbus.service.method
831
 
                                      (alt_interface,
832
 
                                       attribute._dbus_in_signature,
833
 
                                       attribute._dbus_out_signature)
834
 
                                      (types.FunctionType
835
 
                                       (attribute.func_code,
836
 
                                        attribute.func_globals,
837
 
                                        attribute.func_name,
838
 
                                        attribute.func_defaults,
839
 
                                        attribute.func_closure)))
840
 
                # Is this a D-Bus property?
841
 
                elif getattr(attribute, "_dbus_is_property", False):
842
 
                    # Create a new, but exactly alike, function
843
 
                    # object, and decorate it to be a new D-Bus
844
 
                    # property with the alternate D-Bus interface
845
 
                    # name.  Add it to the class.
846
 
                    attr[attrname] = (dbus_service_property
847
 
                                      (alt_interface,
848
 
                                       attribute._dbus_signature,
849
 
                                       attribute._dbus_access,
850
 
                                       attribute
851
 
                                       ._dbus_get_args_options
852
 
                                       ["byte_arrays"])
853
 
                                      (types.FunctionType
854
 
                                       (attribute.func_code,
855
 
                                        attribute.func_globals,
856
 
                                        attribute.func_name,
857
 
                                        attribute.func_defaults,
858
 
                                        attribute.func_closure)))
859
 
        return type.__new__(mcs, name, bases, attr)
860
 
 
861
754
class ClientDBus(Client, DBusObjectWithProperties):
862
755
    """A Client class using D-Bus
863
756
    
884
777
                                 ("/clients/" + client_object_name))
885
778
        DBusObjectWithProperties.__init__(self, self.bus,
886
779
                                          self.dbus_object_path)
 
780
    def _set_expires(self, value):
 
781
        old_value = getattr(self, "_expires", None)
 
782
        self._expires = value
 
783
        if hasattr(self, "dbus_object_path") and old_value != value:
 
784
            dbus_time = (self._datetime_to_dbus(self._expires,
 
785
                                                variant_level=1))
 
786
            self.PropertyChanged(dbus.String("Expires"),
 
787
                                 dbus_time)
 
788
    expires = property(lambda self: self._expires, _set_expires)
 
789
    del _set_expires
887
790
        
888
 
    def notifychangeproperty(transform_func,
889
 
                             dbus_name, type_func=lambda x: x,
890
 
                             variant_level=1):
891
 
        """ Modify a variable so that it's a property which announces
892
 
        its changes to DBus.
 
791
    def _get_approvals_pending(self):
 
792
        return self._approvals_pending
 
793
    def _set_approvals_pending(self, value):
 
794
        old_value = self._approvals_pending
 
795
        self._approvals_pending = value
 
796
        bval = bool(value)
 
797
        if (hasattr(self, "dbus_object_path")
 
798
            and bval is not bool(old_value)):
 
799
            dbus_bool = dbus.Boolean(bval, variant_level=1)
 
800
            self.PropertyChanged(dbus.String("ApprovalPending"),
 
801
                                 dbus_bool)
893
802
 
894
 
        transform_fun: Function that takes a value and transforms it
895
 
                       to a D-Bus type.
896
 
        dbus_name: D-Bus name of the variable
897
 
        type_func: Function that transform the value before sending it
898
 
                   to the D-Bus.  Default: no transform
899
 
        variant_level: D-Bus variant level.  Default: 1
900
 
        """
901
 
        attrname = "_{0}".format(dbus_name)
902
 
        def setter(self, value):
903
 
            if hasattr(self, "dbus_object_path"):
904
 
                if (not hasattr(self, attrname) or
905
 
                    type_func(getattr(self, attrname, None))
906
 
                    != type_func(value)):
907
 
                    dbus_value = transform_func(type_func(value),
908
 
                                                variant_level)
909
 
                    self.PropertyChanged(dbus.String(dbus_name),
910
 
                                         dbus_value)
911
 
            setattr(self, attrname, value)
912
 
        
913
 
        return property(lambda self: getattr(self, attrname), setter)
914
 
    
915
 
    
916
 
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
917
 
    approvals_pending = notifychangeproperty(dbus.Boolean,
918
 
                                             "ApprovalPending",
919
 
                                             type_func = bool)
920
 
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
921
 
    last_enabled = notifychangeproperty(datetime_to_dbus,
922
 
                                        "LastEnabled")
923
 
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
924
 
                                   type_func = lambda checker:
925
 
                                       checker is not None)
926
 
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
927
 
                                           "LastCheckedOK")
928
 
    last_approval_request = notifychangeproperty(
929
 
        datetime_to_dbus, "LastApprovalRequest")
930
 
    approved_by_default = notifychangeproperty(dbus.Boolean,
931
 
                                               "ApprovedByDefault")
932
 
    approval_delay = notifychangeproperty(dbus.UInt16,
933
 
                                          "ApprovalDelay",
934
 
                                          type_func =
935
 
                                          _timedelta_to_milliseconds)
936
 
    approval_duration = notifychangeproperty(
937
 
        dbus.UInt16, "ApprovalDuration",
938
 
        type_func = _timedelta_to_milliseconds)
939
 
    host = notifychangeproperty(dbus.String, "Host")
940
 
    timeout = notifychangeproperty(dbus.UInt16, "Timeout",
941
 
                                   type_func =
942
 
                                   _timedelta_to_milliseconds)
943
 
    extended_timeout = notifychangeproperty(
944
 
        dbus.UInt16, "ExtendedTimeout",
945
 
        type_func = _timedelta_to_milliseconds)
946
 
    interval = notifychangeproperty(dbus.UInt16,
947
 
                                    "Interval",
948
 
                                    type_func =
949
 
                                    _timedelta_to_milliseconds)
950
 
    checker_command = notifychangeproperty(dbus.String, "Checker")
951
 
    
952
 
    del notifychangeproperty
 
803
    approvals_pending = property(_get_approvals_pending,
 
804
                                 _set_approvals_pending)
 
805
    del _get_approvals_pending, _set_approvals_pending
 
806
    
 
807
    @staticmethod
 
808
    def _datetime_to_dbus(dt, variant_level=0):
 
809
        """Convert a UTC datetime.datetime() to a D-Bus type."""
 
810
        if dt is None:
 
811
            return dbus.String("", variant_level = variant_level)
 
812
        return dbus.String(dt.isoformat(),
 
813
                           variant_level=variant_level)
 
814
    
 
815
    def enable(self):
 
816
        oldstate = getattr(self, "enabled", False)
 
817
        r = Client.enable(self)
 
818
        if oldstate != self.enabled:
 
819
            # Emit D-Bus signals
 
820
            self.PropertyChanged(dbus.String("Enabled"),
 
821
                                 dbus.Boolean(True, variant_level=1))
 
822
            self.PropertyChanged(
 
823
                dbus.String("LastEnabled"),
 
824
                self._datetime_to_dbus(self.last_enabled,
 
825
                                       variant_level=1))
 
826
        return r
 
827
    
 
828
    def disable(self, quiet = False):
 
829
        oldstate = getattr(self, "enabled", False)
 
830
        r = Client.disable(self, quiet=quiet)
 
831
        if not quiet and oldstate != self.enabled:
 
832
            # Emit D-Bus signal
 
833
            self.PropertyChanged(dbus.String("Enabled"),
 
834
                                 dbus.Boolean(False, variant_level=1))
 
835
        return r
953
836
    
954
837
    def __del__(self, *args, **kwargs):
955
838
        try:
964
847
                         *args, **kwargs):
965
848
        self.checker_callback_tag = None
966
849
        self.checker = None
 
850
        # Emit D-Bus signal
 
851
        self.PropertyChanged(dbus.String("CheckerRunning"),
 
852
                             dbus.Boolean(False, variant_level=1))
967
853
        if os.WIFEXITED(condition):
968
854
            exitstatus = os.WEXITSTATUS(condition)
969
855
            # Emit D-Bus signal
979
865
        return Client.checker_callback(self, pid, condition, command,
980
866
                                       *args, **kwargs)
981
867
    
 
868
    def checked_ok(self, *args, **kwargs):
 
869
        Client.checked_ok(self, *args, **kwargs)
 
870
        # Emit D-Bus signal
 
871
        self.PropertyChanged(
 
872
            dbus.String("LastCheckedOK"),
 
873
            (self._datetime_to_dbus(self.last_checked_ok,
 
874
                                    variant_level=1)))
 
875
    
 
876
    def need_approval(self, *args, **kwargs):
 
877
        r = Client.need_approval(self, *args, **kwargs)
 
878
        # Emit D-Bus signal
 
879
        self.PropertyChanged(
 
880
            dbus.String("LastApprovalRequest"),
 
881
            (self._datetime_to_dbus(self.last_approval_request,
 
882
                                    variant_level=1)))
 
883
        return r
 
884
    
982
885
    def start_checker(self, *args, **kwargs):
983
886
        old_checker = self.checker
984
887
        if self.checker is not None:
991
894
            and old_checker_pid != self.checker.pid):
992
895
            # Emit D-Bus signal
993
896
            self.CheckerStarted(self.current_checker_command)
 
897
            self.PropertyChanged(
 
898
                dbus.String("CheckerRunning"),
 
899
                dbus.Boolean(True, variant_level=1))
994
900
        return r
995
901
    
 
902
    def stop_checker(self, *args, **kwargs):
 
903
        old_checker = getattr(self, "checker", None)
 
904
        r = Client.stop_checker(self, *args, **kwargs)
 
905
        if (old_checker is not None
 
906
            and getattr(self, "checker", None) is None):
 
907
            self.PropertyChanged(dbus.String("CheckerRunning"),
 
908
                                 dbus.Boolean(False, variant_level=1))
 
909
        return r
 
910
 
996
911
    def _reset_approved(self):
997
912
        self._approved = None
998
913
        return False
1000
915
    def approve(self, value=True):
1001
916
        self.send_changedstate()
1002
917
        self._approved = value
1003
 
        gobject.timeout_add(_timedelta_to_milliseconds
 
918
        gobject.timeout_add(self._timedelta_to_milliseconds
1004
919
                            (self.approval_duration),
1005
920
                            self._reset_approved)
1006
921
    
1007
922
    
1008
923
    ## D-Bus methods, signals & properties
1009
 
    _interface = "se.recompile.Mandos.Client"
 
924
    _interface = "se.bsnet.fukt.Mandos.Client"
1010
925
    
1011
926
    ## Signals
1012
927
    
1097
1012
    def ApprovedByDefault_dbus_property(self, value=None):
1098
1013
        if value is None:       # get
1099
1014
            return dbus.Boolean(self.approved_by_default)
 
1015
        old_value = self.approved_by_default
1100
1016
        self.approved_by_default = bool(value)
 
1017
        # Emit D-Bus signal
 
1018
        if old_value != self.approved_by_default:
 
1019
            self.PropertyChanged(dbus.String("ApprovedByDefault"),
 
1020
                                 dbus.Boolean(value, variant_level=1))
1101
1021
    
1102
1022
    # ApprovalDelay - property
1103
1023
    @dbus_service_property(_interface, signature="t",
1105
1025
    def ApprovalDelay_dbus_property(self, value=None):
1106
1026
        if value is None:       # get
1107
1027
            return dbus.UInt64(self.approval_delay_milliseconds())
 
1028
        old_value = self.approval_delay
1108
1029
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
 
1030
        # Emit D-Bus signal
 
1031
        if old_value != self.approval_delay:
 
1032
            self.PropertyChanged(dbus.String("ApprovalDelay"),
 
1033
                                 dbus.UInt64(value, variant_level=1))
1109
1034
    
1110
1035
    # ApprovalDuration - property
1111
1036
    @dbus_service_property(_interface, signature="t",
1112
1037
                           access="readwrite")
1113
1038
    def ApprovalDuration_dbus_property(self, value=None):
1114
1039
        if value is None:       # get
1115
 
            return dbus.UInt64(_timedelta_to_milliseconds(
 
1040
            return dbus.UInt64(self._timedelta_to_milliseconds(
1116
1041
                    self.approval_duration))
 
1042
        old_value = self.approval_duration
1117
1043
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
 
1044
        # Emit D-Bus signal
 
1045
        if old_value != self.approval_duration:
 
1046
            self.PropertyChanged(dbus.String("ApprovalDuration"),
 
1047
                                 dbus.UInt64(value, variant_level=1))
1118
1048
    
1119
1049
    # Name - property
1120
1050
    @dbus_service_property(_interface, signature="s", access="read")
1132
1062
    def Host_dbus_property(self, value=None):
1133
1063
        if value is None:       # get
1134
1064
            return dbus.String(self.host)
 
1065
        old_value = self.host
1135
1066
        self.host = value
 
1067
        # Emit D-Bus signal
 
1068
        if old_value != self.host:
 
1069
            self.PropertyChanged(dbus.String("Host"),
 
1070
                                 dbus.String(value, variant_level=1))
1136
1071
    
1137
1072
    # Created - property
1138
1073
    @dbus_service_property(_interface, signature="s", access="read")
1139
1074
    def Created_dbus_property(self):
1140
 
        return dbus.String(datetime_to_dbus(self.created))
 
1075
        return dbus.String(self._datetime_to_dbus(self.created))
1141
1076
    
1142
1077
    # LastEnabled - property
1143
1078
    @dbus_service_property(_interface, signature="s", access="read")
1144
1079
    def LastEnabled_dbus_property(self):
1145
 
        return datetime_to_dbus(self.last_enabled)
 
1080
        return self._datetime_to_dbus(self.last_enabled)
1146
1081
    
1147
1082
    # Enabled - property
1148
1083
    @dbus_service_property(_interface, signature="b",
1162
1097
        if value is not None:
1163
1098
            self.checked_ok()
1164
1099
            return
1165
 
        return datetime_to_dbus(self.last_checked_ok)
 
1100
        return self._datetime_to_dbus(self.last_checked_ok)
1166
1101
    
1167
1102
    # Expires - property
1168
1103
    @dbus_service_property(_interface, signature="s", access="read")
1169
1104
    def Expires_dbus_property(self):
1170
 
        return datetime_to_dbus(self.expires)
 
1105
        return self._datetime_to_dbus(self.expires)
1171
1106
    
1172
1107
    # LastApprovalRequest - property
1173
1108
    @dbus_service_property(_interface, signature="s", access="read")
1174
1109
    def LastApprovalRequest_dbus_property(self):
1175
 
        return datetime_to_dbus(self.last_approval_request)
 
1110
        return self._datetime_to_dbus(self.last_approval_request)
1176
1111
    
1177
1112
    # Timeout - property
1178
1113
    @dbus_service_property(_interface, signature="t",
1180
1115
    def Timeout_dbus_property(self, value=None):
1181
1116
        if value is None:       # get
1182
1117
            return dbus.UInt64(self.timeout_milliseconds())
 
1118
        old_value = self.timeout
1183
1119
        self.timeout = datetime.timedelta(0, 0, 0, value)
 
1120
        # Emit D-Bus signal
 
1121
        if old_value != self.timeout:
 
1122
            self.PropertyChanged(dbus.String("Timeout"),
 
1123
                                 dbus.UInt64(value, variant_level=1))
1184
1124
        if getattr(self, "disable_initiator_tag", None) is None:
1185
1125
            return
1186
1126
        # Reschedule timeout
1198
1138
            self.disable()
1199
1139
        else:
1200
1140
            self.expires = (datetime.datetime.utcnow()
1201
 
                            + datetime.timedelta(milliseconds =
1202
 
                                                 time_to_die))
 
1141
                            + datetime.timedelta(milliseconds = time_to_die))
1203
1142
            self.disable_initiator_tag = (gobject.timeout_add
1204
1143
                                          (time_to_die, self.disable))
1205
 
    
 
1144
 
1206
1145
    # ExtendedTimeout - property
1207
1146
    @dbus_service_property(_interface, signature="t",
1208
1147
                           access="readwrite")
1209
1148
    def ExtendedTimeout_dbus_property(self, value=None):
1210
1149
        if value is None:       # get
1211
1150
            return dbus.UInt64(self.extended_timeout_milliseconds())
 
1151
        old_value = self.extended_timeout
1212
1152
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1213
 
    
 
1153
        # Emit D-Bus signal
 
1154
        if old_value != self.extended_timeout:
 
1155
            self.PropertyChanged(dbus.String("ExtendedTimeout"),
 
1156
                                 dbus.UInt64(value, variant_level=1))
 
1157
 
1214
1158
    # Interval - property
1215
1159
    @dbus_service_property(_interface, signature="t",
1216
1160
                           access="readwrite")
1217
1161
    def Interval_dbus_property(self, value=None):
1218
1162
        if value is None:       # get
1219
1163
            return dbus.UInt64(self.interval_milliseconds())
 
1164
        old_value = self.interval
1220
1165
        self.interval = datetime.timedelta(0, 0, 0, value)
 
1166
        # Emit D-Bus signal
 
1167
        if old_value != self.interval:
 
1168
            self.PropertyChanged(dbus.String("Interval"),
 
1169
                                 dbus.UInt64(value, variant_level=1))
1221
1170
        if getattr(self, "checker_initiator_tag", None) is None:
1222
1171
            return
1223
1172
        # Reschedule checker run
1225
1174
        self.checker_initiator_tag = (gobject.timeout_add
1226
1175
                                      (value, self.start_checker))
1227
1176
        self.start_checker()    # Start one now, too
1228
 
    
 
1177
 
1229
1178
    # Checker - property
1230
1179
    @dbus_service_property(_interface, signature="s",
1231
1180
                           access="readwrite")
1232
1181
    def Checker_dbus_property(self, value=None):
1233
1182
        if value is None:       # get
1234
1183
            return dbus.String(self.checker_command)
 
1184
        old_value = self.checker_command
1235
1185
        self.checker_command = value
 
1186
        # Emit D-Bus signal
 
1187
        if old_value != self.checker_command:
 
1188
            self.PropertyChanged(dbus.String("Checker"),
 
1189
                                 dbus.String(self.checker_command,
 
1190
                                             variant_level=1))
1236
1191
    
1237
1192
    # CheckerRunning - property
1238
1193
    @dbus_service_property(_interface, signature="b",
1265
1220
        self._pipe.send(('init', fpr, address))
1266
1221
        if not self._pipe.recv():
1267
1222
            raise KeyError()
1268
 
    
 
1223
 
1269
1224
    def __getattribute__(self, name):
1270
1225
        if(name == '_pipe'):
1271
1226
            return super(ProxyClient, self).__getattribute__(name)
1278
1233
                self._pipe.send(('funcall', name, args, kwargs))
1279
1234
                return self._pipe.recv()[1]
1280
1235
            return func
1281
 
    
 
1236
 
1282
1237
    def __setattr__(self, name, value):
1283
1238
        if(name == '_pipe'):
1284
1239
            return super(ProxyClient, self).__setattr__(name, value)
1285
1240
        self._pipe.send(('setattr', name, value))
1286
1241
 
1287
 
class ClientDBusTransitional(ClientDBus):
1288
 
    __metaclass__ = AlternateDBusNamesMetaclass
1289
1242
 
1290
1243
class ClientHandler(socketserver.BaseRequestHandler, object):
1291
1244
    """A class to handle client connections.
1299
1252
                        unicode(self.client_address))
1300
1253
            logger.debug("Pipe FD: %d",
1301
1254
                         self.server.child_pipe.fileno())
1302
 
            
 
1255
 
1303
1256
            session = (gnutls.connection
1304
1257
                       .ClientSession(self.request,
1305
1258
                                      gnutls.connection
1306
1259
                                      .X509Credentials()))
1307
 
            
 
1260
 
1308
1261
            # Note: gnutls.connection.X509Credentials is really a
1309
1262
            # generic GnuTLS certificate credentials object so long as
1310
1263
            # no X.509 keys are added to it.  Therefore, we can use it
1311
1264
            # here despite using OpenPGP certificates.
1312
 
            
 
1265
 
1313
1266
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1314
1267
            #                      "+AES-256-CBC", "+SHA1",
1315
1268
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
1321
1274
            (gnutls.library.functions
1322
1275
             .gnutls_priority_set_direct(session._c_object,
1323
1276
                                         priority, None))
1324
 
            
 
1277
 
1325
1278
            # Start communication using the Mandos protocol
1326
1279
            # Get protocol number
1327
1280
            line = self.request.makefile().readline()
1332
1285
            except (ValueError, IndexError, RuntimeError) as error:
1333
1286
                logger.error("Unknown protocol version: %s", error)
1334
1287
                return
1335
 
            
 
1288
 
1336
1289
            # Start GnuTLS connection
1337
1290
            try:
1338
1291
                session.handshake()
1342
1295
                # established.  Just abandon the request.
1343
1296
                return
1344
1297
            logger.debug("Handshake succeeded")
1345
 
            
 
1298
 
1346
1299
            approval_required = False
1347
1300
            try:
1348
1301
                try:
1353
1306
                    logger.warning("Bad certificate: %s", error)
1354
1307
                    return
1355
1308
                logger.debug("Fingerprint: %s", fpr)
1356
 
                
 
1309
 
1357
1310
                try:
1358
1311
                    client = ProxyClient(child_pipe, fpr,
1359
1312
                                         self.client_address)
1371
1324
                                       client.name)
1372
1325
                        if self.server.use_dbus:
1373
1326
                            # Emit D-Bus signal
1374
 
                            client.Rejected("Disabled")
 
1327
                            client.Rejected("Disabled")                    
1375
1328
                        return
1376
1329
                    
1377
1330
                    if client._approved or not client.approval_delay:
1394
1347
                        return
1395
1348
                    
1396
1349
                    #wait until timeout or approved
1397
 
                    #x = float(client
1398
 
                    #          ._timedelta_to_milliseconds(delay))
 
1350
                    #x = float(client._timedelta_to_milliseconds(delay))
1399
1351
                    time = datetime.datetime.now()
1400
1352
                    client.changedstate.acquire()
1401
 
                    (client.changedstate.wait
1402
 
                     (float(client._timedelta_to_milliseconds(delay)
1403
 
                            / 1000)))
 
1353
                    client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1404
1354
                    client.changedstate.release()
1405
1355
                    time2 = datetime.datetime.now()
1406
1356
                    if (time2 - time) >= delay:
1428
1378
                                 sent, len(client.secret)
1429
1379
                                 - (sent_size + sent))
1430
1380
                    sent_size += sent
1431
 
                
 
1381
 
1432
1382
                logger.info("Sending secret to %s", client.name)
1433
1383
                # bump the timeout as if seen
1434
1384
                client.checked_ok(client.extended_timeout)
1522
1472
        multiprocessing.Process(target = self.sub_process_main,
1523
1473
                                args = (request, address)).start()
1524
1474
 
1525
 
 
1526
1475
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1527
1476
    """ adds a pipe to the MixIn """
1528
1477
    def process_request(self, request, client_address):
1531
1480
        This function creates a new pipe in self.pipe
1532
1481
        """
1533
1482
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1534
 
        
 
1483
 
1535
1484
        super(MultiprocessingMixInWithPipe,
1536
1485
              self).process_request(request, client_address)
1537
1486
        self.child_pipe.close()
1538
1487
        self.add_pipe(parent_pipe)
1539
 
    
 
1488
 
1540
1489
    def add_pipe(self, parent_pipe):
1541
1490
        """Dummy function; override as necessary"""
1542
1491
        raise NotImplementedError
1543
1492
 
1544
 
 
1545
1493
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1546
1494
                     socketserver.TCPServer, object):
1547
1495
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1638
1586
        gobject.io_add_watch(parent_pipe.fileno(),
1639
1587
                             gobject.IO_IN | gobject.IO_HUP,
1640
1588
                             functools.partial(self.handle_ipc,
1641
 
                                               parent_pipe =
1642
 
                                               parent_pipe))
 
1589
                                               parent_pipe = parent_pipe))
1643
1590
        
1644
1591
    def handle_ipc(self, source, condition, parent_pipe=None,
1645
1592
                   client_object=None):
1678
1625
                            "dress: %s", fpr, address)
1679
1626
                if self.use_dbus:
1680
1627
                    # Emit D-Bus signal
1681
 
                    mandos_dbus_service.ClientNotFound(fpr,
1682
 
                                                       address[0])
 
1628
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1683
1629
                parent_pipe.send(False)
1684
1630
                return False
1685
1631
            
1686
1632
            gobject.io_add_watch(parent_pipe.fileno(),
1687
1633
                                 gobject.IO_IN | gobject.IO_HUP,
1688
1634
                                 functools.partial(self.handle_ipc,
1689
 
                                                   parent_pipe =
1690
 
                                                   parent_pipe,
1691
 
                                                   client_object =
1692
 
                                                   client))
 
1635
                                                   parent_pipe = parent_pipe,
 
1636
                                                   client_object = client))
1693
1637
            parent_pipe.send(True)
1694
 
            # remove the old hook in favor of the new above hook on
1695
 
            # same fileno
 
1638
            # remove the old hook in favor of the new above hook on same fileno
1696
1639
            return False
1697
1640
        if command == 'funcall':
1698
1641
            funcname = request[1]
1699
1642
            args = request[2]
1700
1643
            kwargs = request[3]
1701
1644
            
1702
 
            parent_pipe.send(('data', getattr(client_object,
1703
 
                                              funcname)(*args,
1704
 
                                                         **kwargs)))
1705
 
        
 
1645
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
 
1646
 
1706
1647
        if command == 'getattr':
1707
1648
            attrname = request[1]
1708
1649
            if callable(client_object.__getattribute__(attrname)):
1709
1650
                parent_pipe.send(('function',))
1710
1651
            else:
1711
 
                parent_pipe.send(('data', client_object
1712
 
                                  .__getattribute__(attrname)))
 
1652
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1713
1653
        
1714
1654
        if command == 'setattr':
1715
1655
            attrname = request[1]
1716
1656
            value = request[2]
1717
1657
            setattr(client_object, attrname, value)
1718
 
        
 
1658
 
1719
1659
        return True
1720
1660
 
1721
1661
 
1900
1840
    debuglevel = server_settings["debuglevel"]
1901
1841
    use_dbus = server_settings["use_dbus"]
1902
1842
    use_ipv6 = server_settings["use_ipv6"]
1903
 
    
 
1843
 
1904
1844
    if server_settings["servicename"] != "Mandos":
1905
1845
        syslogger.setFormatter(logging.Formatter
1906
1846
                               ('Mandos (%s) [%%(process)d]:'
1967
1907
        level = getattr(logging, debuglevel.upper())
1968
1908
        syslogger.setLevel(level)
1969
1909
        console.setLevel(level)
1970
 
    
 
1910
 
1971
1911
    if debug:
1972
1912
        # Enable all possible GnuTLS debugging
1973
1913
        
2004
1944
    # End of Avahi example code
2005
1945
    if use_dbus:
2006
1946
        try:
2007
 
            bus_name = dbus.service.BusName("se.recompile.Mandos",
 
1947
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
2008
1948
                                            bus, do_not_queue=True)
2009
 
            old_bus_name = (dbus.service.BusName
2010
 
                            ("se.bsnet.fukt.Mandos", bus,
2011
 
                             do_not_queue=True))
2012
1949
        except dbus.exceptions.NameExistsException as e:
2013
1950
            logger.error(unicode(e) + ", disabling D-Bus")
2014
1951
            use_dbus = False
2027
1964
    
2028
1965
    client_class = Client
2029
1966
    if use_dbus:
2030
 
        client_class = functools.partial(ClientDBusTransitional,
2031
 
                                         bus = bus)
 
1967
        client_class = functools.partial(ClientDBus, bus = bus)
2032
1968
    def client_config_items(config, section):
2033
1969
        special_settings = {
2034
1970
            "approved_by_default":
2064
2000
        del pidfilename
2065
2001
        
2066
2002
        signal.signal(signal.SIGINT, signal.SIG_IGN)
2067
 
    
 
2003
 
2068
2004
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2069
2005
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2070
2006
    
2073
2009
            """A D-Bus proxy object"""
2074
2010
            def __init__(self):
2075
2011
                dbus.service.Object.__init__(self, bus, "/")
2076
 
            _interface = "se.recompile.Mandos"
 
2012
            _interface = "se.bsnet.fukt.Mandos"
2077
2013
            
2078
2014
            @dbus.service.signal(_interface, signature="o")
2079
2015
            def ClientAdded(self, objpath):
2121
2057
            
2122
2058
            del _interface
2123
2059
        
2124
 
        class MandosDBusServiceTransitional(MandosDBusService):
2125
 
            __metaclass__ = AlternateDBusNamesMetaclass
2126
 
        mandos_dbus_service = MandosDBusServiceTransitional()
 
2060
        mandos_dbus_service = MandosDBusService()
2127
2061
    
2128
2062
    def cleanup():
2129
2063
        "Cleanup function; run on exit"
2138
2072
            client.disable(quiet=True)
2139
2073
            if use_dbus:
2140
2074
                # Emit D-Bus signal
2141
 
                mandos_dbus_service.ClientRemoved(client
2142
 
                                                  .dbus_object_path,
 
2075
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2143
2076
                                                  client.name)
2144
2077
    
2145
2078
    atexit.register(cleanup)
2194
2127
    # Must run before the D-Bus bus name gets deregistered
2195
2128
    cleanup()
2196
2129
 
2197
 
 
2198
2130
if __name__ == '__main__':
2199
2131
    main()