/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: Björn Påhlsson
  • Date: 2011-09-26 18:47:38 UTC
  • mto: This revision was merged to the branch mainline in revision 502.
  • Revision ID: belorn@fukt.bsnet.se-20110926184738-ee8kz5vc9pb3393m
updated TODO

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
 
import hashlib
67
65
 
68
66
import dbus
69
67
import dbus.service
74
72
import ctypes.util
75
73
import xml.dom.minidom
76
74
import inspect
77
 
import Crypto.Cipher.AES
78
75
 
79
76
try:
80
77
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
85
82
        SO_BINDTODEVICE = None
86
83
 
87
84
 
88
 
version = "1.4.1"
89
 
stored_state_path = "/var/lib/mandos/clients.pickle"
 
85
version = "1.3.1"
90
86
 
91
 
logger = logging.getLogger()
 
87
#logger = logging.getLogger('mandos')
 
88
logger = logging.Logger('mandos')
92
89
syslogger = (logging.handlers.SysLogHandler
93
90
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
94
91
              address = str("/dev/log")))
95
 
 
96
 
def initlogger(level=logging.WARNING):
97
 
    """init logger and add loglevel"""
98
 
    
99
 
    syslogger.setFormatter(logging.Formatter
100
 
                           ('Mandos [%(process)d]: %(levelname)s:'
101
 
                            ' %(message)s'))
102
 
    logger.addHandler(syslogger)
103
 
    
104
 
    console = logging.StreamHandler()
105
 
    console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
106
 
                                           ' [%(process)d]:'
107
 
                                           ' %(levelname)s:'
108
 
                                           ' %(message)s'))
109
 
    logger.addHandler(console)
110
 
    logger.setLevel(level)
111
 
 
 
92
syslogger.setFormatter(logging.Formatter
 
93
                       ('Mandos [%(process)d]: %(levelname)s:'
 
94
                        ' %(message)s'))
 
95
logger.addHandler(syslogger)
 
96
 
 
97
console = logging.StreamHandler()
 
98
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
 
99
                                       ' %(levelname)s:'
 
100
                                       ' %(message)s'))
 
101
logger.addHandler(console)
112
102
 
113
103
class AvahiError(Exception):
114
104
    def __init__(self, value, *args, **kwargs):
169
159
                            " after %i retries, exiting.",
170
160
                            self.rename_count)
171
161
            raise AvahiServiceError("Too many renames")
172
 
        self.name = unicode(self.server
173
 
                            .GetAlternativeServiceName(self.name))
 
162
        self.name = unicode(self.server.GetAlternativeServiceName(self.name))
174
163
        logger.info("Changing Zeroconf service name to %r ...",
175
164
                    self.name)
 
165
        syslogger.setFormatter(logging.Formatter
 
166
                               ('Mandos (%s) [%%(process)d]:'
 
167
                                ' %%(levelname)s: %%(message)s'
 
168
                                % self.name))
176
169
        self.remove()
177
170
        try:
178
171
            self.add()
198
191
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
199
192
        self.entry_group_state_changed_match = (
200
193
            self.group.connect_to_signal(
201
 
                'StateChanged', self.entry_group_state_changed))
 
194
                'StateChanged', self .entry_group_state_changed))
202
195
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
203
196
                     self.name, self.type)
204
197
        self.group.AddService(
270
263
                                 self.server_state_changed)
271
264
        self.server_state_changed(self.server.GetState())
272
265
 
273
 
class AvahiServiceToSyslog(AvahiService):
274
 
    def rename(self):
275
 
        """Add the new name to the syslog messages"""
276
 
        ret = AvahiService.rename(self)
277
 
        syslogger.setFormatter(logging.Formatter
278
 
                               ('Mandos (%s) [%%(process)d]:'
279
 
                                ' %%(levelname)s: %%(message)s'
280
 
                                % self.name))
281
 
        return ret
282
266
 
283
267
def _timedelta_to_milliseconds(td):
284
268
    "Convert a datetime.timedelta() to milliseconds"
303
287
                     instance %(name)s can be used in the command.
304
288
    checker_initiator_tag: a gobject event source tag, or None
305
289
    created:    datetime.datetime(); (UTC) object creation
306
 
    client_structure: Object describing what attributes a client has
307
 
                      and is used for storing the client at exit
308
290
    current_checker_command: string; current running checker_command
 
291
    disable_hook:  If set, called by disable() as disable_hook(self)
309
292
    disable_initiator_tag: a gobject event source tag, or None
310
293
    enabled:    bool()
311
294
    fingerprint: string (40 or 32 hexadecimal digits); used to
314
297
    interval:   datetime.timedelta(); How often to start a new checker
315
298
    last_approval_request: datetime.datetime(); (UTC) or None
316
299
    last_checked_ok: datetime.datetime(); (UTC) or None
317
 
    last_checker_status: integer between 0 and 255 reflecting exit status
318
 
                         of last checker. -1 reflect crashed checker,
319
 
                         or None.
320
300
    last_enabled: datetime.datetime(); (UTC)
321
301
    name:       string; from the config file, used in log messages and
322
302
                        D-Bus identifiers
333
313
                          "created", "enabled", "fingerprint",
334
314
                          "host", "interval", "last_checked_ok",
335
315
                          "last_enabled", "name", "timeout")
336
 
    
 
316
        
337
317
    def timeout_milliseconds(self):
338
318
        "Return the 'timeout' attribute in milliseconds"
339
319
        return _timedelta_to_milliseconds(self.timeout)
340
 
    
 
320
 
341
321
    def extended_timeout_milliseconds(self):
342
322
        "Return the 'extended_timeout' attribute in milliseconds"
343
 
        return _timedelta_to_milliseconds(self.extended_timeout)
 
323
        return _timedelta_to_milliseconds(self.extended_timeout)    
344
324
    
345
325
    def interval_milliseconds(self):
346
326
        "Return the 'interval' attribute in milliseconds"
347
327
        return _timedelta_to_milliseconds(self.interval)
348
 
    
 
328
 
349
329
    def approval_delay_milliseconds(self):
350
330
        return _timedelta_to_milliseconds(self.approval_delay)
351
331
    
352
 
    def __init__(self, name = None, config=None):
 
332
    def __init__(self, name = None, disable_hook=None, config=None):
353
333
        """Note: the 'checker' key in 'config' sets the
354
334
        'checker_command' attribute and *not* the 'checker'
355
335
        attribute."""
375
355
                            % self.name)
376
356
        self.host = config.get("host", "")
377
357
        self.created = datetime.datetime.utcnow()
378
 
        self.enabled = True
 
358
        self.enabled = False
379
359
        self.last_approval_request = None
380
 
        self.last_enabled = datetime.datetime.utcnow()
 
360
        self.last_enabled = None
381
361
        self.last_checked_ok = None
382
 
        self.last_checker_status = None
383
362
        self.timeout = string_to_delta(config["timeout"])
384
 
        self.extended_timeout = string_to_delta(config
385
 
                                                ["extended_timeout"])
 
363
        self.extended_timeout = string_to_delta(config["extended_timeout"])
386
364
        self.interval = string_to_delta(config["interval"])
 
365
        self.disable_hook = disable_hook
387
366
        self.checker = None
388
367
        self.checker_initiator_tag = None
389
368
        self.disable_initiator_tag = None
390
 
        self.expires = datetime.datetime.utcnow() + self.timeout
 
369
        self.expires = None
391
370
        self.checker_callback_tag = None
392
371
        self.checker_command = config["checker"]
393
372
        self.current_checker_command = None
 
373
        self.last_connect = None
394
374
        self._approved = None
395
375
        self.approved_by_default = config.get("approved_by_default",
396
376
                                              True)
399
379
            config["approval_delay"])
400
380
        self.approval_duration = string_to_delta(
401
381
            config["approval_duration"])
402
 
        self.changedstate = (multiprocessing_manager
403
 
                             .Condition(multiprocessing_manager
404
 
                                        .Lock()))
405
 
        self.client_structure = [attr for attr in self.__dict__.iterkeys() if not attr.startswith("_")]
406
 
        self.client_structure.append("client_structure")
407
 
 
408
 
 
409
 
        for name, t in inspect.getmembers(type(self),
410
 
                                          lambda obj: isinstance(obj, property)):
411
 
            if not name.startswith("_"):
412
 
                self.client_structure.append(name)
 
382
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
413
383
    
414
 
    # Send notice to process children that client state has changed
415
384
    def send_changedstate(self):
416
 
        with self.changedstate:
417
 
            self.changedstate.notify_all()
418
 
    
 
385
        self.changedstate.acquire()
 
386
        self.changedstate.notify_all()
 
387
        self.changedstate.release()
 
388
        
419
389
    def enable(self):
420
390
        """Start this client's checker and timeout hooks"""
421
391
        if getattr(self, "enabled", False):
422
392
            # Already enabled
423
393
            return
424
394
        self.send_changedstate()
 
395
        # Schedule a new checker to be started an 'interval' from now,
 
396
        # and every interval from then on.
 
397
        self.checker_initiator_tag = (gobject.timeout_add
 
398
                                      (self.interval_milliseconds(),
 
399
                                       self.start_checker))
 
400
        # Schedule a disable() when 'timeout' has passed
425
401
        self.expires = datetime.datetime.utcnow() + self.timeout
 
402
        self.disable_initiator_tag = (gobject.timeout_add
 
403
                                   (self.timeout_milliseconds(),
 
404
                                    self.disable))
426
405
        self.enabled = True
427
406
        self.last_enabled = datetime.datetime.utcnow()
428
 
        self.init_checker()
 
407
        # Also start a new checker *right now*.
 
408
        self.start_checker()
429
409
    
430
410
    def disable(self, quiet=True):
431
411
        """Disable this client."""
443
423
            gobject.source_remove(self.checker_initiator_tag)
444
424
            self.checker_initiator_tag = None
445
425
        self.stop_checker()
 
426
        if self.disable_hook:
 
427
            self.disable_hook(self)
446
428
        self.enabled = False
447
429
        # Do not run this again if called by a gobject.timeout_add
448
430
        return False
449
431
    
450
432
    def __del__(self):
 
433
        self.disable_hook = None
451
434
        self.disable()
452
 
 
453
 
    def init_checker(self):
454
 
        # Schedule a new checker to be started an 'interval' from now,
455
 
        # and every interval from then on.
456
 
        self.checker_initiator_tag = (gobject.timeout_add
457
 
                                      (self.interval_milliseconds(),
458
 
                                       self.start_checker))
459
 
        # Schedule a disable() when 'timeout' has passed
460
 
        self.disable_initiator_tag = (gobject.timeout_add
461
 
                                   (self.timeout_milliseconds(),
462
 
                                    self.disable))
463
 
        # Also start a new checker *right now*.
464
 
        self.start_checker()
465
 
 
466
 
        
 
435
    
467
436
    def checker_callback(self, pid, condition, command):
468
437
        """The checker has completed, so take appropriate actions."""
469
438
        self.checker_callback_tag = None
470
439
        self.checker = None
471
440
        if os.WIFEXITED(condition):
472
 
            self.last_checker_status =  os.WEXITSTATUS(condition)
473
 
            if self.last_checker_status == 0:
 
441
            exitstatus = os.WEXITSTATUS(condition)
 
442
            if exitstatus == 0:
474
443
                logger.info("Checker for %(name)s succeeded",
475
444
                            vars(self))
476
445
                self.checked_ok()
478
447
                logger.info("Checker for %(name)s failed",
479
448
                            vars(self))
480
449
        else:
481
 
            self.last_checker_status = -1
482
450
            logger.warning("Checker for %(name)s crashed?",
483
451
                           vars(self))
484
452
    
491
459
        if timeout is None:
492
460
            timeout = self.timeout
493
461
        self.last_checked_ok = datetime.datetime.utcnow()
494
 
        if self.disable_initiator_tag is not None:
495
 
            gobject.source_remove(self.disable_initiator_tag)
496
 
        if getattr(self, "enabled", False):
497
 
            self.disable_initiator_tag = (gobject.timeout_add
498
 
                                          (_timedelta_to_milliseconds
499
 
                                           (timeout), self.disable))
500
 
            self.expires = datetime.datetime.utcnow() + timeout
 
462
        gobject.source_remove(self.disable_initiator_tag)
 
463
        self.expires = datetime.datetime.utcnow() + timeout
 
464
        self.disable_initiator_tag = (gobject.timeout_add
 
465
                                      (_timedelta_to_milliseconds(timeout),
 
466
                                       self.disable))
501
467
    
502
468
    def need_approval(self):
503
469
        self.last_approval_request = datetime.datetime.utcnow()
543
509
                                       'replace')))
544
510
                    for attr in
545
511
                    self.runtime_expansions)
546
 
                
 
512
 
547
513
                try:
548
514
                    command = self.checker_command % escaped_attrs
549
515
                except TypeError as error:
595
561
                raise
596
562
        self.checker = None
597
563
 
598
 
    # Encrypts a client secret and stores it in a varible encrypted_secret
599
 
    def encrypt_secret(self, key):
600
 
        # Encryption-key need to be of a specific size, so we hash inputed key
601
 
        hasheng = hashlib.sha256()
602
 
        hasheng.update(key)
603
 
        encryptionkey = hasheng.digest()
604
 
 
605
 
        # Create validation hash so we know at decryption if it was sucessful
606
 
        hasheng = hashlib.sha256()
607
 
        hasheng.update(self.secret)
608
 
        validationhash = hasheng.digest()
609
 
 
610
 
        # Encrypt secret
611
 
        iv = os.urandom(Crypto.Cipher.AES.block_size)
612
 
        ciphereng = Crypto.Cipher.AES.new(encryptionkey,
613
 
                                        Crypto.Cipher.AES.MODE_CFB, iv)
614
 
        ciphertext = ciphereng.encrypt(validationhash+self.secret)
615
 
        self.encrypted_secret = (ciphertext, iv)
616
 
 
617
 
    # Decrypt a encrypted client secret
618
 
    def decrypt_secret(self, key):
619
 
        # Decryption-key need to be of a specific size, so we hash inputed key
620
 
        hasheng = hashlib.sha256()
621
 
        hasheng.update(key)
622
 
        encryptionkey = hasheng.digest()
623
 
 
624
 
        # Decrypt encrypted secret
625
 
        ciphertext, iv = self.encrypted_secret
626
 
        ciphereng = Crypto.Cipher.AES.new(encryptionkey,
627
 
                                        Crypto.Cipher.AES.MODE_CFB, iv)
628
 
        plain = ciphereng.decrypt(ciphertext)
629
 
 
630
 
        # Validate decrypted secret to know if it was succesful
631
 
        hasheng = hashlib.sha256()
632
 
        validationhash = plain[:hasheng.digest_size]
633
 
        secret = plain[hasheng.digest_size:]
634
 
        hasheng.update(secret)
635
 
 
636
 
        # if validation fails, we use key as new secret. Otherwhise, we use
637
 
        # the decrypted secret
638
 
        if hasheng.digest() == validationhash:
639
 
            self.secret = secret
640
 
        else:
641
 
            self.secret = key
642
 
        del self.encrypted_secret
643
 
 
644
 
 
645
564
def dbus_service_property(dbus_interface, signature="v",
646
565
                          access="readwrite", byte_arrays=False):
647
566
    """Decorators for marking methods of a DBusObjectWithProperties to
693
612
 
694
613
class DBusObjectWithProperties(dbus.service.Object):
695
614
    """A D-Bus object with properties.
696
 
    
 
615
 
697
616
    Classes inheriting from this can use the dbus_service_property
698
617
    decorator to expose methods as D-Bus properties.  It exposes the
699
618
    standard Get(), Set(), and GetAll() methods on the D-Bus.
706
625
    def _get_all_dbus_properties(self):
707
626
        """Returns a generator of (name, attribute) pairs
708
627
        """
709
 
        return ((prop.__get__(self)._dbus_name, prop.__get__(self))
710
 
                for cls in self.__class__.__mro__
 
628
        return ((prop._dbus_name, prop)
711
629
                for name, prop in
712
 
                inspect.getmembers(cls, self._is_dbus_property))
 
630
                inspect.getmembers(self, self._is_dbus_property))
713
631
    
714
632
    def _get_dbus_property(self, interface_name, property_name):
715
633
        """Returns a bound method if one exists which is a D-Bus
716
634
        property with the specified name and interface.
717
635
        """
718
 
        for cls in  self.__class__.__mro__:
719
 
            for name, value in (inspect.getmembers
720
 
                                (cls, self._is_dbus_property)):
721
 
                if (value._dbus_name == property_name
722
 
                    and value._dbus_interface == interface_name):
723
 
                    return value.__get__(self)
724
 
        
 
636
        for name in (property_name,
 
637
                     property_name + "_dbus_property"):
 
638
            prop = getattr(self, name, None)
 
639
            if (prop is None
 
640
                or not self._is_dbus_property(prop)
 
641
                or prop._dbus_name != property_name
 
642
                or (interface_name and prop._dbus_interface
 
643
                    and interface_name != prop._dbus_interface)):
 
644
                continue
 
645
            return prop
725
646
        # No such property
726
647
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
727
648
                                   + interface_name + "."
761
682
    def GetAll(self, interface_name):
762
683
        """Standard D-Bus property GetAll() method, see D-Bus
763
684
        standard.
764
 
        
 
685
 
765
686
        Note: Will not include properties with access="write".
766
687
        """
767
688
        all = {}
836
757
    return dbus.String(dt.isoformat(),
837
758
                       variant_level=variant_level)
838
759
 
839
 
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
840
 
                                  .__metaclass__):
841
 
    """Applied to an empty subclass of a D-Bus object, this metaclass
842
 
    will add additional D-Bus attributes matching a certain pattern.
843
 
    """
844
 
    def __new__(mcs, name, bases, attr):
845
 
        # Go through all the base classes which could have D-Bus
846
 
        # methods, signals, or properties in them
847
 
        for base in (b for b in bases
848
 
                     if issubclass(b, dbus.service.Object)):
849
 
            # Go though all attributes of the base class
850
 
            for attrname, attribute in inspect.getmembers(base):
851
 
                # Ignore non-D-Bus attributes, and D-Bus attributes
852
 
                # with the wrong interface name
853
 
                if (not hasattr(attribute, "_dbus_interface")
854
 
                    or not attribute._dbus_interface
855
 
                    .startswith("se.recompile.Mandos")):
856
 
                    continue
857
 
                # Create an alternate D-Bus interface name based on
858
 
                # the current name
859
 
                alt_interface = (attribute._dbus_interface
860
 
                                 .replace("se.recompile.Mandos",
861
 
                                          "se.bsnet.fukt.Mandos"))
862
 
                # Is this a D-Bus signal?
863
 
                if getattr(attribute, "_dbus_is_signal", False):
864
 
                    # Extract the original non-method function by
865
 
                    # black magic
866
 
                    nonmethod_func = (dict(
867
 
                            zip(attribute.func_code.co_freevars,
868
 
                                attribute.__closure__))["func"]
869
 
                                      .cell_contents)
870
 
                    # Create a new, but exactly alike, function
871
 
                    # object, and decorate it to be a new D-Bus signal
872
 
                    # with the alternate D-Bus interface name
873
 
                    new_function = (dbus.service.signal
874
 
                                    (alt_interface,
875
 
                                     attribute._dbus_signature)
876
 
                                    (types.FunctionType(
877
 
                                nonmethod_func.func_code,
878
 
                                nonmethod_func.func_globals,
879
 
                                nonmethod_func.func_name,
880
 
                                nonmethod_func.func_defaults,
881
 
                                nonmethod_func.func_closure)))
882
 
                    # Define a creator of a function to call both the
883
 
                    # old and new functions, so both the old and new
884
 
                    # signals gets sent when the function is called
885
 
                    def fixscope(func1, func2):
886
 
                        """This function is a scope container to pass
887
 
                        func1 and func2 to the "call_both" function
888
 
                        outside of its arguments"""
889
 
                        def call_both(*args, **kwargs):
890
 
                            """This function will emit two D-Bus
891
 
                            signals by calling func1 and func2"""
892
 
                            func1(*args, **kwargs)
893
 
                            func2(*args, **kwargs)
894
 
                        return call_both
895
 
                    # Create the "call_both" function and add it to
896
 
                    # the class
897
 
                    attr[attrname] = fixscope(attribute,
898
 
                                              new_function)
899
 
                # Is this a D-Bus method?
900
 
                elif getattr(attribute, "_dbus_is_method", False):
901
 
                    # Create a new, but exactly alike, function
902
 
                    # object.  Decorate it to be a new D-Bus method
903
 
                    # with the alternate D-Bus interface name.  Add it
904
 
                    # to the class.
905
 
                    attr[attrname] = (dbus.service.method
906
 
                                      (alt_interface,
907
 
                                       attribute._dbus_in_signature,
908
 
                                       attribute._dbus_out_signature)
909
 
                                      (types.FunctionType
910
 
                                       (attribute.func_code,
911
 
                                        attribute.func_globals,
912
 
                                        attribute.func_name,
913
 
                                        attribute.func_defaults,
914
 
                                        attribute.func_closure)))
915
 
                # Is this a D-Bus property?
916
 
                elif getattr(attribute, "_dbus_is_property", False):
917
 
                    # Create a new, but exactly alike, function
918
 
                    # object, and decorate it to be a new D-Bus
919
 
                    # property with the alternate D-Bus interface
920
 
                    # name.  Add it to the class.
921
 
                    attr[attrname] = (dbus_service_property
922
 
                                      (alt_interface,
923
 
                                       attribute._dbus_signature,
924
 
                                       attribute._dbus_access,
925
 
                                       attribute
926
 
                                       ._dbus_get_args_options
927
 
                                       ["byte_arrays"])
928
 
                                      (types.FunctionType
929
 
                                       (attribute.func_code,
930
 
                                        attribute.func_globals,
931
 
                                        attribute.func_name,
932
 
                                        attribute.func_defaults,
933
 
                                        attribute.func_closure)))
934
 
        return type.__new__(mcs, name, bases, attr)
935
 
 
936
760
class ClientDBus(Client, DBusObjectWithProperties):
937
761
    """A Client class using D-Bus
938
762
    
947
771
    # dbus.service.Object doesn't use super(), so we can't either.
948
772
    
949
773
    def __init__(self, bus = None, *args, **kwargs):
 
774
        self._approvals_pending = 0
950
775
        self.bus = bus
951
776
        Client.__init__(self, *args, **kwargs)
952
 
 
953
 
        self._approvals_pending = 0
954
777
        # Only now, when this client is initialized, can it show up on
955
778
        # the D-Bus
956
779
        client_object_name = unicode(self.name).translate(
964
787
    def notifychangeproperty(transform_func,
965
788
                             dbus_name, type_func=lambda x: x,
966
789
                             variant_level=1):
967
 
        """ Modify a variable so that it's a property which announces
968
 
        its changes to DBus.
969
 
 
970
 
        transform_fun: Function that takes a value and a variant_level
971
 
                       and transforms it to a D-Bus type.
972
 
        dbus_name: D-Bus name of the variable
 
790
        """ Modify a variable so that its a property that announce its
 
791
        changes to DBus.
 
792
        transform_fun: Function that takes a value and transform it to
 
793
                       DBus type.
 
794
        dbus_name: DBus name of the variable
973
795
        type_func: Function that transform the value before sending it
974
 
                   to the D-Bus.  Default: no transform
975
 
        variant_level: D-Bus variant level.  Default: 1
 
796
                   to DBus
 
797
        variant_level: DBus variant level. default: 1
976
798
        """
977
 
        attrname = "_{0}".format(dbus_name)
 
799
        real_value = [None,]
978
800
        def setter(self, value):
 
801
            old_value = real_value[0]
 
802
            real_value[0] = value
979
803
            if hasattr(self, "dbus_object_path"):
980
 
                if (not hasattr(self, attrname) or
981
 
                    type_func(getattr(self, attrname, None))
982
 
                    != type_func(value)):
983
 
                    dbus_value = transform_func(type_func(value),
984
 
                                                variant_level
985
 
                                                =variant_level)
 
804
                if type_func(old_value) != type_func(real_value[0]):
 
805
                    dbus_value = transform_func(type_func(real_value[0]),
 
806
                                                variant_level)
986
807
                    self.PropertyChanged(dbus.String(dbus_name),
987
808
                                         dbus_value)
988
 
            setattr(self, attrname, value)
989
 
        
990
 
        return property(lambda self: getattr(self, attrname), setter)
991
 
    
992
 
    
 
809
 
 
810
        return property(lambda self: real_value[0], setter)
 
811
 
 
812
 
993
813
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
994
814
    approvals_pending = notifychangeproperty(dbus.Boolean,
995
815
                                             "ApprovalPending",
998
818
    last_enabled = notifychangeproperty(datetime_to_dbus,
999
819
                                        "LastEnabled")
1000
820
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1001
 
                                   type_func = lambda checker:
1002
 
                                       checker is not None)
 
821
                                   type_func = lambda checker: checker is not None)
1003
822
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1004
823
                                           "LastCheckedOK")
1005
 
    last_approval_request = notifychangeproperty(
1006
 
        datetime_to_dbus, "LastApprovalRequest")
 
824
    last_approval_request = notifychangeproperty(datetime_to_dbus,
 
825
                                                 "LastApprovalRequest")
1007
826
    approved_by_default = notifychangeproperty(dbus.Boolean,
1008
827
                                               "ApprovedByDefault")
1009
 
    approval_delay = notifychangeproperty(dbus.UInt16,
1010
 
                                          "ApprovalDelay",
1011
 
                                          type_func =
1012
 
                                          _timedelta_to_milliseconds)
1013
 
    approval_duration = notifychangeproperty(
1014
 
        dbus.UInt16, "ApprovalDuration",
1015
 
        type_func = _timedelta_to_milliseconds)
 
828
    approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
 
829
                                          type_func = _timedelta_to_milliseconds)
 
830
    approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
 
831
                                             type_func = _timedelta_to_milliseconds)
1016
832
    host = notifychangeproperty(dbus.String, "Host")
1017
833
    timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1018
 
                                   type_func =
1019
 
                                   _timedelta_to_milliseconds)
1020
 
    extended_timeout = notifychangeproperty(
1021
 
        dbus.UInt16, "ExtendedTimeout",
1022
 
        type_func = _timedelta_to_milliseconds)
1023
 
    interval = notifychangeproperty(dbus.UInt16,
1024
 
                                    "Interval",
1025
 
                                    type_func =
1026
 
                                    _timedelta_to_milliseconds)
 
834
                                   type_func = _timedelta_to_milliseconds)
 
835
    extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
 
836
                                            type_func = _timedelta_to_milliseconds)
 
837
    interval = notifychangeproperty(dbus.UInt16, "Interval",
 
838
                                    type_func = _timedelta_to_milliseconds)
1027
839
    checker_command = notifychangeproperty(dbus.String, "Checker")
1028
840
    
1029
841
    del notifychangeproperty
1055
867
        
1056
868
        return Client.checker_callback(self, pid, condition, command,
1057
869
                                       *args, **kwargs)
1058
 
    
 
870
 
1059
871
    def start_checker(self, *args, **kwargs):
1060
872
        old_checker = self.checker
1061
873
        if self.checker is not None:
1083
895
    
1084
896
    
1085
897
    ## D-Bus methods, signals & properties
1086
 
    _interface = "se.recompile.Mandos.Client"
 
898
    _interface = "se.bsnet.fukt.Mandos.Client"
1087
899
    
1088
900
    ## Signals
1089
901
    
1126
938
        "D-Bus signal"
1127
939
        return self.need_approval()
1128
940
    
1129
 
    # NeRwequest - signal
1130
 
    @dbus.service.signal(_interface, signature="s")
1131
 
    def NewRequest(self, ip):
1132
 
        """D-Bus signal
1133
 
        Is sent after a client request a password.
1134
 
        """
1135
 
        pass
1136
 
 
1137
941
    ## Methods
1138
942
    
1139
943
    # Approve - method
1272
1076
        gobject.source_remove(self.disable_initiator_tag)
1273
1077
        self.disable_initiator_tag = None
1274
1078
        self.expires = None
1275
 
        time_to_die = _timedelta_to_milliseconds((self
1276
 
                                                  .last_checked_ok
1277
 
                                                  + self.timeout)
1278
 
                                                 - datetime.datetime
1279
 
                                                 .utcnow())
 
1079
        time_to_die = (self.
 
1080
                       _timedelta_to_milliseconds((self
 
1081
                                                   .last_checked_ok
 
1082
                                                   + self.timeout)
 
1083
                                                  - datetime.datetime
 
1084
                                                  .utcnow()))
1280
1085
        if time_to_die <= 0:
1281
1086
            # The timeout has passed
1282
1087
            self.disable()
1283
1088
        else:
1284
1089
            self.expires = (datetime.datetime.utcnow()
1285
 
                            + datetime.timedelta(milliseconds =
1286
 
                                                 time_to_die))
 
1090
                            + datetime.timedelta(milliseconds = time_to_die))
1287
1091
            self.disable_initiator_tag = (gobject.timeout_add
1288
1092
                                          (time_to_die, self.disable))
1289
 
    
 
1093
 
1290
1094
    # ExtendedTimeout - property
1291
1095
    @dbus_service_property(_interface, signature="t",
1292
1096
                           access="readwrite")
1294
1098
        if value is None:       # get
1295
1099
            return dbus.UInt64(self.extended_timeout_milliseconds())
1296
1100
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1297
 
    
 
1101
 
1298
1102
    # Interval - property
1299
1103
    @dbus_service_property(_interface, signature="t",
1300
1104
                           access="readwrite")
1309
1113
        self.checker_initiator_tag = (gobject.timeout_add
1310
1114
                                      (value, self.start_checker))
1311
1115
        self.start_checker()    # Start one now, too
1312
 
    
 
1116
 
1313
1117
    # Checker - property
1314
1118
    @dbus_service_property(_interface, signature="s",
1315
1119
                           access="readwrite")
1349
1153
        self._pipe.send(('init', fpr, address))
1350
1154
        if not self._pipe.recv():
1351
1155
            raise KeyError()
1352
 
    
 
1156
 
1353
1157
    def __getattribute__(self, name):
1354
1158
        if(name == '_pipe'):
1355
1159
            return super(ProxyClient, self).__getattribute__(name)
1362
1166
                self._pipe.send(('funcall', name, args, kwargs))
1363
1167
                return self._pipe.recv()[1]
1364
1168
            return func
1365
 
    
 
1169
 
1366
1170
    def __setattr__(self, name, value):
1367
1171
        if(name == '_pipe'):
1368
1172
            return super(ProxyClient, self).__setattr__(name, value)
1369
1173
        self._pipe.send(('setattr', name, value))
1370
1174
 
1371
 
class ClientDBusTransitional(ClientDBus):
1372
 
    __metaclass__ = AlternateDBusNamesMetaclass
1373
1175
 
1374
1176
class ClientHandler(socketserver.BaseRequestHandler, object):
1375
1177
    """A class to handle client connections.
1383
1185
                        unicode(self.client_address))
1384
1186
            logger.debug("Pipe FD: %d",
1385
1187
                         self.server.child_pipe.fileno())
1386
 
            
 
1188
 
1387
1189
            session = (gnutls.connection
1388
1190
                       .ClientSession(self.request,
1389
1191
                                      gnutls.connection
1390
1192
                                      .X509Credentials()))
1391
 
            
 
1193
 
1392
1194
            # Note: gnutls.connection.X509Credentials is really a
1393
1195
            # generic GnuTLS certificate credentials object so long as
1394
1196
            # no X.509 keys are added to it.  Therefore, we can use it
1395
1197
            # here despite using OpenPGP certificates.
1396
 
            
 
1198
 
1397
1199
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1398
1200
            #                      "+AES-256-CBC", "+SHA1",
1399
1201
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
1405
1207
            (gnutls.library.functions
1406
1208
             .gnutls_priority_set_direct(session._c_object,
1407
1209
                                         priority, None))
1408
 
            
 
1210
 
1409
1211
            # Start communication using the Mandos protocol
1410
1212
            # Get protocol number
1411
1213
            line = self.request.makefile().readline()
1416
1218
            except (ValueError, IndexError, RuntimeError) as error:
1417
1219
                logger.error("Unknown protocol version: %s", error)
1418
1220
                return
1419
 
            
 
1221
 
1420
1222
            # Start GnuTLS connection
1421
1223
            try:
1422
1224
                session.handshake()
1426
1228
                # established.  Just abandon the request.
1427
1229
                return
1428
1230
            logger.debug("Handshake succeeded")
1429
 
            
 
1231
 
1430
1232
            approval_required = False
1431
1233
            try:
1432
1234
                try:
1437
1239
                    logger.warning("Bad certificate: %s", error)
1438
1240
                    return
1439
1241
                logger.debug("Fingerprint: %s", fpr)
1440
 
                if self.server.use_dbus:
1441
 
                    # Emit D-Bus signal
1442
 
                    client.NewRequest(str(self.client_address))
1443
 
                
 
1242
 
1444
1243
                try:
1445
1244
                    client = ProxyClient(child_pipe, fpr,
1446
1245
                                         self.client_address)
1458
1257
                                       client.name)
1459
1258
                        if self.server.use_dbus:
1460
1259
                            # Emit D-Bus signal
1461
 
                            client.Rejected("Disabled")
 
1260
                            client.Rejected("Disabled")                    
1462
1261
                        return
1463
1262
                    
1464
1263
                    if client._approved or not client.approval_delay:
1481
1280
                        return
1482
1281
                    
1483
1282
                    #wait until timeout or approved
 
1283
                    #x = float(client._timedelta_to_milliseconds(delay))
1484
1284
                    time = datetime.datetime.now()
1485
1285
                    client.changedstate.acquire()
1486
 
                    (client.changedstate.wait
1487
 
                     (float(client._timedelta_to_milliseconds(delay)
1488
 
                            / 1000)))
 
1286
                    client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1489
1287
                    client.changedstate.release()
1490
1288
                    time2 = datetime.datetime.now()
1491
1289
                    if (time2 - time) >= delay:
1513
1311
                                 sent, len(client.secret)
1514
1312
                                 - (sent_size + sent))
1515
1313
                    sent_size += sent
1516
 
                
 
1314
 
1517
1315
                logger.info("Sending secret to %s", client.name)
1518
 
                # bump the timeout using extended_timeout
 
1316
                # bump the timeout as if seen
1519
1317
                client.checked_ok(client.extended_timeout)
1520
1318
                if self.server.use_dbus:
1521
1319
                    # Emit D-Bus signal
1601
1399
        except:
1602
1400
            self.handle_error(request, address)
1603
1401
        self.close_request(request)
1604
 
    
 
1402
            
1605
1403
    def process_request(self, request, address):
1606
1404
        """Start a new process to process the request."""
1607
 
        proc = multiprocessing.Process(target = self.sub_process_main,
1608
 
                                       args = (request,
1609
 
                                               address))
1610
 
        proc.start()
1611
 
        return proc
1612
 
 
 
1405
        multiprocessing.Process(target = self.sub_process_main,
 
1406
                                args = (request, address)).start()
1613
1407
 
1614
1408
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1615
1409
    """ adds a pipe to the MixIn """
1619
1413
        This function creates a new pipe in self.pipe
1620
1414
        """
1621
1415
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1622
 
        
1623
 
        proc = MultiprocessingMixIn.process_request(self, request,
1624
 
                                                    client_address)
 
1416
 
 
1417
        super(MultiprocessingMixInWithPipe,
 
1418
              self).process_request(request, client_address)
1625
1419
        self.child_pipe.close()
1626
 
        self.add_pipe(parent_pipe, proc)
1627
 
    
1628
 
    def add_pipe(self, parent_pipe, proc):
 
1420
        self.add_pipe(parent_pipe)
 
1421
 
 
1422
    def add_pipe(self, parent_pipe):
1629
1423
        """Dummy function; override as necessary"""
1630
1424
        raise NotImplementedError
1631
1425
 
1632
 
 
1633
1426
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1634
1427
                     socketserver.TCPServer, object):
1635
1428
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1709
1502
        self.enabled = False
1710
1503
        self.clients = clients
1711
1504
        if self.clients is None:
1712
 
            self.clients = {}
 
1505
            self.clients = set()
1713
1506
        self.use_dbus = use_dbus
1714
1507
        self.gnutls_priority = gnutls_priority
1715
1508
        IPv6_TCPServer.__init__(self, server_address,
1719
1512
    def server_activate(self):
1720
1513
        if self.enabled:
1721
1514
            return socketserver.TCPServer.server_activate(self)
1722
 
    
1723
1515
    def enable(self):
1724
1516
        self.enabled = True
1725
 
    
1726
 
    def add_pipe(self, parent_pipe, proc):
 
1517
    def add_pipe(self, parent_pipe):
1727
1518
        # Call "handle_ipc" for both data and EOF events
1728
1519
        gobject.io_add_watch(parent_pipe.fileno(),
1729
1520
                             gobject.IO_IN | gobject.IO_HUP,
1730
1521
                             functools.partial(self.handle_ipc,
1731
 
                                               parent_pipe =
1732
 
                                               parent_pipe,
1733
 
                                               proc = proc))
1734
 
    
 
1522
                                               parent_pipe = parent_pipe))
 
1523
        
1735
1524
    def handle_ipc(self, source, condition, parent_pipe=None,
1736
 
                   proc = None, client_object=None):
 
1525
                   client_object=None):
1737
1526
        condition_names = {
1738
1527
            gobject.IO_IN: "IN",   # There is data to read.
1739
1528
            gobject.IO_OUT: "OUT", # Data can be written (without
1748
1537
                                       for cond, name in
1749
1538
                                       condition_names.iteritems()
1750
1539
                                       if cond & condition)
1751
 
        # error, or the other end of multiprocessing.Pipe has closed
 
1540
        # error or the other end of multiprocessing.Pipe has closed
1752
1541
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
1753
 
            # Wait for other process to exit
1754
 
            proc.join()
1755
1542
            return False
1756
1543
        
1757
1544
        # Read a request from the child
1762
1549
            fpr = request[1]
1763
1550
            address = request[2]
1764
1551
            
1765
 
            for c in self.clients.itervalues():
 
1552
            for c in self.clients:
1766
1553
                if c.fingerprint == fpr:
1767
1554
                    client = c
1768
1555
                    break
1771
1558
                            "dress: %s", fpr, address)
1772
1559
                if self.use_dbus:
1773
1560
                    # Emit D-Bus signal
1774
 
                    mandos_dbus_service.ClientNotFound(fpr,
1775
 
                                                       address[0])
 
1561
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1776
1562
                parent_pipe.send(False)
1777
1563
                return False
1778
1564
            
1779
1565
            gobject.io_add_watch(parent_pipe.fileno(),
1780
1566
                                 gobject.IO_IN | gobject.IO_HUP,
1781
1567
                                 functools.partial(self.handle_ipc,
1782
 
                                                   parent_pipe =
1783
 
                                                   parent_pipe,
1784
 
                                                   proc = proc,
1785
 
                                                   client_object =
1786
 
                                                   client))
 
1568
                                                   parent_pipe = parent_pipe,
 
1569
                                                   client_object = client))
1787
1570
            parent_pipe.send(True)
1788
 
            # remove the old hook in favor of the new above hook on
1789
 
            # same fileno
 
1571
            # remove the old hook in favor of the new above hook on same fileno
1790
1572
            return False
1791
1573
        if command == 'funcall':
1792
1574
            funcname = request[1]
1793
1575
            args = request[2]
1794
1576
            kwargs = request[3]
1795
1577
            
1796
 
            parent_pipe.send(('data', getattr(client_object,
1797
 
                                              funcname)(*args,
1798
 
                                                         **kwargs)))
1799
 
        
 
1578
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
 
1579
 
1800
1580
        if command == 'getattr':
1801
1581
            attrname = request[1]
1802
1582
            if callable(client_object.__getattribute__(attrname)):
1803
1583
                parent_pipe.send(('function',))
1804
1584
            else:
1805
 
                parent_pipe.send(('data', client_object
1806
 
                                  .__getattribute__(attrname)))
 
1585
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1807
1586
        
1808
1587
        if command == 'setattr':
1809
1588
            attrname = request[1]
1810
1589
            value = request[2]
1811
1590
            setattr(client_object, attrname, value)
1812
 
        
 
1591
 
1813
1592
        return True
1814
1593
 
1815
1594
 
1936
1715
                        " system bus interface")
1937
1716
    parser.add_argument("--no-ipv6", action="store_false",
1938
1717
                        dest="use_ipv6", help="Do not use IPv6")
1939
 
    parser.add_argument("--no-restore", action="store_false",
1940
 
                        dest="restore", help="Do not restore stored state",
1941
 
                        default=True)
1942
 
 
1943
1718
    options = parser.parse_args()
1944
1719
    
1945
1720
    if options.check:
1980
1755
    # options, if set.
1981
1756
    for option in ("interface", "address", "port", "debug",
1982
1757
                   "priority", "servicename", "configdir",
1983
 
                   "use_dbus", "use_ipv6", "debuglevel", "restore"):
 
1758
                   "use_dbus", "use_ipv6", "debuglevel"):
1984
1759
        value = getattr(options, option)
1985
1760
        if value is not None:
1986
1761
            server_settings[option] = value
1998
1773
    debuglevel = server_settings["debuglevel"]
1999
1774
    use_dbus = server_settings["use_dbus"]
2000
1775
    use_ipv6 = server_settings["use_ipv6"]
2001
 
    
2002
 
    if debug:
2003
 
        initlogger(logging.DEBUG)
2004
 
    else:
2005
 
        if not debuglevel:
2006
 
            initlogger()
2007
 
        else:
2008
 
            level = getattr(logging, debuglevel.upper())
2009
 
            initlogger(level)    
2010
 
    
 
1776
 
2011
1777
    if server_settings["servicename"] != "Mandos":
2012
1778
        syslogger.setFormatter(logging.Formatter
2013
1779
                               ('Mandos (%s) [%%(process)d]:'
2067
1833
        if error[0] != errno.EPERM:
2068
1834
            raise error
2069
1835
    
 
1836
    if not debug and not debuglevel:
 
1837
        syslogger.setLevel(logging.WARNING)
 
1838
        console.setLevel(logging.WARNING)
 
1839
    if debuglevel:
 
1840
        level = getattr(logging, debuglevel.upper())
 
1841
        syslogger.setLevel(level)
 
1842
        console.setLevel(level)
 
1843
 
2070
1844
    if debug:
2071
1845
        # Enable all possible GnuTLS debugging
2072
1846
        
2103
1877
    # End of Avahi example code
2104
1878
    if use_dbus:
2105
1879
        try:
2106
 
            bus_name = dbus.service.BusName("se.recompile.Mandos",
 
1880
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
2107
1881
                                            bus, do_not_queue=True)
2108
 
            old_bus_name = (dbus.service.BusName
2109
 
                            ("se.bsnet.fukt.Mandos", bus,
2110
 
                             do_not_queue=True))
2111
1882
        except dbus.exceptions.NameExistsException as e:
2112
1883
            logger.error(unicode(e) + ", disabling D-Bus")
2113
1884
            use_dbus = False
2114
1885
            server_settings["use_dbus"] = False
2115
1886
            tcp_server.use_dbus = False
2116
1887
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2117
 
    service = AvahiServiceToSyslog(name =
2118
 
                                   server_settings["servicename"],
2119
 
                                   servicetype = "_mandos._tcp",
2120
 
                                   protocol = protocol, bus = bus)
 
1888
    service = AvahiService(name = server_settings["servicename"],
 
1889
                           servicetype = "_mandos._tcp",
 
1890
                           protocol = protocol, bus = bus)
2121
1891
    if server_settings["interface"]:
2122
1892
        service.interface = (if_nametoindex
2123
1893
                             (str(server_settings["interface"])))
2127
1897
    
2128
1898
    client_class = Client
2129
1899
    if use_dbus:
2130
 
        client_class = functools.partial(ClientDBusTransitional,
2131
 
                                         bus = bus)
2132
 
    
2133
 
    special_settings = {
2134
 
        # Some settings need to be accessd by special methods;
2135
 
        # booleans need .getboolean(), etc.  Here is a list of them:
2136
 
        "approved_by_default":
2137
 
            lambda section:
2138
 
            client_config.getboolean(section, "approved_by_default"),
2139
 
        }
2140
 
    # Construct a new dict of client settings of this form:
2141
 
    # { client_name: {setting_name: value, ...}, ...}
2142
 
    # with exceptions for any special settings as defined above
2143
 
    client_settings = dict((clientname,
2144
 
                           dict((setting,
2145
 
                                 (value if setting not in special_settings
2146
 
                                  else special_settings[setting](clientname)))
2147
 
                                for setting, value in client_config.items(clientname)))
2148
 
                          for clientname in client_config.sections())
2149
 
    
2150
 
    old_client_settings = {}
2151
 
    clients_data = []
2152
 
 
2153
 
    # Get client data and settings from last running state. 
2154
 
    if server_settings["restore"]:
2155
 
        try:
2156
 
            with open(stored_state_path, "rb") as stored_state:
2157
 
                clients_data, old_client_settings = pickle.load(stored_state)
2158
 
            os.remove(stored_state_path)
2159
 
        except IOError as e:
2160
 
            logger.warning("Could not load persistant state: {0}".format(e))
2161
 
            if e.errno != errno.ENOENT:
2162
 
                raise
2163
 
 
2164
 
    for client in clients_data:
2165
 
        client_name = client["name"]
2166
 
        
2167
 
        # Decide which value to use after restoring saved state.
2168
 
        # We have three different values: Old config file,
2169
 
        # new config file, and saved state.
2170
 
        # New config value takes precedence if it differs from old
2171
 
        # config value, otherwise use saved state.
2172
 
        for name, value in client_settings[client_name].items():
 
1900
        client_class = functools.partial(ClientDBus, bus = bus)
 
1901
    def client_config_items(config, section):
 
1902
        special_settings = {
 
1903
            "approved_by_default":
 
1904
                lambda: config.getboolean(section,
 
1905
                                          "approved_by_default"),
 
1906
            }
 
1907
        for name, value in config.items(section):
2173
1908
            try:
2174
 
                # For each value in new config, check if it differs
2175
 
                # from the old config value (Except for the "secret"
2176
 
                # attribute)
2177
 
                if name != "secret" and value != old_client_settings[client_name][name]:
2178
 
                    setattr(client, name, value)
 
1909
                yield (name, special_settings[name]())
2179
1910
            except KeyError:
2180
 
                pass
2181
 
 
2182
 
        # Clients who has passed its expire date, can still be enabled if its
2183
 
        # last checker was sucessful. Clients who checkers failed before we
2184
 
        # stored it state is asumed to had failed checker during downtime.
2185
 
        if client["enabled"] and client["last_checked_ok"]:
2186
 
            if ((datetime.datetime.utcnow() - client["last_checked_ok"])
2187
 
                > client["interval"]):
2188
 
                if client["last_checker_status"] != 0:
2189
 
                    client["enabled"] = False
2190
 
                else:
2191
 
                    client["expires"] = datetime.datetime.utcnow() + client["timeout"]
2192
 
 
2193
 
        client["changedstate"] = (multiprocessing_manager
2194
 
                                  .Condition(multiprocessing_manager
2195
 
                                             .Lock()))
2196
 
        if use_dbus:
2197
 
            new_client = ClientDBusTransitional.__new__(ClientDBusTransitional)
2198
 
            tcp_server.clients[client_name] = new_client
2199
 
            new_client.bus = bus
2200
 
            for name, value in client.iteritems():
2201
 
                setattr(new_client, name, value)
2202
 
            client_object_name = unicode(client_name).translate(
2203
 
                {ord("."): ord("_"),
2204
 
                 ord("-"): ord("_")})
2205
 
            new_client.dbus_object_path = (dbus.ObjectPath
2206
 
                                     ("/clients/" + client_object_name))
2207
 
            DBusObjectWithProperties.__init__(new_client,
2208
 
                                              new_client.bus,
2209
 
                                              new_client.dbus_object_path)
2210
 
        else:
2211
 
            tcp_server.clients[client_name] = Client.__new__(Client)
2212
 
            for name, value in client.iteritems():
2213
 
                setattr(tcp_server.clients[client_name], name, value)
2214
 
                
2215
 
        tcp_server.clients[client_name].decrypt_secret(
2216
 
            client_settings[client_name]["secret"])            
2217
 
        
2218
 
    # Create/remove clients based on new changes made to config
2219
 
    for clientname in set(old_client_settings) - set(client_settings):
2220
 
        del tcp_server.clients[clientname]
2221
 
    for clientname in set(client_settings) - set(old_client_settings):
2222
 
        tcp_server.clients[clientname] = (client_class(name = clientname,
2223
 
                                                       config =
2224
 
                                                       client_settings
2225
 
                                                       [clientname]))
 
1911
                yield (name, value)
2226
1912
    
2227
 
 
 
1913
    tcp_server.clients.update(set(
 
1914
            client_class(name = section,
 
1915
                         config= dict(client_config_items(
 
1916
                        client_config, section)))
 
1917
            for section in client_config.sections()))
2228
1918
    if not tcp_server.clients:
2229
1919
        logger.warning("No clients defined")
2230
1920
        
2243
1933
        del pidfilename
2244
1934
        
2245
1935
        signal.signal(signal.SIGINT, signal.SIG_IGN)
2246
 
    
 
1936
 
2247
1937
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2248
1938
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2249
1939
    
2252
1942
            """A D-Bus proxy object"""
2253
1943
            def __init__(self):
2254
1944
                dbus.service.Object.__init__(self, bus, "/")
2255
 
            _interface = "se.recompile.Mandos"
 
1945
            _interface = "se.bsnet.fukt.Mandos"
2256
1946
            
2257
1947
            @dbus.service.signal(_interface, signature="o")
2258
1948
            def ClientAdded(self, objpath):
2273
1963
            def GetAllClients(self):
2274
1964
                "D-Bus method"
2275
1965
                return dbus.Array(c.dbus_object_path
2276
 
                                  for c in
2277
 
                                  tcp_server.clients.itervalues())
 
1966
                                  for c in tcp_server.clients)
2278
1967
            
2279
1968
            @dbus.service.method(_interface,
2280
1969
                                 out_signature="a{oa{sv}}")
2282
1971
                "D-Bus method"
2283
1972
                return dbus.Dictionary(
2284
1973
                    ((c.dbus_object_path, c.GetAll(""))
2285
 
                     for c in tcp_server.clients.itervalues()),
 
1974
                     for c in tcp_server.clients),
2286
1975
                    signature="oa{sv}")
2287
1976
            
2288
1977
            @dbus.service.method(_interface, in_signature="o")
2289
1978
            def RemoveClient(self, object_path):
2290
1979
                "D-Bus method"
2291
 
                for c in tcp_server.clients.itervalues():
 
1980
                for c in tcp_server.clients:
2292
1981
                    if c.dbus_object_path == object_path:
2293
 
                        del tcp_server.clients[c.name]
 
1982
                        tcp_server.clients.remove(c)
2294
1983
                        c.remove_from_connection()
2295
1984
                        # Don't signal anything except ClientRemoved
2296
1985
                        c.disable(quiet=True)
2301
1990
            
2302
1991
            del _interface
2303
1992
        
2304
 
        class MandosDBusServiceTransitional(MandosDBusService):
2305
 
            __metaclass__ = AlternateDBusNamesMetaclass
2306
 
        mandos_dbus_service = MandosDBusServiceTransitional()
 
1993
        mandos_dbus_service = MandosDBusService()
2307
1994
    
2308
1995
    def cleanup():
2309
1996
        "Cleanup function; run on exit"
2310
1997
        service.cleanup()
2311
1998
        
2312
 
        multiprocessing.active_children()
2313
 
        if not (tcp_server.clients or client_settings):
2314
 
            return
2315
 
 
2316
 
        # Store client before exiting. Secrets are encrypted with key based
2317
 
        # on what config file has. If config file is removed/edited, old
2318
 
        # secret will thus be unrecovable.
2319
 
        clients = []
2320
 
        for client in tcp_server.clients.itervalues():
2321
 
            client.encrypt_secret(client_settings[client.name]["secret"])
2322
 
 
2323
 
            client_dict = {}
2324
 
 
2325
 
            # A list of attributes that will not be stored when shuting down.
2326
 
            exclude = set(("bus", "changedstate", "secret"))            
2327
 
            for name, typ in inspect.getmembers(dbus.service.Object):
2328
 
                exclude.add(name)
2329
 
                
2330
 
            client_dict["encrypted_secret"] = client.encrypted_secret
2331
 
            for attr in client.client_structure:
2332
 
                if attr not in exclude:
2333
 
                    client_dict[attr] = getattr(client, attr)
2334
 
 
2335
 
            clients.append(client_dict) 
2336
 
            del client_settings[client.name]["secret"]
2337
 
            
2338
 
        try:
2339
 
            with os.fdopen(os.open(stored_state_path, os.O_CREAT|os.O_WRONLY|os.O_TRUNC, 0600), "wb") as stored_state:
2340
 
                pickle.dump((clients, client_settings), stored_state)
2341
 
        except IOError as e:
2342
 
            logger.warning("Could not save persistant state: {0}".format(e))
2343
 
            if e.errno != errno.ENOENT:
2344
 
                raise
2345
 
 
2346
 
        # Delete all clients, and settings from config
2347
1999
        while tcp_server.clients:
2348
 
            name, client = tcp_server.clients.popitem()
 
2000
            client = tcp_server.clients.pop()
2349
2001
            if use_dbus:
2350
2002
                client.remove_from_connection()
 
2003
            client.disable_hook = None
2351
2004
            # Don't signal anything except ClientRemoved
2352
2005
            client.disable(quiet=True)
2353
2006
            if use_dbus:
2354
2007
                # Emit D-Bus signal
2355
 
                mandos_dbus_service.ClientRemoved(client
2356
 
                                                  .dbus_object_path,
 
2008
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2357
2009
                                                  client.name)
2358
 
        client_settings.clear()
2359
2010
    
2360
2011
    atexit.register(cleanup)
2361
2012
    
2362
 
    for client in tcp_server.clients.itervalues():
 
2013
    for client in tcp_server.clients:
2363
2014
        if use_dbus:
2364
2015
            # Emit D-Bus signal
2365
2016
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
2366
 
        # Need to initiate checking of clients
2367
 
        if client.enabled:
2368
 
            client.init_checker()
2369
 
 
 
2017
        client.enable()
2370
2018
    
2371
2019
    tcp_server.enable()
2372
2020
    tcp_server.server_activate()
2412
2060
    # Must run before the D-Bus bus name gets deregistered
2413
2061
    cleanup()
2414
2062
 
2415
 
 
2416
2063
if __name__ == '__main__':
2417
2064
    main()