/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: 2011-04-02 06:37:18 UTC
  • Revision ID: teddy@fukt.bsnet.se-20110402063718-13ldrcuu0t33sdc4
* mandos: Tolerate restarting Avahi servers.  Also Changed to new
          "except x as y" exception syntax.
  (AvahiService.entry_group_state_changed_match): New; contains the
                                                  SignalMatch object.
  (AvahiService.remove): Really remove the group and the signal
                         connection, if any.
  (AvahiService.add): Always create a new group and signal connection.
  (AvahiService.cleanup): Changed to simply call remove().
  (AvahiService.server_state_changed): Handle and log more bad states.
  (AvahiService.activate): Set "follow_name_owner_changes=True" on the
                           Avahi Server proxy object.
  (ClientDBus.checked_ok): Do not return anything.
  (ClientDBus.CheckedOK): Do not return anything, as documented.
* mandos-monitor: Call D-Bus methods asynchronously.

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
83
82
        SO_BINDTODEVICE = None
84
83
 
85
84
 
86
 
version = "1.3.1"
 
85
version = "1.3.0"
87
86
 
88
87
#logger = logging.getLogger('mandos')
89
88
logger = logging.Logger('mandos')
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
178
176
        self.rename_count += 1
179
177
    def remove(self):
180
178
        """Derived from the Avahi example code"""
 
179
        if self.group is not None:
 
180
            try:
 
181
                self.group.Free()
 
182
            except (dbus.exceptions.UnknownMethodException,
 
183
                    dbus.exceptions.DBusException) as e:
 
184
                pass
 
185
            self.group = None
181
186
        if self.entry_group_state_changed_match is not None:
182
187
            self.entry_group_state_changed_match.remove()
183
188
            self.entry_group_state_changed_match = None
184
 
        if self.group is not None:
185
 
            self.group.Reset()
186
189
    def add(self):
187
190
        """Derived from the Avahi example code"""
188
191
        self.remove()
189
 
        if self.group is None:
190
 
            self.group = dbus.Interface(
191
 
                self.bus.get_object(avahi.DBUS_NAME,
192
 
                                    self.server.EntryGroupNew()),
193
 
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
 
192
        self.group = dbus.Interface(
 
193
            self.bus.get_object(avahi.DBUS_NAME,
 
194
                                self.server.EntryGroupNew(),
 
195
                                follow_name_owner_changes=True),
 
196
            avahi.DBUS_INTERFACE_ENTRY_GROUP)
194
197
        self.entry_group_state_changed_match = (
195
198
            self.group.connect_to_signal(
196
199
                'StateChanged', self .entry_group_state_changed))
221
224
                                  % unicode(error))
222
225
    def cleanup(self):
223
226
        """Derived from the Avahi example code"""
224
 
        if self.group is not None:
225
 
            try:
226
 
                self.group.Free()
227
 
            except (dbus.exceptions.UnknownMethodException,
228
 
                    dbus.exceptions.DBusException) as e:
229
 
                pass
230
 
            self.group = None
231
227
        self.remove()
232
228
    def server_state_changed(self, state, error=None):
233
229
        """Derived from the Avahi example code"""
240
236
                       avahi.SERVER_FAILURE:
241
237
                           "Zeroconf server failure" }
242
238
        if state in bad_states:
243
 
            if bad_states[state] is not None:
244
 
                if error is None:
245
 
                    logger.error(bad_states[state])
246
 
                else:
247
 
                    logger.error(bad_states[state] + ": %r", error)
248
 
            self.cleanup()
 
239
            if bad_states[state]:
 
240
                logger.error(bad_states[state])
 
241
            self.remove()
249
242
        elif state == avahi.SERVER_RUNNING:
250
243
            self.add()
251
244
        else:
252
 
            if error is None:
253
 
                logger.debug("Unknown state: %r", state)
254
 
            else:
255
 
                logger.debug("Unknown state: %r: %r", state, error)
 
245
            logger.debug("Unknown state: %r", state)
256
246
    def activate(self):
257
247
        """Derived from the Avahi example code"""
258
248
        if self.server is None:
266
256
        self.server_state_changed(self.server.GetState())
267
257
 
268
258
 
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
259
class Client(object):
276
260
    """A representation of a client host served by this server.
277
261
    
305
289
    secret:     bytestring; sent verbatim (over TLS) to client
306
290
    timeout:    datetime.timedelta(); How long from last_checked_ok
307
291
                                      until this client is disabled
308
 
    extended_timeout:   extra long timeout when password has been sent
309
292
    runtime_expansions: Allowed attributes for runtime expansion.
310
 
    expires:    datetime.datetime(); time (UTC) when a client will be
311
 
                disabled, or None
312
293
    """
313
294
    
314
295
    runtime_expansions = ("approval_delay", "approval_duration",
316
297
                          "host", "interval", "last_checked_ok",
317
298
                          "last_enabled", "name", "timeout")
318
299
    
 
300
    @staticmethod
 
301
    def _timedelta_to_milliseconds(td):
 
302
        "Convert a datetime.timedelta() to milliseconds"
 
303
        return ((td.days * 24 * 60 * 60 * 1000)
 
304
                + (td.seconds * 1000)
 
305
                + (td.microseconds // 1000))
 
306
    
319
307
    def timeout_milliseconds(self):
320
308
        "Return the 'timeout' attribute in milliseconds"
321
 
        return _timedelta_to_milliseconds(self.timeout)
322
 
    
323
 
    def extended_timeout_milliseconds(self):
324
 
        "Return the 'extended_timeout' attribute in milliseconds"
325
 
        return _timedelta_to_milliseconds(self.extended_timeout)
 
309
        return self._timedelta_to_milliseconds(self.timeout)
326
310
    
327
311
    def interval_milliseconds(self):
328
312
        "Return the 'interval' attribute in milliseconds"
329
 
        return _timedelta_to_milliseconds(self.interval)
330
 
    
 
313
        return self._timedelta_to_milliseconds(self.interval)
 
314
 
331
315
    def approval_delay_milliseconds(self):
332
 
        return _timedelta_to_milliseconds(self.approval_delay)
 
316
        return self._timedelta_to_milliseconds(self.approval_delay)
333
317
    
334
318
    def __init__(self, name = None, disable_hook=None, config=None):
335
319
        """Note: the 'checker' key in 'config' sets the
362
346
        self.last_enabled = None
363
347
        self.last_checked_ok = None
364
348
        self.timeout = string_to_delta(config["timeout"])
365
 
        self.extended_timeout = string_to_delta(config
366
 
                                                ["extended_timeout"])
367
349
        self.interval = string_to_delta(config["interval"])
368
350
        self.disable_hook = disable_hook
369
351
        self.checker = None
370
352
        self.checker_initiator_tag = None
371
353
        self.disable_initiator_tag = None
372
 
        self.expires = None
373
354
        self.checker_callback_tag = None
374
355
        self.checker_command = config["checker"]
375
356
        self.current_checker_command = None
382
363
            config["approval_delay"])
383
364
        self.approval_duration = string_to_delta(
384
365
            config["approval_duration"])
385
 
        self.changedstate = (multiprocessing_manager
386
 
                             .Condition(multiprocessing_manager
387
 
                                        .Lock()))
 
366
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
388
367
    
389
368
    def send_changedstate(self):
390
369
        self.changedstate.acquire()
391
370
        self.changedstate.notify_all()
392
371
        self.changedstate.release()
393
 
    
 
372
        
394
373
    def enable(self):
395
374
        """Start this client's checker and timeout hooks"""
396
375
        if getattr(self, "enabled", False):
397
376
            # Already enabled
398
377
            return
399
378
        self.send_changedstate()
 
379
        self.last_enabled = datetime.datetime.utcnow()
400
380
        # Schedule a new checker to be started an 'interval' from now,
401
381
        # and every interval from then on.
402
382
        self.checker_initiator_tag = (gobject.timeout_add
403
383
                                      (self.interval_milliseconds(),
404
384
                                       self.start_checker))
405
385
        # Schedule a disable() when 'timeout' has passed
406
 
        self.expires = datetime.datetime.utcnow() + self.timeout
407
386
        self.disable_initiator_tag = (gobject.timeout_add
408
387
                                   (self.timeout_milliseconds(),
409
388
                                    self.disable))
410
389
        self.enabled = True
411
 
        self.last_enabled = datetime.datetime.utcnow()
412
390
        # Also start a new checker *right now*.
413
391
        self.start_checker()
414
392
    
423
401
        if getattr(self, "disable_initiator_tag", False):
424
402
            gobject.source_remove(self.disable_initiator_tag)
425
403
            self.disable_initiator_tag = None
426
 
        self.expires = None
427
404
        if getattr(self, "checker_initiator_tag", False):
428
405
            gobject.source_remove(self.checker_initiator_tag)
429
406
            self.checker_initiator_tag = None
455
432
            logger.warning("Checker for %(name)s crashed?",
456
433
                           vars(self))
457
434
    
458
 
    def checked_ok(self, timeout=None):
 
435
    def checked_ok(self):
459
436
        """Bump up the timeout for this client.
460
437
        
461
438
        This should only be called when the client has been seen,
462
439
        alive and well.
463
440
        """
464
 
        if timeout is None:
465
 
            timeout = self.timeout
466
441
        self.last_checked_ok = datetime.datetime.utcnow()
467
442
        gobject.source_remove(self.disable_initiator_tag)
468
 
        self.expires = datetime.datetime.utcnow() + timeout
469
443
        self.disable_initiator_tag = (gobject.timeout_add
470
 
                                      (_timedelta_to_milliseconds
471
 
                                       (timeout), self.disable))
 
444
                                      (self.timeout_milliseconds(),
 
445
                                       self.disable))
472
446
    
473
447
    def need_approval(self):
474
448
        self.last_approval_request = datetime.datetime.utcnow()
514
488
                                       'replace')))
515
489
                    for attr in
516
490
                    self.runtime_expansions)
517
 
                
 
491
 
518
492
                try:
519
493
                    command = self.checker_command % escaped_attrs
520
494
                except TypeError as error:
566
540
                raise
567
541
        self.checker = None
568
542
 
569
 
 
570
543
def dbus_service_property(dbus_interface, signature="v",
571
544
                          access="readwrite", byte_arrays=False):
572
545
    """Decorators for marking methods of a DBusObjectWithProperties to
618
591
 
619
592
class DBusObjectWithProperties(dbus.service.Object):
620
593
    """A D-Bus object with properties.
621
 
    
 
594
 
622
595
    Classes inheriting from this can use the dbus_service_property
623
596
    decorator to expose methods as D-Bus properties.  It exposes the
624
597
    standard Get(), Set(), and GetAll() methods on the D-Bus.
631
604
    def _get_all_dbus_properties(self):
632
605
        """Returns a generator of (name, attribute) pairs
633
606
        """
634
 
        return ((prop.__get__(self)._dbus_name, prop.__get__(self))
635
 
                for cls in self.__class__.__mro__
 
607
        return ((prop._dbus_name, prop)
636
608
                for name, prop in
637
 
                inspect.getmembers(cls, self._is_dbus_property))
 
609
                inspect.getmembers(self, self._is_dbus_property))
638
610
    
639
611
    def _get_dbus_property(self, interface_name, property_name):
640
612
        """Returns a bound method if one exists which is a D-Bus
641
613
        property with the specified name and interface.
642
614
        """
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
 
        
 
615
        for name in (property_name,
 
616
                     property_name + "_dbus_property"):
 
617
            prop = getattr(self, name, None)
 
618
            if (prop is None
 
619
                or not self._is_dbus_property(prop)
 
620
                or prop._dbus_name != property_name
 
621
                or (interface_name and prop._dbus_interface
 
622
                    and interface_name != prop._dbus_interface)):
 
623
                continue
 
624
            return prop
650
625
        # No such property
651
626
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
652
627
                                   + interface_name + "."
686
661
    def GetAll(self, interface_name):
687
662
        """Standard D-Bus property GetAll() method, see D-Bus
688
663
        standard.
689
 
        
 
664
 
690
665
        Note: Will not include properties with access="write".
691
666
        """
692
667
        all = {}
754
729
        return xmlstring
755
730
 
756
731
 
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
732
class ClientDBus(Client, DBusObjectWithProperties):
862
733
    """A Client class using D-Bus
863
734
    
885
756
        DBusObjectWithProperties.__init__(self, self.bus,
886
757
                                          self.dbus_object_path)
887
758
        
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.
 
759
    def _get_approvals_pending(self):
 
760
        return self._approvals_pending
 
761
    def _set_approvals_pending(self, value):
 
762
        old_value = self._approvals_pending
 
763
        self._approvals_pending = value
 
764
        bval = bool(value)
 
765
        if (hasattr(self, "dbus_object_path")
 
766
            and bval is not bool(old_value)):
 
767
            dbus_bool = dbus.Boolean(bval, variant_level=1)
 
768
            self.PropertyChanged(dbus.String("ApprovalPending"),
 
769
                                 dbus_bool)
893
770
 
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
 
771
    approvals_pending = property(_get_approvals_pending,
 
772
                                 _set_approvals_pending)
 
773
    del _get_approvals_pending, _set_approvals_pending
 
774
    
 
775
    @staticmethod
 
776
    def _datetime_to_dbus(dt, variant_level=0):
 
777
        """Convert a UTC datetime.datetime() to a D-Bus type."""
 
778
        return dbus.String(dt.isoformat(),
 
779
                           variant_level=variant_level)
 
780
    
 
781
    def enable(self):
 
782
        oldstate = getattr(self, "enabled", False)
 
783
        r = Client.enable(self)
 
784
        if oldstate != self.enabled:
 
785
            # Emit D-Bus signals
 
786
            self.PropertyChanged(dbus.String("Enabled"),
 
787
                                 dbus.Boolean(True, variant_level=1))
 
788
            self.PropertyChanged(
 
789
                dbus.String("LastEnabled"),
 
790
                self._datetime_to_dbus(self.last_enabled,
 
791
                                       variant_level=1))
 
792
        return r
 
793
    
 
794
    def disable(self, quiet = False):
 
795
        oldstate = getattr(self, "enabled", False)
 
796
        r = Client.disable(self, quiet=quiet)
 
797
        if not quiet and oldstate != self.enabled:
 
798
            # Emit D-Bus signal
 
799
            self.PropertyChanged(dbus.String("Enabled"),
 
800
                                 dbus.Boolean(False, variant_level=1))
 
801
        return r
953
802
    
954
803
    def __del__(self, *args, **kwargs):
955
804
        try:
964
813
                         *args, **kwargs):
965
814
        self.checker_callback_tag = None
966
815
        self.checker = None
 
816
        # Emit D-Bus signal
 
817
        self.PropertyChanged(dbus.String("CheckerRunning"),
 
818
                             dbus.Boolean(False, variant_level=1))
967
819
        if os.WIFEXITED(condition):
968
820
            exitstatus = os.WEXITSTATUS(condition)
969
821
            # Emit D-Bus signal
979
831
        return Client.checker_callback(self, pid, condition, command,
980
832
                                       *args, **kwargs)
981
833
    
 
834
    def checked_ok(self, *args, **kwargs):
 
835
        Client.checked_ok(self, *args, **kwargs)
 
836
        # Emit D-Bus signal
 
837
        self.PropertyChanged(
 
838
            dbus.String("LastCheckedOK"),
 
839
            (self._datetime_to_dbus(self.last_checked_ok,
 
840
                                    variant_level=1)))
 
841
    
 
842
    def need_approval(self, *args, **kwargs):
 
843
        r = Client.need_approval(self, *args, **kwargs)
 
844
        # Emit D-Bus signal
 
845
        self.PropertyChanged(
 
846
            dbus.String("LastApprovalRequest"),
 
847
            (self._datetime_to_dbus(self.last_approval_request,
 
848
                                    variant_level=1)))
 
849
        return r
 
850
    
982
851
    def start_checker(self, *args, **kwargs):
983
852
        old_checker = self.checker
984
853
        if self.checker is not None:
991
860
            and old_checker_pid != self.checker.pid):
992
861
            # Emit D-Bus signal
993
862
            self.CheckerStarted(self.current_checker_command)
 
863
            self.PropertyChanged(
 
864
                dbus.String("CheckerRunning"),
 
865
                dbus.Boolean(True, variant_level=1))
994
866
        return r
995
867
    
 
868
    def stop_checker(self, *args, **kwargs):
 
869
        old_checker = getattr(self, "checker", None)
 
870
        r = Client.stop_checker(self, *args, **kwargs)
 
871
        if (old_checker is not None
 
872
            and getattr(self, "checker", None) is None):
 
873
            self.PropertyChanged(dbus.String("CheckerRunning"),
 
874
                                 dbus.Boolean(False, variant_level=1))
 
875
        return r
 
876
 
996
877
    def _reset_approved(self):
997
878
        self._approved = None
998
879
        return False
1000
881
    def approve(self, value=True):
1001
882
        self.send_changedstate()
1002
883
        self._approved = value
1003
 
        gobject.timeout_add(_timedelta_to_milliseconds
 
884
        gobject.timeout_add(self._timedelta_to_milliseconds
1004
885
                            (self.approval_duration),
1005
886
                            self._reset_approved)
1006
887
    
1007
888
    
1008
889
    ## D-Bus methods, signals & properties
1009
 
    _interface = "se.recompile.Mandos.Client"
 
890
    _interface = "se.bsnet.fukt.Mandos.Client"
1010
891
    
1011
892
    ## Signals
1012
893
    
1098
979
        if value is None:       # get
1099
980
            return dbus.Boolean(self.approved_by_default)
1100
981
        self.approved_by_default = bool(value)
 
982
        # Emit D-Bus signal
 
983
        self.PropertyChanged(dbus.String("ApprovedByDefault"),
 
984
                             dbus.Boolean(value, variant_level=1))
1101
985
    
1102
986
    # ApprovalDelay - property
1103
987
    @dbus_service_property(_interface, signature="t",
1106
990
        if value is None:       # get
1107
991
            return dbus.UInt64(self.approval_delay_milliseconds())
1108
992
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
 
993
        # Emit D-Bus signal
 
994
        self.PropertyChanged(dbus.String("ApprovalDelay"),
 
995
                             dbus.UInt64(value, variant_level=1))
1109
996
    
1110
997
    # ApprovalDuration - property
1111
998
    @dbus_service_property(_interface, signature="t",
1112
999
                           access="readwrite")
1113
1000
    def ApprovalDuration_dbus_property(self, value=None):
1114
1001
        if value is None:       # get
1115
 
            return dbus.UInt64(_timedelta_to_milliseconds(
 
1002
            return dbus.UInt64(self._timedelta_to_milliseconds(
1116
1003
                    self.approval_duration))
1117
1004
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
 
1005
        # Emit D-Bus signal
 
1006
        self.PropertyChanged(dbus.String("ApprovalDuration"),
 
1007
                             dbus.UInt64(value, variant_level=1))
1118
1008
    
1119
1009
    # Name - property
1120
1010
    @dbus_service_property(_interface, signature="s", access="read")
1133
1023
        if value is None:       # get
1134
1024
            return dbus.String(self.host)
1135
1025
        self.host = value
 
1026
        # Emit D-Bus signal
 
1027
        self.PropertyChanged(dbus.String("Host"),
 
1028
                             dbus.String(value, variant_level=1))
1136
1029
    
1137
1030
    # Created - property
1138
1031
    @dbus_service_property(_interface, signature="s", access="read")
1139
1032
    def Created_dbus_property(self):
1140
 
        return dbus.String(datetime_to_dbus(self.created))
 
1033
        return dbus.String(self._datetime_to_dbus(self.created))
1141
1034
    
1142
1035
    # LastEnabled - property
1143
1036
    @dbus_service_property(_interface, signature="s", access="read")
1144
1037
    def LastEnabled_dbus_property(self):
1145
 
        return datetime_to_dbus(self.last_enabled)
 
1038
        if self.last_enabled is None:
 
1039
            return dbus.String("")
 
1040
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
1146
1041
    
1147
1042
    # Enabled - property
1148
1043
    @dbus_service_property(_interface, signature="b",
1162
1057
        if value is not None:
1163
1058
            self.checked_ok()
1164
1059
            return
1165
 
        return datetime_to_dbus(self.last_checked_ok)
1166
 
    
1167
 
    # Expires - property
1168
 
    @dbus_service_property(_interface, signature="s", access="read")
1169
 
    def Expires_dbus_property(self):
1170
 
        return datetime_to_dbus(self.expires)
 
1060
        if self.last_checked_ok is None:
 
1061
            return dbus.String("")
 
1062
        return dbus.String(self._datetime_to_dbus(self
 
1063
                                                  .last_checked_ok))
1171
1064
    
1172
1065
    # LastApprovalRequest - property
1173
1066
    @dbus_service_property(_interface, signature="s", access="read")
1174
1067
    def LastApprovalRequest_dbus_property(self):
1175
 
        return datetime_to_dbus(self.last_approval_request)
 
1068
        if self.last_approval_request is None:
 
1069
            return dbus.String("")
 
1070
        return dbus.String(self.
 
1071
                           _datetime_to_dbus(self
 
1072
                                             .last_approval_request))
1176
1073
    
1177
1074
    # Timeout - property
1178
1075
    @dbus_service_property(_interface, signature="t",
1181
1078
        if value is None:       # get
1182
1079
            return dbus.UInt64(self.timeout_milliseconds())
1183
1080
        self.timeout = datetime.timedelta(0, 0, 0, value)
 
1081
        # Emit D-Bus signal
 
1082
        self.PropertyChanged(dbus.String("Timeout"),
 
1083
                             dbus.UInt64(value, variant_level=1))
1184
1084
        if getattr(self, "disable_initiator_tag", None) is None:
1185
1085
            return
1186
1086
        # Reschedule timeout
1187
1087
        gobject.source_remove(self.disable_initiator_tag)
1188
1088
        self.disable_initiator_tag = None
1189
 
        self.expires = None
1190
1089
        time_to_die = (self.
1191
1090
                       _timedelta_to_milliseconds((self
1192
1091
                                                   .last_checked_ok
1197
1096
            # The timeout has passed
1198
1097
            self.disable()
1199
1098
        else:
1200
 
            self.expires = (datetime.datetime.utcnow()
1201
 
                            + datetime.timedelta(milliseconds =
1202
 
                                                 time_to_die))
1203
1099
            self.disable_initiator_tag = (gobject.timeout_add
1204
1100
                                          (time_to_die, self.disable))
1205
1101
    
1206
 
    # ExtendedTimeout - property
1207
 
    @dbus_service_property(_interface, signature="t",
1208
 
                           access="readwrite")
1209
 
    def ExtendedTimeout_dbus_property(self, value=None):
1210
 
        if value is None:       # get
1211
 
            return dbus.UInt64(self.extended_timeout_milliseconds())
1212
 
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1213
 
    
1214
1102
    # Interval - property
1215
1103
    @dbus_service_property(_interface, signature="t",
1216
1104
                           access="readwrite")
1218
1106
        if value is None:       # get
1219
1107
            return dbus.UInt64(self.interval_milliseconds())
1220
1108
        self.interval = datetime.timedelta(0, 0, 0, value)
 
1109
        # Emit D-Bus signal
 
1110
        self.PropertyChanged(dbus.String("Interval"),
 
1111
                             dbus.UInt64(value, variant_level=1))
1221
1112
        if getattr(self, "checker_initiator_tag", None) is None:
1222
1113
            return
1223
1114
        # Reschedule checker run
1225
1116
        self.checker_initiator_tag = (gobject.timeout_add
1226
1117
                                      (value, self.start_checker))
1227
1118
        self.start_checker()    # Start one now, too
1228
 
    
 
1119
 
1229
1120
    # Checker - property
1230
1121
    @dbus_service_property(_interface, signature="s",
1231
1122
                           access="readwrite")
1233
1124
        if value is None:       # get
1234
1125
            return dbus.String(self.checker_command)
1235
1126
        self.checker_command = value
 
1127
        # Emit D-Bus signal
 
1128
        self.PropertyChanged(dbus.String("Checker"),
 
1129
                             dbus.String(self.checker_command,
 
1130
                                         variant_level=1))
1236
1131
    
1237
1132
    # CheckerRunning - property
1238
1133
    @dbus_service_property(_interface, signature="b",
1265
1160
        self._pipe.send(('init', fpr, address))
1266
1161
        if not self._pipe.recv():
1267
1162
            raise KeyError()
1268
 
    
 
1163
 
1269
1164
    def __getattribute__(self, name):
1270
1165
        if(name == '_pipe'):
1271
1166
            return super(ProxyClient, self).__getattribute__(name)
1278
1173
                self._pipe.send(('funcall', name, args, kwargs))
1279
1174
                return self._pipe.recv()[1]
1280
1175
            return func
1281
 
    
 
1176
 
1282
1177
    def __setattr__(self, name, value):
1283
1178
        if(name == '_pipe'):
1284
1179
            return super(ProxyClient, self).__setattr__(name, value)
1285
1180
        self._pipe.send(('setattr', name, value))
1286
1181
 
1287
 
class ClientDBusTransitional(ClientDBus):
1288
 
    __metaclass__ = AlternateDBusNamesMetaclass
1289
1182
 
1290
1183
class ClientHandler(socketserver.BaseRequestHandler, object):
1291
1184
    """A class to handle client connections.
1299
1192
                        unicode(self.client_address))
1300
1193
            logger.debug("Pipe FD: %d",
1301
1194
                         self.server.child_pipe.fileno())
1302
 
            
 
1195
 
1303
1196
            session = (gnutls.connection
1304
1197
                       .ClientSession(self.request,
1305
1198
                                      gnutls.connection
1306
1199
                                      .X509Credentials()))
1307
 
            
 
1200
 
1308
1201
            # Note: gnutls.connection.X509Credentials is really a
1309
1202
            # generic GnuTLS certificate credentials object so long as
1310
1203
            # no X.509 keys are added to it.  Therefore, we can use it
1311
1204
            # here despite using OpenPGP certificates.
1312
 
            
 
1205
 
1313
1206
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1314
1207
            #                      "+AES-256-CBC", "+SHA1",
1315
1208
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
1321
1214
            (gnutls.library.functions
1322
1215
             .gnutls_priority_set_direct(session._c_object,
1323
1216
                                         priority, None))
1324
 
            
 
1217
 
1325
1218
            # Start communication using the Mandos protocol
1326
1219
            # Get protocol number
1327
1220
            line = self.request.makefile().readline()
1332
1225
            except (ValueError, IndexError, RuntimeError) as error:
1333
1226
                logger.error("Unknown protocol version: %s", error)
1334
1227
                return
1335
 
            
 
1228
 
1336
1229
            # Start GnuTLS connection
1337
1230
            try:
1338
1231
                session.handshake()
1342
1235
                # established.  Just abandon the request.
1343
1236
                return
1344
1237
            logger.debug("Handshake succeeded")
1345
 
            
 
1238
 
1346
1239
            approval_required = False
1347
1240
            try:
1348
1241
                try:
1353
1246
                    logger.warning("Bad certificate: %s", error)
1354
1247
                    return
1355
1248
                logger.debug("Fingerprint: %s", fpr)
1356
 
                
 
1249
 
1357
1250
                try:
1358
1251
                    client = ProxyClient(child_pipe, fpr,
1359
1252
                                         self.client_address)
1367
1260
                
1368
1261
                while True:
1369
1262
                    if not client.enabled:
1370
 
                        logger.info("Client %s is disabled",
 
1263
                        logger.warning("Client %s is disabled",
1371
1264
                                       client.name)
1372
1265
                        if self.server.use_dbus:
1373
1266
                            # Emit D-Bus signal
1374
 
                            client.Rejected("Disabled")
 
1267
                            client.Rejected("Disabled")                    
1375
1268
                        return
1376
1269
                    
1377
1270
                    if client._approved or not client.approval_delay:
1394
1287
                        return
1395
1288
                    
1396
1289
                    #wait until timeout or approved
1397
 
                    #x = float(client
1398
 
                    #          ._timedelta_to_milliseconds(delay))
 
1290
                    #x = float(client._timedelta_to_milliseconds(delay))
1399
1291
                    time = datetime.datetime.now()
1400
1292
                    client.changedstate.acquire()
1401
 
                    (client.changedstate.wait
1402
 
                     (float(client._timedelta_to_milliseconds(delay)
1403
 
                            / 1000)))
 
1293
                    client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1404
1294
                    client.changedstate.release()
1405
1295
                    time2 = datetime.datetime.now()
1406
1296
                    if (time2 - time) >= delay:
1428
1318
                                 sent, len(client.secret)
1429
1319
                                 - (sent_size + sent))
1430
1320
                    sent_size += sent
1431
 
                
 
1321
 
1432
1322
                logger.info("Sending secret to %s", client.name)
1433
1323
                # bump the timeout as if seen
1434
 
                client.checked_ok(client.extended_timeout)
 
1324
                client.checked_ok()
1435
1325
                if self.server.use_dbus:
1436
1326
                    # Emit D-Bus signal
1437
1327
                    client.GotSecret()
1522
1412
        multiprocessing.Process(target = self.sub_process_main,
1523
1413
                                args = (request, address)).start()
1524
1414
 
1525
 
 
1526
1415
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1527
1416
    """ adds a pipe to the MixIn """
1528
1417
    def process_request(self, request, client_address):
1531
1420
        This function creates a new pipe in self.pipe
1532
1421
        """
1533
1422
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1534
 
        
 
1423
 
1535
1424
        super(MultiprocessingMixInWithPipe,
1536
1425
              self).process_request(request, client_address)
1537
1426
        self.child_pipe.close()
1538
1427
        self.add_pipe(parent_pipe)
1539
 
    
 
1428
 
1540
1429
    def add_pipe(self, parent_pipe):
1541
1430
        """Dummy function; override as necessary"""
1542
1431
        raise NotImplementedError
1543
1432
 
1544
 
 
1545
1433
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1546
1434
                     socketserver.TCPServer, object):
1547
1435
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1638
1526
        gobject.io_add_watch(parent_pipe.fileno(),
1639
1527
                             gobject.IO_IN | gobject.IO_HUP,
1640
1528
                             functools.partial(self.handle_ipc,
1641
 
                                               parent_pipe =
1642
 
                                               parent_pipe))
 
1529
                                               parent_pipe = parent_pipe))
1643
1530
        
1644
1531
    def handle_ipc(self, source, condition, parent_pipe=None,
1645
1532
                   client_object=None):
1674
1561
                    client = c
1675
1562
                    break
1676
1563
            else:
1677
 
                logger.info("Client not found for fingerprint: %s, ad"
1678
 
                            "dress: %s", fpr, address)
 
1564
                logger.warning("Client not found for fingerprint: %s, ad"
 
1565
                               "dress: %s", fpr, address)
1679
1566
                if self.use_dbus:
1680
1567
                    # Emit D-Bus signal
1681
 
                    mandos_dbus_service.ClientNotFound(fpr,
1682
 
                                                       address[0])
 
1568
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1683
1569
                parent_pipe.send(False)
1684
1570
                return False
1685
1571
            
1686
1572
            gobject.io_add_watch(parent_pipe.fileno(),
1687
1573
                                 gobject.IO_IN | gobject.IO_HUP,
1688
1574
                                 functools.partial(self.handle_ipc,
1689
 
                                                   parent_pipe =
1690
 
                                                   parent_pipe,
1691
 
                                                   client_object =
1692
 
                                                   client))
 
1575
                                                   parent_pipe = parent_pipe,
 
1576
                                                   client_object = client))
1693
1577
            parent_pipe.send(True)
1694
 
            # remove the old hook in favor of the new above hook on
1695
 
            # same fileno
 
1578
            # remove the old hook in favor of the new above hook on same fileno
1696
1579
            return False
1697
1580
        if command == 'funcall':
1698
1581
            funcname = request[1]
1699
1582
            args = request[2]
1700
1583
            kwargs = request[3]
1701
1584
            
1702
 
            parent_pipe.send(('data', getattr(client_object,
1703
 
                                              funcname)(*args,
1704
 
                                                         **kwargs)))
1705
 
        
 
1585
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
 
1586
 
1706
1587
        if command == 'getattr':
1707
1588
            attrname = request[1]
1708
1589
            if callable(client_object.__getattribute__(attrname)):
1709
1590
                parent_pipe.send(('function',))
1710
1591
            else:
1711
 
                parent_pipe.send(('data', client_object
1712
 
                                  .__getattribute__(attrname)))
 
1592
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1713
1593
        
1714
1594
        if command == 'setattr':
1715
1595
            attrname = request[1]
1716
1596
            value = request[2]
1717
1597
            setattr(client_object, attrname, value)
1718
 
        
 
1598
 
1719
1599
        return True
1720
1600
 
1721
1601
 
1900
1780
    debuglevel = server_settings["debuglevel"]
1901
1781
    use_dbus = server_settings["use_dbus"]
1902
1782
    use_ipv6 = server_settings["use_ipv6"]
1903
 
    
 
1783
 
1904
1784
    if server_settings["servicename"] != "Mandos":
1905
1785
        syslogger.setFormatter(logging.Formatter
1906
1786
                               ('Mandos (%s) [%%(process)d]:'
1908
1788
                                % server_settings["servicename"]))
1909
1789
    
1910
1790
    # Parse config file with clients
1911
 
    client_defaults = { "timeout": "5m",
1912
 
                        "extended_timeout": "15m",
1913
 
                        "interval": "2m",
 
1791
    client_defaults = { "timeout": "1h",
 
1792
                        "interval": "5m",
1914
1793
                        "checker": "fping -q -- %%(host)s",
1915
1794
                        "host": "",
1916
1795
                        "approval_delay": "0s",
1967
1846
        level = getattr(logging, debuglevel.upper())
1968
1847
        syslogger.setLevel(level)
1969
1848
        console.setLevel(level)
1970
 
    
 
1849
 
1971
1850
    if debug:
1972
1851
        # Enable all possible GnuTLS debugging
1973
1852
        
2004
1883
    # End of Avahi example code
2005
1884
    if use_dbus:
2006
1885
        try:
2007
 
            bus_name = dbus.service.BusName("se.recompile.Mandos",
 
1886
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
2008
1887
                                            bus, do_not_queue=True)
2009
 
            old_bus_name = (dbus.service.BusName
2010
 
                            ("se.bsnet.fukt.Mandos", bus,
2011
 
                             do_not_queue=True))
2012
1888
        except dbus.exceptions.NameExistsException as e:
2013
1889
            logger.error(unicode(e) + ", disabling D-Bus")
2014
1890
            use_dbus = False
2027
1903
    
2028
1904
    client_class = Client
2029
1905
    if use_dbus:
2030
 
        client_class = functools.partial(ClientDBusTransitional,
2031
 
                                         bus = bus)
 
1906
        client_class = functools.partial(ClientDBus, bus = bus)
2032
1907
    def client_config_items(config, section):
2033
1908
        special_settings = {
2034
1909
            "approved_by_default":
2064
1939
        del pidfilename
2065
1940
        
2066
1941
        signal.signal(signal.SIGINT, signal.SIG_IGN)
2067
 
    
 
1942
 
2068
1943
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2069
1944
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2070
1945
    
2073
1948
            """A D-Bus proxy object"""
2074
1949
            def __init__(self):
2075
1950
                dbus.service.Object.__init__(self, bus, "/")
2076
 
            _interface = "se.recompile.Mandos"
 
1951
            _interface = "se.bsnet.fukt.Mandos"
2077
1952
            
2078
1953
            @dbus.service.signal(_interface, signature="o")
2079
1954
            def ClientAdded(self, objpath):
2121
1996
            
2122
1997
            del _interface
2123
1998
        
2124
 
        class MandosDBusServiceTransitional(MandosDBusService):
2125
 
            __metaclass__ = AlternateDBusNamesMetaclass
2126
 
        mandos_dbus_service = MandosDBusServiceTransitional()
 
1999
        mandos_dbus_service = MandosDBusService()
2127
2000
    
2128
2001
    def cleanup():
2129
2002
        "Cleanup function; run on exit"
2138
2011
            client.disable(quiet=True)
2139
2012
            if use_dbus:
2140
2013
                # Emit D-Bus signal
2141
 
                mandos_dbus_service.ClientRemoved(client
2142
 
                                                  .dbus_object_path,
 
2014
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2143
2015
                                                  client.name)
2144
2016
    
2145
2017
    atexit.register(cleanup)
2194
2066
    # Must run before the D-Bus bus name gets deregistered
2195
2067
    cleanup()
2196
2068
 
2197
 
 
2198
2069
if __name__ == '__main__':
2199
2070
    main()