/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Björn Påhlsson
  • Date: 2011-09-24 14:11:08 UTC
  • mto: (237.7.50 mandos)
  • mto: This revision was merged to the branch mainline in revision 286.
  • Revision ID: belorn@fukt.bsnet.se-20110924141108-uejkiva9fqwt8il8
Refactoring code related to PropertyChanged dbus signal. Made sending
PropertyChanged signal to a python properties of interval variables.

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 binascii
67
 
import tempfile
68
65
 
69
66
import dbus
70
67
import dbus.service
75
72
import ctypes.util
76
73
import xml.dom.minidom
77
74
import inspect
78
 
import GnuPGInterface
79
75
 
80
76
try:
81
77
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
86
82
        SO_BINDTODEVICE = None
87
83
 
88
84
 
89
 
version = "1.4.1"
90
 
stored_state_path = "/var/lib/mandos/clients.pickle"
 
85
version = "1.3.1"
91
86
 
92
 
logger = logging.getLogger()
 
87
#logger = logging.getLogger('mandos')
 
88
logger = logging.Logger('mandos')
93
89
syslogger = (logging.handlers.SysLogHandler
94
90
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
95
91
              address = str("/dev/log")))
96
 
 
97
 
try:
98
 
    if_nametoindex = (ctypes.cdll.LoadLibrary
99
 
                      (ctypes.util.find_library("c"))
100
 
                      .if_nametoindex)
101
 
except (OSError, AttributeError):
102
 
    def if_nametoindex(interface):
103
 
        "Get an interface index the hard way, i.e. using fcntl()"
104
 
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
105
 
        with contextlib.closing(socket.socket()) as s:
106
 
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
107
 
                                struct.pack(str("16s16x"),
108
 
                                            interface))
109
 
        interface_index = struct.unpack(str("I"),
110
 
                                        ifreq[16:20])[0]
111
 
        return interface_index
112
 
 
113
 
 
114
 
def initlogger(level=logging.WARNING):
115
 
    """init logger and add loglevel"""
116
 
    
117
 
    syslogger.setFormatter(logging.Formatter
118
 
                           ('Mandos [%(process)d]: %(levelname)s:'
119
 
                            ' %(message)s'))
120
 
    logger.addHandler(syslogger)
121
 
    
122
 
    console = logging.StreamHandler()
123
 
    console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
124
 
                                           ' [%(process)d]:'
125
 
                                           ' %(levelname)s:'
126
 
                                           ' %(message)s'))
127
 
    logger.addHandler(console)
128
 
    logger.setLevel(level)
129
 
 
130
 
 
131
 
class CryptoError(Exception):
132
 
    pass
133
 
 
134
 
 
135
 
class Crypto(object):
136
 
    """A simple class for OpenPGP symmetric encryption & decryption"""
137
 
    def __init__(self):
138
 
        self.gnupg = GnuPGInterface.GnuPG()
139
 
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
140
 
        self.gnupg = GnuPGInterface.GnuPG()
141
 
        self.gnupg.options.meta_interactive = False
142
 
        self.gnupg.options.homedir = self.tempdir
143
 
        self.gnupg.options.extra_args.extend(['--force-mdc',
144
 
                                              '--quiet'])
145
 
    
146
 
    def __enter__(self):
147
 
        return self
148
 
    
149
 
    def __exit__ (self, exc_type, exc_value, traceback):
150
 
        self._cleanup()
151
 
        return False
152
 
    
153
 
    def __del__(self):
154
 
        self._cleanup()
155
 
    
156
 
    def _cleanup(self):
157
 
        if self.tempdir is not None:
158
 
            # Delete contents of tempdir
159
 
            for root, dirs, files in os.walk(self.tempdir,
160
 
                                             topdown = False):
161
 
                for filename in files:
162
 
                    os.remove(os.path.join(root, filename))
163
 
                for dirname in dirs:
164
 
                    os.rmdir(os.path.join(root, dirname))
165
 
            # Remove tempdir
166
 
            os.rmdir(self.tempdir)
167
 
            self.tempdir = None
168
 
    
169
 
    def password_encode(self, password):
170
 
        # Passphrase can not be empty and can not contain newlines or
171
 
        # NUL bytes.  So we prefix it and hex encode it.
172
 
        return b"mandos" + binascii.hexlify(password)
173
 
    
174
 
    def encrypt(self, data, password):
175
 
        self.gnupg.passphrase = self.password_encode(password)
176
 
        with open(os.devnull) as devnull:
177
 
            try:
178
 
                proc = self.gnupg.run(['--symmetric'],
179
 
                                      create_fhs=['stdin', 'stdout'],
180
 
                                      attach_fhs={'stderr': devnull})
181
 
                with contextlib.closing(proc.handles['stdin']) as f:
182
 
                    f.write(data)
183
 
                with contextlib.closing(proc.handles['stdout']) as f:
184
 
                    ciphertext = f.read()
185
 
                proc.wait()
186
 
            except IOError as e:
187
 
                raise CryptoError(e)
188
 
        self.gnupg.passphrase = None
189
 
        return ciphertext
190
 
    
191
 
    def decrypt(self, data, password):
192
 
        self.gnupg.passphrase = self.password_encode(password)
193
 
        with open(os.devnull) as devnull:
194
 
            try:
195
 
                proc = self.gnupg.run(['--decrypt'],
196
 
                                      create_fhs=['stdin', 'stdout'],
197
 
                                      attach_fhs={'stderr': devnull})
198
 
                with contextlib.closing(proc.handles['stdin'] ) as f:
199
 
                    f.write(data)
200
 
                with contextlib.closing(proc.handles['stdout']) as f:
201
 
                    decrypted_plaintext = f.read()
202
 
                proc.wait()
203
 
            except IOError as e:
204
 
                raise CryptoError(e)
205
 
        self.gnupg.passphrase = None
206
 
        return decrypted_plaintext
207
 
 
208
 
 
 
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)
209
102
 
210
103
class AvahiError(Exception):
211
104
    def __init__(self, value, *args, **kwargs):
266
159
                            " after %i retries, exiting.",
267
160
                            self.rename_count)
268
161
            raise AvahiServiceError("Too many renames")
269
 
        self.name = unicode(self.server
270
 
                            .GetAlternativeServiceName(self.name))
 
162
        self.name = unicode(self.server.GetAlternativeServiceName(self.name))
271
163
        logger.info("Changing Zeroconf service name to %r ...",
272
164
                    self.name)
 
165
        syslogger.setFormatter(logging.Formatter
 
166
                               ('Mandos (%s) [%%(process)d]:'
 
167
                                ' %%(levelname)s: %%(message)s'
 
168
                                % self.name))
273
169
        self.remove()
274
170
        try:
275
171
            self.add()
295
191
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
296
192
        self.entry_group_state_changed_match = (
297
193
            self.group.connect_to_signal(
298
 
                'StateChanged', self.entry_group_state_changed))
 
194
                'StateChanged', self .entry_group_state_changed))
299
195
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
300
196
                     self.name, self.type)
301
197
        self.group.AddService(
327
223
            try:
328
224
                self.group.Free()
329
225
            except (dbus.exceptions.UnknownMethodException,
330
 
                    dbus.exceptions.DBusException):
 
226
                    dbus.exceptions.DBusException) as e:
331
227
                pass
332
228
            self.group = None
333
229
        self.remove()
367
263
                                 self.server_state_changed)
368
264
        self.server_state_changed(self.server.GetState())
369
265
 
370
 
class AvahiServiceToSyslog(AvahiService):
371
 
    def rename(self):
372
 
        """Add the new name to the syslog messages"""
373
 
        ret = AvahiService.rename(self)
374
 
        syslogger.setFormatter(logging.Formatter
375
 
                               ('Mandos (%s) [%%(process)d]:'
376
 
                                ' %%(levelname)s: %%(message)s'
377
 
                                % self.name))
378
 
        return ret
379
266
 
380
267
def _timedelta_to_milliseconds(td):
381
268
    "Convert a datetime.timedelta() to milliseconds"
400
287
                     instance %(name)s can be used in the command.
401
288
    checker_initiator_tag: a gobject event source tag, or None
402
289
    created:    datetime.datetime(); (UTC) object creation
403
 
    client_structure: Object describing what attributes a client has
404
 
                      and is used for storing the client at exit
405
290
    current_checker_command: string; current running checker_command
 
291
    disable_hook:  If set, called by disable() as disable_hook(self)
406
292
    disable_initiator_tag: a gobject event source tag, or None
407
293
    enabled:    bool()
408
294
    fingerprint: string (40 or 32 hexadecimal digits); used to
411
297
    interval:   datetime.timedelta(); How often to start a new checker
412
298
    last_approval_request: datetime.datetime(); (UTC) or None
413
299
    last_checked_ok: datetime.datetime(); (UTC) or None
414
 
 
415
 
    last_checker_status: integer between 0 and 255 reflecting exit
416
 
                         status of last checker. -1 reflects crashed
417
 
                         checker, or None.
418
300
    last_enabled: datetime.datetime(); (UTC)
419
301
    name:       string; from the config file, used in log messages and
420
302
                        D-Bus identifiers
431
313
                          "created", "enabled", "fingerprint",
432
314
                          "host", "interval", "last_checked_ok",
433
315
                          "last_enabled", "name", "timeout")
434
 
    
 
316
        
435
317
    def timeout_milliseconds(self):
436
318
        "Return the 'timeout' attribute in milliseconds"
437
319
        return _timedelta_to_milliseconds(self.timeout)
438
 
    
 
320
 
439
321
    def extended_timeout_milliseconds(self):
440
322
        "Return the 'extended_timeout' attribute in milliseconds"
441
 
        return _timedelta_to_milliseconds(self.extended_timeout)
 
323
        return _timedelta_to_milliseconds(self.extended_timeout)    
442
324
    
443
325
    def interval_milliseconds(self):
444
326
        "Return the 'interval' attribute in milliseconds"
445
327
        return _timedelta_to_milliseconds(self.interval)
446
 
    
 
328
 
447
329
    def approval_delay_milliseconds(self):
448
330
        return _timedelta_to_milliseconds(self.approval_delay)
449
331
    
450
 
    def __init__(self, name = None, config=None):
 
332
    def __init__(self, name = None, disable_hook=None, config=None):
451
333
        """Note: the 'checker' key in 'config' sets the
452
334
        'checker_command' attribute and *not* the 'checker'
453
335
        attribute."""
473
355
                            % self.name)
474
356
        self.host = config.get("host", "")
475
357
        self.created = datetime.datetime.utcnow()
476
 
        self.enabled = True
 
358
        self.enabled = False
477
359
        self.last_approval_request = None
478
 
        self.last_enabled = datetime.datetime.utcnow()
 
360
        self.last_enabled = None
479
361
        self.last_checked_ok = None
480
 
        self.last_checker_status = None
481
362
        self.timeout = string_to_delta(config["timeout"])
482
 
        self.extended_timeout = string_to_delta(config
483
 
                                                ["extended_timeout"])
 
363
        self.extended_timeout = string_to_delta(config["extended_timeout"])
484
364
        self.interval = string_to_delta(config["interval"])
 
365
        self.disable_hook = disable_hook
485
366
        self.checker = None
486
367
        self.checker_initiator_tag = None
487
368
        self.disable_initiator_tag = None
488
 
        self.expires = datetime.datetime.utcnow() + self.timeout
 
369
        self.expires = None
489
370
        self.checker_callback_tag = None
490
371
        self.checker_command = config["checker"]
491
372
        self.current_checker_command = None
 
373
        self.last_connect = None
492
374
        self._approved = None
493
375
        self.approved_by_default = config.get("approved_by_default",
494
376
                                              True)
497
379
            config["approval_delay"])
498
380
        self.approval_duration = string_to_delta(
499
381
            config["approval_duration"])
500
 
        self.changedstate = (multiprocessing_manager
501
 
                             .Condition(multiprocessing_manager
502
 
                                        .Lock()))
503
 
        self.client_structure = [attr for attr in
504
 
                                 self.__dict__.iterkeys()
505
 
                                 if not attr.startswith("_")]
506
 
        self.client_structure.append("client_structure")
507
 
        
508
 
        for name, t in inspect.getmembers(type(self),
509
 
                                          lambda obj:
510
 
                                              isinstance(obj,
511
 
                                                         property)):
512
 
            if not name.startswith("_"):
513
 
                self.client_structure.append(name)
 
382
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
514
383
    
515
 
    # Send notice to process children that client state has changed
516
384
    def send_changedstate(self):
517
 
        with self.changedstate:
518
 
            self.changedstate.notify_all()
519
 
    
 
385
        self.changedstate.acquire()
 
386
        self.changedstate.notify_all()
 
387
        self.changedstate.release()
 
388
        
520
389
    def enable(self):
521
390
        """Start this client's checker and timeout hooks"""
522
391
        if getattr(self, "enabled", False):
523
392
            # Already enabled
524
393
            return
525
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
526
401
        self.expires = datetime.datetime.utcnow() + self.timeout
 
402
        self.disable_initiator_tag = (gobject.timeout_add
 
403
                                   (self.timeout_milliseconds(),
 
404
                                    self.disable))
527
405
        self.enabled = True
528
406
        self.last_enabled = datetime.datetime.utcnow()
529
 
        self.init_checker()
 
407
        # Also start a new checker *right now*.
 
408
        self.start_checker()
530
409
    
531
410
    def disable(self, quiet=True):
532
411
        """Disable this client."""
544
423
            gobject.source_remove(self.checker_initiator_tag)
545
424
            self.checker_initiator_tag = None
546
425
        self.stop_checker()
 
426
        if self.disable_hook:
 
427
            self.disable_hook(self)
547
428
        self.enabled = False
548
429
        # Do not run this again if called by a gobject.timeout_add
549
430
        return False
550
431
    
551
432
    def __del__(self):
 
433
        self.disable_hook = None
552
434
        self.disable()
553
435
    
554
 
    def init_checker(self):
555
 
        # Schedule a new checker to be started an 'interval' from now,
556
 
        # and every interval from then on.
557
 
        self.checker_initiator_tag = (gobject.timeout_add
558
 
                                      (self.interval_milliseconds(),
559
 
                                       self.start_checker))
560
 
        # Schedule a disable() when 'timeout' has passed
561
 
        self.disable_initiator_tag = (gobject.timeout_add
562
 
                                   (self.timeout_milliseconds(),
563
 
                                    self.disable))
564
 
        # Also start a new checker *right now*.
565
 
        self.start_checker()
566
 
    
567
436
    def checker_callback(self, pid, condition, command):
568
437
        """The checker has completed, so take appropriate actions."""
569
438
        self.checker_callback_tag = None
570
439
        self.checker = None
571
440
        if os.WIFEXITED(condition):
572
 
            self.last_checker_status =  os.WEXITSTATUS(condition)
573
 
            if self.last_checker_status == 0:
 
441
            exitstatus = os.WEXITSTATUS(condition)
 
442
            if exitstatus == 0:
574
443
                logger.info("Checker for %(name)s succeeded",
575
444
                            vars(self))
576
445
                self.checked_ok()
578
447
                logger.info("Checker for %(name)s failed",
579
448
                            vars(self))
580
449
        else:
581
 
            self.last_checker_status = -1
582
450
            logger.warning("Checker for %(name)s crashed?",
583
451
                           vars(self))
584
452
    
591
459
        if timeout is None:
592
460
            timeout = self.timeout
593
461
        self.last_checked_ok = datetime.datetime.utcnow()
594
 
        if self.disable_initiator_tag is not None:
595
 
            gobject.source_remove(self.disable_initiator_tag)
596
 
        if getattr(self, "enabled", False):
597
 
            self.disable_initiator_tag = (gobject.timeout_add
598
 
                                          (_timedelta_to_milliseconds
599
 
                                           (timeout), self.disable))
600
 
            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))
601
467
    
602
468
    def need_approval(self):
603
469
        self.last_approval_request = datetime.datetime.utcnow()
643
509
                                       'replace')))
644
510
                    for attr in
645
511
                    self.runtime_expansions)
646
 
                
 
512
 
647
513
                try:
648
514
                    command = self.checker_command % escaped_attrs
649
515
                except TypeError as error:
695
561
                raise
696
562
        self.checker = None
697
563
 
698
 
 
699
564
def dbus_service_property(dbus_interface, signature="v",
700
565
                          access="readwrite", byte_arrays=False):
701
566
    """Decorators for marking methods of a DBusObjectWithProperties to
747
612
 
748
613
class DBusObjectWithProperties(dbus.service.Object):
749
614
    """A D-Bus object with properties.
750
 
    
 
615
 
751
616
    Classes inheriting from this can use the dbus_service_property
752
617
    decorator to expose methods as D-Bus properties.  It exposes the
753
618
    standard Get(), Set(), and GetAll() methods on the D-Bus.
760
625
    def _get_all_dbus_properties(self):
761
626
        """Returns a generator of (name, attribute) pairs
762
627
        """
763
 
        return ((prop.__get__(self)._dbus_name, prop.__get__(self))
764
 
                for cls in self.__class__.__mro__
 
628
        return ((prop._dbus_name, prop)
765
629
                for name, prop in
766
 
                inspect.getmembers(cls, self._is_dbus_property))
 
630
                inspect.getmembers(self, self._is_dbus_property))
767
631
    
768
632
    def _get_dbus_property(self, interface_name, property_name):
769
633
        """Returns a bound method if one exists which is a D-Bus
770
634
        property with the specified name and interface.
771
635
        """
772
 
        for cls in  self.__class__.__mro__:
773
 
            for name, value in (inspect.getmembers
774
 
                                (cls, self._is_dbus_property)):
775
 
                if (value._dbus_name == property_name
776
 
                    and value._dbus_interface == interface_name):
777
 
                    return value.__get__(self)
778
 
        
 
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
779
646
        # No such property
780
647
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
781
648
                                   + interface_name + "."
815
682
    def GetAll(self, interface_name):
816
683
        """Standard D-Bus property GetAll() method, see D-Bus
817
684
        standard.
818
 
        
 
685
 
819
686
        Note: Will not include properties with access="write".
820
687
        """
821
 
        properties = {}
 
688
        all = {}
822
689
        for name, prop in self._get_all_dbus_properties():
823
690
            if (interface_name
824
691
                and interface_name != prop._dbus_interface):
829
696
                continue
830
697
            value = prop()
831
698
            if not hasattr(value, "variant_level"):
832
 
                properties[name] = value
 
699
                all[name] = value
833
700
                continue
834
 
            properties[name] = type(value)(value, variant_level=
835
 
                                           value.variant_level+1)
836
 
        return dbus.Dictionary(properties, signature="sv")
 
701
            all[name] = type(value)(value, variant_level=
 
702
                                    value.variant_level+1)
 
703
        return dbus.Dictionary(all, signature="sv")
837
704
    
838
705
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
839
706
                         out_signature="s",
890
757
    return dbus.String(dt.isoformat(),
891
758
                       variant_level=variant_level)
892
759
 
893
 
 
894
 
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
895
 
                                  .__metaclass__):
896
 
    """Applied to an empty subclass of a D-Bus object, this metaclass
897
 
    will add additional D-Bus attributes matching a certain pattern.
898
 
    """
899
 
    def __new__(mcs, name, bases, attr):
900
 
        # Go through all the base classes which could have D-Bus
901
 
        # methods, signals, or properties in them
902
 
        for base in (b for b in bases
903
 
                     if issubclass(b, dbus.service.Object)):
904
 
            # Go though all attributes of the base class
905
 
            for attrname, attribute in inspect.getmembers(base):
906
 
                # Ignore non-D-Bus attributes, and D-Bus attributes
907
 
                # with the wrong interface name
908
 
                if (not hasattr(attribute, "_dbus_interface")
909
 
                    or not attribute._dbus_interface
910
 
                    .startswith("se.recompile.Mandos")):
911
 
                    continue
912
 
                # Create an alternate D-Bus interface name based on
913
 
                # the current name
914
 
                alt_interface = (attribute._dbus_interface
915
 
                                 .replace("se.recompile.Mandos",
916
 
                                          "se.bsnet.fukt.Mandos"))
917
 
                # Is this a D-Bus signal?
918
 
                if getattr(attribute, "_dbus_is_signal", False):
919
 
                    # Extract the original non-method function by
920
 
                    # black magic
921
 
                    nonmethod_func = (dict(
922
 
                            zip(attribute.func_code.co_freevars,
923
 
                                attribute.__closure__))["func"]
924
 
                                      .cell_contents)
925
 
                    # Create a new, but exactly alike, function
926
 
                    # object, and decorate it to be a new D-Bus signal
927
 
                    # with the alternate D-Bus interface name
928
 
                    new_function = (dbus.service.signal
929
 
                                    (alt_interface,
930
 
                                     attribute._dbus_signature)
931
 
                                    (types.FunctionType(
932
 
                                nonmethod_func.func_code,
933
 
                                nonmethod_func.func_globals,
934
 
                                nonmethod_func.func_name,
935
 
                                nonmethod_func.func_defaults,
936
 
                                nonmethod_func.func_closure)))
937
 
                    # Define a creator of a function to call both the
938
 
                    # old and new functions, so both the old and new
939
 
                    # signals gets sent when the function is called
940
 
                    def fixscope(func1, func2):
941
 
                        """This function is a scope container to pass
942
 
                        func1 and func2 to the "call_both" function
943
 
                        outside of its arguments"""
944
 
                        def call_both(*args, **kwargs):
945
 
                            """This function will emit two D-Bus
946
 
                            signals by calling func1 and func2"""
947
 
                            func1(*args, **kwargs)
948
 
                            func2(*args, **kwargs)
949
 
                        return call_both
950
 
                    # Create the "call_both" function and add it to
951
 
                    # the class
952
 
                    attr[attrname] = fixscope(attribute,
953
 
                                              new_function)
954
 
                # Is this a D-Bus method?
955
 
                elif getattr(attribute, "_dbus_is_method", False):
956
 
                    # Create a new, but exactly alike, function
957
 
                    # object.  Decorate it to be a new D-Bus method
958
 
                    # with the alternate D-Bus interface name.  Add it
959
 
                    # to the class.
960
 
                    attr[attrname] = (dbus.service.method
961
 
                                      (alt_interface,
962
 
                                       attribute._dbus_in_signature,
963
 
                                       attribute._dbus_out_signature)
964
 
                                      (types.FunctionType
965
 
                                       (attribute.func_code,
966
 
                                        attribute.func_globals,
967
 
                                        attribute.func_name,
968
 
                                        attribute.func_defaults,
969
 
                                        attribute.func_closure)))
970
 
                # Is this a D-Bus property?
971
 
                elif getattr(attribute, "_dbus_is_property", False):
972
 
                    # Create a new, but exactly alike, function
973
 
                    # object, and decorate it to be a new D-Bus
974
 
                    # property with the alternate D-Bus interface
975
 
                    # name.  Add it to the class.
976
 
                    attr[attrname] = (dbus_service_property
977
 
                                      (alt_interface,
978
 
                                       attribute._dbus_signature,
979
 
                                       attribute._dbus_access,
980
 
                                       attribute
981
 
                                       ._dbus_get_args_options
982
 
                                       ["byte_arrays"])
983
 
                                      (types.FunctionType
984
 
                                       (attribute.func_code,
985
 
                                        attribute.func_globals,
986
 
                                        attribute.func_name,
987
 
                                        attribute.func_defaults,
988
 
                                        attribute.func_closure)))
989
 
        return type.__new__(mcs, name, bases, attr)
990
 
 
991
 
 
992
760
class ClientDBus(Client, DBusObjectWithProperties):
993
761
    """A Client class using D-Bus
994
762
    
1003
771
    # dbus.service.Object doesn't use super(), so we can't either.
1004
772
    
1005
773
    def __init__(self, bus = None, *args, **kwargs):
 
774
        self._approvals_pending = 0
1006
775
        self.bus = bus
1007
776
        Client.__init__(self, *args, **kwargs)
1008
 
        
1009
 
        self._approvals_pending = 0
1010
777
        # Only now, when this client is initialized, can it show up on
1011
778
        # the D-Bus
1012
779
        client_object_name = unicode(self.name).translate(
1020
787
    def notifychangeproperty(transform_func,
1021
788
                             dbus_name, type_func=lambda x: x,
1022
789
                             variant_level=1):
1023
 
        """ Modify a variable so that it's a property which announces
1024
 
        its changes to DBus.
1025
 
        
1026
 
        transform_fun: Function that takes a value and a variant_level
1027
 
                       and transforms it to a D-Bus type.
1028
 
        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
1029
795
        type_func: Function that transform the value before sending it
1030
 
                   to the D-Bus.  Default: no transform
1031
 
        variant_level: D-Bus variant level.  Default: 1
 
796
                   to DBus
 
797
        variant_level: DBus variant level. default: 1
1032
798
        """
1033
 
        attrname = "_{0}".format(dbus_name)
 
799
        real_value = [None,]
1034
800
        def setter(self, value):
 
801
            old_value = real_value[0]
 
802
            real_value[0] = value
1035
803
            if hasattr(self, "dbus_object_path"):
1036
 
                if (not hasattr(self, attrname) or
1037
 
                    type_func(getattr(self, attrname, None))
1038
 
                    != type_func(value)):
1039
 
                    dbus_value = transform_func(type_func(value),
1040
 
                                                variant_level
1041
 
                                                =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)
1042
807
                    self.PropertyChanged(dbus.String(dbus_name),
1043
808
                                         dbus_value)
1044
 
            setattr(self, attrname, value)
1045
 
        
1046
 
        return property(lambda self: getattr(self, attrname), setter)
1047
 
    
1048
 
    
 
809
 
 
810
        return property(lambda self: real_value[0], setter)
 
811
 
 
812
 
1049
813
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
1050
814
    approvals_pending = notifychangeproperty(dbus.Boolean,
1051
815
                                             "ApprovalPending",
1054
818
    last_enabled = notifychangeproperty(datetime_to_dbus,
1055
819
                                        "LastEnabled")
1056
820
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
1057
 
                                   type_func = lambda checker:
1058
 
                                       checker is not None)
 
821
                                   type_func = lambda checker: checker is not None)
1059
822
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1060
823
                                           "LastCheckedOK")
1061
 
    last_approval_request = notifychangeproperty(
1062
 
        datetime_to_dbus, "LastApprovalRequest")
 
824
    last_approval_request = notifychangeproperty(datetime_to_dbus,
 
825
                                                 "LastApprovalRequest")
1063
826
    approved_by_default = notifychangeproperty(dbus.Boolean,
1064
827
                                               "ApprovedByDefault")
1065
 
    approval_delay = notifychangeproperty(dbus.UInt16,
1066
 
                                          "ApprovalDelay",
1067
 
                                          type_func =
1068
 
                                          _timedelta_to_milliseconds)
1069
 
    approval_duration = notifychangeproperty(
1070
 
        dbus.UInt16, "ApprovalDuration",
1071
 
        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)
1072
832
    host = notifychangeproperty(dbus.String, "Host")
1073
833
    timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1074
 
                                   type_func =
1075
 
                                   _timedelta_to_milliseconds)
1076
 
    extended_timeout = notifychangeproperty(
1077
 
        dbus.UInt16, "ExtendedTimeout",
1078
 
        type_func = _timedelta_to_milliseconds)
1079
 
    interval = notifychangeproperty(dbus.UInt16,
1080
 
                                    "Interval",
1081
 
                                    type_func =
1082
 
                                    _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)
1083
839
    checker_command = notifychangeproperty(dbus.String, "Checker")
1084
840
    
1085
841
    del notifychangeproperty
1111
867
        
1112
868
        return Client.checker_callback(self, pid, condition, command,
1113
869
                                       *args, **kwargs)
1114
 
    
 
870
 
1115
871
    def start_checker(self, *args, **kwargs):
1116
872
        old_checker = self.checker
1117
873
        if self.checker is not None:
1139
895
    
1140
896
    
1141
897
    ## D-Bus methods, signals & properties
1142
 
    _interface = "se.recompile.Mandos.Client"
 
898
    _interface = "se.bsnet.fukt.Mandos.Client"
1143
899
    
1144
900
    ## Signals
1145
901
    
1182
938
        "D-Bus signal"
1183
939
        return self.need_approval()
1184
940
    
1185
 
    # NeRwequest - signal
1186
 
    @dbus.service.signal(_interface, signature="s")
1187
 
    def NewRequest(self, ip):
1188
 
        """D-Bus signal
1189
 
        Is sent after a client request a password.
1190
 
        """
1191
 
        pass
1192
 
    
1193
941
    ## Methods
1194
942
    
1195
943
    # Approve - method
1328
1076
        gobject.source_remove(self.disable_initiator_tag)
1329
1077
        self.disable_initiator_tag = None
1330
1078
        self.expires = None
1331
 
        time_to_die = _timedelta_to_milliseconds((self
1332
 
                                                  .last_checked_ok
1333
 
                                                  + self.timeout)
1334
 
                                                 - datetime.datetime
1335
 
                                                 .utcnow())
 
1079
        time_to_die = (self.
 
1080
                       _timedelta_to_milliseconds((self
 
1081
                                                   .last_checked_ok
 
1082
                                                   + self.timeout)
 
1083
                                                  - datetime.datetime
 
1084
                                                  .utcnow()))
1336
1085
        if time_to_die <= 0:
1337
1086
            # The timeout has passed
1338
1087
            self.disable()
1339
1088
        else:
1340
1089
            self.expires = (datetime.datetime.utcnow()
1341
 
                            + datetime.timedelta(milliseconds =
1342
 
                                                 time_to_die))
 
1090
                            + datetime.timedelta(milliseconds = time_to_die))
1343
1091
            self.disable_initiator_tag = (gobject.timeout_add
1344
1092
                                          (time_to_die, self.disable))
1345
 
    
 
1093
 
1346
1094
    # ExtendedTimeout - property
1347
1095
    @dbus_service_property(_interface, signature="t",
1348
1096
                           access="readwrite")
1350
1098
        if value is None:       # get
1351
1099
            return dbus.UInt64(self.extended_timeout_milliseconds())
1352
1100
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1353
 
    
 
1101
 
1354
1102
    # Interval - property
1355
1103
    @dbus_service_property(_interface, signature="t",
1356
1104
                           access="readwrite")
1365
1113
        self.checker_initiator_tag = (gobject.timeout_add
1366
1114
                                      (value, self.start_checker))
1367
1115
        self.start_checker()    # Start one now, too
1368
 
    
 
1116
 
1369
1117
    # Checker - property
1370
1118
    @dbus_service_property(_interface, signature="s",
1371
1119
                           access="readwrite")
1405
1153
        self._pipe.send(('init', fpr, address))
1406
1154
        if not self._pipe.recv():
1407
1155
            raise KeyError()
1408
 
    
 
1156
 
1409
1157
    def __getattribute__(self, name):
1410
1158
        if(name == '_pipe'):
1411
1159
            return super(ProxyClient, self).__getattribute__(name)
1418
1166
                self._pipe.send(('funcall', name, args, kwargs))
1419
1167
                return self._pipe.recv()[1]
1420
1168
            return func
1421
 
    
 
1169
 
1422
1170
    def __setattr__(self, name, value):
1423
1171
        if(name == '_pipe'):
1424
1172
            return super(ProxyClient, self).__setattr__(name, value)
1425
1173
        self._pipe.send(('setattr', name, value))
1426
1174
 
1427
1175
 
1428
 
class ClientDBusTransitional(ClientDBus):
1429
 
    __metaclass__ = AlternateDBusNamesMetaclass
1430
 
 
1431
 
 
1432
1176
class ClientHandler(socketserver.BaseRequestHandler, object):
1433
1177
    """A class to handle client connections.
1434
1178
    
1441
1185
                        unicode(self.client_address))
1442
1186
            logger.debug("Pipe FD: %d",
1443
1187
                         self.server.child_pipe.fileno())
1444
 
            
 
1188
 
1445
1189
            session = (gnutls.connection
1446
1190
                       .ClientSession(self.request,
1447
1191
                                      gnutls.connection
1448
1192
                                      .X509Credentials()))
1449
 
            
 
1193
 
1450
1194
            # Note: gnutls.connection.X509Credentials is really a
1451
1195
            # generic GnuTLS certificate credentials object so long as
1452
1196
            # no X.509 keys are added to it.  Therefore, we can use it
1453
1197
            # here despite using OpenPGP certificates.
1454
 
            
 
1198
 
1455
1199
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1456
1200
            #                      "+AES-256-CBC", "+SHA1",
1457
1201
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
1463
1207
            (gnutls.library.functions
1464
1208
             .gnutls_priority_set_direct(session._c_object,
1465
1209
                                         priority, None))
1466
 
            
 
1210
 
1467
1211
            # Start communication using the Mandos protocol
1468
1212
            # Get protocol number
1469
1213
            line = self.request.makefile().readline()
1474
1218
            except (ValueError, IndexError, RuntimeError) as error:
1475
1219
                logger.error("Unknown protocol version: %s", error)
1476
1220
                return
1477
 
            
 
1221
 
1478
1222
            # Start GnuTLS connection
1479
1223
            try:
1480
1224
                session.handshake()
1484
1228
                # established.  Just abandon the request.
1485
1229
                return
1486
1230
            logger.debug("Handshake succeeded")
1487
 
            
 
1231
 
1488
1232
            approval_required = False
1489
1233
            try:
1490
1234
                try:
1495
1239
                    logger.warning("Bad certificate: %s", error)
1496
1240
                    return
1497
1241
                logger.debug("Fingerprint: %s", fpr)
1498
 
                if self.server.use_dbus:
1499
 
                    # Emit D-Bus signal
1500
 
                    client.NewRequest(str(self.client_address))
1501
 
                
 
1242
 
1502
1243
                try:
1503
1244
                    client = ProxyClient(child_pipe, fpr,
1504
1245
                                         self.client_address)
1516
1257
                                       client.name)
1517
1258
                        if self.server.use_dbus:
1518
1259
                            # Emit D-Bus signal
1519
 
                            client.Rejected("Disabled")
 
1260
                            client.Rejected("Disabled")                    
1520
1261
                        return
1521
1262
                    
1522
1263
                    if client._approved or not client.approval_delay:
1539
1280
                        return
1540
1281
                    
1541
1282
                    #wait until timeout or approved
 
1283
                    #x = float(client._timedelta_to_milliseconds(delay))
1542
1284
                    time = datetime.datetime.now()
1543
1285
                    client.changedstate.acquire()
1544
 
                    (client.changedstate.wait
1545
 
                     (float(client._timedelta_to_milliseconds(delay)
1546
 
                            / 1000)))
 
1286
                    client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000))
1547
1287
                    client.changedstate.release()
1548
1288
                    time2 = datetime.datetime.now()
1549
1289
                    if (time2 - time) >= delay:
1571
1311
                                 sent, len(client.secret)
1572
1312
                                 - (sent_size + sent))
1573
1313
                    sent_size += sent
1574
 
                
 
1314
 
1575
1315
                logger.info("Sending secret to %s", client.name)
1576
 
                # bump the timeout using extended_timeout
 
1316
                # bump the timeout as if seen
1577
1317
                client.checked_ok(client.extended_timeout)
1578
1318
                if self.server.use_dbus:
1579
1319
                    # Emit D-Bus signal
1647
1387
        # Convert the buffer to a Python bytestring
1648
1388
        fpr = ctypes.string_at(buf, buf_len.value)
1649
1389
        # Convert the bytestring to hexadecimal notation
1650
 
        hex_fpr = binascii.hexlify(fpr).upper()
 
1390
        hex_fpr = ''.join("%02X" % ord(char) for char in fpr)
1651
1391
        return hex_fpr
1652
1392
 
1653
1393
 
1659
1399
        except:
1660
1400
            self.handle_error(request, address)
1661
1401
        self.close_request(request)
1662
 
    
 
1402
            
1663
1403
    def process_request(self, request, address):
1664
1404
        """Start a new process to process the request."""
1665
 
        proc = multiprocessing.Process(target = self.sub_process_main,
1666
 
                                       args = (request,
1667
 
                                               address))
1668
 
        proc.start()
1669
 
        return proc
1670
 
 
 
1405
        multiprocessing.Process(target = self.sub_process_main,
 
1406
                                args = (request, address)).start()
1671
1407
 
1672
1408
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1673
1409
    """ adds a pipe to the MixIn """
1677
1413
        This function creates a new pipe in self.pipe
1678
1414
        """
1679
1415
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1680
 
        
1681
 
        proc = MultiprocessingMixIn.process_request(self, request,
1682
 
                                                    client_address)
 
1416
 
 
1417
        super(MultiprocessingMixInWithPipe,
 
1418
              self).process_request(request, client_address)
1683
1419
        self.child_pipe.close()
1684
 
        self.add_pipe(parent_pipe, proc)
1685
 
    
1686
 
    def add_pipe(self, parent_pipe, proc):
 
1420
        self.add_pipe(parent_pipe)
 
1421
 
 
1422
    def add_pipe(self, parent_pipe):
1687
1423
        """Dummy function; override as necessary"""
1688
1424
        raise NotImplementedError
1689
1425
 
1690
 
 
1691
1426
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1692
1427
                     socketserver.TCPServer, object):
1693
1428
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1767
1502
        self.enabled = False
1768
1503
        self.clients = clients
1769
1504
        if self.clients is None:
1770
 
            self.clients = {}
 
1505
            self.clients = set()
1771
1506
        self.use_dbus = use_dbus
1772
1507
        self.gnutls_priority = gnutls_priority
1773
1508
        IPv6_TCPServer.__init__(self, server_address,
1777
1512
    def server_activate(self):
1778
1513
        if self.enabled:
1779
1514
            return socketserver.TCPServer.server_activate(self)
1780
 
    
1781
1515
    def enable(self):
1782
1516
        self.enabled = True
1783
 
    
1784
 
    def add_pipe(self, parent_pipe, proc):
 
1517
    def add_pipe(self, parent_pipe):
1785
1518
        # Call "handle_ipc" for both data and EOF events
1786
1519
        gobject.io_add_watch(parent_pipe.fileno(),
1787
1520
                             gobject.IO_IN | gobject.IO_HUP,
1788
1521
                             functools.partial(self.handle_ipc,
1789
 
                                               parent_pipe =
1790
 
                                               parent_pipe,
1791
 
                                               proc = proc))
1792
 
    
 
1522
                                               parent_pipe = parent_pipe))
 
1523
        
1793
1524
    def handle_ipc(self, source, condition, parent_pipe=None,
1794
 
                   proc = None, client_object=None):
 
1525
                   client_object=None):
1795
1526
        condition_names = {
1796
1527
            gobject.IO_IN: "IN",   # There is data to read.
1797
1528
            gobject.IO_OUT: "OUT", # Data can be written (without
1806
1537
                                       for cond, name in
1807
1538
                                       condition_names.iteritems()
1808
1539
                                       if cond & condition)
1809
 
        # error, or the other end of multiprocessing.Pipe has closed
 
1540
        # error or the other end of multiprocessing.Pipe has closed
1810
1541
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
1811
 
            # Wait for other process to exit
1812
 
            proc.join()
1813
1542
            return False
1814
1543
        
1815
1544
        # Read a request from the child
1820
1549
            fpr = request[1]
1821
1550
            address = request[2]
1822
1551
            
1823
 
            for c in self.clients.itervalues():
 
1552
            for c in self.clients:
1824
1553
                if c.fingerprint == fpr:
1825
1554
                    client = c
1826
1555
                    break
1829
1558
                            "dress: %s", fpr, address)
1830
1559
                if self.use_dbus:
1831
1560
                    # Emit D-Bus signal
1832
 
                    mandos_dbus_service.ClientNotFound(fpr,
1833
 
                                                       address[0])
 
1561
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1834
1562
                parent_pipe.send(False)
1835
1563
                return False
1836
1564
            
1837
1565
            gobject.io_add_watch(parent_pipe.fileno(),
1838
1566
                                 gobject.IO_IN | gobject.IO_HUP,
1839
1567
                                 functools.partial(self.handle_ipc,
1840
 
                                                   parent_pipe =
1841
 
                                                   parent_pipe,
1842
 
                                                   proc = proc,
1843
 
                                                   client_object =
1844
 
                                                   client))
 
1568
                                                   parent_pipe = parent_pipe,
 
1569
                                                   client_object = client))
1845
1570
            parent_pipe.send(True)
1846
 
            # remove the old hook in favor of the new above hook on
1847
 
            # same fileno
 
1571
            # remove the old hook in favor of the new above hook on same fileno
1848
1572
            return False
1849
1573
        if command == 'funcall':
1850
1574
            funcname = request[1]
1851
1575
            args = request[2]
1852
1576
            kwargs = request[3]
1853
1577
            
1854
 
            parent_pipe.send(('data', getattr(client_object,
1855
 
                                              funcname)(*args,
1856
 
                                                         **kwargs)))
1857
 
        
 
1578
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
 
1579
 
1858
1580
        if command == 'getattr':
1859
1581
            attrname = request[1]
1860
1582
            if callable(client_object.__getattribute__(attrname)):
1861
1583
                parent_pipe.send(('function',))
1862
1584
            else:
1863
 
                parent_pipe.send(('data', client_object
1864
 
                                  .__getattribute__(attrname)))
 
1585
                parent_pipe.send(('data', client_object.__getattribute__(attrname)))
1865
1586
        
1866
1587
        if command == 'setattr':
1867
1588
            attrname = request[1]
1868
1589
            value = request[2]
1869
1590
            setattr(client_object, attrname, value)
1870
 
        
 
1591
 
1871
1592
        return True
1872
1593
 
1873
1594
 
1910
1631
    return timevalue
1911
1632
 
1912
1633
 
 
1634
def if_nametoindex(interface):
 
1635
    """Call the C function if_nametoindex(), or equivalent
 
1636
    
 
1637
    Note: This function cannot accept a unicode string."""
 
1638
    global if_nametoindex
 
1639
    try:
 
1640
        if_nametoindex = (ctypes.cdll.LoadLibrary
 
1641
                          (ctypes.util.find_library("c"))
 
1642
                          .if_nametoindex)
 
1643
    except (OSError, AttributeError):
 
1644
        logger.warning("Doing if_nametoindex the hard way")
 
1645
        def if_nametoindex(interface):
 
1646
            "Get an interface index the hard way, i.e. using fcntl()"
 
1647
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
 
1648
            with contextlib.closing(socket.socket()) as s:
 
1649
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
 
1650
                                    struct.pack(str("16s16x"),
 
1651
                                                interface))
 
1652
            interface_index = struct.unpack(str("I"),
 
1653
                                            ifreq[16:20])[0]
 
1654
            return interface_index
 
1655
    return if_nametoindex(interface)
 
1656
 
 
1657
 
1913
1658
def daemon(nochdir = False, noclose = False):
1914
1659
    """See daemon(3).  Standard BSD Unix function.
1915
1660
    
1970
1715
                        " system bus interface")
1971
1716
    parser.add_argument("--no-ipv6", action="store_false",
1972
1717
                        dest="use_ipv6", help="Do not use IPv6")
1973
 
    parser.add_argument("--no-restore", action="store_false",
1974
 
                        dest="restore", help="Do not restore stored"
1975
 
                        " state", default=True)
1976
 
    
1977
1718
    options = parser.parse_args()
1978
1719
    
1979
1720
    if options.check:
2014
1755
    # options, if set.
2015
1756
    for option in ("interface", "address", "port", "debug",
2016
1757
                   "priority", "servicename", "configdir",
2017
 
                   "use_dbus", "use_ipv6", "debuglevel", "restore"):
 
1758
                   "use_dbus", "use_ipv6", "debuglevel"):
2018
1759
        value = getattr(options, option)
2019
1760
        if value is not None:
2020
1761
            server_settings[option] = value
2032
1773
    debuglevel = server_settings["debuglevel"]
2033
1774
    use_dbus = server_settings["use_dbus"]
2034
1775
    use_ipv6 = server_settings["use_ipv6"]
2035
 
    
2036
 
    if debug:
2037
 
        initlogger(logging.DEBUG)
2038
 
    else:
2039
 
        if not debuglevel:
2040
 
            initlogger()
2041
 
        else:
2042
 
            level = getattr(logging, debuglevel.upper())
2043
 
            initlogger(level)
2044
 
    
 
1776
 
2045
1777
    if server_settings["servicename"] != "Mandos":
2046
1778
        syslogger.setFormatter(logging.Formatter
2047
1779
                               ('Mandos (%s) [%%(process)d]:'
2101
1833
        if error[0] != errno.EPERM:
2102
1834
            raise error
2103
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
 
2104
1844
    if debug:
2105
1845
        # Enable all possible GnuTLS debugging
2106
1846
        
2137
1877
    # End of Avahi example code
2138
1878
    if use_dbus:
2139
1879
        try:
2140
 
            bus_name = dbus.service.BusName("se.recompile.Mandos",
 
1880
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
2141
1881
                                            bus, do_not_queue=True)
2142
 
            old_bus_name = (dbus.service.BusName
2143
 
                            ("se.bsnet.fukt.Mandos", bus,
2144
 
                             do_not_queue=True))
2145
1882
        except dbus.exceptions.NameExistsException as e:
2146
1883
            logger.error(unicode(e) + ", disabling D-Bus")
2147
1884
            use_dbus = False
2148
1885
            server_settings["use_dbus"] = False
2149
1886
            tcp_server.use_dbus = False
2150
1887
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2151
 
    service = AvahiServiceToSyslog(name =
2152
 
                                   server_settings["servicename"],
2153
 
                                   servicetype = "_mandos._tcp",
2154
 
                                   protocol = protocol, bus = bus)
 
1888
    service = AvahiService(name = server_settings["servicename"],
 
1889
                           servicetype = "_mandos._tcp",
 
1890
                           protocol = protocol, bus = bus)
2155
1891
    if server_settings["interface"]:
2156
1892
        service.interface = (if_nametoindex
2157
1893
                             (str(server_settings["interface"])))
2161
1897
    
2162
1898
    client_class = Client
2163
1899
    if use_dbus:
2164
 
        client_class = functools.partial(ClientDBusTransitional,
2165
 
                                         bus = bus)
2166
 
    
2167
 
    special_settings = {
2168
 
        # Some settings need to be accessd by special methods;
2169
 
        # booleans need .getboolean(), etc.  Here is a list of them:
2170
 
        "approved_by_default":
2171
 
            lambda section:
2172
 
            client_config.getboolean(section, "approved_by_default"),
2173
 
        }
2174
 
    # Construct a new dict of client settings of this form:
2175
 
    # { client_name: {setting_name: value, ...}, ...}
2176
 
    # with exceptions for any special settings as defined above
2177
 
    client_settings = dict((clientname,
2178
 
                           dict((setting,
2179
 
                                 (value
2180
 
                                  if setting not in special_settings
2181
 
                                  else special_settings[setting]
2182
 
                                  (clientname)))
2183
 
                                for setting, value in
2184
 
                                client_config.items(clientname)))
2185
 
                          for clientname in client_config.sections())
2186
 
    
2187
 
    old_client_settings = {}
2188
 
    clients_data = []
2189
 
    
2190
 
    # Get client data and settings from last running state.
2191
 
    if server_settings["restore"]:
2192
 
        try:
2193
 
            with open(stored_state_path, "rb") as stored_state:
2194
 
                clients_data, old_client_settings = (pickle.load
2195
 
                                                     (stored_state))
2196
 
            os.remove(stored_state_path)
2197
 
        except IOError as e:
2198
 
            logger.warning("Could not load persistent state: {0}"
2199
 
                           .format(e))
2200
 
            if e.errno != errno.ENOENT:
2201
 
                raise
2202
 
    
2203
 
    with Crypto() as crypt:
2204
 
        for client in clients_data:
2205
 
            client_name = client["name"]
2206
 
            
2207
 
            # Decide which value to use after restoring saved state.
2208
 
            # We have three different values: Old config file,
2209
 
            # new config file, and saved state.
2210
 
            # New config value takes precedence if it differs from old
2211
 
            # config value, otherwise use saved state.
2212
 
            for name, value in client_settings[client_name].items():
2213
 
                try:
2214
 
                    # For each value in new config, check if it
2215
 
                    # differs from the old config value (Except for
2216
 
                    # the "secret" attribute)
2217
 
                    if (name != "secret" and
2218
 
                        value != old_client_settings[client_name]
2219
 
                        [name]):
2220
 
                        setattr(client, name, value)
2221
 
                except KeyError:
2222
 
                    pass
2223
 
            
2224
 
            # Clients who has passed its expire date can still be
2225
 
            # enabled if its last checker was sucessful.  Clients
2226
 
            # whose checker failed before we stored its state is
2227
 
            # assumed to have failed all checkers during downtime.
2228
 
            if client["enabled"] and client["last_checked_ok"]:
2229
 
                if ((datetime.datetime.utcnow()
2230
 
                     - client["last_checked_ok"])
2231
 
                    > client["interval"]):
2232
 
                    if client["last_checker_status"] != 0:
2233
 
                        client["enabled"] = False
2234
 
                    else:
2235
 
                        client["expires"] = (datetime.datetime
2236
 
                                             .utcnow()
2237
 
                                             + client["timeout"])
2238
 
            
2239
 
            client["changedstate"] = (multiprocessing_manager
2240
 
                                      .Condition
2241
 
                                      (multiprocessing_manager
2242
 
                                       .Lock()))
2243
 
            if use_dbus:
2244
 
                new_client = (ClientDBusTransitional.__new__
2245
 
                              (ClientDBusTransitional))
2246
 
                tcp_server.clients[client_name] = new_client
2247
 
                new_client.bus = bus
2248
 
                for name, value in client.iteritems():
2249
 
                    setattr(new_client, name, value)
2250
 
                client_object_name = unicode(client_name).translate(
2251
 
                    {ord("."): ord("_"),
2252
 
                     ord("-"): ord("_")})
2253
 
                new_client.dbus_object_path = (dbus.ObjectPath
2254
 
                                               ("/clients/"
2255
 
                                                + client_object_name))
2256
 
                DBusObjectWithProperties.__init__(new_client,
2257
 
                                                  new_client.bus,
2258
 
                                                  new_client
2259
 
                                                  .dbus_object_path)
2260
 
            else:
2261
 
                tcp_server.clients[client_name] = (Client.__new__
2262
 
                                                   (Client))
2263
 
                for name, value in client.iteritems():
2264
 
                    setattr(tcp_server.clients[client_name],
2265
 
                            name, value)
2266
 
            
 
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):
2267
1908
            try:
2268
 
                tcp_server.clients[client_name].secret = (
2269
 
                    crypt.decrypt(tcp_server.clients[client_name]
2270
 
                                  .encrypted_secret,
2271
 
                                  client_settings[client_name]
2272
 
                                  ["secret"]))
2273
 
            except CryptoError:
2274
 
                # If decryption fails, we use secret from new settings
2275
 
                tcp_server.clients[client_name].secret = (
2276
 
                    client_settings[client_name]["secret"])
2277
 
    
2278
 
    # Create/remove clients based on new changes made to config
2279
 
    for clientname in set(old_client_settings) - set(client_settings):
2280
 
        del tcp_server.clients[clientname]
2281
 
    for clientname in set(client_settings) - set(old_client_settings):
2282
 
        tcp_server.clients[clientname] = (client_class(name
2283
 
                                                       = clientname,
2284
 
                                                       config =
2285
 
                                                       client_settings
2286
 
                                                       [clientname]))
2287
 
    
 
1909
                yield (name, special_settings[name]())
 
1910
            except KeyError:
 
1911
                yield (name, value)
 
1912
    
 
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()))
2288
1918
    if not tcp_server.clients:
2289
1919
        logger.warning("No clients defined")
2290
1920
        
2303
1933
        del pidfilename
2304
1934
        
2305
1935
        signal.signal(signal.SIGINT, signal.SIG_IGN)
2306
 
    
 
1936
 
2307
1937
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2308
1938
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2309
1939
    
2312
1942
            """A D-Bus proxy object"""
2313
1943
            def __init__(self):
2314
1944
                dbus.service.Object.__init__(self, bus, "/")
2315
 
            _interface = "se.recompile.Mandos"
 
1945
            _interface = "se.bsnet.fukt.Mandos"
2316
1946
            
2317
1947
            @dbus.service.signal(_interface, signature="o")
2318
1948
            def ClientAdded(self, objpath):
2333
1963
            def GetAllClients(self):
2334
1964
                "D-Bus method"
2335
1965
                return dbus.Array(c.dbus_object_path
2336
 
                                  for c in
2337
 
                                  tcp_server.clients.itervalues())
 
1966
                                  for c in tcp_server.clients)
2338
1967
            
2339
1968
            @dbus.service.method(_interface,
2340
1969
                                 out_signature="a{oa{sv}}")
2342
1971
                "D-Bus method"
2343
1972
                return dbus.Dictionary(
2344
1973
                    ((c.dbus_object_path, c.GetAll(""))
2345
 
                     for c in tcp_server.clients.itervalues()),
 
1974
                     for c in tcp_server.clients),
2346
1975
                    signature="oa{sv}")
2347
1976
            
2348
1977
            @dbus.service.method(_interface, in_signature="o")
2349
1978
            def RemoveClient(self, object_path):
2350
1979
                "D-Bus method"
2351
 
                for c in tcp_server.clients.itervalues():
 
1980
                for c in tcp_server.clients:
2352
1981
                    if c.dbus_object_path == object_path:
2353
 
                        del tcp_server.clients[c.name]
 
1982
                        tcp_server.clients.remove(c)
2354
1983
                        c.remove_from_connection()
2355
1984
                        # Don't signal anything except ClientRemoved
2356
1985
                        c.disable(quiet=True)
2361
1990
            
2362
1991
            del _interface
2363
1992
        
2364
 
        class MandosDBusServiceTransitional(MandosDBusService):
2365
 
            __metaclass__ = AlternateDBusNamesMetaclass
2366
 
        mandos_dbus_service = MandosDBusServiceTransitional()
 
1993
        mandos_dbus_service = MandosDBusService()
2367
1994
    
2368
1995
    def cleanup():
2369
1996
        "Cleanup function; run on exit"
2370
1997
        service.cleanup()
2371
1998
        
2372
 
        multiprocessing.active_children()
2373
 
        if not (tcp_server.clients or client_settings):
2374
 
            return
2375
 
        
2376
 
        # Store client before exiting. Secrets are encrypted with key
2377
 
        # based on what config file has. If config file is
2378
 
        # removed/edited, old secret will thus be unrecovable.
2379
 
        clients = []
2380
 
        with Crypto() as crypt:
2381
 
            for client in tcp_server.clients.itervalues():
2382
 
                key = client_settings[client.name]["secret"]
2383
 
                client.encrypted_secret = crypt.encrypt(client.secret,
2384
 
                                                        key)
2385
 
                client_dict = {}
2386
 
                
2387
 
                # A list of attributes that will not be stored when
2388
 
                # shutting down.
2389
 
                exclude = set(("bus", "changedstate", "secret"))
2390
 
                for name, typ in (inspect.getmembers
2391
 
                                  (dbus.service.Object)):
2392
 
                    exclude.add(name)
2393
 
                
2394
 
                client_dict["encrypted_secret"] = (client
2395
 
                                                   .encrypted_secret)
2396
 
                for attr in client.client_structure:
2397
 
                    if attr not in exclude:
2398
 
                        client_dict[attr] = getattr(client, attr)
2399
 
                
2400
 
                clients.append(client_dict)
2401
 
                del client_settings[client.name]["secret"]
2402
 
        
2403
 
        try:
2404
 
            with os.fdopen(os.open(stored_state_path,
2405
 
                                   os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2406
 
                                   0600), "wb") as stored_state:
2407
 
                pickle.dump((clients, client_settings), stored_state)
2408
 
        except (IOError, OSError) as e:
2409
 
            logger.warning("Could not save persistent state: {0}"
2410
 
                           .format(e))
2411
 
            if e.errno not in (errno.ENOENT, errno.EACCES):
2412
 
                raise
2413
 
        
2414
 
        # Delete all clients, and settings from config
2415
1999
        while tcp_server.clients:
2416
 
            name, client = tcp_server.clients.popitem()
 
2000
            client = tcp_server.clients.pop()
2417
2001
            if use_dbus:
2418
2002
                client.remove_from_connection()
 
2003
            client.disable_hook = None
2419
2004
            # Don't signal anything except ClientRemoved
2420
2005
            client.disable(quiet=True)
2421
2006
            if use_dbus:
2422
2007
                # Emit D-Bus signal
2423
 
                mandos_dbus_service.ClientRemoved(client
2424
 
                                                  .dbus_object_path,
 
2008
                mandos_dbus_service.ClientRemoved(client.dbus_object_path,
2425
2009
                                                  client.name)
2426
 
        client_settings.clear()
2427
2010
    
2428
2011
    atexit.register(cleanup)
2429
2012
    
2430
 
    for client in tcp_server.clients.itervalues():
 
2013
    for client in tcp_server.clients:
2431
2014
        if use_dbus:
2432
2015
            # Emit D-Bus signal
2433
2016
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
2434
 
        # Need to initiate checking of clients
2435
 
        if client.enabled:
2436
 
            client.init_checker()
 
2017
        client.enable()
2437
2018
    
2438
2019
    tcp_server.enable()
2439
2020
    tcp_server.server_activate()
2479
2060
    # Must run before the D-Bus bus name gets deregistered
2480
2061
    cleanup()
2481
2062
 
2482
 
 
2483
2063
if __name__ == '__main__':
2484
2064
    main()