/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2011-11-26 23:08:17 UTC
  • mto: (518.1.8 mandos-persistent)
  • mto: This revision was merged to the branch mainline in revision 524.
  • Revision ID: teddy@recompile.se-20111126230817-tv08v831s2yltbkd
Make "enabled" a client config option.

* DBUS-API: Fix wording on "Expires" option.
* clients.conf (enabled): New.
* mandos (Client): "last_enabled" can now be None.
  (Client.__init__): Get "enabled" from config.  Only set
                     "last_enabled" and "expires" if enabled.
  (ClientDBus.Created_dbus_property): Removed redundant dbus.String().
  (ClientDBus.Interval_dbus_property): If changed, only reschedule
                                       checker if enabled.
  (main/special_settings): Added "enabled".
* mandos-clients.conf (OPTIONS): Added "enabled".

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008-2012 Teddy Hogeborn
15
 
# Copyright © 2008-2012 Björn Påhlsson
 
14
# Copyright © 2008-2011 Teddy Hogeborn
 
15
# Copyright © 2008-2011 Björn Påhlsson
16
16
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
65
65
import types
66
66
import binascii
67
67
import tempfile
68
 
import itertools
69
68
 
70
69
import dbus
71
70
import dbus.service
86
85
    except ImportError:
87
86
        SO_BINDTODEVICE = None
88
87
 
89
 
version = "1.5.3"
 
88
 
 
89
version = "1.4.1"
90
90
stored_state_file = "clients.pickle"
91
91
 
92
92
logger = logging.getLogger()
111
111
        return interface_index
112
112
 
113
113
 
114
 
def initlogger(debug, level=logging.WARNING):
 
114
def initlogger(level=logging.WARNING):
115
115
    """init logger and add loglevel"""
116
116
    
117
117
    syslogger.setFormatter(logging.Formatter
119
119
                            ' %(message)s'))
120
120
    logger.addHandler(syslogger)
121
121
    
122
 
    if debug:
123
 
        console = logging.StreamHandler()
124
 
        console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
125
 
                                               ' [%(process)d]:'
126
 
                                               ' %(levelname)s:'
127
 
                                               ' %(message)s'))
128
 
        logger.addHandler(console)
 
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)
129
128
    logger.setLevel(level)
130
129
 
131
130
 
132
 
class PGPError(Exception):
133
 
    """Exception if encryption/decryption fails"""
 
131
class CryptoError(Exception):
134
132
    pass
135
133
 
136
134
 
137
 
class PGPEngine(object):
 
135
class Crypto(object):
138
136
    """A simple class for OpenPGP symmetric encryption & decryption"""
139
137
    def __init__(self):
140
138
        self.gnupg = GnuPGInterface.GnuPG()
143
141
        self.gnupg.options.meta_interactive = False
144
142
        self.gnupg.options.homedir = self.tempdir
145
143
        self.gnupg.options.extra_args.extend(['--force-mdc',
146
 
                                              '--quiet',
147
 
                                              '--no-use-agent'])
 
144
                                              '--quiet'])
148
145
    
149
146
    def __enter__(self):
150
147
        return self
176
173
    
177
174
    def encrypt(self, data, password):
178
175
        self.gnupg.passphrase = self.password_encode(password)
179
 
        with open(os.devnull, "w") as devnull:
 
176
        with open(os.devnull) as devnull:
180
177
            try:
181
178
                proc = self.gnupg.run(['--symmetric'],
182
179
                                      create_fhs=['stdin', 'stdout'],
187
184
                    ciphertext = f.read()
188
185
                proc.wait()
189
186
            except IOError as e:
190
 
                raise PGPError(e)
 
187
                raise CryptoError(e)
191
188
        self.gnupg.passphrase = None
192
189
        return ciphertext
193
190
    
194
191
    def decrypt(self, data, password):
195
192
        self.gnupg.passphrase = self.password_encode(password)
196
 
        with open(os.devnull, "w") as devnull:
 
193
        with open(os.devnull) as devnull:
197
194
            try:
198
195
                proc = self.gnupg.run(['--decrypt'],
199
196
                                      create_fhs=['stdin', 'stdout'],
200
197
                                      attach_fhs={'stderr': devnull})
201
 
                with contextlib.closing(proc.handles['stdin']) as f:
 
198
                with contextlib.closing(proc.handles['stdin'] ) as f:
202
199
                    f.write(data)
203
200
                with contextlib.closing(proc.handles['stdout']) as f:
204
201
                    decrypted_plaintext = f.read()
205
202
                proc.wait()
206
203
            except IOError as e:
207
 
                raise PGPError(e)
 
204
                raise CryptoError(e)
208
205
        self.gnupg.passphrase = None
209
206
        return decrypted_plaintext
210
207
 
211
208
 
 
209
 
212
210
class AvahiError(Exception):
213
211
    def __init__(self, value, *args, **kwargs):
214
212
        self.value = value
243
241
    server: D-Bus Server
244
242
    bus: dbus.SystemBus()
245
243
    """
246
 
    
247
244
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
248
245
                 servicetype = None, port = None, TXT = None,
249
246
                 domain = "", host = "", max_renames = 32768,
262
259
        self.server = None
263
260
        self.bus = bus
264
261
        self.entry_group_state_changed_match = None
265
 
    
266
262
    def rename(self):
267
263
        """Derived from the Avahi example code"""
268
264
        if self.rename_count >= self.max_renames:
278
274
        try:
279
275
            self.add()
280
276
        except dbus.exceptions.DBusException as error:
281
 
            logger.critical("D-Bus Exception", exc_info=error)
 
277
            logger.critical("DBusException: %s", error)
282
278
            self.cleanup()
283
279
            os._exit(1)
284
280
        self.rename_count += 1
285
 
    
286
281
    def remove(self):
287
282
        """Derived from the Avahi example code"""
288
283
        if self.entry_group_state_changed_match is not None:
290
285
            self.entry_group_state_changed_match = None
291
286
        if self.group is not None:
292
287
            self.group.Reset()
293
 
    
294
288
    def add(self):
295
289
        """Derived from the Avahi example code"""
296
290
        self.remove()
313
307
            dbus.UInt16(self.port),
314
308
            avahi.string_array_to_txt_array(self.TXT))
315
309
        self.group.Commit()
316
 
    
317
310
    def entry_group_state_changed(self, state, error):
318
311
        """Derived from the Avahi example code"""
319
312
        logger.debug("Avahi entry group state change: %i", state)
326
319
        elif state == avahi.ENTRY_GROUP_FAILURE:
327
320
            logger.critical("Avahi: Error in group state changed %s",
328
321
                            unicode(error))
329
 
            raise AvahiGroupError("State changed: {0!s}"
330
 
                                  .format(error))
331
 
    
 
322
            raise AvahiGroupError("State changed: %s"
 
323
                                  % unicode(error))
332
324
    def cleanup(self):
333
325
        """Derived from the Avahi example code"""
334
326
        if self.group is not None:
339
331
                pass
340
332
            self.group = None
341
333
        self.remove()
342
 
    
343
334
    def server_state_changed(self, state, error=None):
344
335
        """Derived from the Avahi example code"""
345
336
        logger.debug("Avahi server state change: %i", state)
364
355
                logger.debug("Unknown state: %r", state)
365
356
            else:
366
357
                logger.debug("Unknown state: %r: %r", state, error)
367
 
    
368
358
    def activate(self):
369
359
        """Derived from the Avahi example code"""
370
360
        if self.server is None:
382
372
        """Add the new name to the syslog messages"""
383
373
        ret = AvahiService.rename(self)
384
374
        syslogger.setFormatter(logging.Formatter
385
 
                               ('Mandos ({0}) [%(process)d]:'
386
 
                                ' %(levelname)s: %(message)s'
387
 
                                .format(self.name)))
 
375
                               ('Mandos (%s) [%%(process)d]:'
 
376
                                ' %%(levelname)s: %%(message)s'
 
377
                                % self.name))
388
378
        return ret
389
379
 
390
 
def timedelta_to_milliseconds(td):
 
380
def _timedelta_to_milliseconds(td):
391
381
    "Convert a datetime.timedelta() to milliseconds"
392
382
    return ((td.days * 24 * 60 * 60 * 1000)
393
383
            + (td.seconds * 1000)
394
384
            + (td.microseconds // 1000))
395
 
 
 
385
        
396
386
class Client(object):
397
387
    """A representation of a client host served by this server.
398
388
    
399
389
    Attributes:
400
 
    approved:   bool(); 'None' if not yet approved/disapproved
 
390
    _approved:   bool(); 'None' if not yet approved/disapproved
401
391
    approval_delay: datetime.timedelta(); Time to wait for approval
402
392
    approval_duration: datetime.timedelta(); Duration of one approval
403
393
    checker:    subprocess.Popen(); a running checker process used
421
411
    interval:   datetime.timedelta(); How often to start a new checker
422
412
    last_approval_request: datetime.datetime(); (UTC) or None
423
413
    last_checked_ok: datetime.datetime(); (UTC) or None
 
414
 
424
415
    last_checker_status: integer between 0 and 255 reflecting exit
425
416
                         status of last checker. -1 reflects crashed
426
 
                         checker, -2 means no checker completed yet.
 
417
                         checker, or None.
427
418
    last_enabled: datetime.datetime(); (UTC) or None
428
419
    name:       string; from the config file, used in log messages and
429
420
                        D-Bus identifiers
430
421
    secret:     bytestring; sent verbatim (over TLS) to client
431
422
    timeout:    datetime.timedelta(); How long from last_checked_ok
432
423
                                      until this client is disabled
433
 
    extended_timeout:   extra long timeout when secret has been sent
 
424
    extended_timeout:   extra long timeout when password has been sent
434
425
    runtime_expansions: Allowed attributes for runtime expansion.
435
426
    expires:    datetime.datetime(); time (UTC) when a client will be
436
427
                disabled, or None
440
431
                          "created", "enabled", "fingerprint",
441
432
                          "host", "interval", "last_checked_ok",
442
433
                          "last_enabled", "name", "timeout")
443
 
    client_defaults = { "timeout": "5m",
444
 
                        "extended_timeout": "15m",
445
 
                        "interval": "2m",
446
 
                        "checker": "fping -q -- %%(host)s",
447
 
                        "host": "",
448
 
                        "approval_delay": "0s",
449
 
                        "approval_duration": "1s",
450
 
                        "approved_by_default": "True",
451
 
                        "enabled": "True",
452
 
                        }
453
434
    
454
435
    def timeout_milliseconds(self):
455
436
        "Return the 'timeout' attribute in milliseconds"
456
 
        return timedelta_to_milliseconds(self.timeout)
 
437
        return _timedelta_to_milliseconds(self.timeout)
457
438
    
458
439
    def extended_timeout_milliseconds(self):
459
440
        "Return the 'extended_timeout' attribute in milliseconds"
460
 
        return timedelta_to_milliseconds(self.extended_timeout)
 
441
        return _timedelta_to_milliseconds(self.extended_timeout)
461
442
    
462
443
    def interval_milliseconds(self):
463
444
        "Return the 'interval' attribute in milliseconds"
464
 
        return timedelta_to_milliseconds(self.interval)
 
445
        return _timedelta_to_milliseconds(self.interval)
465
446
    
466
447
    def approval_delay_milliseconds(self):
467
 
        return timedelta_to_milliseconds(self.approval_delay)
468
 
    
469
 
    @staticmethod
470
 
    def config_parser(config):
471
 
        """Construct a new dict of client settings of this form:
472
 
        { client_name: {setting_name: value, ...}, ...}
473
 
        with exceptions for any special settings as defined above.
474
 
        NOTE: Must be a pure function. Must return the same result
475
 
        value given the same arguments.
476
 
        """
477
 
        settings = {}
478
 
        for client_name in config.sections():
479
 
            section = dict(config.items(client_name))
480
 
            client = settings[client_name] = {}
481
 
            
482
 
            client["host"] = section["host"]
483
 
            # Reformat values from string types to Python types
484
 
            client["approved_by_default"] = config.getboolean(
485
 
                client_name, "approved_by_default")
486
 
            client["enabled"] = config.getboolean(client_name,
487
 
                                                  "enabled")
488
 
            
489
 
            client["fingerprint"] = (section["fingerprint"].upper()
490
 
                                     .replace(" ", ""))
491
 
            if "secret" in section:
492
 
                client["secret"] = section["secret"].decode("base64")
493
 
            elif "secfile" in section:
494
 
                with open(os.path.expanduser(os.path.expandvars
495
 
                                             (section["secfile"])),
496
 
                          "rb") as secfile:
497
 
                    client["secret"] = secfile.read()
498
 
            else:
499
 
                raise TypeError("No secret or secfile for section {0}"
500
 
                                .format(section))
501
 
            client["timeout"] = string_to_delta(section["timeout"])
502
 
            client["extended_timeout"] = string_to_delta(
503
 
                section["extended_timeout"])
504
 
            client["interval"] = string_to_delta(section["interval"])
505
 
            client["approval_delay"] = string_to_delta(
506
 
                section["approval_delay"])
507
 
            client["approval_duration"] = string_to_delta(
508
 
                section["approval_duration"])
509
 
            client["checker_command"] = section["checker"]
510
 
            client["last_approval_request"] = None
511
 
            client["last_checked_ok"] = None
512
 
            client["last_checker_status"] = -2
513
 
        
514
 
        return settings
515
 
    
516
 
    def __init__(self, settings, name = None):
 
448
        return _timedelta_to_milliseconds(self.approval_delay)
 
449
    
 
450
    def __init__(self, name = None, config=None):
 
451
        """Note: the 'checker' key in 'config' sets the
 
452
        'checker_command' attribute and *not* the 'checker'
 
453
        attribute."""
517
454
        self.name = name
518
 
        # adding all client settings
519
 
        for setting, value in settings.iteritems():
520
 
            setattr(self, setting, value)
521
 
        
522
 
        if self.enabled:
523
 
            if not hasattr(self, "last_enabled"):
524
 
                self.last_enabled = datetime.datetime.utcnow()
525
 
            if not hasattr(self, "expires"):
526
 
                self.expires = (datetime.datetime.utcnow()
527
 
                                + self.timeout)
528
 
        else:
529
 
            self.last_enabled = None
530
 
            self.expires = None
531
 
        
 
455
        if config is None:
 
456
            config = {}
532
457
        logger.debug("Creating client %r", self.name)
533
458
        # Uppercase and remove spaces from fingerprint for later
534
459
        # comparison purposes with return value from the fingerprint()
535
460
        # function
 
461
        self.fingerprint = (config["fingerprint"].upper()
 
462
                            .replace(" ", ""))
536
463
        logger.debug("  Fingerprint: %s", self.fingerprint)
537
 
        self.created = settings.get("created",
538
 
                                    datetime.datetime.utcnow())
539
 
        
540
 
        # attributes specific for this server instance
 
464
        if "secret" in config:
 
465
            self.secret = config["secret"].decode("base64")
 
466
        elif "secfile" in config:
 
467
            with open(os.path.expanduser(os.path.expandvars
 
468
                                         (config["secfile"])),
 
469
                      "rb") as secfile:
 
470
                self.secret = secfile.read()
 
471
        else:
 
472
            raise TypeError("No secret or secfile for client %s"
 
473
                            % self.name)
 
474
        self.host = config.get("host", "")
 
475
        self.created = datetime.datetime.utcnow()
 
476
        self.enabled = config.get("enabled", True)
 
477
        self.last_approval_request = None
 
478
        if self.enabled:
 
479
            self.last_enabled = datetime.datetime.utcnow()
 
480
        else:
 
481
            self.last_enabled = None
 
482
        self.last_checked_ok = None
 
483
        self.last_checker_status = None
 
484
        self.timeout = string_to_delta(config["timeout"])
 
485
        self.extended_timeout = string_to_delta(config
 
486
                                                ["extended_timeout"])
 
487
        self.interval = string_to_delta(config["interval"])
541
488
        self.checker = None
542
489
        self.checker_initiator_tag = None
543
490
        self.disable_initiator_tag = None
 
491
        if self.enabled:
 
492
            self.expires = datetime.datetime.utcnow() + self.timeout
 
493
        else:
 
494
            self.expires = None
544
495
        self.checker_callback_tag = None
 
496
        self.checker_command = config["checker"]
545
497
        self.current_checker_command = None
546
 
        self.approved = None
 
498
        self._approved = None
 
499
        self.approved_by_default = config.get("approved_by_default",
 
500
                                              True)
547
501
        self.approvals_pending = 0
 
502
        self.approval_delay = string_to_delta(
 
503
            config["approval_delay"])
 
504
        self.approval_duration = string_to_delta(
 
505
            config["approval_duration"])
548
506
        self.changedstate = (multiprocessing_manager
549
507
                             .Condition(multiprocessing_manager
550
508
                                        .Lock()))
617
575
        self.checker_callback_tag = None
618
576
        self.checker = None
619
577
        if os.WIFEXITED(condition):
620
 
            self.last_checker_status = os.WEXITSTATUS(condition)
 
578
            self.last_checker_status =  os.WEXITSTATUS(condition)
621
579
            if self.last_checker_status == 0:
622
580
                logger.info("Checker for %(name)s succeeded",
623
581
                            vars(self))
630
588
            logger.warning("Checker for %(name)s crashed?",
631
589
                           vars(self))
632
590
    
633
 
    def checked_ok(self):
634
 
        """Assert that the client has been seen, alive and well."""
635
 
        self.last_checked_ok = datetime.datetime.utcnow()
636
 
        self.last_checker_status = 0
637
 
        self.bump_timeout()
638
 
    
639
 
    def bump_timeout(self, timeout=None):
640
 
        """Bump up the timeout for this client."""
 
591
    def checked_ok(self, timeout=None):
 
592
        """Bump up the timeout for this client.
 
593
        
 
594
        This should only be called when the client has been seen,
 
595
        alive and well.
 
596
        """
641
597
        if timeout is None:
642
598
            timeout = self.timeout
 
599
        self.last_checked_ok = datetime.datetime.utcnow()
643
600
        if self.disable_initiator_tag is not None:
644
601
            gobject.source_remove(self.disable_initiator_tag)
645
602
        if getattr(self, "enabled", False):
646
603
            self.disable_initiator_tag = (gobject.timeout_add
647
 
                                          (timedelta_to_milliseconds
 
604
                                          (_timedelta_to_milliseconds
648
605
                                           (timeout), self.disable))
649
606
            self.expires = datetime.datetime.utcnow() + timeout
650
607
    
696
653
                try:
697
654
                    command = self.checker_command % escaped_attrs
698
655
                except TypeError as error:
699
 
                    logger.error('Could not format string "%s"',
700
 
                                 self.checker_command, exc_info=error)
 
656
                    logger.error('Could not format string "%s":'
 
657
                                 ' %s', self.checker_command, error)
701
658
                    return True # Try again later
702
659
            self.current_checker_command = command
703
660
            try:
721
678
                    gobject.source_remove(self.checker_callback_tag)
722
679
                    self.checker_callback(pid, status, command)
723
680
            except OSError as error:
724
 
                logger.error("Failed to start subprocess",
725
 
                             exc_info=error)
 
681
                logger.error("Failed to start subprocess: %s",
 
682
                             error)
726
683
        # Re-run this periodically if run by gobject.timeout_add
727
684
        return True
728
685
    
735
692
            return
736
693
        logger.debug("Stopping checker for %(name)s", vars(self))
737
694
        try:
738
 
            self.checker.terminate()
 
695
            os.kill(self.checker.pid, signal.SIGTERM)
739
696
            #time.sleep(0.5)
740
697
            #if self.checker.poll() is None:
741
 
            #    self.checker.kill()
 
698
            #    os.kill(self.checker.pid, signal.SIGKILL)
742
699
        except OSError as error:
743
700
            if error.errno != errno.ESRCH: # No such process
744
701
                raise
761
718
    # "Set" method, so we fail early here:
762
719
    if byte_arrays and signature != "ay":
763
720
        raise ValueError("Byte arrays not supported for non-'ay'"
764
 
                         " signature {0!r}".format(signature))
 
721
                         " signature %r" % signature)
765
722
    def decorator(func):
766
723
        func._dbus_is_property = True
767
724
        func._dbus_interface = dbus_interface
775
732
    return decorator
776
733
 
777
734
 
778
 
def dbus_interface_annotations(dbus_interface):
779
 
    """Decorator for marking functions returning interface annotations
780
 
    
781
 
    Usage:
782
 
    
783
 
    @dbus_interface_annotations("org.example.Interface")
784
 
    def _foo(self):  # Function name does not matter
785
 
        return {"org.freedesktop.DBus.Deprecated": "true",
786
 
                "org.freedesktop.DBus.Property.EmitsChangedSignal":
787
 
                    "false"}
788
 
    """
789
 
    def decorator(func):
790
 
        func._dbus_is_interface = True
791
 
        func._dbus_interface = dbus_interface
792
 
        func._dbus_name = dbus_interface
793
 
        return func
794
 
    return decorator
795
 
 
796
 
 
797
 
def dbus_annotations(annotations):
798
 
    """Decorator to annotate D-Bus methods, signals or properties
799
 
    Usage:
800
 
    
801
 
    @dbus_service_property("org.example.Interface", signature="b",
802
 
                           access="r")
803
 
    @dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
804
 
                        "org.freedesktop.DBus.Property."
805
 
                        "EmitsChangedSignal": "false"})
806
 
    def Property_dbus_property(self):
807
 
        return dbus.Boolean(False)
808
 
    """
809
 
    def decorator(func):
810
 
        func._dbus_annotations = annotations
811
 
        return func
812
 
    return decorator
813
 
 
814
 
 
815
735
class DBusPropertyException(dbus.exceptions.DBusException):
816
736
    """A base class for D-Bus property-related exceptions
817
737
    """
840
760
    """
841
761
    
842
762
    @staticmethod
843
 
    def _is_dbus_thing(thing):
844
 
        """Returns a function testing if an attribute is a D-Bus thing
845
 
        
846
 
        If called like _is_dbus_thing("method") it returns a function
847
 
        suitable for use as predicate to inspect.getmembers().
848
 
        """
849
 
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
850
 
                                   False)
 
763
    def _is_dbus_property(obj):
 
764
        return getattr(obj, "_dbus_is_property", False)
851
765
    
852
 
    def _get_all_dbus_things(self, thing):
 
766
    def _get_all_dbus_properties(self):
853
767
        """Returns a generator of (name, attribute) pairs
854
768
        """
855
 
        return ((getattr(athing.__get__(self), "_dbus_name",
856
 
                         name),
857
 
                 athing.__get__(self))
 
769
        return ((prop.__get__(self)._dbus_name, prop.__get__(self))
858
770
                for cls in self.__class__.__mro__
859
 
                for name, athing in
860
 
                inspect.getmembers(cls,
861
 
                                   self._is_dbus_thing(thing)))
 
771
                for name, prop in
 
772
                inspect.getmembers(cls, self._is_dbus_property))
862
773
    
863
774
    def _get_dbus_property(self, interface_name, property_name):
864
775
        """Returns a bound method if one exists which is a D-Bus
866
777
        """
867
778
        for cls in  self.__class__.__mro__:
868
779
            for name, value in (inspect.getmembers
869
 
                                (cls,
870
 
                                 self._is_dbus_thing("property"))):
 
780
                                (cls, self._is_dbus_property)):
871
781
                if (value._dbus_name == property_name
872
782
                    and value._dbus_interface == interface_name):
873
783
                    return value.__get__(self)
902
812
            # signatures other than "ay".
903
813
            if prop._dbus_signature != "ay":
904
814
                raise ValueError
905
 
            value = dbus.ByteArray(b''.join(chr(byte)
906
 
                                            for byte in value))
 
815
            value = dbus.ByteArray(''.join(unichr(byte)
 
816
                                           for byte in value))
907
817
        prop(value)
908
818
    
909
819
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
915
825
        Note: Will not include properties with access="write".
916
826
        """
917
827
        properties = {}
918
 
        for name, prop in self._get_all_dbus_things("property"):
 
828
        for name, prop in self._get_all_dbus_properties():
919
829
            if (interface_name
920
830
                and interface_name != prop._dbus_interface):
921
831
                # Interface non-empty but did not match
936
846
                         path_keyword='object_path',
937
847
                         connection_keyword='connection')
938
848
    def Introspect(self, object_path, connection):
939
 
        """Overloading of standard D-Bus method.
940
 
        
941
 
        Inserts property tags and interface annotation tags.
 
849
        """Standard D-Bus method, overloaded to insert property tags.
942
850
        """
943
851
        xmlstring = dbus.service.Object.Introspect(self, object_path,
944
852
                                                   connection)
951
859
                e.setAttribute("access", prop._dbus_access)
952
860
                return e
953
861
            for if_tag in document.getElementsByTagName("interface"):
954
 
                # Add property tags
955
862
                for tag in (make_tag(document, name, prop)
956
863
                            for name, prop
957
 
                            in self._get_all_dbus_things("property")
 
864
                            in self._get_all_dbus_properties()
958
865
                            if prop._dbus_interface
959
866
                            == if_tag.getAttribute("name")):
960
867
                    if_tag.appendChild(tag)
961
 
                # Add annotation tags
962
 
                for typ in ("method", "signal", "property"):
963
 
                    for tag in if_tag.getElementsByTagName(typ):
964
 
                        annots = dict()
965
 
                        for name, prop in (self.
966
 
                                           _get_all_dbus_things(typ)):
967
 
                            if (name == tag.getAttribute("name")
968
 
                                and prop._dbus_interface
969
 
                                == if_tag.getAttribute("name")):
970
 
                                annots.update(getattr
971
 
                                              (prop,
972
 
                                               "_dbus_annotations",
973
 
                                               {}))
974
 
                        for name, value in annots.iteritems():
975
 
                            ann_tag = document.createElement(
976
 
                                "annotation")
977
 
                            ann_tag.setAttribute("name", name)
978
 
                            ann_tag.setAttribute("value", value)
979
 
                            tag.appendChild(ann_tag)
980
 
                # Add interface annotation tags
981
 
                for annotation, value in dict(
982
 
                    itertools.chain(
983
 
                        *(annotations().iteritems()
984
 
                          for name, annotations in
985
 
                          self._get_all_dbus_things("interface")
986
 
                          if name == if_tag.getAttribute("name")
987
 
                          ))).iteritems():
988
 
                    ann_tag = document.createElement("annotation")
989
 
                    ann_tag.setAttribute("name", annotation)
990
 
                    ann_tag.setAttribute("value", value)
991
 
                    if_tag.appendChild(ann_tag)
992
868
                # Add the names to the return values for the
993
869
                # "org.freedesktop.DBus.Properties" methods
994
870
                if (if_tag.getAttribute("name")
1009
885
        except (AttributeError, xml.dom.DOMException,
1010
886
                xml.parsers.expat.ExpatError) as error:
1011
887
            logger.error("Failed to override Introspection method",
1012
 
                         exc_info=error)
 
888
                         error)
1013
889
        return xmlstring
1014
890
 
1015
891
 
1029
905
    def __new__(mcs, name, bases, attr):
1030
906
        # Go through all the base classes which could have D-Bus
1031
907
        # methods, signals, or properties in them
1032
 
        old_interface_names = []
1033
908
        for base in (b for b in bases
1034
909
                     if issubclass(b, dbus.service.Object)):
1035
910
            # Go though all attributes of the base class
1045
920
                alt_interface = (attribute._dbus_interface
1046
921
                                 .replace("se.recompile.Mandos",
1047
922
                                          "se.bsnet.fukt.Mandos"))
1048
 
                if alt_interface != attribute._dbus_interface:
1049
 
                    old_interface_names.append(alt_interface)
1050
923
                # Is this a D-Bus signal?
1051
924
                if getattr(attribute, "_dbus_is_signal", False):
1052
925
                    # Extract the original non-method function by
1067
940
                                nonmethod_func.func_name,
1068
941
                                nonmethod_func.func_defaults,
1069
942
                                nonmethod_func.func_closure)))
1070
 
                    # Copy annotations, if any
1071
 
                    try:
1072
 
                        new_function._dbus_annotations = (
1073
 
                            dict(attribute._dbus_annotations))
1074
 
                    except AttributeError:
1075
 
                        pass
1076
943
                    # Define a creator of a function to call both the
1077
944
                    # old and new functions, so both the old and new
1078
945
                    # signals gets sent when the function is called
1106
973
                                        attribute.func_name,
1107
974
                                        attribute.func_defaults,
1108
975
                                        attribute.func_closure)))
1109
 
                    # Copy annotations, if any
1110
 
                    try:
1111
 
                        attr[attrname]._dbus_annotations = (
1112
 
                            dict(attribute._dbus_annotations))
1113
 
                    except AttributeError:
1114
 
                        pass
1115
976
                # Is this a D-Bus property?
1116
977
                elif getattr(attribute, "_dbus_is_property", False):
1117
978
                    # Create a new, but exactly alike, function
1131
992
                                        attribute.func_name,
1132
993
                                        attribute.func_defaults,
1133
994
                                        attribute.func_closure)))
1134
 
                    # Copy annotations, if any
1135
 
                    try:
1136
 
                        attr[attrname]._dbus_annotations = (
1137
 
                            dict(attribute._dbus_annotations))
1138
 
                    except AttributeError:
1139
 
                        pass
1140
 
                # Is this a D-Bus interface?
1141
 
                elif getattr(attribute, "_dbus_is_interface", False):
1142
 
                    # Create a new, but exactly alike, function
1143
 
                    # object.  Decorate it to be a new D-Bus interface
1144
 
                    # with the alternate D-Bus interface name.  Add it
1145
 
                    # to the class.
1146
 
                    attr[attrname] = (dbus_interface_annotations
1147
 
                                      (alt_interface)
1148
 
                                      (types.FunctionType
1149
 
                                       (attribute.func_code,
1150
 
                                        attribute.func_globals,
1151
 
                                        attribute.func_name,
1152
 
                                        attribute.func_defaults,
1153
 
                                        attribute.func_closure)))
1154
 
        # Deprecate all old interfaces
1155
 
        iname="_AlternateDBusNamesMetaclass_interface_annotation{0}"
1156
 
        for old_interface_name in old_interface_names:
1157
 
            @dbus_interface_annotations(old_interface_name)
1158
 
            def func(self):
1159
 
                return { "org.freedesktop.DBus.Deprecated": "true" }
1160
 
            # Find an unused name
1161
 
            for aname in (iname.format(i) for i in itertools.count()):
1162
 
                if aname not in attr:
1163
 
                    attr[aname] = func
1164
 
                    break
1165
995
        return type.__new__(mcs, name, bases, attr)
1166
996
 
1167
997
 
1181
1011
    def __init__(self, bus = None, *args, **kwargs):
1182
1012
        self.bus = bus
1183
1013
        Client.__init__(self, *args, **kwargs)
 
1014
        
 
1015
        self._approvals_pending = 0
1184
1016
        # Only now, when this client is initialized, can it show up on
1185
1017
        # the D-Bus
1186
1018
        client_object_name = unicode(self.name).translate(
1190
1022
                                 ("/clients/" + client_object_name))
1191
1023
        DBusObjectWithProperties.__init__(self, self.bus,
1192
1024
                                          self.dbus_object_path)
1193
 
    
 
1025
        
1194
1026
    def notifychangeproperty(transform_func,
1195
1027
                             dbus_name, type_func=lambda x: x,
1196
1028
                             variant_level=1):
1219
1051
        
1220
1052
        return property(lambda self: getattr(self, attrname), setter)
1221
1053
    
 
1054
    
1222
1055
    expires = notifychangeproperty(datetime_to_dbus, "Expires")
1223
1056
    approvals_pending = notifychangeproperty(dbus.Boolean,
1224
1057
                                             "ApprovalPending",
1231
1064
                                       checker is not None)
1232
1065
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1233
1066
                                           "LastCheckedOK")
1234
 
    last_checker_status = notifychangeproperty(dbus.Int16,
1235
 
                                               "LastCheckerStatus")
1236
1067
    last_approval_request = notifychangeproperty(
1237
1068
        datetime_to_dbus, "LastApprovalRequest")
1238
1069
    approved_by_default = notifychangeproperty(dbus.Boolean,
1239
1070
                                               "ApprovedByDefault")
1240
 
    approval_delay = notifychangeproperty(dbus.UInt64,
 
1071
    approval_delay = notifychangeproperty(dbus.UInt16,
1241
1072
                                          "ApprovalDelay",
1242
1073
                                          type_func =
1243
 
                                          timedelta_to_milliseconds)
 
1074
                                          _timedelta_to_milliseconds)
1244
1075
    approval_duration = notifychangeproperty(
1245
 
        dbus.UInt64, "ApprovalDuration",
1246
 
        type_func = timedelta_to_milliseconds)
 
1076
        dbus.UInt16, "ApprovalDuration",
 
1077
        type_func = _timedelta_to_milliseconds)
1247
1078
    host = notifychangeproperty(dbus.String, "Host")
1248
 
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
 
1079
    timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1249
1080
                                   type_func =
1250
 
                                   timedelta_to_milliseconds)
 
1081
                                   _timedelta_to_milliseconds)
1251
1082
    extended_timeout = notifychangeproperty(
1252
 
        dbus.UInt64, "ExtendedTimeout",
1253
 
        type_func = timedelta_to_milliseconds)
1254
 
    interval = notifychangeproperty(dbus.UInt64,
 
1083
        dbus.UInt16, "ExtendedTimeout",
 
1084
        type_func = _timedelta_to_milliseconds)
 
1085
    interval = notifychangeproperty(dbus.UInt16,
1255
1086
                                    "Interval",
1256
1087
                                    type_func =
1257
 
                                    timedelta_to_milliseconds)
 
1088
                                    _timedelta_to_milliseconds)
1258
1089
    checker_command = notifychangeproperty(dbus.String, "Checker")
1259
1090
    
1260
1091
    del notifychangeproperty
1302
1133
        return r
1303
1134
    
1304
1135
    def _reset_approved(self):
1305
 
        self.approved = None
 
1136
        self._approved = None
1306
1137
        return False
1307
1138
    
1308
1139
    def approve(self, value=True):
1309
1140
        self.send_changedstate()
1310
 
        self.approved = value
1311
 
        gobject.timeout_add(timedelta_to_milliseconds
 
1141
        self._approved = value
 
1142
        gobject.timeout_add(_timedelta_to_milliseconds
1312
1143
                            (self.approval_duration),
1313
1144
                            self._reset_approved)
1314
1145
    
 
1146
    
1315
1147
    ## D-Bus methods, signals & properties
1316
1148
    _interface = "se.recompile.Mandos.Client"
1317
1149
    
1318
 
    ## Interfaces
1319
 
    
1320
 
    @dbus_interface_annotations(_interface)
1321
 
    def _foo(self):
1322
 
        return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
1323
 
                     "false"}
1324
 
    
1325
1150
    ## Signals
1326
1151
    
1327
1152
    # CheckerCompleted - signal
1363
1188
        "D-Bus signal"
1364
1189
        return self.need_approval()
1365
1190
    
 
1191
    # NeRwequest - signal
 
1192
    @dbus.service.signal(_interface, signature="s")
 
1193
    def NewRequest(self, ip):
 
1194
        """D-Bus signal
 
1195
        Is sent after a client request a password.
 
1196
        """
 
1197
        pass
 
1198
    
1366
1199
    ## Methods
1367
1200
    
1368
1201
    # Approve - method
1426
1259
                           access="readwrite")
1427
1260
    def ApprovalDuration_dbus_property(self, value=None):
1428
1261
        if value is None:       # get
1429
 
            return dbus.UInt64(timedelta_to_milliseconds(
 
1262
            return dbus.UInt64(_timedelta_to_milliseconds(
1430
1263
                    self.approval_duration))
1431
1264
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1432
1265
    
1446
1279
    def Host_dbus_property(self, value=None):
1447
1280
        if value is None:       # get
1448
1281
            return dbus.String(self.host)
1449
 
        self.host = unicode(value)
 
1282
        self.host = value
1450
1283
    
1451
1284
    # Created - property
1452
1285
    @dbus_service_property(_interface, signature="s", access="read")
1478
1311
            return
1479
1312
        return datetime_to_dbus(self.last_checked_ok)
1480
1313
    
1481
 
    # LastCheckerStatus - property
1482
 
    @dbus_service_property(_interface, signature="n",
1483
 
                           access="read")
1484
 
    def LastCheckerStatus_dbus_property(self):
1485
 
        return dbus.Int16(self.last_checker_status)
1486
 
    
1487
1314
    # Expires - property
1488
1315
    @dbus_service_property(_interface, signature="s", access="read")
1489
1316
    def Expires_dbus_property(self):
1501
1328
        if value is None:       # get
1502
1329
            return dbus.UInt64(self.timeout_milliseconds())
1503
1330
        self.timeout = datetime.timedelta(0, 0, 0, value)
 
1331
        if getattr(self, "disable_initiator_tag", None) is None:
 
1332
            return
1504
1333
        # Reschedule timeout
1505
 
        if self.enabled:
1506
 
            now = datetime.datetime.utcnow()
1507
 
            time_to_die = timedelta_to_milliseconds(
1508
 
                (self.last_checked_ok + self.timeout) - now)
1509
 
            if time_to_die <= 0:
1510
 
                # The timeout has passed
1511
 
                self.disable()
1512
 
            else:
1513
 
                self.expires = (now +
1514
 
                                datetime.timedelta(milliseconds =
1515
 
                                                   time_to_die))
1516
 
                if (getattr(self, "disable_initiator_tag", None)
1517
 
                    is None):
1518
 
                    return
1519
 
                gobject.source_remove(self.disable_initiator_tag)
1520
 
                self.disable_initiator_tag = (gobject.timeout_add
1521
 
                                              (time_to_die,
1522
 
                                               self.disable))
 
1334
        gobject.source_remove(self.disable_initiator_tag)
 
1335
        self.disable_initiator_tag = None
 
1336
        self.expires = None
 
1337
        time_to_die = _timedelta_to_milliseconds((self
 
1338
                                                  .last_checked_ok
 
1339
                                                  + self.timeout)
 
1340
                                                 - datetime.datetime
 
1341
                                                 .utcnow())
 
1342
        if time_to_die <= 0:
 
1343
            # The timeout has passed
 
1344
            self.disable()
 
1345
        else:
 
1346
            self.expires = (datetime.datetime.utcnow()
 
1347
                            + datetime.timedelta(milliseconds =
 
1348
                                                 time_to_die))
 
1349
            self.disable_initiator_tag = (gobject.timeout_add
 
1350
                                          (time_to_die, self.disable))
1523
1351
    
1524
1352
    # ExtendedTimeout - property
1525
1353
    @dbus_service_property(_interface, signature="t",
1551
1379
    def Checker_dbus_property(self, value=None):
1552
1380
        if value is None:       # get
1553
1381
            return dbus.String(self.checker_command)
1554
 
        self.checker_command = unicode(value)
 
1382
        self.checker_command = value
1555
1383
    
1556
1384
    # CheckerRunning - property
1557
1385
    @dbus_service_property(_interface, signature="b",
1586
1414
            raise KeyError()
1587
1415
    
1588
1416
    def __getattribute__(self, name):
1589
 
        if name == '_pipe':
 
1417
        if(name == '_pipe'):
1590
1418
            return super(ProxyClient, self).__getattribute__(name)
1591
1419
        self._pipe.send(('getattr', name))
1592
1420
        data = self._pipe.recv()
1599
1427
            return func
1600
1428
    
1601
1429
    def __setattr__(self, name, value):
1602
 
        if name == '_pipe':
 
1430
        if(name == '_pipe'):
1603
1431
            return super(ProxyClient, self).__setattr__(name, value)
1604
1432
        self._pipe.send(('setattr', name, value))
1605
1433
 
1674
1502
                    logger.warning("Bad certificate: %s", error)
1675
1503
                    return
1676
1504
                logger.debug("Fingerprint: %s", fpr)
 
1505
                if self.server.use_dbus:
 
1506
                    # Emit D-Bus signal
 
1507
                    client.NewRequest(str(self.client_address))
1677
1508
                
1678
1509
                try:
1679
1510
                    client = ProxyClient(child_pipe, fpr,
1695
1526
                            client.Rejected("Disabled")
1696
1527
                        return
1697
1528
                    
1698
 
                    if client.approved or not client.approval_delay:
 
1529
                    if client._approved or not client.approval_delay:
1699
1530
                        #We are approved or approval is disabled
1700
1531
                        break
1701
 
                    elif client.approved is None:
 
1532
                    elif client._approved is None:
1702
1533
                        logger.info("Client %s needs approval",
1703
1534
                                    client.name)
1704
1535
                        if self.server.use_dbus:
1718
1549
                    time = datetime.datetime.now()
1719
1550
                    client.changedstate.acquire()
1720
1551
                    (client.changedstate.wait
1721
 
                     (float(client.timedelta_to_milliseconds(delay)
 
1552
                     (float(client._timedelta_to_milliseconds(delay)
1722
1553
                            / 1000)))
1723
1554
                    client.changedstate.release()
1724
1555
                    time2 = datetime.datetime.now()
1741
1572
                    try:
1742
1573
                        sent = session.send(client.secret[sent_size:])
1743
1574
                    except gnutls.errors.GNUTLSError as error:
1744
 
                        logger.warning("gnutls send failed",
1745
 
                                       exc_info=error)
 
1575
                        logger.warning("gnutls send failed")
1746
1576
                        return
1747
1577
                    logger.debug("Sent: %d, remaining: %d",
1748
1578
                                 sent, len(client.secret)
1751
1581
                
1752
1582
                logger.info("Sending secret to %s", client.name)
1753
1583
                # bump the timeout using extended_timeout
1754
 
                client.bump_timeout(client.extended_timeout)
 
1584
                client.checked_ok(client.extended_timeout)
1755
1585
                if self.server.use_dbus:
1756
1586
                    # Emit D-Bus signal
1757
1587
                    client.GotSecret()
1762
1592
                try:
1763
1593
                    session.bye()
1764
1594
                except gnutls.errors.GNUTLSError as error:
1765
 
                    logger.warning("GnuTLS bye failed",
1766
 
                                   exc_info=error)
 
1595
                    logger.warning("GnuTLS bye failed")
1767
1596
    
1768
1597
    @staticmethod
1769
1598
    def peer_certificate(session):
1834
1663
    def sub_process_main(self, request, address):
1835
1664
        try:
1836
1665
            self.finish_request(request, address)
1837
 
        except Exception:
 
1666
        except:
1838
1667
            self.handle_error(request, address)
1839
1668
        self.close_request(request)
1840
1669
    
2081
1910
            elif suffix == "w":
2082
1911
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2083
1912
            else:
2084
 
                raise ValueError("Unknown suffix {0!r}"
2085
 
                                 .format(suffix))
 
1913
                raise ValueError("Unknown suffix %r" % suffix)
2086
1914
        except (ValueError, IndexError) as e:
2087
1915
            raise ValueError(*(e.args))
2088
1916
        timevalue += delta
2102
1930
        sys.exit()
2103
1931
    if not noclose:
2104
1932
        # Close all standard open file descriptors
2105
 
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
 
1933
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
2106
1934
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2107
1935
            raise OSError(errno.ENODEV,
2108
 
                          "{0} not a character device"
2109
 
                          .format(os.devnull))
 
1936
                          "%s not a character device"
 
1937
                          % os.path.devnull)
2110
1938
        os.dup2(null, sys.stdin.fileno())
2111
1939
        os.dup2(null, sys.stdout.fileno())
2112
1940
        os.dup2(null, sys.stderr.fileno())
2121
1949
    
2122
1950
    parser = argparse.ArgumentParser()
2123
1951
    parser.add_argument("-v", "--version", action="version",
2124
 
                        version = "%(prog)s {0}".format(version),
 
1952
                        version = "%%(prog)s %s" % version,
2125
1953
                        help="show version number and exit")
2126
1954
    parser.add_argument("-i", "--interface", metavar="IF",
2127
1955
                        help="Bind to interface IF")
2220
2048
                                     stored_state_file)
2221
2049
    
2222
2050
    if debug:
2223
 
        initlogger(debug, logging.DEBUG)
 
2051
        initlogger(logging.DEBUG)
2224
2052
    else:
2225
2053
        if not debuglevel:
2226
 
            initlogger(debug)
 
2054
            initlogger()
2227
2055
        else:
2228
2056
            level = getattr(logging, debuglevel.upper())
2229
 
            initlogger(debug, level)
 
2057
            initlogger(level)
2230
2058
    
2231
2059
    if server_settings["servicename"] != "Mandos":
2232
2060
        syslogger.setFormatter(logging.Formatter
2233
 
                               ('Mandos ({0}) [%(process)d]:'
2234
 
                                ' %(levelname)s: %(message)s'
2235
 
                                .format(server_settings
2236
 
                                        ["servicename"])))
 
2061
                               ('Mandos (%s) [%%(process)d]:'
 
2062
                                ' %%(levelname)s: %%(message)s'
 
2063
                                % server_settings["servicename"]))
2237
2064
    
2238
2065
    # Parse config file with clients
2239
 
    client_config = configparser.SafeConfigParser(Client
2240
 
                                                  .client_defaults)
 
2066
    client_defaults = { "timeout": "5m",
 
2067
                        "extended_timeout": "15m",
 
2068
                        "interval": "2m",
 
2069
                        "checker": "fping -q -- %%(host)s",
 
2070
                        "host": "",
 
2071
                        "approval_delay": "0s",
 
2072
                        "approval_duration": "1s",
 
2073
                        }
 
2074
    client_config = configparser.SafeConfigParser(client_defaults)
2241
2075
    client_config.read(os.path.join(server_settings["configdir"],
2242
2076
                                    "clients.conf"))
2243
2077
    
2257
2091
        pidfilename = "/var/run/mandos.pid"
2258
2092
        try:
2259
2093
            pidfile = open(pidfilename, "w")
2260
 
        except IOError as e:
2261
 
            logger.error("Could not open file %r", pidfilename,
2262
 
                         exc_info=e)
 
2094
        except IOError:
 
2095
            logger.error("Could not open file %r", pidfilename)
2263
2096
    
2264
 
    for name in ("_mandos", "mandos", "nobody"):
 
2097
    try:
 
2098
        uid = pwd.getpwnam("_mandos").pw_uid
 
2099
        gid = pwd.getpwnam("_mandos").pw_gid
 
2100
    except KeyError:
2265
2101
        try:
2266
 
            uid = pwd.getpwnam(name).pw_uid
2267
 
            gid = pwd.getpwnam(name).pw_gid
2268
 
            break
 
2102
            uid = pwd.getpwnam("mandos").pw_uid
 
2103
            gid = pwd.getpwnam("mandos").pw_gid
2269
2104
        except KeyError:
2270
 
            continue
2271
 
    else:
2272
 
        uid = 65534
2273
 
        gid = 65534
 
2105
            try:
 
2106
                uid = pwd.getpwnam("nobody").pw_uid
 
2107
                gid = pwd.getpwnam("nobody").pw_gid
 
2108
            except KeyError:
 
2109
                uid = 65534
 
2110
                gid = 65534
2274
2111
    try:
2275
2112
        os.setgid(gid)
2276
2113
        os.setuid(uid)
2293
2130
         .gnutls_global_set_log_function(debug_gnutls))
2294
2131
        
2295
2132
        # Redirect stdin so all checkers get /dev/null
2296
 
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
 
2133
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
2297
2134
        os.dup2(null, sys.stdin.fileno())
2298
2135
        if null > 2:
2299
2136
            os.close(null)
 
2137
    else:
 
2138
        # No console logging
 
2139
        logger.removeHandler(console)
2300
2140
    
2301
2141
    # Need to fork before connecting to D-Bus
2302
2142
    if not debug:
2303
2143
        # Close all input and output, do double fork, etc.
2304
2144
        daemon()
2305
2145
    
2306
 
    gobject.threads_init()
2307
 
    
2308
2146
    global main_loop
2309
2147
    # From the Avahi example code
2310
 
    DBusGMainLoop(set_as_default=True)
 
2148
    DBusGMainLoop(set_as_default=True )
2311
2149
    main_loop = gobject.MainLoop()
2312
2150
    bus = dbus.SystemBus()
2313
2151
    # End of Avahi example code
2319
2157
                            ("se.bsnet.fukt.Mandos", bus,
2320
2158
                             do_not_queue=True))
2321
2159
        except dbus.exceptions.NameExistsException as e:
2322
 
            logger.error("Disabling D-Bus:", exc_info=e)
 
2160
            logger.error(unicode(e) + ", disabling D-Bus")
2323
2161
            use_dbus = False
2324
2162
            server_settings["use_dbus"] = False
2325
2163
            tcp_server.use_dbus = False
2340
2178
        client_class = functools.partial(ClientDBusTransitional,
2341
2179
                                         bus = bus)
2342
2180
    
2343
 
    client_settings = Client.config_parser(client_config)
 
2181
    special_settings = {
 
2182
        # Some settings need to be accessd by special methods;
 
2183
        # booleans need .getboolean(), etc.  Here is a list of them:
 
2184
        "approved_by_default":
 
2185
            lambda section:
 
2186
            client_config.getboolean(section, "approved_by_default"),
 
2187
        "enabled":
 
2188
            lambda section:
 
2189
            client_config.getboolean(section, "enabled"),
 
2190
        }
 
2191
    # Construct a new dict of client settings of this form:
 
2192
    # { client_name: {setting_name: value, ...}, ...}
 
2193
    # with exceptions for any special settings as defined above
 
2194
    client_settings = dict((clientname,
 
2195
                           dict((setting,
 
2196
                                 (value
 
2197
                                  if setting not in special_settings
 
2198
                                  else special_settings[setting]
 
2199
                                  (clientname)))
 
2200
                                for setting, value in
 
2201
                                client_config.items(clientname)))
 
2202
                          for clientname in client_config.sections())
 
2203
    
2344
2204
    old_client_settings = {}
2345
 
    clients_data = {}
 
2205
    clients_data = []
2346
2206
    
2347
2207
    # Get client data and settings from last running state.
2348
2208
    if server_settings["restore"]:
2352
2212
                                                     (stored_state))
2353
2213
            os.remove(stored_state_path)
2354
2214
        except IOError as e:
2355
 
            if e.errno == errno.ENOENT:
2356
 
                logger.warning("Could not load persistent state: {0}"
2357
 
                                .format(os.strerror(e.errno)))
2358
 
            else:
2359
 
                logger.critical("Could not load persistent state:",
2360
 
                                exc_info=e)
 
2215
            logger.warning("Could not load persistent state: {0}"
 
2216
                           .format(e))
 
2217
            if e.errno != errno.ENOENT:
2361
2218
                raise
2362
 
        except EOFError as e:
2363
 
            logger.warning("Could not load persistent state: "
2364
 
                           "EOFError:", exc_info=e)
2365
2219
    
2366
 
    with PGPEngine() as pgp:
2367
 
        for client_name, client in clients_data.iteritems():
 
2220
    with Crypto() as crypt:
 
2221
        for client in clients_data:
 
2222
            client_name = client["name"]
 
2223
            
2368
2224
            # Decide which value to use after restoring saved state.
2369
2225
            # We have three different values: Old config file,
2370
2226
            # new config file, and saved state.
2378
2234
                    if (name != "secret" and
2379
2235
                        value != old_client_settings[client_name]
2380
2236
                        [name]):
2381
 
                        client[name] = value
 
2237
                        setattr(client, name, value)
2382
2238
                except KeyError:
2383
2239
                    pass
2384
2240
            
2385
2241
            # Clients who has passed its expire date can still be
2386
 
            # enabled if its last checker was successful.  Clients
2387
 
            # whose checker succeeded before we stored its state is
2388
 
            # assumed to have successfully run all checkers during
2389
 
            # downtime.
2390
 
            if client["enabled"]:
2391
 
                if datetime.datetime.utcnow() >= client["expires"]:
2392
 
                    if not client["last_checked_ok"]:
2393
 
                        logger.warning(
2394
 
                            "disabling client {0} - Client never "
2395
 
                            "performed a successful checker"
2396
 
                            .format(client_name))
2397
 
                        client["enabled"] = False
2398
 
                    elif client["last_checker_status"] != 0:
2399
 
                        logger.warning(
2400
 
                            "disabling client {0} - Client "
2401
 
                            "last checker failed with error code {1}"
2402
 
                            .format(client_name,
2403
 
                                    client["last_checker_status"]))
 
2242
            # enabled if its last checker was sucessful.  Clients
 
2243
            # whose checker failed before we stored its state is
 
2244
            # assumed to have failed all checkers during downtime.
 
2245
            if client["enabled"] and client["last_checked_ok"]:
 
2246
                if ((datetime.datetime.utcnow()
 
2247
                     - client["last_checked_ok"])
 
2248
                    > client["interval"]):
 
2249
                    if client["last_checker_status"] != 0:
2404
2250
                        client["enabled"] = False
2405
2251
                    else:
2406
2252
                        client["expires"] = (datetime.datetime
2407
2253
                                             .utcnow()
2408
2254
                                             + client["timeout"])
2409
 
                        logger.debug("Last checker succeeded,"
2410
 
                                     " keeping {0} enabled"
2411
 
                                     .format(client_name))
 
2255
            
 
2256
            client["changedstate"] = (multiprocessing_manager
 
2257
                                      .Condition
 
2258
                                      (multiprocessing_manager
 
2259
                                       .Lock()))
 
2260
            if use_dbus:
 
2261
                new_client = (ClientDBusTransitional.__new__
 
2262
                              (ClientDBusTransitional))
 
2263
                tcp_server.clients[client_name] = new_client
 
2264
                new_client.bus = bus
 
2265
                for name, value in client.iteritems():
 
2266
                    setattr(new_client, name, value)
 
2267
                client_object_name = unicode(client_name).translate(
 
2268
                    {ord("."): ord("_"),
 
2269
                     ord("-"): ord("_")})
 
2270
                new_client.dbus_object_path = (dbus.ObjectPath
 
2271
                                               ("/clients/"
 
2272
                                                + client_object_name))
 
2273
                DBusObjectWithProperties.__init__(new_client,
 
2274
                                                  new_client.bus,
 
2275
                                                  new_client
 
2276
                                                  .dbus_object_path)
 
2277
            else:
 
2278
                tcp_server.clients[client_name] = (Client.__new__
 
2279
                                                   (Client))
 
2280
                for name, value in client.iteritems():
 
2281
                    setattr(tcp_server.clients[client_name],
 
2282
                            name, value)
 
2283
            
2412
2284
            try:
2413
 
                client["secret"] = (
2414
 
                    pgp.decrypt(client["encrypted_secret"],
2415
 
                                client_settings[client_name]
2416
 
                                ["secret"]))
2417
 
            except PGPError:
 
2285
                tcp_server.clients[client_name].secret = (
 
2286
                    crypt.decrypt(tcp_server.clients[client_name]
 
2287
                                  .encrypted_secret,
 
2288
                                  client_settings[client_name]
 
2289
                                  ["secret"]))
 
2290
            except CryptoError:
2418
2291
                # If decryption fails, we use secret from new settings
2419
 
                logger.debug("Failed to decrypt {0} old secret"
2420
 
                             .format(client_name))
2421
 
                client["secret"] = (
 
2292
                tcp_server.clients[client_name].secret = (
2422
2293
                    client_settings[client_name]["secret"])
2423
2294
    
2424
 
    # Add/remove clients based on new changes made to config
2425
 
    for client_name in (set(old_client_settings)
2426
 
                        - set(client_settings)):
2427
 
        del clients_data[client_name]
2428
 
    for client_name in (set(client_settings)
2429
 
                        - set(old_client_settings)):
2430
 
        clients_data[client_name] = client_settings[client_name]
2431
 
    
2432
 
    # Create all client objects
2433
 
    for client_name, client in clients_data.iteritems():
2434
 
        tcp_server.clients[client_name] = client_class(
2435
 
            name = client_name, settings = client)
 
2295
    # Create/remove clients based on new changes made to config
 
2296
    for clientname in set(old_client_settings) - set(client_settings):
 
2297
        del tcp_server.clients[clientname]
 
2298
    for clientname in set(client_settings) - set(old_client_settings):
 
2299
        tcp_server.clients[clientname] = (client_class(name
 
2300
                                                       = clientname,
 
2301
                                                       config =
 
2302
                                                       client_settings
 
2303
                                                       [clientname]))
2436
2304
    
2437
2305
    if not tcp_server.clients:
2438
2306
        logger.warning("No clients defined")
2439
 
    
 
2307
        
2440
2308
    if not debug:
2441
2309
        try:
2442
2310
            with pidfile:
2450
2318
            # "pidfile" was never created
2451
2319
            pass
2452
2320
        del pidfilename
 
2321
        
2453
2322
        signal.signal(signal.SIGINT, signal.SIG_IGN)
2454
2323
    
2455
2324
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2456
2325
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2457
2326
    
2458
2327
    if use_dbus:
2459
 
        class MandosDBusService(DBusObjectWithProperties):
 
2328
        class MandosDBusService(dbus.service.Object):
2460
2329
            """A D-Bus proxy object"""
2461
2330
            def __init__(self):
2462
2331
                dbus.service.Object.__init__(self, bus, "/")
2463
2332
            _interface = "se.recompile.Mandos"
2464
2333
            
2465
 
            @dbus_interface_annotations(_interface)
2466
 
            def _foo(self):
2467
 
                return { "org.freedesktop.DBus.Property"
2468
 
                         ".EmitsChangedSignal":
2469
 
                             "false"}
2470
 
            
2471
2334
            @dbus.service.signal(_interface, signature="o")
2472
2335
            def ClientAdded(self, objpath):
2473
2336
                "D-Bus signal"
2530
2393
        # Store client before exiting. Secrets are encrypted with key
2531
2394
        # based on what config file has. If config file is
2532
2395
        # removed/edited, old secret will thus be unrecovable.
2533
 
        clients = {}
2534
 
        with PGPEngine() as pgp:
 
2396
        clients = []
 
2397
        with Crypto() as crypt:
2535
2398
            for client in tcp_server.clients.itervalues():
2536
2399
                key = client_settings[client.name]["secret"]
2537
 
                client.encrypted_secret = pgp.encrypt(client.secret,
2538
 
                                                      key)
 
2400
                client.encrypted_secret = crypt.encrypt(client.secret,
 
2401
                                                        key)
2539
2402
                client_dict = {}
2540
2403
                
2541
 
                # A list of attributes that can not be pickled
2542
 
                # + secret.
2543
 
                exclude = set(("bus", "changedstate", "secret",
2544
 
                               "checker"))
 
2404
                # A list of attributes that will not be stored when
 
2405
                # shutting down.
 
2406
                exclude = set(("bus", "changedstate", "secret"))
2545
2407
                for name, typ in (inspect.getmembers
2546
2408
                                  (dbus.service.Object)):
2547
2409
                    exclude.add(name)
2552
2414
                    if attr not in exclude:
2553
2415
                        client_dict[attr] = getattr(client, attr)
2554
2416
                
2555
 
                clients[client.name] = client_dict
 
2417
                clients.append(client_dict)
2556
2418
                del client_settings[client.name]["secret"]
2557
2419
        
2558
2420
        try:
2559
 
            tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2560
 
                                                prefix="clients-",
2561
 
                                                dir=os.path.dirname
2562
 
                                                (stored_state_path))
2563
 
            with os.fdopen(tempfd, "wb") as stored_state:
 
2421
            with os.fdopen(os.open(stored_state_path,
 
2422
                                   os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
 
2423
                                   0600), "wb") as stored_state:
2564
2424
                pickle.dump((clients, client_settings), stored_state)
2565
 
            os.rename(tempname, stored_state_path)
2566
2425
        except (IOError, OSError) as e:
2567
 
            if not debug:
2568
 
                try:
2569
 
                    os.remove(tempname)
2570
 
                except NameError:
2571
 
                    pass
2572
 
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2573
 
                logger.warning("Could not save persistent state: {0}"
2574
 
                               .format(os.strerror(e.errno)))
2575
 
            else:
2576
 
                logger.warning("Could not save persistent state:",
2577
 
                               exc_info=e)
2578
 
                raise e
 
2426
            logger.warning("Could not save persistent state: {0}"
 
2427
                           .format(e))
 
2428
            if e.errno not in (errno.ENOENT, errno.EACCES):
 
2429
                raise
2579
2430
        
2580
2431
        # Delete all clients, and settings from config
2581
2432
        while tcp_server.clients:
2608
2459
    service.port = tcp_server.socket.getsockname()[1]
2609
2460
    if use_ipv6:
2610
2461
        logger.info("Now listening on address %r, port %d,"
2611
 
                    " flowinfo %d, scope_id %d",
2612
 
                    *tcp_server.socket.getsockname())
 
2462
                    " flowinfo %d, scope_id %d"
 
2463
                    % tcp_server.socket.getsockname())
2613
2464
    else:                       # IPv4
2614
 
        logger.info("Now listening on address %r, port %d",
2615
 
                    *tcp_server.socket.getsockname())
 
2465
        logger.info("Now listening on address %r, port %d"
 
2466
                    % tcp_server.socket.getsockname())
2616
2467
    
2617
2468
    #service.interface = tcp_server.socket.getsockname()[3]
2618
2469
    
2621
2472
        try:
2622
2473
            service.activate()
2623
2474
        except dbus.exceptions.DBusException as error:
2624
 
            logger.critical("D-Bus Exception", exc_info=error)
 
2475
            logger.critical("DBusException: %s", error)
2625
2476
            cleanup()
2626
2477
            sys.exit(1)
2627
2478
        # End of Avahi example code
2634
2485
        logger.debug("Starting main loop")
2635
2486
        main_loop.run()
2636
2487
    except AvahiError as error:
2637
 
        logger.critical("Avahi Error", exc_info=error)
 
2488
        logger.critical("AvahiError: %s", error)
2638
2489
        cleanup()
2639
2490
        sys.exit(1)
2640
2491
    except KeyboardInterrupt:
2645
2496
    # Must run before the D-Bus bus name gets deregistered
2646
2497
    cleanup()
2647
2498
 
 
2499
 
2648
2500
if __name__ == '__main__':
2649
2501
    main()