/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

Change "fukt.bsnet.se" to "recompile.se" throughout.

* README: - '' -
* debian/control: - '' -
* debian/copyright: - '' -
* debian/mandos-client.README.Debian: - '' - and some rewriting.
* debian/mandos.README.Debian: - '' -
* debian/watch: Change "fukt.bsnet.se" to "recompile.se".
* init.d-mandos: - '' -
* intro.xml: - '' -
* mandos: - '' -
* mandos-clients.conf.xml: - '' -
* mandos-ctl: - '' -
* mandos-ctl.xml: - '' -
* mandos-keygen: - '' -
* mandos-keygen.xml: - '' -
* mandos-monitor: - '' -
* mandos-monitor.xml: - '' -
* mandos.conf.xml: - '' -
* mandos.lsm: - '' -
* mandos.xml: - '' -
* plugin-runner.c: - '' -
* plugin-runner.xml: - '' -
* plugins.d/askpass-fifo.c: - '' -
* plugins.d/askpass-fifo.xml: - '' -
* plugins.d/mandos-client.c: - '' -
* plugins.d/mandos-client.xml: - '' -
* plugins.d/password-prompt.c: - '' -
* plugins.d/password-prompt.xml: - '' -
* plugins.d/plymouth.c: - '' -
* plugins.d/plymouth.xml: - '' -
* plugins.d/splashy.c: - '' -
* plugins.d/splashy.xml: - '' -
* plugins.d/usplash.c: - '' -
* plugins.d/usplash.xml: - '' -

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@fukt.bsnet.se>.
 
31
# Contact the authors at <mandos@recompile.se>.
32
32
33
33
 
34
34
from __future__ import (division, absolute_import, print_function,
36
36
 
37
37
import SocketServer as socketserver
38
38
import socket
39
 
import optparse
 
39
import argparse
40
40
import datetime
41
41
import errno
42
42
import gnutls.crypto
62
62
import functools
63
63
import cPickle as pickle
64
64
import multiprocessing
 
65
import types
65
66
 
66
67
import dbus
67
68
import dbus.service
82
83
        SO_BINDTODEVICE = None
83
84
 
84
85
 
85
 
version = "1.2.3"
 
86
version = "1.3.1"
86
87
 
87
88
#logger = logging.getLogger('mandos')
88
89
logger = logging.Logger('mandos')
151
152
        self.group = None       # our entry group
152
153
        self.server = None
153
154
        self.bus = bus
 
155
        self.entry_group_state_changed_match = None
154
156
    def rename(self):
155
157
        """Derived from the Avahi example code"""
156
158
        if self.rename_count >= self.max_renames:
168
170
        self.remove()
169
171
        try:
170
172
            self.add()
171
 
        except dbus.exceptions.DBusException, error:
 
173
        except dbus.exceptions.DBusException as error:
172
174
            logger.critical("DBusException: %s", error)
173
175
            self.cleanup()
174
176
            os._exit(1)
175
177
        self.rename_count += 1
176
178
    def remove(self):
177
179
        """Derived from the Avahi example code"""
 
180
        if self.entry_group_state_changed_match is not None:
 
181
            self.entry_group_state_changed_match.remove()
 
182
            self.entry_group_state_changed_match = None
178
183
        if self.group is not None:
179
184
            self.group.Reset()
180
185
    def add(self):
181
186
        """Derived from the Avahi example code"""
 
187
        self.remove()
182
188
        if self.group is None:
183
189
            self.group = dbus.Interface(
184
190
                self.bus.get_object(avahi.DBUS_NAME,
185
191
                                    self.server.EntryGroupNew()),
186
192
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
187
 
            self.group.connect_to_signal('StateChanged',
188
 
                                         self
189
 
                                         .entry_group_state_changed)
 
193
        self.entry_group_state_changed_match = (
 
194
            self.group.connect_to_signal(
 
195
                'StateChanged', self .entry_group_state_changed))
190
196
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
191
197
                     self.name, self.type)
192
198
        self.group.AddService(
215
221
    def cleanup(self):
216
222
        """Derived from the Avahi example code"""
217
223
        if self.group is not None:
218
 
            self.group.Free()
 
224
            try:
 
225
                self.group.Free()
 
226
            except (dbus.exceptions.UnknownMethodException,
 
227
                    dbus.exceptions.DBusException) as e:
 
228
                pass
219
229
            self.group = None
220
 
    def server_state_changed(self, state):
 
230
        self.remove()
 
231
    def server_state_changed(self, state, error=None):
221
232
        """Derived from the Avahi example code"""
222
233
        logger.debug("Avahi server state change: %i", state)
223
 
        if state == avahi.SERVER_COLLISION:
224
 
            logger.error("Zeroconf server name collision")
225
 
            self.remove()
 
234
        bad_states = { avahi.SERVER_INVALID:
 
235
                           "Zeroconf server invalid",
 
236
                       avahi.SERVER_REGISTERING: None,
 
237
                       avahi.SERVER_COLLISION:
 
238
                           "Zeroconf server name collision",
 
239
                       avahi.SERVER_FAILURE:
 
240
                           "Zeroconf server failure" }
 
241
        if state in bad_states:
 
242
            if bad_states[state] is not None:
 
243
                if error is None:
 
244
                    logger.error(bad_states[state])
 
245
                else:
 
246
                    logger.error(bad_states[state] + ": %r", error)
 
247
            self.cleanup()
226
248
        elif state == avahi.SERVER_RUNNING:
227
249
            self.add()
 
250
        else:
 
251
            if error is None:
 
252
                logger.debug("Unknown state: %r", state)
 
253
            else:
 
254
                logger.debug("Unknown state: %r: %r", state, error)
228
255
    def activate(self):
229
256
        """Derived from the Avahi example code"""
230
257
        if self.server is None:
231
258
            self.server = dbus.Interface(
232
259
                self.bus.get_object(avahi.DBUS_NAME,
233
 
                                    avahi.DBUS_PATH_SERVER),
 
260
                                    avahi.DBUS_PATH_SERVER,
 
261
                                    follow_name_owner_changes=True),
234
262
                avahi.DBUS_INTERFACE_SERVER)
235
263
        self.server.connect_to_signal("StateChanged",
236
264
                                 self.server_state_changed)
237
265
        self.server_state_changed(self.server.GetState())
238
266
 
239
267
 
 
268
def _timedelta_to_milliseconds(td):
 
269
    "Convert a datetime.timedelta() to milliseconds"
 
270
    return ((td.days * 24 * 60 * 60 * 1000)
 
271
            + (td.seconds * 1000)
 
272
            + (td.microseconds // 1000))
 
273
        
240
274
class Client(object):
241
275
    """A representation of a client host served by this server.
242
276
    
270
304
    secret:     bytestring; sent verbatim (over TLS) to client
271
305
    timeout:    datetime.timedelta(); How long from last_checked_ok
272
306
                                      until this client is disabled
 
307
    extended_timeout:   extra long timeout when password has been sent
273
308
    runtime_expansions: Allowed attributes for runtime expansion.
 
309
    expires:    datetime.datetime(); time (UTC) when a client will be
 
310
                disabled, or None
274
311
    """
275
312
    
276
313
    runtime_expansions = ("approval_delay", "approval_duration",
278
315
                          "host", "interval", "last_checked_ok",
279
316
                          "last_enabled", "name", "timeout")
280
317
    
281
 
    @staticmethod
282
 
    def _timedelta_to_milliseconds(td):
283
 
        "Convert a datetime.timedelta() to milliseconds"
284
 
        return ((td.days * 24 * 60 * 60 * 1000)
285
 
                + (td.seconds * 1000)
286
 
                + (td.microseconds // 1000))
287
 
    
288
318
    def timeout_milliseconds(self):
289
319
        "Return the 'timeout' attribute in milliseconds"
290
 
        return self._timedelta_to_milliseconds(self.timeout)
 
320
        return _timedelta_to_milliseconds(self.timeout)
 
321
    
 
322
    def extended_timeout_milliseconds(self):
 
323
        "Return the 'extended_timeout' attribute in milliseconds"
 
324
        return _timedelta_to_milliseconds(self.extended_timeout)    
291
325
    
292
326
    def interval_milliseconds(self):
293
327
        "Return the 'interval' attribute in milliseconds"
294
 
        return self._timedelta_to_milliseconds(self.interval)
295
 
 
 
328
        return _timedelta_to_milliseconds(self.interval)
 
329
    
296
330
    def approval_delay_milliseconds(self):
297
 
        return self._timedelta_to_milliseconds(self.approval_delay)
 
331
        return _timedelta_to_milliseconds(self.approval_delay)
298
332
    
299
333
    def __init__(self, name = None, disable_hook=None, config=None):
300
334
        """Note: the 'checker' key in 'config' sets the
327
361
        self.last_enabled = None
328
362
        self.last_checked_ok = None
329
363
        self.timeout = string_to_delta(config["timeout"])
 
364
        self.extended_timeout = string_to_delta(config["extended_timeout"])
330
365
        self.interval = string_to_delta(config["interval"])
331
366
        self.disable_hook = disable_hook
332
367
        self.checker = None
333
368
        self.checker_initiator_tag = None
334
369
        self.disable_initiator_tag = None
 
370
        self.expires = None
335
371
        self.checker_callback_tag = None
336
372
        self.checker_command = config["checker"]
337
373
        self.current_checker_command = None
357
393
            # Already enabled
358
394
            return
359
395
        self.send_changedstate()
360
 
        self.last_enabled = datetime.datetime.utcnow()
361
396
        # Schedule a new checker to be started an 'interval' from now,
362
397
        # and every interval from then on.
363
398
        self.checker_initiator_tag = (gobject.timeout_add
364
399
                                      (self.interval_milliseconds(),
365
400
                                       self.start_checker))
366
401
        # Schedule a disable() when 'timeout' has passed
 
402
        self.expires = datetime.datetime.utcnow() + self.timeout
367
403
        self.disable_initiator_tag = (gobject.timeout_add
368
404
                                   (self.timeout_milliseconds(),
369
405
                                    self.disable))
370
406
        self.enabled = True
 
407
        self.last_enabled = datetime.datetime.utcnow()
371
408
        # Also start a new checker *right now*.
372
409
        self.start_checker()
373
410
    
382
419
        if getattr(self, "disable_initiator_tag", False):
383
420
            gobject.source_remove(self.disable_initiator_tag)
384
421
            self.disable_initiator_tag = None
 
422
        self.expires = None
385
423
        if getattr(self, "checker_initiator_tag", False):
386
424
            gobject.source_remove(self.checker_initiator_tag)
387
425
            self.checker_initiator_tag = None
413
451
            logger.warning("Checker for %(name)s crashed?",
414
452
                           vars(self))
415
453
    
416
 
    def checked_ok(self):
 
454
    def checked_ok(self, timeout=None):
417
455
        """Bump up the timeout for this client.
418
456
        
419
457
        This should only be called when the client has been seen,
420
458
        alive and well.
421
459
        """
 
460
        if timeout is None:
 
461
            timeout = self.timeout
422
462
        self.last_checked_ok = datetime.datetime.utcnow()
423
463
        gobject.source_remove(self.disable_initiator_tag)
 
464
        self.expires = datetime.datetime.utcnow() + timeout
424
465
        self.disable_initiator_tag = (gobject.timeout_add
425
 
                                      (self.timeout_milliseconds(),
 
466
                                      (_timedelta_to_milliseconds(timeout),
426
467
                                       self.disable))
427
468
    
428
469
    def need_approval(self):
445
486
        # If a checker exists, make sure it is not a zombie
446
487
        try:
447
488
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
448
 
        except (AttributeError, OSError), error:
 
489
        except (AttributeError, OSError) as error:
449
490
            if (isinstance(error, OSError)
450
491
                and error.errno != errno.ECHILD):
451
492
                raise error
469
510
                                       'replace')))
470
511
                    for attr in
471
512
                    self.runtime_expansions)
472
 
 
 
513
                
473
514
                try:
474
515
                    command = self.checker_command % escaped_attrs
475
 
                except TypeError, error:
 
516
                except TypeError as error:
476
517
                    logger.error('Could not format string "%s":'
477
518
                                 ' %s', self.checker_command, error)
478
519
                    return True # Try again later
497
538
                if pid:
498
539
                    gobject.source_remove(self.checker_callback_tag)
499
540
                    self.checker_callback(pid, status, command)
500
 
            except OSError, error:
 
541
            except OSError as error:
501
542
                logger.error("Failed to start subprocess: %s",
502
543
                             error)
503
544
        # Re-run this periodically if run by gobject.timeout_add
516
557
            #time.sleep(0.5)
517
558
            #if self.checker.poll() is None:
518
559
            #    os.kill(self.checker.pid, signal.SIGKILL)
519
 
        except OSError, error:
 
560
        except OSError as error:
520
561
            if error.errno != errno.ESRCH: # No such process
521
562
                raise
522
563
        self.checker = None
523
564
 
 
565
 
524
566
def dbus_service_property(dbus_interface, signature="v",
525
567
                          access="readwrite", byte_arrays=False):
526
568
    """Decorators for marking methods of a DBusObjectWithProperties to
572
614
 
573
615
class DBusObjectWithProperties(dbus.service.Object):
574
616
    """A D-Bus object with properties.
575
 
 
 
617
    
576
618
    Classes inheriting from this can use the dbus_service_property
577
619
    decorator to expose methods as D-Bus properties.  It exposes the
578
620
    standard Get(), Set(), and GetAll() methods on the D-Bus.
585
627
    def _get_all_dbus_properties(self):
586
628
        """Returns a generator of (name, attribute) pairs
587
629
        """
588
 
        return ((prop._dbus_name, prop)
589
 
                for name, prop in
590
 
                inspect.getmembers(self, self._is_dbus_property))
 
630
        return ((prop.__get__(self)._dbus_name, prop.__get__(self))
 
631
                for cls in self.__class__.__mro__
 
632
                for name, prop in inspect.getmembers(cls, self._is_dbus_property))
591
633
    
592
634
    def _get_dbus_property(self, interface_name, property_name):
593
635
        """Returns a bound method if one exists which is a D-Bus
594
636
        property with the specified name and interface.
595
637
        """
596
 
        for name in (property_name,
597
 
                     property_name + "_dbus_property"):
598
 
            prop = getattr(self, name, None)
599
 
            if (prop is None
600
 
                or not self._is_dbus_property(prop)
601
 
                or prop._dbus_name != property_name
602
 
                or (interface_name and prop._dbus_interface
603
 
                    and interface_name != prop._dbus_interface)):
604
 
                continue
605
 
            return prop
 
638
        for cls in  self.__class__.__mro__:
 
639
            for name, value in inspect.getmembers(cls, self._is_dbus_property):
 
640
                if value._dbus_name == property_name and value._dbus_interface == interface_name:
 
641
                    return value.__get__(self)
 
642
        
606
643
        # No such property
607
644
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
608
645
                                   + interface_name + "."
642
679
    def GetAll(self, interface_name):
643
680
        """Standard D-Bus property GetAll() method, see D-Bus
644
681
        standard.
645
 
 
 
682
        
646
683
        Note: Will not include properties with access="write".
647
684
        """
648
685
        all = {}
704
741
            xmlstring = document.toxml("utf-8")
705
742
            document.unlink()
706
743
        except (AttributeError, xml.dom.DOMException,
707
 
                xml.parsers.expat.ExpatError), error:
 
744
                xml.parsers.expat.ExpatError) as error:
708
745
            logger.error("Failed to override Introspection method",
709
746
                         error)
710
747
        return xmlstring
711
748
 
712
749
 
 
750
def datetime_to_dbus (dt, variant_level=0):
 
751
    """Convert a UTC datetime.datetime() to a D-Bus type."""
 
752
    if dt is None:
 
753
        return dbus.String("", variant_level = variant_level)
 
754
    return dbus.String(dt.isoformat(),
 
755
                       variant_level=variant_level)
 
756
 
 
757
class AlternateDBusNamesMetaclass(DBusObjectWithProperties.__metaclass__):
 
758
    """Applied to an empty subclass of a D-Bus object, this metaclass
 
759
    will add additional D-Bus attributes matching a certain pattern.
 
760
    """
 
761
    def __new__(mcs, name, bases, attr):
 
762
        # Go through all the base classes which could have D-Bus
 
763
        # methods, signals, or properties in them
 
764
        for base in (b for b in bases
 
765
                     if issubclass(b, dbus.service.Object)):
 
766
            # Go though all attributes of the base class
 
767
            for attrname, attribute in inspect.getmembers(base):
 
768
                # Ignore non-D-Bus attributes, and D-Bus attributes
 
769
                # with the wrong interface name
 
770
                if (not hasattr(attribute, "_dbus_interface")
 
771
                    or not attribute._dbus_interface
 
772
                    .startswith("se.recompile.Mandos")):
 
773
                    continue
 
774
                # Create an alternate D-Bus interface name based on
 
775
                # the current name
 
776
                alt_interface = (attribute._dbus_interface
 
777
                                 .replace("se.recompile.Mandos",
 
778
                                          "se.bsnet.fukt.Mandos"))
 
779
                # Is this a D-Bus signal?
 
780
                if getattr(attribute, "_dbus_is_signal", False):
 
781
                    # Extract the original non-method function by
 
782
                    # black magic
 
783
                    nonmethod_func = (dict(
 
784
                            zip(attribute.func_code.co_freevars,
 
785
                                attribute.__closure__))["func"]
 
786
                                      .cell_contents)
 
787
                    # Create a new, but exactly alike, function
 
788
                    # object, and decorate it to be a new D-Bus signal
 
789
                    # with the alternate D-Bus interface name
 
790
                    new_function = (dbus.service.signal
 
791
                                    (alt_interface,
 
792
                                     attribute._dbus_signature)
 
793
                                    (types.FunctionType(
 
794
                                nonmethod_func.func_code,
 
795
                                nonmethod_func.func_globals,
 
796
                                nonmethod_func.func_name,
 
797
                                nonmethod_func.func_defaults,
 
798
                                nonmethod_func.func_closure)))
 
799
                    # Define a creator of a function to call both the
 
800
                    # old and new functions, so both the old and new
 
801
                    # signals gets sent when the function is called
 
802
                    def fixscope(func1, func2):
 
803
                        """This function is a scope container to pass
 
804
                        func1 and func2 to the "call_both" function
 
805
                        outside of its arguments"""
 
806
                        def call_both(*args, **kwargs):
 
807
                            """This function will emit two D-Bus
 
808
                            signals by calling func1 and func2"""
 
809
                            func1(*args, **kwargs)
 
810
                            func2(*args, **kwargs)
 
811
                        return call_both
 
812
                    # Create the "call_both" function and add it to
 
813
                    # the class
 
814
                    attr[attrname] = fixscope(attribute,
 
815
                                              new_function)
 
816
                # Is this a D-Bus method?
 
817
                elif getattr(attribute, "_dbus_is_method", False):
 
818
                    # Create a new, but exactly alike, function
 
819
                    # object.  Decorate it to be a new D-Bus method
 
820
                    # with the alternate D-Bus interface name.  Add it
 
821
                    # to the class.
 
822
                    attr[attrname] = (dbus.service.method
 
823
                                      (alt_interface,
 
824
                                       attribute._dbus_in_signature,
 
825
                                       attribute._dbus_out_signature)
 
826
                                      (types.FunctionType
 
827
                                       (attribute.func_code,
 
828
                                        attribute.func_globals,
 
829
                                        attribute.func_name,
 
830
                                        attribute.func_defaults,
 
831
                                        attribute.func_closure)))
 
832
                # Is this a D-Bus property?
 
833
                elif getattr(attribute, "_dbus_is_property", False):
 
834
                    # Create a new, but exactly alike, function
 
835
                    # object, and decorate it to be a new D-Bus
 
836
                    # property with the alternate D-Bus interface
 
837
                    # name.  Add it to the class.
 
838
                    attr[attrname] = (dbus_service_property
 
839
                                      (alt_interface,
 
840
                                       attribute._dbus_signature,
 
841
                                       attribute._dbus_access,
 
842
                                       attribute
 
843
                                       ._dbus_get_args_options
 
844
                                       ["byte_arrays"])
 
845
                                      (types.FunctionType
 
846
                                       (attribute.func_code,
 
847
                                        attribute.func_globals,
 
848
                                        attribute.func_name,
 
849
                                        attribute.func_defaults,
 
850
                                        attribute.func_closure)))
 
851
        return type.__new__(mcs, name, bases, attr)
 
852
 
713
853
class ClientDBus(Client, DBusObjectWithProperties):
714
854
    """A Client class using D-Bus
715
855
    
737
877
        DBusObjectWithProperties.__init__(self, self.bus,
738
878
                                          self.dbus_object_path)
739
879
        
740
 
    def _get_approvals_pending(self):
741
 
        return self._approvals_pending
742
 
    def _set_approvals_pending(self, value):
743
 
        old_value = self._approvals_pending
744
 
        self._approvals_pending = value
745
 
        bval = bool(value)
746
 
        if (hasattr(self, "dbus_object_path")
747
 
            and bval is not bool(old_value)):
748
 
            dbus_bool = dbus.Boolean(bval, variant_level=1)
749
 
            self.PropertyChanged(dbus.String("ApprovalPending"),
750
 
                                 dbus_bool)
 
880
    def notifychangeproperty(transform_func,
 
881
                             dbus_name, type_func=lambda x: x,
 
882
                             variant_level=1):
 
883
        """ Modify a variable so that it's a property which announces
 
884
        its changes to DBus.
751
885
 
752
 
    approvals_pending = property(_get_approvals_pending,
753
 
                                 _set_approvals_pending)
754
 
    del _get_approvals_pending, _set_approvals_pending
755
 
    
756
 
    @staticmethod
757
 
    def _datetime_to_dbus(dt, variant_level=0):
758
 
        """Convert a UTC datetime.datetime() to a D-Bus type."""
759
 
        return dbus.String(dt.isoformat(),
760
 
                           variant_level=variant_level)
761
 
    
762
 
    def enable(self):
763
 
        oldstate = getattr(self, "enabled", False)
764
 
        r = Client.enable(self)
765
 
        if oldstate != self.enabled:
766
 
            # Emit D-Bus signals
767
 
            self.PropertyChanged(dbus.String("Enabled"),
768
 
                                 dbus.Boolean(True, variant_level=1))
769
 
            self.PropertyChanged(
770
 
                dbus.String("LastEnabled"),
771
 
                self._datetime_to_dbus(self.last_enabled,
772
 
                                       variant_level=1))
773
 
        return r
774
 
    
775
 
    def disable(self, quiet = False):
776
 
        oldstate = getattr(self, "enabled", False)
777
 
        r = Client.disable(self, quiet=quiet)
778
 
        if not quiet and oldstate != self.enabled:
779
 
            # Emit D-Bus signal
780
 
            self.PropertyChanged(dbus.String("Enabled"),
781
 
                                 dbus.Boolean(False, variant_level=1))
782
 
        return r
 
886
        transform_fun: Function that takes a value and transforms it
 
887
                       to a D-Bus type.
 
888
        dbus_name: D-Bus name of the variable
 
889
        type_func: Function that transform the value before sending it
 
890
                   to the D-Bus.  Default: no transform
 
891
        variant_level: D-Bus variant level.  Default: 1
 
892
        """
 
893
        real_value = [None,]
 
894
        def setter(self, value):
 
895
            old_value = real_value[0]
 
896
            real_value[0] = value
 
897
            if hasattr(self, "dbus_object_path"):
 
898
                if type_func(old_value) != type_func(real_value[0]):
 
899
                    dbus_value = transform_func(type_func(real_value[0]),
 
900
                                                variant_level)
 
901
                    self.PropertyChanged(dbus.String(dbus_name),
 
902
                                         dbus_value)
 
903
        
 
904
        return property(lambda self: real_value[0], setter)
 
905
    
 
906
    
 
907
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
 
908
    approvals_pending = notifychangeproperty(dbus.Boolean,
 
909
                                             "ApprovalPending",
 
910
                                             type_func = bool)
 
911
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
 
912
    last_enabled = notifychangeproperty(datetime_to_dbus,
 
913
                                        "LastEnabled")
 
914
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
 
915
                                   type_func = lambda checker: checker is not None)
 
916
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
 
917
                                           "LastCheckedOK")
 
918
    last_approval_request = notifychangeproperty(datetime_to_dbus,
 
919
                                                 "LastApprovalRequest")
 
920
    approved_by_default = notifychangeproperty(dbus.Boolean,
 
921
                                               "ApprovedByDefault")
 
922
    approval_delay = notifychangeproperty(dbus.UInt16, "ApprovalDelay",
 
923
                                          type_func = _timedelta_to_milliseconds)
 
924
    approval_duration = notifychangeproperty(dbus.UInt16, "ApprovalDuration",
 
925
                                             type_func = _timedelta_to_milliseconds)
 
926
    host = notifychangeproperty(dbus.String, "Host")
 
927
    timeout = notifychangeproperty(dbus.UInt16, "Timeout",
 
928
                                   type_func = _timedelta_to_milliseconds)
 
929
    extended_timeout = notifychangeproperty(dbus.UInt16, "ExtendedTimeout",
 
930
                                            type_func = _timedelta_to_milliseconds)
 
931
    interval = notifychangeproperty(dbus.UInt16, "Interval",
 
932
                                    type_func = _timedelta_to_milliseconds)
 
933
    checker_command = notifychangeproperty(dbus.String, "Checker")
 
934
    
 
935
    del notifychangeproperty
783
936
    
784
937
    def __del__(self, *args, **kwargs):
785
938
        try:
794
947
                         *args, **kwargs):
795
948
        self.checker_callback_tag = None
796
949
        self.checker = None
797
 
        # Emit D-Bus signal
798
 
        self.PropertyChanged(dbus.String("CheckerRunning"),
799
 
                             dbus.Boolean(False, variant_level=1))
800
950
        if os.WIFEXITED(condition):
801
951
            exitstatus = os.WEXITSTATUS(condition)
802
952
            # Emit D-Bus signal
812
962
        return Client.checker_callback(self, pid, condition, command,
813
963
                                       *args, **kwargs)
814
964
    
815
 
    def checked_ok(self, *args, **kwargs):
816
 
        r = Client.checked_ok(self, *args, **kwargs)
817
 
        # Emit D-Bus signal
818
 
        self.PropertyChanged(
819
 
            dbus.String("LastCheckedOK"),
820
 
            (self._datetime_to_dbus(self.last_checked_ok,
821
 
                                    variant_level=1)))
822
 
        return r
823
 
    
824
 
    def need_approval(self, *args, **kwargs):
825
 
        r = Client.need_approval(self, *args, **kwargs)
826
 
        # Emit D-Bus signal
827
 
        self.PropertyChanged(
828
 
            dbus.String("LastApprovalRequest"),
829
 
            (self._datetime_to_dbus(self.last_approval_request,
830
 
                                    variant_level=1)))
831
 
        return r
832
 
    
833
965
    def start_checker(self, *args, **kwargs):
834
966
        old_checker = self.checker
835
967
        if self.checker is not None:
842
974
            and old_checker_pid != self.checker.pid):
843
975
            # Emit D-Bus signal
844
976
            self.CheckerStarted(self.current_checker_command)
845
 
            self.PropertyChanged(
846
 
                dbus.String("CheckerRunning"),
847
 
                dbus.Boolean(True, variant_level=1))
848
977
        return r
849
978
    
850
 
    def stop_checker(self, *args, **kwargs):
851
 
        old_checker = getattr(self, "checker", None)
852
 
        r = Client.stop_checker(self, *args, **kwargs)
853
 
        if (old_checker is not None
854
 
            and getattr(self, "checker", None) is None):
855
 
            self.PropertyChanged(dbus.String("CheckerRunning"),
856
 
                                 dbus.Boolean(False, variant_level=1))
857
 
        return r
858
 
 
859
979
    def _reset_approved(self):
860
980
        self._approved = None
861
981
        return False
863
983
    def approve(self, value=True):
864
984
        self.send_changedstate()
865
985
        self._approved = value
866
 
        gobject.timeout_add(self._timedelta_to_milliseconds
 
986
        gobject.timeout_add(_timedelta_to_milliseconds
867
987
                            (self.approval_duration),
868
988
                            self._reset_approved)
869
989
    
870
990
    
871
991
    ## D-Bus methods, signals & properties
872
 
    _interface = "se.bsnet.fukt.Mandos.Client"
 
992
    _interface = "se.recompile.Mandos.Client"
873
993
    
874
994
    ## Signals
875
995
    
922
1042
    # CheckedOK - method
923
1043
    @dbus.service.method(_interface)
924
1044
    def CheckedOK(self):
925
 
        return self.checked_ok()
 
1045
        self.checked_ok()
926
1046
    
927
1047
    # Enable - method
928
1048
    @dbus.service.method(_interface)
961
1081
        if value is None:       # get
962
1082
            return dbus.Boolean(self.approved_by_default)
963
1083
        self.approved_by_default = bool(value)
964
 
        # Emit D-Bus signal
965
 
        self.PropertyChanged(dbus.String("ApprovedByDefault"),
966
 
                             dbus.Boolean(value, variant_level=1))
967
1084
    
968
1085
    # ApprovalDelay - property
969
1086
    @dbus_service_property(_interface, signature="t",
972
1089
        if value is None:       # get
973
1090
            return dbus.UInt64(self.approval_delay_milliseconds())
974
1091
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
975
 
        # Emit D-Bus signal
976
 
        self.PropertyChanged(dbus.String("ApprovalDelay"),
977
 
                             dbus.UInt64(value, variant_level=1))
978
1092
    
979
1093
    # ApprovalDuration - property
980
1094
    @dbus_service_property(_interface, signature="t",
981
1095
                           access="readwrite")
982
1096
    def ApprovalDuration_dbus_property(self, value=None):
983
1097
        if value is None:       # get
984
 
            return dbus.UInt64(self._timedelta_to_milliseconds(
 
1098
            return dbus.UInt64(_timedelta_to_milliseconds(
985
1099
                    self.approval_duration))
986
1100
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
987
 
        # Emit D-Bus signal
988
 
        self.PropertyChanged(dbus.String("ApprovalDuration"),
989
 
                             dbus.UInt64(value, variant_level=1))
990
1101
    
991
1102
    # Name - property
992
1103
    @dbus_service_property(_interface, signature="s", access="read")
1005
1116
        if value is None:       # get
1006
1117
            return dbus.String(self.host)
1007
1118
        self.host = value
1008
 
        # Emit D-Bus signal
1009
 
        self.PropertyChanged(dbus.String("Host"),
1010
 
                             dbus.String(value, variant_level=1))
1011
1119
    
1012
1120
    # Created - property
1013
1121
    @dbus_service_property(_interface, signature="s", access="read")
1014
1122
    def Created_dbus_property(self):
1015
 
        return dbus.String(self._datetime_to_dbus(self.created))
 
1123
        return dbus.String(datetime_to_dbus(self.created))
1016
1124
    
1017
1125
    # LastEnabled - property
1018
1126
    @dbus_service_property(_interface, signature="s", access="read")
1019
1127
    def LastEnabled_dbus_property(self):
1020
 
        if self.last_enabled is None:
1021
 
            return dbus.String("")
1022
 
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
 
1128
        return datetime_to_dbus(self.last_enabled)
1023
1129
    
1024
1130
    # Enabled - property
1025
1131
    @dbus_service_property(_interface, signature="b",
1039
1145
        if value is not None:
1040
1146
            self.checked_ok()
1041
1147
            return
1042
 
        if self.last_checked_ok is None:
1043
 
            return dbus.String("")
1044
 
        return dbus.String(self._datetime_to_dbus(self
1045
 
                                                  .last_checked_ok))
 
1148
        return datetime_to_dbus(self.last_checked_ok)
 
1149
    
 
1150
    # Expires - property
 
1151
    @dbus_service_property(_interface, signature="s", access="read")
 
1152
    def Expires_dbus_property(self):
 
1153
        return datetime_to_dbus(self.expires)
1046
1154
    
1047
1155
    # LastApprovalRequest - property
1048
1156
    @dbus_service_property(_interface, signature="s", access="read")
1049
1157
    def LastApprovalRequest_dbus_property(self):
1050
 
        if self.last_approval_request is None:
1051
 
            return dbus.String("")
1052
 
        return dbus.String(self.
1053
 
                           _datetime_to_dbus(self
1054
 
                                             .last_approval_request))
 
1158
        return datetime_to_dbus(self.last_approval_request)
1055
1159
    
1056
1160
    # Timeout - property
1057
1161
    @dbus_service_property(_interface, signature="t",
1060
1164
        if value is None:       # get
1061
1165
            return dbus.UInt64(self.timeout_milliseconds())
1062
1166
        self.timeout = datetime.timedelta(0, 0, 0, value)
1063
 
        # Emit D-Bus signal
1064
 
        self.PropertyChanged(dbus.String("Timeout"),
1065
 
                             dbus.UInt64(value, variant_level=1))
1066
1167
        if getattr(self, "disable_initiator_tag", None) is None:
1067
1168
            return
1068
1169
        # Reschedule timeout
1069
1170
        gobject.source_remove(self.disable_initiator_tag)
1070
1171
        self.disable_initiator_tag = None
 
1172
        self.expires = None
1071
1173
        time_to_die = (self.
1072
1174
                       _timedelta_to_milliseconds((self
1073
1175
                                                   .last_checked_ok
1078
1180
            # The timeout has passed
1079
1181
            self.disable()
1080
1182
        else:
 
1183
            self.expires = (datetime.datetime.utcnow()
 
1184
                            + datetime.timedelta(milliseconds = time_to_die))
1081
1185
            self.disable_initiator_tag = (gobject.timeout_add
1082
1186
                                          (time_to_die, self.disable))
1083
1187
    
 
1188
    # ExtendedTimeout - property
 
1189
    @dbus_service_property(_interface, signature="t",
 
1190
                           access="readwrite")
 
1191
    def ExtendedTimeout_dbus_property(self, value=None):
 
1192
        if value is None:       # get
 
1193
            return dbus.UInt64(self.extended_timeout_milliseconds())
 
1194
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
 
1195
    
1084
1196
    # Interval - property
1085
1197
    @dbus_service_property(_interface, signature="t",
1086
1198
                           access="readwrite")
1088
1200
        if value is None:       # get
1089
1201
            return dbus.UInt64(self.interval_milliseconds())
1090
1202
        self.interval = datetime.timedelta(0, 0, 0, value)
1091
 
        # Emit D-Bus signal
1092
 
        self.PropertyChanged(dbus.String("Interval"),
1093
 
                             dbus.UInt64(value, variant_level=1))
1094
1203
        if getattr(self, "checker_initiator_tag", None) is None:
1095
1204
            return
1096
1205
        # Reschedule checker run
1098
1207
        self.checker_initiator_tag = (gobject.timeout_add
1099
1208
                                      (value, self.start_checker))
1100
1209
        self.start_checker()    # Start one now, too
1101
 
 
 
1210
    
1102
1211
    # Checker - property
1103
1212
    @dbus_service_property(_interface, signature="s",
1104
1213
                           access="readwrite")
1106
1215
        if value is None:       # get
1107
1216
            return dbus.String(self.checker_command)
1108
1217
        self.checker_command = value
1109
 
        # Emit D-Bus signal
1110
 
        self.PropertyChanged(dbus.String("Checker"),
1111
 
                             dbus.String(self.checker_command,
1112
 
                                         variant_level=1))
1113
1218
    
1114
1219
    # CheckerRunning - property
1115
1220
    @dbus_service_property(_interface, signature="b",
1142
1247
        self._pipe.send(('init', fpr, address))
1143
1248
        if not self._pipe.recv():
1144
1249
            raise KeyError()
1145
 
 
 
1250
    
1146
1251
    def __getattribute__(self, name):
1147
1252
        if(name == '_pipe'):
1148
1253
            return super(ProxyClient, self).__getattribute__(name)
1155
1260
                self._pipe.send(('funcall', name, args, kwargs))
1156
1261
                return self._pipe.recv()[1]
1157
1262
            return func
1158
 
 
 
1263
    
1159
1264
    def __setattr__(self, name, value):
1160
1265
        if(name == '_pipe'):
1161
1266
            return super(ProxyClient, self).__setattr__(name, value)
1162
1267
        self._pipe.send(('setattr', name, value))
1163
1268
 
 
1269
class ClientDBusTransitional(ClientDBus):
 
1270
    __metaclass__ = AlternateDBusNamesMetaclass
1164
1271
 
1165
1272
class ClientHandler(socketserver.BaseRequestHandler, object):
1166
1273
    """A class to handle client connections.
1174
1281
                        unicode(self.client_address))
1175
1282
            logger.debug("Pipe FD: %d",
1176
1283
                         self.server.child_pipe.fileno())
1177
 
 
 
1284
            
1178
1285
            session = (gnutls.connection
1179
1286
                       .ClientSession(self.request,
1180
1287
                                      gnutls.connection
1181
1288
                                      .X509Credentials()))
1182
 
 
 
1289
            
1183
1290
            # Note: gnutls.connection.X509Credentials is really a
1184
1291
            # generic GnuTLS certificate credentials object so long as
1185
1292
            # no X.509 keys are added to it.  Therefore, we can use it
1186
1293
            # here despite using OpenPGP certificates.
1187
 
 
 
1294
            
1188
1295
            #priority = ':'.join(("NONE", "+VERS-TLS1.1",
1189
1296
            #                      "+AES-256-CBC", "+SHA1",
1190
1297
            #                      "+COMP-NULL", "+CTYPE-OPENPGP",
1196
1303
            (gnutls.library.functions
1197
1304
             .gnutls_priority_set_direct(session._c_object,
1198
1305
                                         priority, None))
1199
 
 
 
1306
            
1200
1307
            # Start communication using the Mandos protocol
1201
1308
            # Get protocol number
1202
1309
            line = self.request.makefile().readline()
1204
1311
            try:
1205
1312
                if int(line.strip().split()[0]) > 1:
1206
1313
                    raise RuntimeError
1207
 
            except (ValueError, IndexError, RuntimeError), error:
 
1314
            except (ValueError, IndexError, RuntimeError) as error:
1208
1315
                logger.error("Unknown protocol version: %s", error)
1209
1316
                return
1210
 
 
 
1317
            
1211
1318
            # Start GnuTLS connection
1212
1319
            try:
1213
1320
                session.handshake()
1214
 
            except gnutls.errors.GNUTLSError, error:
 
1321
            except gnutls.errors.GNUTLSError as error:
1215
1322
                logger.warning("Handshake failed: %s", error)
1216
1323
                # Do not run session.bye() here: the session is not
1217
1324
                # established.  Just abandon the request.
1218
1325
                return
1219
1326
            logger.debug("Handshake succeeded")
1220
 
 
 
1327
            
1221
1328
            approval_required = False
1222
1329
            try:
1223
1330
                try:
1224
1331
                    fpr = self.fingerprint(self.peer_certificate
1225
1332
                                           (session))
1226
 
                except (TypeError, gnutls.errors.GNUTLSError), error:
 
1333
                except (TypeError,
 
1334
                        gnutls.errors.GNUTLSError) as error:
1227
1335
                    logger.warning("Bad certificate: %s", error)
1228
1336
                    return
1229
1337
                logger.debug("Fingerprint: %s", fpr)
1230
 
 
 
1338
                
1231
1339
                try:
1232
1340
                    client = ProxyClient(child_pipe, fpr,
1233
1341
                                         self.client_address)
1241
1349
                
1242
1350
                while True:
1243
1351
                    if not client.enabled:
1244
 
                        logger.warning("Client %s is disabled",
 
1352
                        logger.info("Client %s is disabled",
1245
1353
                                       client.name)
1246
1354
                        if self.server.use_dbus:
1247
1355
                            # Emit D-Bus signal
1292
1400
                while sent_size < len(client.secret):
1293
1401
                    try:
1294
1402
                        sent = session.send(client.secret[sent_size:])
1295
 
                    except (gnutls.errors.GNUTLSError), error:
 
1403
                    except gnutls.errors.GNUTLSError as error:
1296
1404
                        logger.warning("gnutls send failed")
1297
1405
                        return
1298
1406
                    logger.debug("Sent: %d, remaining: %d",
1299
1407
                                 sent, len(client.secret)
1300
1408
                                 - (sent_size + sent))
1301
1409
                    sent_size += sent
1302
 
 
 
1410
                
1303
1411
                logger.info("Sending secret to %s", client.name)
1304
1412
                # bump the timeout as if seen
1305
 
                client.checked_ok()
 
1413
                client.checked_ok(client.extended_timeout)
1306
1414
                if self.server.use_dbus:
1307
1415
                    # Emit D-Bus signal
1308
1416
                    client.GotSecret()
1312
1420
                    client.approvals_pending -= 1
1313
1421
                try:
1314
1422
                    session.bye()
1315
 
                except (gnutls.errors.GNUTLSError), error:
 
1423
                except gnutls.errors.GNUTLSError as error:
1316
1424
                    logger.warning("GnuTLS bye failed")
1317
1425
    
1318
1426
    @staticmethod
1393
1501
        multiprocessing.Process(target = self.sub_process_main,
1394
1502
                                args = (request, address)).start()
1395
1503
 
 
1504
 
1396
1505
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1397
1506
    """ adds a pipe to the MixIn """
1398
1507
    def process_request(self, request, client_address):
1401
1510
        This function creates a new pipe in self.pipe
1402
1511
        """
1403
1512
        parent_pipe, self.child_pipe = multiprocessing.Pipe()
1404
 
 
 
1513
        
1405
1514
        super(MultiprocessingMixInWithPipe,
1406
1515
              self).process_request(request, client_address)
1407
1516
        self.child_pipe.close()
1408
1517
        self.add_pipe(parent_pipe)
1409
 
 
 
1518
    
1410
1519
    def add_pipe(self, parent_pipe):
1411
1520
        """Dummy function; override as necessary"""
1412
1521
        raise NotImplementedError
1413
1522
 
 
1523
 
1414
1524
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1415
1525
                     socketserver.TCPServer, object):
1416
1526
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
1442
1552
                                           SO_BINDTODEVICE,
1443
1553
                                           str(self.interface
1444
1554
                                               + '\0'))
1445
 
                except socket.error, error:
 
1555
                except socket.error as error:
1446
1556
                    if error[0] == errno.EPERM:
1447
1557
                        logger.error("No permission to"
1448
1558
                                     " bind to interface %s",
1542
1652
                    client = c
1543
1653
                    break
1544
1654
            else:
1545
 
                logger.warning("Client not found for fingerprint: %s, ad"
1546
 
                               "dress: %s", fpr, address)
 
1655
                logger.info("Client not found for fingerprint: %s, ad"
 
1656
                            "dress: %s", fpr, address)
1547
1657
                if self.use_dbus:
1548
1658
                    # Emit D-Bus signal
1549
1659
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1564
1674
            kwargs = request[3]
1565
1675
            
1566
1676
            parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs)))
1567
 
 
 
1677
        
1568
1678
        if command == 'getattr':
1569
1679
            attrname = request[1]
1570
1680
            if callable(client_object.__getattribute__(attrname)):
1576
1686
            attrname = request[1]
1577
1687
            value = request[2]
1578
1688
            setattr(client_object, attrname, value)
1579
 
 
 
1689
        
1580
1690
        return True
1581
1691
 
1582
1692
 
1613
1723
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
1614
1724
            else:
1615
1725
                raise ValueError("Unknown suffix %r" % suffix)
1616
 
        except (ValueError, IndexError), e:
 
1726
        except (ValueError, IndexError) as e:
1617
1727
            raise ValueError(*(e.args))
1618
1728
        timevalue += delta
1619
1729
    return timevalue
1673
1783
    ##################################################################
1674
1784
    # Parsing of options, both command line and config file
1675
1785
    
1676
 
    parser = optparse.OptionParser(version = "%%prog %s" % version)
1677
 
    parser.add_option("-i", "--interface", type="string",
1678
 
                      metavar="IF", help="Bind to interface IF")
1679
 
    parser.add_option("-a", "--address", type="string",
1680
 
                      help="Address to listen for requests on")
1681
 
    parser.add_option("-p", "--port", type="int",
1682
 
                      help="Port number to receive requests on")
1683
 
    parser.add_option("--check", action="store_true",
1684
 
                      help="Run self-test")
1685
 
    parser.add_option("--debug", action="store_true",
1686
 
                      help="Debug mode; run in foreground and log to"
1687
 
                      " terminal")
1688
 
    parser.add_option("--debuglevel", type="string", metavar="LEVEL",
1689
 
                      help="Debug level for stdout output")
1690
 
    parser.add_option("--priority", type="string", help="GnuTLS"
1691
 
                      " priority string (see GnuTLS documentation)")
1692
 
    parser.add_option("--servicename", type="string",
1693
 
                      metavar="NAME", help="Zeroconf service name")
1694
 
    parser.add_option("--configdir", type="string",
1695
 
                      default="/etc/mandos", metavar="DIR",
1696
 
                      help="Directory to search for configuration"
1697
 
                      " files")
1698
 
    parser.add_option("--no-dbus", action="store_false",
1699
 
                      dest="use_dbus", help="Do not provide D-Bus"
1700
 
                      " system bus interface")
1701
 
    parser.add_option("--no-ipv6", action="store_false",
1702
 
                      dest="use_ipv6", help="Do not use IPv6")
1703
 
    options = parser.parse_args()[0]
 
1786
    parser = argparse.ArgumentParser()
 
1787
    parser.add_argument("-v", "--version", action="version",
 
1788
                        version = "%%(prog)s %s" % version,
 
1789
                        help="show version number and exit")
 
1790
    parser.add_argument("-i", "--interface", metavar="IF",
 
1791
                        help="Bind to interface IF")
 
1792
    parser.add_argument("-a", "--address",
 
1793
                        help="Address to listen for requests on")
 
1794
    parser.add_argument("-p", "--port", type=int,
 
1795
                        help="Port number to receive requests on")
 
1796
    parser.add_argument("--check", action="store_true",
 
1797
                        help="Run self-test")
 
1798
    parser.add_argument("--debug", action="store_true",
 
1799
                        help="Debug mode; run in foreground and log"
 
1800
                        " to terminal")
 
1801
    parser.add_argument("--debuglevel", metavar="LEVEL",
 
1802
                        help="Debug level for stdout output")
 
1803
    parser.add_argument("--priority", help="GnuTLS"
 
1804
                        " priority string (see GnuTLS documentation)")
 
1805
    parser.add_argument("--servicename",
 
1806
                        metavar="NAME", help="Zeroconf service name")
 
1807
    parser.add_argument("--configdir",
 
1808
                        default="/etc/mandos", metavar="DIR",
 
1809
                        help="Directory to search for configuration"
 
1810
                        " files")
 
1811
    parser.add_argument("--no-dbus", action="store_false",
 
1812
                        dest="use_dbus", help="Do not provide D-Bus"
 
1813
                        " system bus interface")
 
1814
    parser.add_argument("--no-ipv6", action="store_false",
 
1815
                        dest="use_ipv6", help="Do not use IPv6")
 
1816
    options = parser.parse_args()
1704
1817
    
1705
1818
    if options.check:
1706
1819
        import doctest
1758
1871
    debuglevel = server_settings["debuglevel"]
1759
1872
    use_dbus = server_settings["use_dbus"]
1760
1873
    use_ipv6 = server_settings["use_ipv6"]
1761
 
 
 
1874
    
1762
1875
    if server_settings["servicename"] != "Mandos":
1763
1876
        syslogger.setFormatter(logging.Formatter
1764
1877
                               ('Mandos (%s) [%%(process)d]:'
1766
1879
                                % server_settings["servicename"]))
1767
1880
    
1768
1881
    # Parse config file with clients
1769
 
    client_defaults = { "timeout": "1h",
1770
 
                        "interval": "5m",
 
1882
    client_defaults = { "timeout": "5m",
 
1883
                        "extended_timeout": "15m",
 
1884
                        "interval": "2m",
1771
1885
                        "checker": "fping -q -- %%(host)s",
1772
1886
                        "host": "",
1773
1887
                        "approval_delay": "0s",
1813
1927
    try:
1814
1928
        os.setgid(gid)
1815
1929
        os.setuid(uid)
1816
 
    except OSError, error:
 
1930
    except OSError as error:
1817
1931
        if error[0] != errno.EPERM:
1818
1932
            raise error
1819
1933
    
1824
1938
        level = getattr(logging, debuglevel.upper())
1825
1939
        syslogger.setLevel(level)
1826
1940
        console.setLevel(level)
1827
 
 
 
1941
    
1828
1942
    if debug:
1829
1943
        # Enable all possible GnuTLS debugging
1830
1944
        
1861
1975
    # End of Avahi example code
1862
1976
    if use_dbus:
1863
1977
        try:
1864
 
            bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
 
1978
            bus_name = dbus.service.BusName("se.recompile.Mandos",
1865
1979
                                            bus, do_not_queue=True)
1866
 
        except dbus.exceptions.NameExistsException, e:
 
1980
            old_bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos",
 
1981
                                                bus, do_not_queue=True)
 
1982
        except dbus.exceptions.NameExistsException as e:
1867
1983
            logger.error(unicode(e) + ", disabling D-Bus")
1868
1984
            use_dbus = False
1869
1985
            server_settings["use_dbus"] = False
1881
1997
    
1882
1998
    client_class = Client
1883
1999
    if use_dbus:
1884
 
        client_class = functools.partial(ClientDBus, bus = bus)
 
2000
        client_class = functools.partial(ClientDBusTransitional, bus = bus)        
1885
2001
    def client_config_items(config, section):
1886
2002
        special_settings = {
1887
2003
            "approved_by_default":
1917
2033
        del pidfilename
1918
2034
        
1919
2035
        signal.signal(signal.SIGINT, signal.SIG_IGN)
1920
 
 
 
2036
    
1921
2037
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1922
2038
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1923
2039
    
1926
2042
            """A D-Bus proxy object"""
1927
2043
            def __init__(self):
1928
2044
                dbus.service.Object.__init__(self, bus, "/")
1929
 
            _interface = "se.bsnet.fukt.Mandos"
 
2045
            _interface = "se.recompile.Mandos"
1930
2046
            
1931
2047
            @dbus.service.signal(_interface, signature="o")
1932
2048
            def ClientAdded(self, objpath):
1974
2090
            
1975
2091
            del _interface
1976
2092
        
1977
 
        mandos_dbus_service = MandosDBusService()
 
2093
        class MandosDBusServiceTransitional(MandosDBusService):
 
2094
            __metaclass__ = AlternateDBusNamesMetaclass
 
2095
        mandos_dbus_service = MandosDBusServiceTransitional()
1978
2096
    
1979
2097
    def cleanup():
1980
2098
        "Cleanup function; run on exit"
2019
2137
        # From the Avahi example code
2020
2138
        try:
2021
2139
            service.activate()
2022
 
        except dbus.exceptions.DBusException, error:
 
2140
        except dbus.exceptions.DBusException as error:
2023
2141
            logger.critical("DBusException: %s", error)
2024
2142
            cleanup()
2025
2143
            sys.exit(1)
2032
2150
        
2033
2151
        logger.debug("Starting main loop")
2034
2152
        main_loop.run()
2035
 
    except AvahiError, error:
 
2153
    except AvahiError as error:
2036
2154
        logger.critical("AvahiError: %s", error)
2037
2155
        cleanup()
2038
2156
        sys.exit(1)
2044
2162
    # Must run before the D-Bus bus name gets deregistered
2045
2163
    cleanup()
2046
2164
 
 
2165
 
2047
2166
if __name__ == '__main__':
2048
2167
    main()