/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2015-04-02 18:59:29 UTC
  • mto: (237.7.304 trunk)
  • mto: This revision was merged to the branch mainline in revision 325.
  • Revision ID: teddy@recompile.se-20150402185929-1q1rf1zelbpzzn74
Add "!RSA" also to examples/documentation.

* mandos.conf (priority): Add "!RSA" to default commented-out value.
* mandos.conf.xml (EXAMPLE): Add "!RSA" to example priority setting.

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-2015 Teddy Hogeborn
15
 
# Copyright © 2008-2015 Björn Påhlsson
 
14
# Copyright © 2008-2014 Teddy Hogeborn
 
15
# Copyright © 2008-2014 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
36
36
 
37
37
from future_builtins import *
38
38
 
39
 
try:
40
 
    import SocketServer as socketserver
41
 
except ImportError:
42
 
    import socketserver
 
39
import SocketServer as socketserver
43
40
import socket
44
41
import argparse
45
42
import datetime
50
47
import gnutls.library.functions
51
48
import gnutls.library.constants
52
49
import gnutls.library.types
53
 
try:
54
 
    import ConfigParser as configparser
55
 
except ImportError:
56
 
    import configparser
 
50
import ConfigParser as configparser
57
51
import sys
58
52
import re
59
53
import os
68
62
import struct
69
63
import fcntl
70
64
import functools
71
 
try:
72
 
    import cPickle as pickle
73
 
except ImportError:
74
 
    import pickle
 
65
import cPickle as pickle
75
66
import multiprocessing
76
67
import types
77
68
import binascii
78
69
import tempfile
79
70
import itertools
80
71
import collections
81
 
import codecs
82
72
 
83
73
import dbus
84
74
import dbus.service
85
 
try:
86
 
    import gobject
87
 
except ImportError:
88
 
    from gi.repository import GObject as gobject
 
75
import gobject
89
76
import avahi
90
77
from dbus.mainloop.glib import DBusGMainLoop
91
78
import ctypes
111
98
syslogger = None
112
99
 
113
100
try:
114
 
    if_nametoindex = ctypes.cdll.LoadLibrary(
115
 
        ctypes.util.find_library("c")).if_nametoindex
 
101
    if_nametoindex = (ctypes.cdll.LoadLibrary
 
102
                      (ctypes.util.find_library("c"))
 
103
                      .if_nametoindex)
116
104
except (OSError, AttributeError):
117
 
    
118
105
    def if_nametoindex(interface):
119
106
        "Get an interface index the hard way, i.e. using fcntl()"
120
107
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
129
116
    """init logger and add loglevel"""
130
117
    
131
118
    global syslogger
132
 
    syslogger = (logging.handlers.SysLogHandler(
133
 
        facility = logging.handlers.SysLogHandler.LOG_DAEMON,
134
 
        address = "/dev/log"))
 
119
    syslogger = (logging.handlers.SysLogHandler
 
120
                 (facility =
 
121
                  logging.handlers.SysLogHandler.LOG_DAEMON,
 
122
                  address = "/dev/log"))
135
123
    syslogger.setFormatter(logging.Formatter
136
124
                           ('Mandos [%(process)d]: %(levelname)s:'
137
125
                            ' %(message)s'))
154
142
 
155
143
class PGPEngine(object):
156
144
    """A simple class for OpenPGP symmetric encryption & decryption"""
157
 
    
158
145
    def __init__(self):
159
146
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
160
147
        self.gnupgargs = ['--batch',
199
186
    
200
187
    def encrypt(self, data, password):
201
188
        passphrase = self.password_encode(password)
202
 
        with tempfile.NamedTemporaryFile(
203
 
                dir=self.tempdir) as passfile:
 
189
        with tempfile.NamedTemporaryFile(dir=self.tempdir
 
190
                                         ) as passfile:
204
191
            passfile.write(passphrase)
205
192
            passfile.flush()
206
193
            proc = subprocess.Popen(['gpg', '--symmetric',
217
204
    
218
205
    def decrypt(self, data, password):
219
206
        passphrase = self.password_encode(password)
220
 
        with tempfile.NamedTemporaryFile(
221
 
                dir = self.tempdir) as passfile:
 
207
        with tempfile.NamedTemporaryFile(dir = self.tempdir
 
208
                                         ) as passfile:
222
209
            passfile.write(passphrase)
223
210
            passfile.flush()
224
211
            proc = subprocess.Popen(['gpg', '--decrypt',
228
215
                                    stdin = subprocess.PIPE,
229
216
                                    stdout = subprocess.PIPE,
230
217
                                    stderr = subprocess.PIPE)
231
 
            decrypted_plaintext, err = proc.communicate(input = data)
 
218
            decrypted_plaintext, err = proc.communicate(input
 
219
                                                        = data)
232
220
        if proc.returncode != 0:
233
221
            raise PGPError(err)
234
222
        return decrypted_plaintext
240
228
        return super(AvahiError, self).__init__(value, *args,
241
229
                                                **kwargs)
242
230
 
243
 
 
244
231
class AvahiServiceError(AvahiError):
245
232
    pass
246
233
 
247
 
 
248
234
class AvahiGroupError(AvahiError):
249
235
    pass
250
236
 
270
256
    bus: dbus.SystemBus()
271
257
    """
272
258
    
273
 
    def __init__(self,
274
 
                 interface = avahi.IF_UNSPEC,
275
 
                 name = None,
276
 
                 servicetype = None,
277
 
                 port = None,
278
 
                 TXT = None,
279
 
                 domain = "",
280
 
                 host = "",
281
 
                 max_renames = 32768,
282
 
                 protocol = avahi.PROTO_UNSPEC,
283
 
                 bus = None):
 
259
    def __init__(self, interface = avahi.IF_UNSPEC, name = None,
 
260
                 servicetype = None, port = None, TXT = None,
 
261
                 domain = "", host = "", max_renames = 32768,
 
262
                 protocol = avahi.PROTO_UNSPEC, bus = None):
284
263
        self.interface = interface
285
264
        self.name = name
286
265
        self.type = servicetype
303
282
                            " after %i retries, exiting.",
304
283
                            self.rename_count)
305
284
            raise AvahiServiceError("Too many renames")
306
 
        self.name = str(
307
 
            self.server.GetAlternativeServiceName(self.name))
 
285
        self.name = str(self.server
 
286
                        .GetAlternativeServiceName(self.name))
308
287
        self.rename_count += 1
309
288
        logger.info("Changing Zeroconf service name to %r ...",
310
289
                    self.name)
365
344
        elif state == avahi.ENTRY_GROUP_FAILURE:
366
345
            logger.critical("Avahi: Error in group state changed %s",
367
346
                            str(error))
368
 
            raise AvahiGroupError("State changed: {!s}".format(error))
 
347
            raise AvahiGroupError("State changed: {!s}"
 
348
                                  .format(error))
369
349
    
370
350
    def cleanup(self):
371
351
        """Derived from the Avahi example code"""
381
361
    def server_state_changed(self, state, error=None):
382
362
        """Derived from the Avahi example code"""
383
363
        logger.debug("Avahi server state change: %i", state)
384
 
        bad_states = {
385
 
            avahi.SERVER_INVALID: "Zeroconf server invalid",
386
 
            avahi.SERVER_REGISTERING: None,
387
 
            avahi.SERVER_COLLISION: "Zeroconf server name collision",
388
 
            avahi.SERVER_FAILURE: "Zeroconf server failure",
389
 
        }
 
364
        bad_states = { avahi.SERVER_INVALID:
 
365
                           "Zeroconf server invalid",
 
366
                       avahi.SERVER_REGISTERING: None,
 
367
                       avahi.SERVER_COLLISION:
 
368
                           "Zeroconf server name collision",
 
369
                       avahi.SERVER_FAILURE:
 
370
                           "Zeroconf server failure" }
390
371
        if state in bad_states:
391
372
            if bad_states[state] is not None:
392
373
                if error is None:
395
376
                    logger.error(bad_states[state] + ": %r", error)
396
377
            self.cleanup()
397
378
        elif state == avahi.SERVER_RUNNING:
398
 
            try:
399
 
                self.add()
400
 
            except dbus.exceptions.DBusException as error:
401
 
                if (error.get_dbus_name()
402
 
                    == "org.freedesktop.Avahi.CollisionError"):
403
 
                    logger.info("Local Zeroconf service name"
404
 
                                " collision.")
405
 
                    return self.rename(remove=False)
406
 
                else:
407
 
                    logger.critical("D-Bus Exception", exc_info=error)
408
 
                    self.cleanup()
409
 
                    os._exit(1)
 
379
            self.add()
410
380
        else:
411
381
            if error is None:
412
382
                logger.debug("Unknown state: %r", state)
422
392
                                    follow_name_owner_changes=True),
423
393
                avahi.DBUS_INTERFACE_SERVER)
424
394
        self.server.connect_to_signal("StateChanged",
425
 
                                      self.server_state_changed)
 
395
                                 self.server_state_changed)
426
396
        self.server_state_changed(self.server.GetState())
427
397
 
428
398
 
430
400
    def rename(self, *args, **kwargs):
431
401
        """Add the new name to the syslog messages"""
432
402
        ret = AvahiService.rename(self, *args, **kwargs)
433
 
        syslogger.setFormatter(logging.Formatter(
434
 
            'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
435
 
            .format(self.name)))
 
403
        syslogger.setFormatter(logging.Formatter
 
404
                               ('Mandos ({}) [%(process)d]:'
 
405
                                ' %(levelname)s: %(message)s'
 
406
                                .format(self.name)))
436
407
        return ret
437
408
 
438
 
def call_pipe(connection,       # : multiprocessing.Connection
439
 
              func, *args, **kwargs):
440
 
    """This function is meant to be called by multiprocessing.Process
441
 
    
442
 
    This function runs func(*args, **kwargs), and writes the resulting
443
 
    return value on the provided multiprocessing.Connection.
444
 
    """
445
 
    connection.send(func(*args, **kwargs))
446
 
    connection.close()
447
409
 
448
410
class Client(object):
449
411
    """A representation of a client host served by this server.
476
438
    last_checker_status: integer between 0 and 255 reflecting exit
477
439
                         status of last checker. -1 reflects crashed
478
440
                         checker, -2 means no checker completed yet.
479
 
    last_checker_signal: The signal which killed the last checker, if
480
 
                         last_checker_status is -1
481
441
    last_enabled: datetime.datetime(); (UTC) or None
482
442
    name:       string; from the config file, used in log messages and
483
443
                        D-Bus identifiers
496
456
                          "fingerprint", "host", "interval",
497
457
                          "last_approval_request", "last_checked_ok",
498
458
                          "last_enabled", "name", "timeout")
499
 
    client_defaults = {
500
 
        "timeout": "PT5M",
501
 
        "extended_timeout": "PT15M",
502
 
        "interval": "PT2M",
503
 
        "checker": "fping -q -- %%(host)s",
504
 
        "host": "",
505
 
        "approval_delay": "PT0S",
506
 
        "approval_duration": "PT1S",
507
 
        "approved_by_default": "True",
508
 
        "enabled": "True",
509
 
    }
 
459
    client_defaults = { "timeout": "PT5M",
 
460
                        "extended_timeout": "PT15M",
 
461
                        "interval": "PT2M",
 
462
                        "checker": "fping -q -- %%(host)s",
 
463
                        "host": "",
 
464
                        "approval_delay": "PT0S",
 
465
                        "approval_duration": "PT1S",
 
466
                        "approved_by_default": "True",
 
467
                        "enabled": "True",
 
468
                        }
510
469
    
511
470
    @staticmethod
512
471
    def config_parser(config):
590
549
        self.current_checker_command = None
591
550
        self.approved = None
592
551
        self.approvals_pending = 0
593
 
        self.changedstate = multiprocessing_manager.Condition(
594
 
            multiprocessing_manager.Lock())
595
 
        self.client_structure = [attr
596
 
                                 for attr in self.__dict__.iterkeys()
 
552
        self.changedstate = (multiprocessing_manager
 
553
                             .Condition(multiprocessing_manager
 
554
                                        .Lock()))
 
555
        self.client_structure = [attr for attr in
 
556
                                 self.__dict__.iterkeys()
597
557
                                 if not attr.startswith("_")]
598
558
        self.client_structure.append("client_structure")
599
559
        
600
 
        for name, t in inspect.getmembers(
601
 
                type(self), lambda obj: isinstance(obj, property)):
 
560
        for name, t in inspect.getmembers(type(self),
 
561
                                          lambda obj:
 
562
                                              isinstance(obj,
 
563
                                                         property)):
602
564
            if not name.startswith("_"):
603
565
                self.client_structure.append(name)
604
566
    
646
608
        # and every interval from then on.
647
609
        if self.checker_initiator_tag is not None:
648
610
            gobject.source_remove(self.checker_initiator_tag)
649
 
        self.checker_initiator_tag = gobject.timeout_add(
650
 
            int(self.interval.total_seconds() * 1000),
651
 
            self.start_checker)
 
611
        self.checker_initiator_tag = (gobject.timeout_add
 
612
                                      (int(self.interval
 
613
                                           .total_seconds() * 1000),
 
614
                                       self.start_checker))
652
615
        # Schedule a disable() when 'timeout' has passed
653
616
        if self.disable_initiator_tag is not None:
654
617
            gobject.source_remove(self.disable_initiator_tag)
655
 
        self.disable_initiator_tag = gobject.timeout_add(
656
 
            int(self.timeout.total_seconds() * 1000), self.disable)
 
618
        self.disable_initiator_tag = (gobject.timeout_add
 
619
                                      (int(self.timeout
 
620
                                           .total_seconds() * 1000),
 
621
                                       self.disable))
657
622
        # Also start a new checker *right now*.
658
623
        self.start_checker()
659
624
    
660
 
    def checker_callback(self, source, condition, connection,
661
 
                         command):
 
625
    def checker_callback(self, pid, condition, command):
662
626
        """The checker has completed, so take appropriate actions."""
663
627
        self.checker_callback_tag = None
664
628
        self.checker = None
665
 
        # Read return code from connection (see call_pipe)
666
 
        returncode = connection.recv()
667
 
        connection.close()
668
 
        
669
 
        if returncode >= 0:
670
 
            self.last_checker_status = returncode
671
 
            self.last_checker_signal = None
 
629
        if os.WIFEXITED(condition):
 
630
            self.last_checker_status = os.WEXITSTATUS(condition)
672
631
            if self.last_checker_status == 0:
673
632
                logger.info("Checker for %(name)s succeeded",
674
633
                            vars(self))
675
634
                self.checked_ok()
676
635
            else:
677
 
                logger.info("Checker for %(name)s failed", vars(self))
 
636
                logger.info("Checker for %(name)s failed",
 
637
                            vars(self))
678
638
        else:
679
639
            self.last_checker_status = -1
680
 
            self.last_checker_signal = -returncode
681
640
            logger.warning("Checker for %(name)s crashed?",
682
641
                           vars(self))
683
 
        return False
684
642
    
685
643
    def checked_ok(self):
686
644
        """Assert that the client has been seen, alive and well."""
687
645
        self.last_checked_ok = datetime.datetime.utcnow()
688
646
        self.last_checker_status = 0
689
 
        self.last_checker_signal = None
690
647
        self.bump_timeout()
691
648
    
692
649
    def bump_timeout(self, timeout=None):
697
654
            gobject.source_remove(self.disable_initiator_tag)
698
655
            self.disable_initiator_tag = None
699
656
        if getattr(self, "enabled", False):
700
 
            self.disable_initiator_tag = gobject.timeout_add(
701
 
                int(timeout.total_seconds() * 1000), self.disable)
 
657
            self.disable_initiator_tag = (gobject.timeout_add
 
658
                                          (int(timeout.total_seconds()
 
659
                                               * 1000), self.disable))
702
660
            self.expires = datetime.datetime.utcnow() + timeout
703
661
    
704
662
    def need_approval(self):
718
676
        # than 'timeout' for the client to be disabled, which is as it
719
677
        # should be.
720
678
        
721
 
        if self.checker is not None and not self.checker.is_alive():
722
 
            logger.warning("Checker was not alive; joining")
723
 
            self.checker.join()
724
 
            self.checker = None
 
679
        # If a checker exists, make sure it is not a zombie
 
680
        try:
 
681
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
682
        except AttributeError:
 
683
            pass
 
684
        except OSError as error:
 
685
            if error.errno != errno.ECHILD:
 
686
                raise
 
687
        else:
 
688
            if pid:
 
689
                logger.warning("Checker was a zombie")
 
690
                gobject.source_remove(self.checker_callback_tag)
 
691
                self.checker_callback(pid, status,
 
692
                                      self.current_checker_command)
725
693
        # Start a new checker if needed
726
694
        if self.checker is None:
727
695
            # Escape attributes for the shell
728
 
            escaped_attrs = {
729
 
                attr: re.escape(str(getattr(self, attr)))
730
 
                for attr in self.runtime_expansions }
 
696
            escaped_attrs = { attr:
 
697
                                  re.escape(str(getattr(self, attr)))
 
698
                              for attr in self.runtime_expansions }
731
699
            try:
732
700
                command = self.checker_command % escaped_attrs
733
701
            except TypeError as error:
734
702
                logger.error('Could not format string "%s"',
735
 
                             self.checker_command,
 
703
                             self.checker_command, exc_info=error)
 
704
                return True # Try again later
 
705
            self.current_checker_command = command
 
706
            try:
 
707
                logger.info("Starting checker %r for %s",
 
708
                            command, self.name)
 
709
                # We don't need to redirect stdout and stderr, since
 
710
                # in normal mode, that is already done by daemon(),
 
711
                # and in debug mode we don't want to.  (Stdin is
 
712
                # always replaced by /dev/null.)
 
713
                # The exception is when not debugging but nevertheless
 
714
                # running in the foreground; use the previously
 
715
                # created wnull.
 
716
                popen_args = {}
 
717
                if (not self.server_settings["debug"]
 
718
                    and self.server_settings["foreground"]):
 
719
                    popen_args.update({"stdout": wnull,
 
720
                                       "stderr": wnull })
 
721
                self.checker = subprocess.Popen(command,
 
722
                                                close_fds=True,
 
723
                                                shell=True, cwd="/",
 
724
                                                **popen_args)
 
725
            except OSError as error:
 
726
                logger.error("Failed to start subprocess",
736
727
                             exc_info=error)
737
 
                return True     # Try again later
738
 
            self.current_checker_command = command
739
 
            logger.info("Starting checker %r for %s", command,
740
 
                        self.name)
741
 
            # We don't need to redirect stdout and stderr, since
742
 
            # in normal mode, that is already done by daemon(),
743
 
            # and in debug mode we don't want to.  (Stdin is
744
 
            # always replaced by /dev/null.)
745
 
            # The exception is when not debugging but nevertheless
746
 
            # running in the foreground; use the previously
747
 
            # created wnull.
748
 
            popen_args = { "close_fds": True,
749
 
                           "shell": True,
750
 
                           "cwd": "/" }
751
 
            if (not self.server_settings["debug"]
752
 
                and self.server_settings["foreground"]):
753
 
                popen_args.update({"stdout": wnull,
754
 
                                   "stderr": wnull })
755
 
            pipe = multiprocessing.Pipe(duplex = False)
756
 
            self.checker = multiprocessing.Process(
757
 
                target = call_pipe,
758
 
                args = (pipe[1], subprocess.call, command),
759
 
                kwargs = popen_args)
760
 
            self.checker.start()
761
 
            self.checker_callback_tag = gobject.io_add_watch(
762
 
                pipe[0].fileno(), gobject.IO_IN,
763
 
                self.checker_callback, pipe[0], command)
 
728
                return True
 
729
            self.checker_callback_tag = (gobject.child_watch_add
 
730
                                         (self.checker.pid,
 
731
                                          self.checker_callback,
 
732
                                          data=command))
 
733
            # The checker may have completed before the gobject
 
734
            # watch was added.  Check for this.
 
735
            try:
 
736
                pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
 
737
            except OSError as error:
 
738
                if error.errno == errno.ECHILD:
 
739
                    # This should never happen
 
740
                    logger.error("Child process vanished",
 
741
                                 exc_info=error)
 
742
                    return True
 
743
                raise
 
744
            if pid:
 
745
                gobject.source_remove(self.checker_callback_tag)
 
746
                self.checker_callback(pid, status, command)
764
747
        # Re-run this periodically if run by gobject.timeout_add
765
748
        return True
766
749
    
772
755
        if getattr(self, "checker", None) is None:
773
756
            return
774
757
        logger.debug("Stopping checker for %(name)s", vars(self))
775
 
        self.checker.terminate()
 
758
        try:
 
759
            self.checker.terminate()
 
760
            #time.sleep(0.5)
 
761
            #if self.checker.poll() is None:
 
762
            #    self.checker.kill()
 
763
        except OSError as error:
 
764
            if error.errno != errno.ESRCH: # No such process
 
765
                raise
776
766
        self.checker = None
777
767
 
778
768
 
779
 
def dbus_service_property(dbus_interface,
780
 
                          signature="v",
781
 
                          access="readwrite",
782
 
                          byte_arrays=False):
 
769
def dbus_service_property(dbus_interface, signature="v",
 
770
                          access="readwrite", byte_arrays=False):
783
771
    """Decorators for marking methods of a DBusObjectWithProperties to
784
772
    become properties on the D-Bus.
785
773
    
795
783
    if byte_arrays and signature != "ay":
796
784
        raise ValueError("Byte arrays not supported for non-'ay'"
797
785
                         " signature {!r}".format(signature))
798
 
    
799
786
    def decorator(func):
800
787
        func._dbus_is_property = True
801
788
        func._dbus_interface = dbus_interface
806
793
            func._dbus_name = func._dbus_name[:-14]
807
794
        func._dbus_get_args_options = {'byte_arrays': byte_arrays }
808
795
        return func
809
 
    
810
796
    return decorator
811
797
 
812
798
 
821
807
                "org.freedesktop.DBus.Property.EmitsChangedSignal":
822
808
                    "false"}
823
809
    """
824
 
    
825
810
    def decorator(func):
826
811
        func._dbus_is_interface = True
827
812
        func._dbus_interface = dbus_interface
828
813
        func._dbus_name = dbus_interface
829
814
        return func
830
 
    
831
815
    return decorator
832
816
 
833
817
 
843
827
    def Property_dbus_property(self):
844
828
        return dbus.Boolean(False)
845
829
    """
846
 
    
847
830
    def decorator(func):
848
831
        func._dbus_annotations = annotations
849
832
        return func
850
 
    
851
833
    return decorator
852
834
 
853
835
 
856
838
    """
857
839
    pass
858
840
 
859
 
 
860
841
class DBusPropertyAccessException(DBusPropertyException):
861
842
    """A property's access permissions disallows an operation.
862
843
    """
890
871
    def _get_all_dbus_things(self, thing):
891
872
        """Returns a generator of (name, attribute) pairs
892
873
        """
893
 
        return ((getattr(athing.__get__(self), "_dbus_name", name),
 
874
        return ((getattr(athing.__get__(self), "_dbus_name",
 
875
                         name),
894
876
                 athing.__get__(self))
895
877
                for cls in self.__class__.__mro__
896
878
                for name, athing in
897
 
                inspect.getmembers(cls, self._is_dbus_thing(thing)))
 
879
                inspect.getmembers(cls,
 
880
                                   self._is_dbus_thing(thing)))
898
881
    
899
882
    def _get_dbus_property(self, interface_name, property_name):
900
883
        """Returns a bound method if one exists which is a D-Bus
901
884
        property with the specified name and interface.
902
885
        """
903
 
        for cls in self.__class__.__mro__:
904
 
            for name, value in inspect.getmembers(
905
 
                    cls, self._is_dbus_thing("property")):
 
886
        for cls in  self.__class__.__mro__:
 
887
            for name, value in (inspect.getmembers
 
888
                                (cls,
 
889
                                 self._is_dbus_thing("property"))):
906
890
                if (value._dbus_name == property_name
907
891
                    and value._dbus_interface == interface_name):
908
892
                    return value.__get__(self)
909
893
        
910
894
        # No such property
911
 
        raise DBusPropertyNotFound("{}:{}.{}".format(
912
 
            self.dbus_object_path, interface_name, property_name))
 
895
        raise DBusPropertyNotFound(self.dbus_object_path + ":"
 
896
                                   + interface_name + "."
 
897
                                   + property_name)
913
898
    
914
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
915
 
                         in_signature="ss",
 
899
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="ss",
916
900
                         out_signature="v")
917
901
    def Get(self, interface_name, property_name):
918
902
        """Standard D-Bus property Get() method, see D-Bus standard.
943
927
                                            for byte in value))
944
928
        prop(value)
945
929
    
946
 
    @dbus.service.method(dbus.PROPERTIES_IFACE,
947
 
                         in_signature="s",
 
930
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
948
931
                         out_signature="a{sv}")
949
932
    def GetAll(self, interface_name):
950
933
        """Standard D-Bus property GetAll() method, see D-Bus
965
948
            if not hasattr(value, "variant_level"):
966
949
                properties[name] = value
967
950
                continue
968
 
            properties[name] = type(value)(
969
 
                value, variant_level = value.variant_level + 1)
 
951
            properties[name] = type(value)(value, variant_level=
 
952
                                           value.variant_level+1)
970
953
        return dbus.Dictionary(properties, signature="sv")
971
954
    
972
955
    @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
990
973
                                                   connection)
991
974
        try:
992
975
            document = xml.dom.minidom.parseString(xmlstring)
993
 
            
994
976
            def make_tag(document, name, prop):
995
977
                e = document.createElement("property")
996
978
                e.setAttribute("name", name)
997
979
                e.setAttribute("type", prop._dbus_signature)
998
980
                e.setAttribute("access", prop._dbus_access)
999
981
                return e
1000
 
            
1001
982
            for if_tag in document.getElementsByTagName("interface"):
1002
983
                # Add property tags
1003
984
                for tag in (make_tag(document, name, prop)
1015
996
                            if (name == tag.getAttribute("name")
1016
997
                                and prop._dbus_interface
1017
998
                                == if_tag.getAttribute("name")):
1018
 
                                annots.update(getattr(
1019
 
                                    prop, "_dbus_annotations", {}))
 
999
                                annots.update(getattr
 
1000
                                              (prop,
 
1001
                                               "_dbus_annotations",
 
1002
                                               {}))
1020
1003
                        for name, value in annots.items():
1021
1004
                            ann_tag = document.createElement(
1022
1005
                                "annotation")
1027
1010
                for annotation, value in dict(
1028
1011
                    itertools.chain.from_iterable(
1029
1012
                        annotations().items()
1030
 
                        for name, annotations
1031
 
                        in self._get_all_dbus_things("interface")
 
1013
                        for name, annotations in
 
1014
                        self._get_all_dbus_things("interface")
1032
1015
                        if name == if_tag.getAttribute("name")
1033
1016
                        )).items():
1034
1017
                    ann_tag = document.createElement("annotation")
1063
1046
    """Convert a UTC datetime.datetime() to a D-Bus type."""
1064
1047
    if dt is None:
1065
1048
        return dbus.String("", variant_level = variant_level)
1066
 
    return dbus.String(dt.isoformat(), variant_level=variant_level)
 
1049
    return dbus.String(dt.isoformat(),
 
1050
                       variant_level=variant_level)
1067
1051
 
1068
1052
 
1069
1053
def alternate_dbus_interfaces(alt_interface_names, deprecate=True):
1089
1073
    (from DBusObjectWithProperties) and interfaces (from the
1090
1074
    dbus_interface_annotations decorator).
1091
1075
    """
1092
 
    
1093
1076
    def wrapper(cls):
1094
1077
        for orig_interface_name, alt_interface_name in (
1095
 
                alt_interface_names.items()):
 
1078
            alt_interface_names.items()):
1096
1079
            attr = {}
1097
1080
            interface_names = set()
1098
1081
            # Go though all attributes of the class
1100
1083
                # Ignore non-D-Bus attributes, and D-Bus attributes
1101
1084
                # with the wrong interface name
1102
1085
                if (not hasattr(attribute, "_dbus_interface")
1103
 
                    or not attribute._dbus_interface.startswith(
1104
 
                        orig_interface_name)):
 
1086
                    or not attribute._dbus_interface
 
1087
                    .startswith(orig_interface_name)):
1105
1088
                    continue
1106
1089
                # Create an alternate D-Bus interface name based on
1107
1090
                # the current name
1108
 
                alt_interface = attribute._dbus_interface.replace(
1109
 
                    orig_interface_name, alt_interface_name)
 
1091
                alt_interface = (attribute._dbus_interface
 
1092
                                 .replace(orig_interface_name,
 
1093
                                          alt_interface_name))
1110
1094
                interface_names.add(alt_interface)
1111
1095
                # Is this a D-Bus signal?
1112
1096
                if getattr(attribute, "_dbus_is_signal", False):
1113
 
                    if sys.version_info.major == 2:
1114
 
                        # Extract the original non-method undecorated
1115
 
                        # function by black magic
1116
 
                        nonmethod_func = (dict(
 
1097
                    # Extract the original non-method undecorated
 
1098
                    # function by black magic
 
1099
                    nonmethod_func = (dict(
1117
1100
                            zip(attribute.func_code.co_freevars,
1118
 
                                attribute.__closure__))
1119
 
                                          ["func"].cell_contents)
1120
 
                    else:
1121
 
                        nonmethod_func = attribute
 
1101
                                attribute.__closure__))["func"]
 
1102
                                      .cell_contents)
1122
1103
                    # Create a new, but exactly alike, function
1123
1104
                    # object, and decorate it to be a new D-Bus signal
1124
1105
                    # with the alternate D-Bus interface name
1125
 
                    if sys.version_info.major == 2:
1126
 
                        new_function = types.FunctionType(
1127
 
                            nonmethod_func.func_code,
1128
 
                            nonmethod_func.func_globals,
1129
 
                            nonmethod_func.func_name,
1130
 
                            nonmethod_func.func_defaults,
1131
 
                            nonmethod_func.func_closure)
1132
 
                    else:
1133
 
                        new_function = types.FunctionType(
1134
 
                            nonmethod_func.__code__,
1135
 
                            nonmethod_func.__globals__,
1136
 
                            nonmethod_func.__name__,
1137
 
                            nonmethod_func.__defaults__,
1138
 
                            nonmethod_func.__closure__)
1139
 
                    new_function = (dbus.service.signal(
1140
 
                        alt_interface,
1141
 
                        attribute._dbus_signature)(new_function))
 
1106
                    new_function = (dbus.service.signal
 
1107
                                    (alt_interface,
 
1108
                                     attribute._dbus_signature)
 
1109
                                    (types.FunctionType(
 
1110
                                nonmethod_func.func_code,
 
1111
                                nonmethod_func.func_globals,
 
1112
                                nonmethod_func.func_name,
 
1113
                                nonmethod_func.func_defaults,
 
1114
                                nonmethod_func.func_closure)))
1142
1115
                    # Copy annotations, if any
1143
1116
                    try:
1144
 
                        new_function._dbus_annotations = dict(
1145
 
                            attribute._dbus_annotations)
 
1117
                        new_function._dbus_annotations = (
 
1118
                            dict(attribute._dbus_annotations))
1146
1119
                    except AttributeError:
1147
1120
                        pass
1148
1121
                    # Define a creator of a function to call both the
1153
1126
                        """This function is a scope container to pass
1154
1127
                        func1 and func2 to the "call_both" function
1155
1128
                        outside of its arguments"""
1156
 
                        
1157
1129
                        def call_both(*args, **kwargs):
1158
1130
                            """This function will emit two D-Bus
1159
1131
                            signals by calling func1 and func2"""
1160
1132
                            func1(*args, **kwargs)
1161
1133
                            func2(*args, **kwargs)
1162
 
                        
1163
1134
                        return call_both
1164
1135
                    # Create the "call_both" function and add it to
1165
1136
                    # the class
1170
1141
                    # object.  Decorate it to be a new D-Bus method
1171
1142
                    # with the alternate D-Bus interface name.  Add it
1172
1143
                    # to the class.
1173
 
                    attr[attrname] = (
1174
 
                        dbus.service.method(
1175
 
                            alt_interface,
1176
 
                            attribute._dbus_in_signature,
1177
 
                            attribute._dbus_out_signature)
1178
 
                        (types.FunctionType(attribute.func_code,
1179
 
                                            attribute.func_globals,
1180
 
                                            attribute.func_name,
1181
 
                                            attribute.func_defaults,
1182
 
                                            attribute.func_closure)))
 
1144
                    attr[attrname] = (dbus.service.method
 
1145
                                      (alt_interface,
 
1146
                                       attribute._dbus_in_signature,
 
1147
                                       attribute._dbus_out_signature)
 
1148
                                      (types.FunctionType
 
1149
                                       (attribute.func_code,
 
1150
                                        attribute.func_globals,
 
1151
                                        attribute.func_name,
 
1152
                                        attribute.func_defaults,
 
1153
                                        attribute.func_closure)))
1183
1154
                    # Copy annotations, if any
1184
1155
                    try:
1185
 
                        attr[attrname]._dbus_annotations = dict(
1186
 
                            attribute._dbus_annotations)
 
1156
                        attr[attrname]._dbus_annotations = (
 
1157
                            dict(attribute._dbus_annotations))
1187
1158
                    except AttributeError:
1188
1159
                        pass
1189
1160
                # Is this a D-Bus property?
1192
1163
                    # object, and decorate it to be a new D-Bus
1193
1164
                    # property with the alternate D-Bus interface
1194
1165
                    # name.  Add it to the class.
1195
 
                    attr[attrname] = (dbus_service_property(
1196
 
                        alt_interface, attribute._dbus_signature,
1197
 
                        attribute._dbus_access,
1198
 
                        attribute._dbus_get_args_options
1199
 
                        ["byte_arrays"])
1200
 
                                      (types.FunctionType(
1201
 
                                          attribute.func_code,
1202
 
                                          attribute.func_globals,
1203
 
                                          attribute.func_name,
1204
 
                                          attribute.func_defaults,
1205
 
                                          attribute.func_closure)))
 
1166
                    attr[attrname] = (dbus_service_property
 
1167
                                      (alt_interface,
 
1168
                                       attribute._dbus_signature,
 
1169
                                       attribute._dbus_access,
 
1170
                                       attribute
 
1171
                                       ._dbus_get_args_options
 
1172
                                       ["byte_arrays"])
 
1173
                                      (types.FunctionType
 
1174
                                       (attribute.func_code,
 
1175
                                        attribute.func_globals,
 
1176
                                        attribute.func_name,
 
1177
                                        attribute.func_defaults,
 
1178
                                        attribute.func_closure)))
1206
1179
                    # Copy annotations, if any
1207
1180
                    try:
1208
 
                        attr[attrname]._dbus_annotations = dict(
1209
 
                            attribute._dbus_annotations)
 
1181
                        attr[attrname]._dbus_annotations = (
 
1182
                            dict(attribute._dbus_annotations))
1210
1183
                    except AttributeError:
1211
1184
                        pass
1212
1185
                # Is this a D-Bus interface?
1215
1188
                    # object.  Decorate it to be a new D-Bus interface
1216
1189
                    # with the alternate D-Bus interface name.  Add it
1217
1190
                    # to the class.
1218
 
                    attr[attrname] = (
1219
 
                        dbus_interface_annotations(alt_interface)
1220
 
                        (types.FunctionType(attribute.func_code,
1221
 
                                            attribute.func_globals,
1222
 
                                            attribute.func_name,
1223
 
                                            attribute.func_defaults,
1224
 
                                            attribute.func_closure)))
 
1191
                    attr[attrname] = (dbus_interface_annotations
 
1192
                                      (alt_interface)
 
1193
                                      (types.FunctionType
 
1194
                                       (attribute.func_code,
 
1195
                                        attribute.func_globals,
 
1196
                                        attribute.func_name,
 
1197
                                        attribute.func_defaults,
 
1198
                                        attribute.func_closure)))
1225
1199
            if deprecate:
1226
1200
                # Deprecate all alternate interfaces
1227
1201
                iname="_AlternateDBusNames_interface_annotation{}"
1228
1202
                for interface_name in interface_names:
1229
 
                    
1230
1203
                    @dbus_interface_annotations(interface_name)
1231
1204
                    def func(self):
1232
1205
                        return { "org.freedesktop.DBus.Deprecated":
1233
 
                                 "true" }
 
1206
                                     "true" }
1234
1207
                    # Find an unused name
1235
1208
                    for aname in (iname.format(i)
1236
1209
                                  for i in itertools.count()):
1241
1214
                # Replace the class with a new subclass of it with
1242
1215
                # methods, signals, etc. as created above.
1243
1216
                cls = type(b"{}Alternate".format(cls.__name__),
1244
 
                           (cls, ), attr)
 
1217
                           (cls,), attr)
1245
1218
        return cls
1246
 
    
1247
1219
    return wrapper
1248
1220
 
1249
1221
 
1250
1222
@alternate_dbus_interfaces({"se.recompile.Mandos":
1251
 
                            "se.bsnet.fukt.Mandos"})
 
1223
                                "se.bsnet.fukt.Mandos"})
1252
1224
class ClientDBus(Client, DBusObjectWithProperties):
1253
1225
    """A Client class using D-Bus
1254
1226
    
1258
1230
    """
1259
1231
    
1260
1232
    runtime_expansions = (Client.runtime_expansions
1261
 
                          + ("dbus_object_path", ))
 
1233
                          + ("dbus_object_path",))
1262
1234
    
1263
1235
    _interface = "se.recompile.Mandos.Client"
1264
1236
    
1272
1244
        client_object_name = str(self.name).translate(
1273
1245
            {ord("."): ord("_"),
1274
1246
             ord("-"): ord("_")})
1275
 
        self.dbus_object_path = dbus.ObjectPath(
1276
 
            "/clients/" + client_object_name)
 
1247
        self.dbus_object_path = (dbus.ObjectPath
 
1248
                                 ("/clients/" + client_object_name))
1277
1249
        DBusObjectWithProperties.__init__(self, self.bus,
1278
1250
                                          self.dbus_object_path)
1279
1251
    
1280
 
    def notifychangeproperty(transform_func, dbus_name,
1281
 
                             type_func=lambda x: x,
1282
 
                             variant_level=1,
1283
 
                             invalidate_only=False,
 
1252
    def notifychangeproperty(transform_func,
 
1253
                             dbus_name, type_func=lambda x: x,
 
1254
                             variant_level=1, invalidate_only=False,
1284
1255
                             _interface=_interface):
1285
1256
        """ Modify a variable so that it's a property which announces
1286
1257
        its changes to DBus.
1293
1264
        variant_level: D-Bus variant level.  Default: 1
1294
1265
        """
1295
1266
        attrname = "_{}".format(dbus_name)
1296
 
        
1297
1267
        def setter(self, value):
1298
1268
            if hasattr(self, "dbus_object_path"):
1299
1269
                if (not hasattr(self, attrname) or
1300
1270
                    type_func(getattr(self, attrname, None))
1301
1271
                    != type_func(value)):
1302
1272
                    if invalidate_only:
1303
 
                        self.PropertiesChanged(
1304
 
                            _interface, dbus.Dictionary(),
1305
 
                            dbus.Array((dbus_name, )))
 
1273
                        self.PropertiesChanged(_interface,
 
1274
                                               dbus.Dictionary(),
 
1275
                                               dbus.Array
 
1276
                                               ((dbus_name,)))
1306
1277
                    else:
1307
 
                        dbus_value = transform_func(
1308
 
                            type_func(value),
1309
 
                            variant_level = variant_level)
 
1278
                        dbus_value = transform_func(type_func(value),
 
1279
                                                    variant_level
 
1280
                                                    =variant_level)
1310
1281
                        self.PropertyChanged(dbus.String(dbus_name),
1311
1282
                                             dbus_value)
1312
 
                        self.PropertiesChanged(
1313
 
                            _interface,
1314
 
                            dbus.Dictionary({ dbus.String(dbus_name):
1315
 
                                              dbus_value }),
1316
 
                            dbus.Array())
 
1283
                        self.PropertiesChanged(_interface,
 
1284
                                               dbus.Dictionary({
 
1285
                                    dbus.String(dbus_name):
 
1286
                                        dbus_value }), dbus.Array())
1317
1287
            setattr(self, attrname, value)
1318
1288
        
1319
1289
        return property(lambda self: getattr(self, attrname), setter)
1325
1295
    enabled = notifychangeproperty(dbus.Boolean, "Enabled")
1326
1296
    last_enabled = notifychangeproperty(datetime_to_dbus,
1327
1297
                                        "LastEnabled")
1328
 
    checker = notifychangeproperty(
1329
 
        dbus.Boolean, "CheckerRunning",
1330
 
        type_func = lambda checker: checker is not None)
 
1298
    checker = notifychangeproperty(dbus.Boolean, "CheckerRunning",
 
1299
                                   type_func = lambda checker:
 
1300
                                       checker is not None)
1331
1301
    last_checked_ok = notifychangeproperty(datetime_to_dbus,
1332
1302
                                           "LastCheckedOK")
1333
1303
    last_checker_status = notifychangeproperty(dbus.Int16,
1336
1306
        datetime_to_dbus, "LastApprovalRequest")
1337
1307
    approved_by_default = notifychangeproperty(dbus.Boolean,
1338
1308
                                               "ApprovedByDefault")
1339
 
    approval_delay = notifychangeproperty(
1340
 
        dbus.UInt64, "ApprovalDelay",
1341
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1309
    approval_delay = notifychangeproperty(dbus.UInt64,
 
1310
                                          "ApprovalDelay",
 
1311
                                          type_func =
 
1312
                                          lambda td: td.total_seconds()
 
1313
                                          * 1000)
1342
1314
    approval_duration = notifychangeproperty(
1343
1315
        dbus.UInt64, "ApprovalDuration",
1344
1316
        type_func = lambda td: td.total_seconds() * 1000)
1345
1317
    host = notifychangeproperty(dbus.String, "Host")
1346
 
    timeout = notifychangeproperty(
1347
 
        dbus.UInt64, "Timeout",
1348
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1318
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
 
1319
                                   type_func = lambda td:
 
1320
                                       td.total_seconds() * 1000)
1349
1321
    extended_timeout = notifychangeproperty(
1350
1322
        dbus.UInt64, "ExtendedTimeout",
1351
1323
        type_func = lambda td: td.total_seconds() * 1000)
1352
 
    interval = notifychangeproperty(
1353
 
        dbus.UInt64, "Interval",
1354
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1324
    interval = notifychangeproperty(dbus.UInt64,
 
1325
                                    "Interval",
 
1326
                                    type_func =
 
1327
                                    lambda td: td.total_seconds()
 
1328
                                    * 1000)
1355
1329
    checker_command = notifychangeproperty(dbus.String, "Checker")
1356
1330
    secret = notifychangeproperty(dbus.ByteArray, "Secret",
1357
1331
                                  invalidate_only=True)
1367
1341
            DBusObjectWithProperties.__del__(self, *args, **kwargs)
1368
1342
        Client.__del__(self, *args, **kwargs)
1369
1343
    
1370
 
    def checker_callback(self, source, condition,
1371
 
                         connection, command, *args, **kwargs):
1372
 
        ret = Client.checker_callback(self, source, condition,
1373
 
                                      connection, command, *args,
1374
 
                                      **kwargs)
1375
 
        exitstatus = self.last_checker_status
1376
 
        if exitstatus >= 0:
 
1344
    def checker_callback(self, pid, condition, command,
 
1345
                         *args, **kwargs):
 
1346
        self.checker_callback_tag = None
 
1347
        self.checker = None
 
1348
        if os.WIFEXITED(condition):
 
1349
            exitstatus = os.WEXITSTATUS(condition)
1377
1350
            # Emit D-Bus signal
1378
1351
            self.CheckerCompleted(dbus.Int16(exitstatus),
1379
 
                                  dbus.Int64(0),
 
1352
                                  dbus.Int64(condition),
1380
1353
                                  dbus.String(command))
1381
1354
        else:
1382
1355
            # Emit D-Bus signal
1383
1356
            self.CheckerCompleted(dbus.Int16(-1),
1384
 
                                  dbus.Int64(
1385
 
                                      self.last_checker_signal),
 
1357
                                  dbus.Int64(condition),
1386
1358
                                  dbus.String(command))
1387
 
        return ret
 
1359
        
 
1360
        return Client.checker_callback(self, pid, condition, command,
 
1361
                                       *args, **kwargs)
1388
1362
    
1389
1363
    def start_checker(self, *args, **kwargs):
1390
1364
        old_checker_pid = getattr(self.checker, "pid", None)
1495
1469
        return dbus.Boolean(bool(self.approvals_pending))
1496
1470
    
1497
1471
    # ApprovedByDefault - property
1498
 
    @dbus_service_property(_interface,
1499
 
                           signature="b",
 
1472
    @dbus_service_property(_interface, signature="b",
1500
1473
                           access="readwrite")
1501
1474
    def ApprovedByDefault_dbus_property(self, value=None):
1502
1475
        if value is None:       # get
1504
1477
        self.approved_by_default = bool(value)
1505
1478
    
1506
1479
    # ApprovalDelay - property
1507
 
    @dbus_service_property(_interface,
1508
 
                           signature="t",
 
1480
    @dbus_service_property(_interface, signature="t",
1509
1481
                           access="readwrite")
1510
1482
    def ApprovalDelay_dbus_property(self, value=None):
1511
1483
        if value is None:       # get
1514
1486
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1515
1487
    
1516
1488
    # ApprovalDuration - property
1517
 
    @dbus_service_property(_interface,
1518
 
                           signature="t",
 
1489
    @dbus_service_property(_interface, signature="t",
1519
1490
                           access="readwrite")
1520
1491
    def ApprovalDuration_dbus_property(self, value=None):
1521
1492
        if value is None:       # get
1534
1505
        return dbus.String(self.fingerprint)
1535
1506
    
1536
1507
    # Host - property
1537
 
    @dbus_service_property(_interface,
1538
 
                           signature="s",
 
1508
    @dbus_service_property(_interface, signature="s",
1539
1509
                           access="readwrite")
1540
1510
    def Host_dbus_property(self, value=None):
1541
1511
        if value is None:       # get
1553
1523
        return datetime_to_dbus(self.last_enabled)
1554
1524
    
1555
1525
    # Enabled - property
1556
 
    @dbus_service_property(_interface,
1557
 
                           signature="b",
 
1526
    @dbus_service_property(_interface, signature="b",
1558
1527
                           access="readwrite")
1559
1528
    def Enabled_dbus_property(self, value=None):
1560
1529
        if value is None:       # get
1565
1534
            self.disable()
1566
1535
    
1567
1536
    # LastCheckedOK - property
1568
 
    @dbus_service_property(_interface,
1569
 
                           signature="s",
 
1537
    @dbus_service_property(_interface, signature="s",
1570
1538
                           access="readwrite")
1571
1539
    def LastCheckedOK_dbus_property(self, value=None):
1572
1540
        if value is not None:
1575
1543
        return datetime_to_dbus(self.last_checked_ok)
1576
1544
    
1577
1545
    # LastCheckerStatus - property
1578
 
    @dbus_service_property(_interface, signature="n", access="read")
 
1546
    @dbus_service_property(_interface, signature="n",
 
1547
                           access="read")
1579
1548
    def LastCheckerStatus_dbus_property(self):
1580
1549
        return dbus.Int16(self.last_checker_status)
1581
1550
    
1590
1559
        return datetime_to_dbus(self.last_approval_request)
1591
1560
    
1592
1561
    # Timeout - property
1593
 
    @dbus_service_property(_interface,
1594
 
                           signature="t",
 
1562
    @dbus_service_property(_interface, signature="t",
1595
1563
                           access="readwrite")
1596
1564
    def Timeout_dbus_property(self, value=None):
1597
1565
        if value is None:       # get
1610
1578
                    is None):
1611
1579
                    return
1612
1580
                gobject.source_remove(self.disable_initiator_tag)
1613
 
                self.disable_initiator_tag = gobject.timeout_add(
1614
 
                    int((self.expires - now).total_seconds() * 1000),
1615
 
                    self.disable)
 
1581
                self.disable_initiator_tag = (
 
1582
                    gobject.timeout_add(
 
1583
                        int((self.expires - now).total_seconds()
 
1584
                            * 1000), self.disable))
1616
1585
    
1617
1586
    # ExtendedTimeout - property
1618
 
    @dbus_service_property(_interface,
1619
 
                           signature="t",
 
1587
    @dbus_service_property(_interface, signature="t",
1620
1588
                           access="readwrite")
1621
1589
    def ExtendedTimeout_dbus_property(self, value=None):
1622
1590
        if value is None:       # get
1625
1593
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1626
1594
    
1627
1595
    # Interval - property
1628
 
    @dbus_service_property(_interface,
1629
 
                           signature="t",
 
1596
    @dbus_service_property(_interface, signature="t",
1630
1597
                           access="readwrite")
1631
1598
    def Interval_dbus_property(self, value=None):
1632
1599
        if value is None:       # get
1637
1604
        if self.enabled:
1638
1605
            # Reschedule checker run
1639
1606
            gobject.source_remove(self.checker_initiator_tag)
1640
 
            self.checker_initiator_tag = gobject.timeout_add(
1641
 
                value, self.start_checker)
1642
 
            self.start_checker() # Start one now, too
 
1607
            self.checker_initiator_tag = (gobject.timeout_add
 
1608
                                          (value, self.start_checker))
 
1609
            self.start_checker()    # Start one now, too
1643
1610
    
1644
1611
    # Checker - property
1645
 
    @dbus_service_property(_interface,
1646
 
                           signature="s",
 
1612
    @dbus_service_property(_interface, signature="s",
1647
1613
                           access="readwrite")
1648
1614
    def Checker_dbus_property(self, value=None):
1649
1615
        if value is None:       # get
1651
1617
        self.checker_command = str(value)
1652
1618
    
1653
1619
    # CheckerRunning - property
1654
 
    @dbus_service_property(_interface,
1655
 
                           signature="b",
 
1620
    @dbus_service_property(_interface, signature="b",
1656
1621
                           access="readwrite")
1657
1622
    def CheckerRunning_dbus_property(self, value=None):
1658
1623
        if value is None:       # get
1668
1633
        return self.dbus_object_path # is already a dbus.ObjectPath
1669
1634
    
1670
1635
    # Secret = property
1671
 
    @dbus_service_property(_interface,
1672
 
                           signature="ay",
1673
 
                           access="write",
1674
 
                           byte_arrays=True)
 
1636
    @dbus_service_property(_interface, signature="ay",
 
1637
                           access="write", byte_arrays=True)
1675
1638
    def Secret_dbus_property(self, value):
1676
1639
        self.secret = bytes(value)
1677
1640
    
1683
1646
        self._pipe = child_pipe
1684
1647
        self._pipe.send(('init', fpr, address))
1685
1648
        if not self._pipe.recv():
1686
 
            raise KeyError(fpr)
 
1649
            raise KeyError()
1687
1650
    
1688
1651
    def __getattribute__(self, name):
1689
1652
        if name == '_pipe':
1693
1656
        if data[0] == 'data':
1694
1657
            return data[1]
1695
1658
        if data[0] == 'function':
1696
 
            
1697
1659
            def func(*args, **kwargs):
1698
1660
                self._pipe.send(('funcall', name, args, kwargs))
1699
1661
                return self._pipe.recv()[1]
1700
 
            
1701
1662
            return func
1702
1663
    
1703
1664
    def __setattr__(self, name, value):
1719
1680
            logger.debug("Pipe FD: %d",
1720
1681
                         self.server.child_pipe.fileno())
1721
1682
            
1722
 
            session = gnutls.connection.ClientSession(
1723
 
                self.request, gnutls.connection .X509Credentials())
 
1683
            session = (gnutls.connection
 
1684
                       .ClientSession(self.request,
 
1685
                                      gnutls.connection
 
1686
                                      .X509Credentials()))
1724
1687
            
1725
1688
            # Note: gnutls.connection.X509Credentials is really a
1726
1689
            # generic GnuTLS certificate credentials object so long as
1735
1698
            priority = self.server.gnutls_priority
1736
1699
            if priority is None:
1737
1700
                priority = "NORMAL"
1738
 
            gnutls.library.functions.gnutls_priority_set_direct(
1739
 
                session._c_object, priority, None)
 
1701
            (gnutls.library.functions
 
1702
             .gnutls_priority_set_direct(session._c_object,
 
1703
                                         priority, None))
1740
1704
            
1741
1705
            # Start communication using the Mandos protocol
1742
1706
            # Get protocol number
1762
1726
            approval_required = False
1763
1727
            try:
1764
1728
                try:
1765
 
                    fpr = self.fingerprint(
1766
 
                        self.peer_certificate(session))
 
1729
                    fpr = self.fingerprint(self.peer_certificate
 
1730
                                           (session))
1767
1731
                except (TypeError,
1768
1732
                        gnutls.errors.GNUTLSError) as error:
1769
1733
                    logger.warning("Bad certificate: %s", error)
1784
1748
                while True:
1785
1749
                    if not client.enabled:
1786
1750
                        logger.info("Client %s is disabled",
1787
 
                                    client.name)
 
1751
                                       client.name)
1788
1752
                        if self.server.use_dbus:
1789
1753
                            # Emit D-Bus signal
1790
1754
                            client.Rejected("Disabled")
1837
1801
                        logger.warning("gnutls send failed",
1838
1802
                                       exc_info=error)
1839
1803
                        return
1840
 
                    logger.debug("Sent: %d, remaining: %d", sent,
1841
 
                                 len(client.secret) - (sent_size
1842
 
                                                       + sent))
 
1804
                    logger.debug("Sent: %d, remaining: %d",
 
1805
                                 sent, len(client.secret)
 
1806
                                 - (sent_size + sent))
1843
1807
                    sent_size += sent
1844
1808
                
1845
1809
                logger.info("Sending secret to %s", client.name)
1862
1826
    def peer_certificate(session):
1863
1827
        "Return the peer's OpenPGP certificate as a bytestring"
1864
1828
        # If not an OpenPGP certificate...
1865
 
        if (gnutls.library.functions.gnutls_certificate_type_get(
1866
 
                session._c_object)
 
1829
        if (gnutls.library.functions
 
1830
            .gnutls_certificate_type_get(session._c_object)
1867
1831
            != gnutls.library.constants.GNUTLS_CRT_OPENPGP):
1868
1832
            # ...do the normal thing
1869
1833
            return session.peer_certificate
1883
1847
    def fingerprint(openpgp):
1884
1848
        "Convert an OpenPGP bytestring to a hexdigit fingerprint"
1885
1849
        # New GnuTLS "datum" with the OpenPGP public key
1886
 
        datum = gnutls.library.types.gnutls_datum_t(
1887
 
            ctypes.cast(ctypes.c_char_p(openpgp),
1888
 
                        ctypes.POINTER(ctypes.c_ubyte)),
1889
 
            ctypes.c_uint(len(openpgp)))
 
1850
        datum = (gnutls.library.types
 
1851
                 .gnutls_datum_t(ctypes.cast(ctypes.c_char_p(openpgp),
 
1852
                                             ctypes.POINTER
 
1853
                                             (ctypes.c_ubyte)),
 
1854
                                 ctypes.c_uint(len(openpgp))))
1890
1855
        # New empty GnuTLS certificate
1891
1856
        crt = gnutls.library.types.gnutls_openpgp_crt_t()
1892
 
        gnutls.library.functions.gnutls_openpgp_crt_init(
1893
 
            ctypes.byref(crt))
 
1857
        (gnutls.library.functions
 
1858
         .gnutls_openpgp_crt_init(ctypes.byref(crt)))
1894
1859
        # Import the OpenPGP public key into the certificate
1895
 
        gnutls.library.functions.gnutls_openpgp_crt_import(
1896
 
            crt, ctypes.byref(datum),
1897
 
            gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
 
1860
        (gnutls.library.functions
 
1861
         .gnutls_openpgp_crt_import(crt, ctypes.byref(datum),
 
1862
                                    gnutls.library.constants
 
1863
                                    .GNUTLS_OPENPGP_FMT_RAW))
1898
1864
        # Verify the self signature in the key
1899
1865
        crtverify = ctypes.c_uint()
1900
 
        gnutls.library.functions.gnutls_openpgp_crt_verify_self(
1901
 
            crt, 0, ctypes.byref(crtverify))
 
1866
        (gnutls.library.functions
 
1867
         .gnutls_openpgp_crt_verify_self(crt, 0,
 
1868
                                         ctypes.byref(crtverify)))
1902
1869
        if crtverify.value != 0:
1903
1870
            gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1904
 
            raise gnutls.errors.CertificateSecurityError(
1905
 
                "Verify failed")
 
1871
            raise (gnutls.errors.CertificateSecurityError
 
1872
                   ("Verify failed"))
1906
1873
        # New buffer for the fingerprint
1907
1874
        buf = ctypes.create_string_buffer(20)
1908
1875
        buf_len = ctypes.c_size_t()
1909
1876
        # Get the fingerprint from the certificate into the buffer
1910
 
        gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
1911
 
            crt, ctypes.byref(buf), ctypes.byref(buf_len))
 
1877
        (gnutls.library.functions
 
1878
         .gnutls_openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
 
1879
                                             ctypes.byref(buf_len)))
1912
1880
        # Deinit the certificate
1913
1881
        gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
1914
1882
        # Convert the buffer to a Python bytestring
1920
1888
 
1921
1889
class MultiprocessingMixIn(object):
1922
1890
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
1923
 
    
1924
1891
    def sub_process_main(self, request, address):
1925
1892
        try:
1926
1893
            self.finish_request(request, address)
1938
1905
 
1939
1906
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
1940
1907
    """ adds a pipe to the MixIn """
1941
 
    
1942
1908
    def process_request(self, request, client_address):
1943
1909
        """Overrides and wraps the original process_request().
1944
1910
        
1965
1931
        interface:      None or a network interface name (string)
1966
1932
        use_ipv6:       Boolean; to use IPv6 or not
1967
1933
    """
1968
 
    
1969
1934
    def __init__(self, server_address, RequestHandlerClass,
1970
 
                 interface=None,
1971
 
                 use_ipv6=True,
1972
 
                 socketfd=None):
 
1935
                 interface=None, use_ipv6=True, socketfd=None):
1973
1936
        """If socketfd is set, use that file descriptor instead of
1974
1937
        creating a new one with socket.socket().
1975
1938
        """
2016
1979
                             self.interface)
2017
1980
            else:
2018
1981
                try:
2019
 
                    self.socket.setsockopt(
2020
 
                        socket.SOL_SOCKET, SO_BINDTODEVICE,
2021
 
                        (self.interface + "\0").encode("utf-8"))
 
1982
                    self.socket.setsockopt(socket.SOL_SOCKET,
 
1983
                                           SO_BINDTODEVICE,
 
1984
                                           (self.interface + "\0")
 
1985
                                           .encode("utf-8"))
2022
1986
                except socket.error as error:
2023
1987
                    if error.errno == errno.EPERM:
2024
1988
                        logger.error("No permission to bind to"
2042
2006
                self.server_address = (any_address,
2043
2007
                                       self.server_address[1])
2044
2008
            elif not self.server_address[1]:
2045
 
                self.server_address = (self.server_address[0], 0)
 
2009
                self.server_address = (self.server_address[0],
 
2010
                                       0)
2046
2011
#                 if self.interface:
2047
2012
#                     self.server_address = (self.server_address[0],
2048
2013
#                                            0, # port
2062
2027
    
2063
2028
    Assumes a gobject.MainLoop event loop.
2064
2029
    """
2065
 
    
2066
2030
    def __init__(self, server_address, RequestHandlerClass,
2067
 
                 interface=None,
2068
 
                 use_ipv6=True,
2069
 
                 clients=None,
2070
 
                 gnutls_priority=None,
2071
 
                 use_dbus=True,
2072
 
                 socketfd=None):
 
2031
                 interface=None, use_ipv6=True, clients=None,
 
2032
                 gnutls_priority=None, use_dbus=True, socketfd=None):
2073
2033
        self.enabled = False
2074
2034
        self.clients = clients
2075
2035
        if self.clients is None:
2081
2041
                                interface = interface,
2082
2042
                                use_ipv6 = use_ipv6,
2083
2043
                                socketfd = socketfd)
2084
 
    
2085
2044
    def server_activate(self):
2086
2045
        if self.enabled:
2087
2046
            return socketserver.TCPServer.server_activate(self)
2091
2050
    
2092
2051
    def add_pipe(self, parent_pipe, proc):
2093
2052
        # Call "handle_ipc" for both data and EOF events
2094
 
        gobject.io_add_watch(
2095
 
            parent_pipe.fileno(),
2096
 
            gobject.IO_IN | gobject.IO_HUP,
2097
 
            functools.partial(self.handle_ipc,
2098
 
                              parent_pipe = parent_pipe,
2099
 
                              proc = proc))
 
2053
        gobject.io_add_watch(parent_pipe.fileno(),
 
2054
                             gobject.IO_IN | gobject.IO_HUP,
 
2055
                             functools.partial(self.handle_ipc,
 
2056
                                               parent_pipe =
 
2057
                                               parent_pipe,
 
2058
                                               proc = proc))
2100
2059
    
2101
 
    def handle_ipc(self, source, condition,
2102
 
                   parent_pipe=None,
2103
 
                   proc = None,
2104
 
                   client_object=None):
 
2060
    def handle_ipc(self, source, condition, parent_pipe=None,
 
2061
                   proc = None, client_object=None):
2105
2062
        # error, or the other end of multiprocessing.Pipe has closed
2106
2063
        if condition & (gobject.IO_ERR | gobject.IO_HUP):
2107
2064
            # Wait for other process to exit
2130
2087
                parent_pipe.send(False)
2131
2088
                return False
2132
2089
            
2133
 
            gobject.io_add_watch(
2134
 
                parent_pipe.fileno(),
2135
 
                gobject.IO_IN | gobject.IO_HUP,
2136
 
                functools.partial(self.handle_ipc,
2137
 
                                  parent_pipe = parent_pipe,
2138
 
                                  proc = proc,
2139
 
                                  client_object = client))
 
2090
            gobject.io_add_watch(parent_pipe.fileno(),
 
2091
                                 gobject.IO_IN | gobject.IO_HUP,
 
2092
                                 functools.partial(self.handle_ipc,
 
2093
                                                   parent_pipe =
 
2094
                                                   parent_pipe,
 
2095
                                                   proc = proc,
 
2096
                                                   client_object =
 
2097
                                                   client))
2140
2098
            parent_pipe.send(True)
2141
2099
            # remove the old hook in favor of the new above hook on
2142
2100
            # same fileno
2148
2106
            
2149
2107
            parent_pipe.send(('data', getattr(client_object,
2150
2108
                                              funcname)(*args,
2151
 
                                                        **kwargs)))
 
2109
                                                         **kwargs)))
2152
2110
        
2153
2111
        if command == 'getattr':
2154
2112
            attrname = request[1]
2155
 
            if isinstance(client_object.__getattribute__(attrname),
2156
 
                          collections.Callable):
2157
 
                parent_pipe.send(('function', ))
 
2113
            if callable(client_object.__getattribute__(attrname)):
 
2114
                parent_pipe.send(('function',))
2158
2115
            else:
2159
 
                parent_pipe.send((
2160
 
                    'data', client_object.__getattribute__(attrname)))
 
2116
                parent_pipe.send(('data', client_object
 
2117
                                  .__getattribute__(attrname)))
2161
2118
        
2162
2119
        if command == 'setattr':
2163
2120
            attrname = request[1]
2194
2151
    # avoid excessive use of external libraries.
2195
2152
    
2196
2153
    # New type for defining tokens, syntax, and semantics all-in-one
2197
 
    Token = collections.namedtuple("Token", (
2198
 
        "regexp",  # To match token; if "value" is not None, must have
2199
 
                   # a "group" containing digits
2200
 
        "value",   # datetime.timedelta or None
2201
 
        "followers"))           # Tokens valid after this token
 
2154
    Token = collections.namedtuple("Token",
 
2155
                                   ("regexp", # To match token; if
 
2156
                                              # "value" is not None,
 
2157
                                              # must have a "group"
 
2158
                                              # containing digits
 
2159
                                    "value",  # datetime.timedelta or
 
2160
                                              # None
 
2161
                                    "followers")) # Tokens valid after
 
2162
                                                  # this token
2202
2163
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
2203
2164
    # the "duration" ABNF definition in RFC 3339, Appendix A.
2204
2165
    token_end = Token(re.compile(r"$"), None, frozenset())
2205
2166
    token_second = Token(re.compile(r"(\d+)S"),
2206
2167
                         datetime.timedelta(seconds=1),
2207
 
                         frozenset((token_end, )))
 
2168
                         frozenset((token_end,)))
2208
2169
    token_minute = Token(re.compile(r"(\d+)M"),
2209
2170
                         datetime.timedelta(minutes=1),
2210
2171
                         frozenset((token_second, token_end)))
2226
2187
                       frozenset((token_month, token_end)))
2227
2188
    token_week = Token(re.compile(r"(\d+)W"),
2228
2189
                       datetime.timedelta(weeks=1),
2229
 
                       frozenset((token_end, )))
 
2190
                       frozenset((token_end,)))
2230
2191
    token_duration = Token(re.compile(r"P"), None,
2231
2192
                           frozenset((token_year, token_month,
2232
2193
                                      token_day, token_time,
2234
2195
    # Define starting values
2235
2196
    value = datetime.timedelta() # Value so far
2236
2197
    found_token = None
2237
 
    followers = frozenset((token_duration, )) # Following valid tokens
 
2198
    followers = frozenset((token_duration,)) # Following valid tokens
2238
2199
    s = duration                # String left to parse
2239
2200
    # Loop until end token is found
2240
2201
    while found_token is not token_end:
2257
2218
                break
2258
2219
        else:
2259
2220
            # No currently valid tokens were found
2260
 
            raise ValueError("Invalid RFC 3339 duration: {!r}"
2261
 
                             .format(duration))
 
2221
            raise ValueError("Invalid RFC 3339 duration")
2262
2222
    # End token found
2263
2223
    return value
2264
2224
 
2301
2261
            elif suffix == "w":
2302
2262
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2303
2263
            else:
2304
 
                raise ValueError("Unknown suffix {!r}".format(suffix))
 
2264
                raise ValueError("Unknown suffix {!r}"
 
2265
                                 .format(suffix))
2305
2266
        except IndexError as e:
2306
2267
            raise ValueError(*(e.args))
2307
2268
        timevalue += delta
2323
2284
        # Close all standard open file descriptors
2324
2285
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2325
2286
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2326
 
            raise OSError(errno.ENODEV,
2327
 
                          "{} not a character device"
 
2287
            raise OSError(errno.ENODEV, "{} not a character device"
2328
2288
                          .format(os.devnull))
2329
2289
        os.dup2(null, sys.stdin.fileno())
2330
2290
        os.dup2(null, sys.stdout.fileno())
2397
2357
                        "debug": "False",
2398
2358
                        "priority":
2399
2359
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2400
 
                        ":+SIGN-DSA-SHA256",
 
2360
                        ":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
2401
2361
                        "servicename": "Mandos",
2402
2362
                        "use_dbus": "True",
2403
2363
                        "use_ipv6": "True",
2407
2367
                        "statedir": "/var/lib/mandos",
2408
2368
                        "foreground": "False",
2409
2369
                        "zeroconf": "True",
2410
 
                    }
 
2370
                        }
2411
2371
    
2412
2372
    # Parse config file for server-global settings
2413
2373
    server_config = configparser.SafeConfigParser(server_defaults)
2414
2374
    del server_defaults
2415
 
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
 
2375
    server_config.read(os.path.join(options.configdir,
 
2376
                                    "mandos.conf"))
2416
2377
    # Convert the SafeConfigParser object to a dict
2417
2378
    server_settings = server_config.defaults()
2418
2379
    # Use the appropriate methods on the non-string config options
2436
2397
    # Override the settings from the config file with command line
2437
2398
    # options, if set.
2438
2399
    for option in ("interface", "address", "port", "debug",
2439
 
                   "priority", "servicename", "configdir", "use_dbus",
2440
 
                   "use_ipv6", "debuglevel", "restore", "statedir",
2441
 
                   "socket", "foreground", "zeroconf"):
 
2400
                   "priority", "servicename", "configdir",
 
2401
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
 
2402
                   "statedir", "socket", "foreground", "zeroconf"):
2442
2403
        value = getattr(options, option)
2443
2404
        if value is not None:
2444
2405
            server_settings[option] = value
2459
2420
    
2460
2421
    ##################################################################
2461
2422
    
2462
 
    if (not server_settings["zeroconf"]
2463
 
        and not (server_settings["port"]
2464
 
                 or server_settings["socket"] != "")):
2465
 
        parser.error("Needs port or socket to work without Zeroconf")
 
2423
    if (not server_settings["zeroconf"] and
 
2424
        not (server_settings["port"]
 
2425
             or server_settings["socket"] != "")):
 
2426
            parser.error("Needs port or socket to work without"
 
2427
                         " Zeroconf")
2466
2428
    
2467
2429
    # For convenience
2468
2430
    debug = server_settings["debug"]
2484
2446
            initlogger(debug, level)
2485
2447
    
2486
2448
    if server_settings["servicename"] != "Mandos":
2487
 
        syslogger.setFormatter(
2488
 
            logging.Formatter('Mandos ({}) [%(process)d]:'
2489
 
                              ' %(levelname)s: %(message)s'.format(
2490
 
                                  server_settings["servicename"])))
 
2449
        syslogger.setFormatter(logging.Formatter
 
2450
                               ('Mandos ({}) [%(process)d]:'
 
2451
                                ' %(levelname)s: %(message)s'
 
2452
                                .format(server_settings
 
2453
                                        ["servicename"])))
2491
2454
    
2492
2455
    # Parse config file with clients
2493
2456
    client_config = configparser.SafeConfigParser(Client
2501
2464
    socketfd = None
2502
2465
    if server_settings["socket"] != "":
2503
2466
        socketfd = server_settings["socket"]
2504
 
    tcp_server = MandosServer(
2505
 
        (server_settings["address"], server_settings["port"]),
2506
 
        ClientHandler,
2507
 
        interface=(server_settings["interface"] or None),
2508
 
        use_ipv6=use_ipv6,
2509
 
        gnutls_priority=server_settings["priority"],
2510
 
        use_dbus=use_dbus,
2511
 
        socketfd=socketfd)
 
2467
    tcp_server = MandosServer((server_settings["address"],
 
2468
                               server_settings["port"]),
 
2469
                              ClientHandler,
 
2470
                              interface=(server_settings["interface"]
 
2471
                                         or None),
 
2472
                              use_ipv6=use_ipv6,
 
2473
                              gnutls_priority=
 
2474
                              server_settings["priority"],
 
2475
                              use_dbus=use_dbus,
 
2476
                              socketfd=socketfd)
2512
2477
    if not foreground:
2513
2478
        pidfilename = "/run/mandos.pid"
2514
2479
        if not os.path.isdir("/run/."):
2515
2480
            pidfilename = "/var/run/mandos.pid"
2516
2481
        pidfile = None
2517
2482
        try:
2518
 
            pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
 
2483
            pidfile = open(pidfilename, "w")
2519
2484
        except IOError as e:
2520
2485
            logger.error("Could not open file %r", pidfilename,
2521
2486
                         exc_info=e)
2548
2513
        def debug_gnutls(level, string):
2549
2514
            logger.debug("GnuTLS: %s", string[:-1])
2550
2515
        
2551
 
        gnutls.library.functions.gnutls_global_set_log_function(
2552
 
            debug_gnutls)
 
2516
        (gnutls.library.functions
 
2517
         .gnutls_global_set_log_function(debug_gnutls))
2553
2518
        
2554
2519
        # Redirect stdin so all checkers get /dev/null
2555
2520
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2575
2540
    if use_dbus:
2576
2541
        try:
2577
2542
            bus_name = dbus.service.BusName("se.recompile.Mandos",
2578
 
                                            bus,
2579
 
                                            do_not_queue=True)
2580
 
            old_bus_name = dbus.service.BusName(
2581
 
                "se.bsnet.fukt.Mandos", bus,
2582
 
                do_not_queue=True)
2583
 
        except dbus.exceptions.DBusException as e:
 
2543
                                            bus, do_not_queue=True)
 
2544
            old_bus_name = (dbus.service.BusName
 
2545
                            ("se.bsnet.fukt.Mandos", bus,
 
2546
                             do_not_queue=True))
 
2547
        except dbus.exceptions.NameExistsException as e:
2584
2548
            logger.error("Disabling D-Bus:", exc_info=e)
2585
2549
            use_dbus = False
2586
2550
            server_settings["use_dbus"] = False
2587
2551
            tcp_server.use_dbus = False
2588
2552
    if zeroconf:
2589
2553
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2590
 
        service = AvahiServiceToSyslog(
2591
 
            name = server_settings["servicename"],
2592
 
            servicetype = "_mandos._tcp",
2593
 
            protocol = protocol,
2594
 
            bus = bus)
 
2554
        service = AvahiServiceToSyslog(name =
 
2555
                                       server_settings["servicename"],
 
2556
                                       servicetype = "_mandos._tcp",
 
2557
                                       protocol = protocol, bus = bus)
2595
2558
        if server_settings["interface"]:
2596
 
            service.interface = if_nametoindex(
2597
 
                server_settings["interface"].encode("utf-8"))
 
2559
            service.interface = (if_nametoindex
 
2560
                                 (server_settings["interface"]
 
2561
                                  .encode("utf-8")))
2598
2562
    
2599
2563
    global multiprocessing_manager
2600
2564
    multiprocessing_manager = multiprocessing.Manager()
2619
2583
    if server_settings["restore"]:
2620
2584
        try:
2621
2585
            with open(stored_state_path, "rb") as stored_state:
2622
 
                clients_data, old_client_settings = pickle.load(
2623
 
                    stored_state)
 
2586
                clients_data, old_client_settings = (pickle.load
 
2587
                                                     (stored_state))
2624
2588
            os.remove(stored_state_path)
2625
2589
        except IOError as e:
2626
2590
            if e.errno == errno.ENOENT:
2627
 
                logger.warning("Could not load persistent state:"
2628
 
                               " {}".format(os.strerror(e.errno)))
 
2591
                logger.warning("Could not load persistent state: {}"
 
2592
                                .format(os.strerror(e.errno)))
2629
2593
            else:
2630
2594
                logger.critical("Could not load persistent state:",
2631
2595
                                exc_info=e)
2632
2596
                raise
2633
2597
        except EOFError as e:
2634
2598
            logger.warning("Could not load persistent state: "
2635
 
                           "EOFError:",
2636
 
                           exc_info=e)
 
2599
                           "EOFError:", exc_info=e)
2637
2600
    
2638
2601
    with PGPEngine() as pgp:
2639
2602
        for client_name, client in clients_data.items():
2651
2614
                    # For each value in new config, check if it
2652
2615
                    # differs from the old config value (Except for
2653
2616
                    # the "secret" attribute)
2654
 
                    if (name != "secret"
2655
 
                        and (value !=
2656
 
                             old_client_settings[client_name][name])):
 
2617
                    if (name != "secret" and
 
2618
                        value != old_client_settings[client_name]
 
2619
                        [name]):
2657
2620
                        client[name] = value
2658
2621
                except KeyError:
2659
2622
                    pass
2660
2623
            
2661
2624
            # Clients who has passed its expire date can still be
2662
 
            # enabled if its last checker was successful.  A Client
 
2625
            # enabled if its last checker was successful.  Clients
2663
2626
            # whose checker succeeded before we stored its state is
2664
2627
            # assumed to have successfully run all checkers during
2665
2628
            # downtime.
2668
2631
                    if not client["last_checked_ok"]:
2669
2632
                        logger.warning(
2670
2633
                            "disabling client {} - Client never "
2671
 
                            "performed a successful checker".format(
2672
 
                                client_name))
 
2634
                            "performed a successful checker"
 
2635
                            .format(client_name))
2673
2636
                        client["enabled"] = False
2674
2637
                    elif client["last_checker_status"] != 0:
2675
2638
                        logger.warning(
2676
2639
                            "disabling client {} - Client last"
2677
 
                            " checker failed with error code"
2678
 
                            " {}".format(
2679
 
                                client_name,
2680
 
                                client["last_checker_status"]))
 
2640
                            " checker failed with error code {}"
 
2641
                            .format(client_name,
 
2642
                                    client["last_checker_status"]))
2681
2643
                        client["enabled"] = False
2682
2644
                    else:
2683
 
                        client["expires"] = (
2684
 
                            datetime.datetime.utcnow()
2685
 
                            + client["timeout"])
 
2645
                        client["expires"] = (datetime.datetime
 
2646
                                             .utcnow()
 
2647
                                             + client["timeout"])
2686
2648
                        logger.debug("Last checker succeeded,"
2687
 
                                     " keeping {} enabled".format(
2688
 
                                         client_name))
 
2649
                                     " keeping {} enabled"
 
2650
                                     .format(client_name))
2689
2651
            try:
2690
 
                client["secret"] = pgp.decrypt(
2691
 
                    client["encrypted_secret"],
2692
 
                    client_settings[client_name]["secret"])
 
2652
                client["secret"] = (
 
2653
                    pgp.decrypt(client["encrypted_secret"],
 
2654
                                client_settings[client_name]
 
2655
                                ["secret"]))
2693
2656
            except PGPError:
2694
2657
                # If decryption fails, we use secret from new settings
2695
 
                logger.debug("Failed to decrypt {} old secret".format(
2696
 
                    client_name))
2697
 
                client["secret"] = (client_settings[client_name]
2698
 
                                    ["secret"])
 
2658
                logger.debug("Failed to decrypt {} old secret"
 
2659
                             .format(client_name))
 
2660
                client["secret"] = (
 
2661
                    client_settings[client_name]["secret"])
2699
2662
    
2700
2663
    # Add/remove clients based on new changes made to config
2701
2664
    for client_name in (set(old_client_settings)
2708
2671
    # Create all client objects
2709
2672
    for client_name, client in clients_data.items():
2710
2673
        tcp_server.clients[client_name] = client_class(
2711
 
            name = client_name,
2712
 
            settings = client,
 
2674
            name = client_name, settings = client,
2713
2675
            server_settings = server_settings)
2714
2676
    
2715
2677
    if not tcp_server.clients:
2717
2679
    
2718
2680
    if not foreground:
2719
2681
        if pidfile is not None:
2720
 
            pid = os.getpid()
2721
2682
            try:
2722
2683
                with pidfile:
2723
 
                    print(pid, file=pidfile)
 
2684
                    pid = os.getpid()
 
2685
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
2724
2686
            except IOError:
2725
2687
                logger.error("Could not write to file %r with PID %d",
2726
2688
                             pidfilename, pid)
2731
2693
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
2732
2694
    
2733
2695
    if use_dbus:
2734
 
        
2735
 
        @alternate_dbus_interfaces(
2736
 
            { "se.recompile.Mandos": "se.bsnet.fukt.Mandos" })
 
2696
        @alternate_dbus_interfaces({"se.recompile.Mandos":
 
2697
                                        "se.bsnet.fukt.Mandos"})
2737
2698
        class MandosDBusService(DBusObjectWithProperties):
2738
2699
            """A D-Bus proxy object"""
2739
 
            
2740
2700
            def __init__(self):
2741
2701
                dbus.service.Object.__init__(self, bus, "/")
2742
 
            
2743
2702
            _interface = "se.recompile.Mandos"
2744
2703
            
2745
2704
            @dbus_interface_annotations(_interface)
2746
2705
            def _foo(self):
2747
 
                return {
2748
 
                    "org.freedesktop.DBus.Property.EmitsChangedSignal":
2749
 
                    "false" }
 
2706
                return { "org.freedesktop.DBus.Property"
 
2707
                         ".EmitsChangedSignal":
 
2708
                             "false"}
2750
2709
            
2751
2710
            @dbus.service.signal(_interface, signature="o")
2752
2711
            def ClientAdded(self, objpath):
2766
2725
            @dbus.service.method(_interface, out_signature="ao")
2767
2726
            def GetAllClients(self):
2768
2727
                "D-Bus method"
2769
 
                return dbus.Array(c.dbus_object_path for c in
 
2728
                return dbus.Array(c.dbus_object_path
 
2729
                                  for c in
2770
2730
                                  tcp_server.clients.itervalues())
2771
2731
            
2772
2732
            @dbus.service.method(_interface,
2821
2781
                # + secret.
2822
2782
                exclude = { "bus", "changedstate", "secret",
2823
2783
                            "checker", "server_settings" }
2824
 
                for name, typ in inspect.getmembers(dbus.service
2825
 
                                                    .Object):
 
2784
                for name, typ in (inspect.getmembers
 
2785
                                  (dbus.service.Object)):
2826
2786
                    exclude.add(name)
2827
2787
                
2828
2788
                client_dict["encrypted_secret"] = (client
2835
2795
                del client_settings[client.name]["secret"]
2836
2796
        
2837
2797
        try:
2838
 
            with tempfile.NamedTemporaryFile(
2839
 
                    mode='wb',
2840
 
                    suffix=".pickle",
2841
 
                    prefix='clients-',
2842
 
                    dir=os.path.dirname(stored_state_path),
2843
 
                    delete=False) as stored_state:
 
2798
            with (tempfile.NamedTemporaryFile
 
2799
                  (mode='wb', suffix=".pickle", prefix='clients-',
 
2800
                   dir=os.path.dirname(stored_state_path),
 
2801
                   delete=False)) as stored_state:
2844
2802
                pickle.dump((clients, client_settings), stored_state)
2845
 
                tempname = stored_state.name
 
2803
                tempname=stored_state.name
2846
2804
            os.rename(tempname, stored_state_path)
2847
2805
        except (IOError, OSError) as e:
2848
2806
            if not debug:
2867
2825
            client.disable(quiet=True)
2868
2826
            if use_dbus:
2869
2827
                # Emit D-Bus signal
2870
 
                mandos_dbus_service.ClientRemoved(
2871
 
                    client.dbus_object_path, client.name)
 
2828
                mandos_dbus_service.ClientRemoved(client
 
2829
                                                  .dbus_object_path,
 
2830
                                                  client.name)
2872
2831
        client_settings.clear()
2873
2832
    
2874
2833
    atexit.register(cleanup)
2927
2886
    # Must run before the D-Bus bus name gets deregistered
2928
2887
    cleanup()
2929
2888
 
2930
 
 
2931
2889
if __name__ == '__main__':
2932
2890
    main()