/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos

merge

Show diffs side-by-side

added added

removed removed

Lines of Context:
63
63
import cPickle as pickle
64
64
import multiprocessing
65
65
import types
66
 
import binascii
67
 
import tempfile
68
66
 
69
67
import dbus
70
68
import dbus.service
75
73
import ctypes.util
76
74
import xml.dom.minidom
77
75
import inspect
78
 
import GnuPGInterface
79
76
 
80
77
try:
81
78
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
87
84
 
88
85
 
89
86
version = "1.4.1"
90
 
stored_state_path = "/var/lib/mandos/clients.pickle"
91
87
 
92
 
logger = logging.getLogger()
 
88
#logger = logging.getLogger('mandos')
 
89
logger = logging.Logger('mandos')
93
90
syslogger = (logging.handlers.SysLogHandler
94
91
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
95
92
              address = str("/dev/log")))
96
 
 
97
 
try:
98
 
    if_nametoindex = (ctypes.cdll.LoadLibrary
99
 
                      (ctypes.util.find_library("c"))
100
 
                      .if_nametoindex)
101
 
except (OSError, AttributeError):
102
 
    def if_nametoindex(interface):
103
 
        "Get an interface index the hard way, i.e. using fcntl()"
104
 
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
105
 
        with contextlib.closing(socket.socket()) as s:
106
 
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
107
 
                                struct.pack(str("16s16x"),
108
 
                                            interface))
109
 
        interface_index = struct.unpack(str("I"),
110
 
                                        ifreq[16:20])[0]
111
 
        return interface_index
112
 
 
113
 
 
114
 
def initlogger(level=logging.WARNING):
115
 
    """init logger and add loglevel"""
116
 
    
117
 
    syslogger.setFormatter(logging.Formatter
118
 
                           ('Mandos [%(process)d]: %(levelname)s:'
119
 
                            ' %(message)s'))
120
 
    logger.addHandler(syslogger)
121
 
    
122
 
    console = logging.StreamHandler()
123
 
    console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
124
 
                                           ' [%(process)d]:'
125
 
                                           ' %(levelname)s:'
126
 
                                           ' %(message)s'))
127
 
    logger.addHandler(console)
128
 
    logger.setLevel(level)
129
 
 
130
 
 
131
 
class CryptoError(Exception):
132
 
    pass
133
 
 
134
 
 
135
 
class Crypto(object):
136
 
    """A simple class for OpenPGP symmetric encryption & decryption"""
137
 
    def __init__(self):
138
 
        self.gnupg = GnuPGInterface.GnuPG()
139
 
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
140
 
        self.gnupg = GnuPGInterface.GnuPG()
141
 
        self.gnupg.options.meta_interactive = False
142
 
        self.gnupg.options.homedir = self.tempdir
143
 
        self.gnupg.options.extra_args.extend(['--force-mdc',
144
 
                                              '--quiet'])
145
 
    
146
 
    def __enter__(self):
147
 
        return self
148
 
    
149
 
    def __exit__ (self, exc_type, exc_value, traceback):
150
 
        self._cleanup()
151
 
        return False
152
 
    
153
 
    def __del__(self):
154
 
        self._cleanup()
155
 
    
156
 
    def _cleanup(self):
157
 
        if self.tempdir is not None:
158
 
            # Delete contents of tempdir
159
 
            for root, dirs, files in os.walk(self.tempdir,
160
 
                                             topdown = False):
161
 
                for filename in files:
162
 
                    os.remove(os.path.join(root, filename))
163
 
                for dirname in dirs:
164
 
                    os.rmdir(os.path.join(root, dirname))
165
 
            # Remove tempdir
166
 
            os.rmdir(self.tempdir)
167
 
            self.tempdir = None
168
 
    
169
 
    def password_encode(self, password):
170
 
        # Passphrase can not be empty and can not contain newlines or
171
 
        # NUL bytes.  So we prefix it and hex encode it.
172
 
        return b"mandos" + binascii.hexlify(password)
173
 
    
174
 
    def encrypt(self, data, password):
175
 
        self.gnupg.passphrase = self.password_encode(password)
176
 
        with open(os.devnull) as devnull:
177
 
            try:
178
 
                proc = self.gnupg.run(['--symmetric'],
179
 
                                      create_fhs=['stdin', 'stdout'],
180
 
                                      attach_fhs={'stderr': devnull})
181
 
                with contextlib.closing(proc.handles['stdin']) as f:
182
 
                    f.write(data)
183
 
                with contextlib.closing(proc.handles['stdout']) as f:
184
 
                    ciphertext = f.read()
185
 
                proc.wait()
186
 
            except IOError as e:
187
 
                raise CryptoError(e)
188
 
        self.gnupg.passphrase = None
189
 
        return ciphertext
190
 
    
191
 
    def decrypt(self, data, password):
192
 
        self.gnupg.passphrase = self.password_encode(password)
193
 
        with open(os.devnull) as devnull:
194
 
            try:
195
 
                proc = self.gnupg.run(['--decrypt'],
196
 
                                      create_fhs=['stdin', 'stdout'],
197
 
                                      attach_fhs={'stderr': devnull})
198
 
                with contextlib.closing(proc.handles['stdin'] ) as f:
199
 
                    f.write(data)
200
 
                with contextlib.closing(proc.handles['stdout']) as f:
201
 
                    decrypted_plaintext = f.read()
202
 
                proc.wait()
203
 
            except IOError as e:
204
 
                raise CryptoError(e)
205
 
        self.gnupg.passphrase = None
206
 
        return decrypted_plaintext
207
 
 
208
 
 
 
93
syslogger.setFormatter(logging.Formatter
 
94
                       ('Mandos [%(process)d]: %(levelname)s:'
 
95
                        ' %(message)s'))
 
96
logger.addHandler(syslogger)
 
97
 
 
98
console = logging.StreamHandler()
 
99
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
 
100
                                       ' %(levelname)s:'
 
101
                                       ' %(message)s'))
 
102
logger.addHandler(console)
209
103
 
210
104
class AvahiError(Exception):
211
105
    def __init__(self, value, *args, **kwargs):
270
164
                            .GetAlternativeServiceName(self.name))
271
165
        logger.info("Changing Zeroconf service name to %r ...",
272
166
                    self.name)
 
167
        syslogger.setFormatter(logging.Formatter
 
168
                               ('Mandos (%s) [%%(process)d]:'
 
169
                                ' %%(levelname)s: %%(message)s'
 
170
                                % self.name))
273
171
        self.remove()
274
172
        try:
275
173
            self.add()
295
193
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
296
194
        self.entry_group_state_changed_match = (
297
195
            self.group.connect_to_signal(
298
 
                'StateChanged', self.entry_group_state_changed))
 
196
                'StateChanged', self .entry_group_state_changed))
299
197
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
300
198
                     self.name, self.type)
301
199
        self.group.AddService(
327
225
            try:
328
226
                self.group.Free()
329
227
            except (dbus.exceptions.UnknownMethodException,
330
 
                    dbus.exceptions.DBusException):
 
228
                    dbus.exceptions.DBusException) as e:
331
229
                pass
332
230
            self.group = None
333
231
        self.remove()
367
265
                                 self.server_state_changed)
368
266
        self.server_state_changed(self.server.GetState())
369
267
 
370
 
class AvahiServiceToSyslog(AvahiService):
371
 
    def rename(self):
372
 
        """Add the new name to the syslog messages"""
373
 
        ret = AvahiService.rename(self)
374
 
        syslogger.setFormatter(logging.Formatter
375
 
                               ('Mandos (%s) [%%(process)d]:'
376
 
                                ' %%(levelname)s: %%(message)s'
377
 
                                % self.name))
378
 
        return ret
379
268
 
380
269
def _timedelta_to_milliseconds(td):
381
270
    "Convert a datetime.timedelta() to milliseconds"
400
289
                     instance %(name)s can be used in the command.
401
290
    checker_initiator_tag: a gobject event source tag, or None
402
291
    created:    datetime.datetime(); (UTC) object creation
403
 
    client_structure: Object describing what attributes a client has
404
 
                      and is used for storing the client at exit
405
292
    current_checker_command: string; current running checker_command
 
293
    disable_hook:  If set, called by disable() as disable_hook(self)
406
294
    disable_initiator_tag: a gobject event source tag, or None
407
295
    enabled:    bool()
408
296
    fingerprint: string (40 or 32 hexadecimal digits); used to
411
299
    interval:   datetime.timedelta(); How often to start a new checker
412
300
    last_approval_request: datetime.datetime(); (UTC) or None
413
301
    last_checked_ok: datetime.datetime(); (UTC) or None
414
 
 
415
 
    last_checker_status: integer between 0 and 255 reflecting exit
416
 
                         status of last checker. -1 reflects crashed
417
 
                         checker, or None.
418
302
    last_enabled: datetime.datetime(); (UTC)
419
303
    name:       string; from the config file, used in log messages and
420
304
                        D-Bus identifiers
447
331
    def approval_delay_milliseconds(self):
448
332
        return _timedelta_to_milliseconds(self.approval_delay)
449
333
    
450
 
    def __init__(self, name = None, config=None):
 
334
    def __init__(self, name = None, disable_hook=None, config=None):
451
335
        """Note: the 'checker' key in 'config' sets the
452
336
        'checker_command' attribute and *not* the 'checker'
453
337
        attribute."""
473
357
                            % self.name)
474
358
        self.host = config.get("host", "")
475
359
        self.created = datetime.datetime.utcnow()
476
 
        self.enabled = True
 
360
        self.enabled = False
477
361
        self.last_approval_request = None
478
 
        self.last_enabled = datetime.datetime.utcnow()
 
362
        self.last_enabled = None
479
363
        self.last_checked_ok = None
480
 
        self.last_checker_status = None
481
364
        self.timeout = string_to_delta(config["timeout"])
482
365
        self.extended_timeout = string_to_delta(config
483
366
                                                ["extended_timeout"])
484
367
        self.interval = string_to_delta(config["interval"])
 
368
        self.disable_hook = disable_hook
485
369
        self.checker = None
486
370
        self.checker_initiator_tag = None
487
371
        self.disable_initiator_tag = None
488
 
        self.expires = datetime.datetime.utcnow() + self.timeout
 
372
        self.expires = None
489
373
        self.checker_callback_tag = None
490
374
        self.checker_command = config["checker"]
491
375
        self.current_checker_command = None
 
376
        self.last_connect = None
492
377
        self._approved = None
493
378
        self.approved_by_default = config.get("approved_by_default",
494
379
                                              True)
500
385
        self.changedstate = (multiprocessing_manager
501
386
                             .Condition(multiprocessing_manager
502
387
                                        .Lock()))
503
 
        self.client_structure = [attr for attr in
504
 
                                 self.__dict__.iterkeys()
505
 
                                 if not attr.startswith("_")]
506
 
        self.client_structure.append("client_structure")
507
 
        
508
 
        for name, t in inspect.getmembers(type(self),
509
 
                                          lambda obj:
510
 
                                              isinstance(obj,
511
 
                                                         property)):
512
 
            if not name.startswith("_"):
513
 
                self.client_structure.append(name)
514
388
    
515
 
    # Send notice to process children that client state has changed
516
389
    def send_changedstate(self):
517
 
        with self.changedstate:
518
 
            self.changedstate.notify_all()
 
390
        self.changedstate.acquire()
 
391
        self.changedstate.notify_all()
 
392
        self.changedstate.release()
519
393
    
520
394
    def enable(self):
521
395
        """Start this client's checker and timeout hooks"""
523
397
            # Already enabled
524
398
            return
525
399
        self.send_changedstate()
 
400
        # Schedule a new checker to be started an 'interval' from now,
 
401
        # and every interval from then on.
 
402
        self.checker_initiator_tag = (gobject.timeout_add
 
403
                                      (self.interval_milliseconds(),
 
404
                                       self.start_checker))
 
405
        # Schedule a disable() when 'timeout' has passed
526
406
        self.expires = datetime.datetime.utcnow() + self.timeout
 
407
        self.disable_initiator_tag = (gobject.timeout_add
 
408
                                   (self.timeout_milliseconds(),
 
409
                                    self.disable))
527
410
        self.enabled = True
528
411
        self.last_enabled = datetime.datetime.utcnow()
529
 
        self.init_checker()
 
412
        # Also start a new checker *right now*.
 
413
        self.start_checker()
530
414
    
531
415
    def disable(self, quiet=True):
532
416
        """Disable this client."""
544
428
            gobject.source_remove(self.checker_initiator_tag)
545
429
            self.checker_initiator_tag = None
546
430
        self.stop_checker()
 
431
        if self.disable_hook:
 
432
            self.disable_hook(self)
547
433
        self.enabled = False
548
434
        # Do not run this again if called by a gobject.timeout_add
549
435
        return False
550
436
    
551
437
    def __del__(self):
 
438
        self.disable_hook = None
552
439
        self.disable()
553
440
    
554
 
    def init_checker(self):
555
 
        # Schedule a new checker to be started an 'interval' from now,
556
 
        # and every interval from then on.
557
 
        self.checker_initiator_tag = (gobject.timeout_add
558
 
                                      (self.interval_milliseconds(),
559
 
                                       self.start_checker))
560
 
        # Schedule a disable() when 'timeout' has passed
561
 
        self.disable_initiator_tag = (gobject.timeout_add
562
 
                                   (self.timeout_milliseconds(),
563
 
                                    self.disable))
564
 
        # Also start a new checker *right now*.
565
 
        self.start_checker()
566
 
    
567
441
    def checker_callback(self, pid, condition, command):
568
442
        """The checker has completed, so take appropriate actions."""
569
443
        self.checker_callback_tag = None
570
444
        self.checker = None
571
445
        if os.WIFEXITED(condition):
572
 
            self.last_checker_status =  os.WEXITSTATUS(condition)
573
 
            if self.last_checker_status == 0:
 
446
            exitstatus = os.WEXITSTATUS(condition)
 
447
            if exitstatus == 0:
574
448
                logger.info("Checker for %(name)s succeeded",
575
449
                            vars(self))
576
450
                self.checked_ok()
578
452
                logger.info("Checker for %(name)s failed",
579
453
                            vars(self))
580
454
        else:
581
 
            self.last_checker_status = -1
582
455
            logger.warning("Checker for %(name)s crashed?",
583
456
                           vars(self))
584
457
    
818
691
        
819
692
        Note: Will not include properties with access="write".
820
693
        """
821
 
        properties = {}
 
694
        all = {}
822
695
        for name, prop in self._get_all_dbus_properties():
823
696
            if (interface_name
824
697
                and interface_name != prop._dbus_interface):
829
702
                continue
830
703
            value = prop()
831
704
            if not hasattr(value, "variant_level"):
832
 
                properties[name] = value
 
705
                all[name] = value
833
706
                continue
834
 
            properties[name] = type(value)(value, variant_level=
835
 
                                           value.variant_level+1)
836
 
        return dbus.Dictionary(properties, signature="sv")
 
707
            all[name] = type(value)(value, variant_level=
 
708
                                    value.variant_level+1)
 
709
        return dbus.Dictionary(all, signature="sv")
837
710
    
838
711
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
839
712
                         out_signature="s",
890
763
    return dbus.String(dt.isoformat(),
891
764
                       variant_level=variant_level)
892
765
 
893
 
 
894
766
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
895
767
                                  .__metaclass__):
896
768
    """Applied to an empty subclass of a D-Bus object, this metaclass
988
860
                                        attribute.func_closure)))
989
861
        return type.__new__(mcs, name, bases, attr)
990
862
 
991
 
 
992
863
class ClientDBus(Client, DBusObjectWithProperties):
993
864
    """A Client class using D-Bus
994
865
    
1003
874
    # dbus.service.Object doesn't use super(), so we can't either.
1004
875
    
1005
876
    def __init__(self, bus = None, *args, **kwargs):
 
877
        self._approvals_pending = 0
1006
878
        self.bus = bus
1007
879
        Client.__init__(self, *args, **kwargs)
1008
 
        
1009
 
        self._approvals_pending = 0
1010
880
        # Only now, when this client is initialized, can it show up on
1011
881
        # the D-Bus
1012
882
        client_object_name = unicode(self.name).translate(
1022
892
                             variant_level=1):
1023
893
        """ Modify a variable so that it's a property which announces
1024
894
        its changes to DBus.
1025
 
        
 
895
 
1026
896
        transform_fun: Function that takes a value and a variant_level
1027
897
                       and transforms it to a D-Bus type.
1028
898
        dbus_name: D-Bus name of the variable
1182
1052
        "D-Bus signal"
1183
1053
        return self.need_approval()
1184
1054
    
1185
 
    # NeRwequest - signal
1186
 
    @dbus.service.signal(_interface, signature="s")
1187
 
    def NewRequest(self, ip):
1188
 
        """D-Bus signal
1189
 
        Is sent after a client request a password.
1190
 
        """
1191
 
        pass
1192
 
    
1193
1055
    ## Methods
1194
1056
    
1195
1057
    # Approve - method
1424
1286
            return super(ProxyClient, self).__setattr__(name, value)
1425
1287
        self._pipe.send(('setattr', name, value))
1426
1288
 
1427
 
 
1428
1289
class ClientDBusTransitional(ClientDBus):
1429
1290
    __metaclass__ = AlternateDBusNamesMetaclass
1430
1291
 
1431
 
 
1432
1292
class ClientHandler(socketserver.BaseRequestHandler, object):
1433
1293
    """A class to handle client connections.
1434
1294
    
1495
1355
                    logger.warning("Bad certificate: %s", error)
1496
1356
                    return
1497
1357
                logger.debug("Fingerprint: %s", fpr)
1498
 
                if self.server.use_dbus:
1499
 
                    # Emit D-Bus signal
1500
 
                    client.NewRequest(str(self.client_address))
1501
1358
                
1502
1359
                try:
1503
1360
                    client = ProxyClient(child_pipe, fpr,
1647
1504
        # Convert the buffer to a Python bytestring
1648
1505
        fpr = ctypes.string_at(buf, buf_len.value)
1649
1506
        # Convert the bytestring to hexadecimal notation
1650
 
        hex_fpr = binascii.hexlify(fpr).upper()
 
1507
        hex_fpr = ''.join("%02X" % ord(char) for char in fpr)
1651
1508
        return hex_fpr
1652
1509
 
1653
1510
 
1767
1624
        self.enabled = False
1768
1625
        self.clients = clients
1769
1626
        if self.clients is None:
1770
 
            self.clients = {}
 
1627
            self.clients = set()
1771
1628
        self.use_dbus = use_dbus
1772
1629
        self.gnutls_priority = gnutls_priority
1773
1630
        IPv6_TCPServer.__init__(self, server_address,
1820
1677
            fpr = request[1]
1821
1678
            address = request[2]
1822
1679
            
1823
 
            for c in self.clients.itervalues():
 
1680
            for c in self.clients:
1824
1681
                if c.fingerprint == fpr:
1825
1682
                    client = c
1826
1683
                    break
1910
1767
    return timevalue
1911
1768
 
1912
1769
 
 
1770
def if_nametoindex(interface):
 
1771
    """Call the C function if_nametoindex(), or equivalent
 
1772
    
 
1773
    Note: This function cannot accept a unicode string."""
 
1774
    global if_nametoindex
 
1775
    try:
 
1776
        if_nametoindex = (ctypes.cdll.LoadLibrary
 
1777
                          (ctypes.util.find_library("c"))
 
1778
                          .if_nametoindex)
 
1779
    except (OSError, AttributeError):
 
1780
        logger.warning("Doing if_nametoindex the hard way")
 
1781
        def if_nametoindex(interface):
 
1782
            "Get an interface index the hard way, i.e. using fcntl()"
 
1783
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
 
1784
            with contextlib.closing(socket.socket()) as s:
 
1785
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
 
1786
                                    struct.pack(str("16s16x"),
 
1787
                                                interface))
 
1788
            interface_index = struct.unpack(str("I"),
 
1789
                                            ifreq[16:20])[0]
 
1790
            return interface_index
 
1791
    return if_nametoindex(interface)
 
1792
 
 
1793
 
1913
1794
def daemon(nochdir = False, noclose = False):
1914
1795
    """See daemon(3).  Standard BSD Unix function.
1915
1796
    
1970
1851
                        " system bus interface")
1971
1852
    parser.add_argument("--no-ipv6", action="store_false",
1972
1853
                        dest="use_ipv6", help="Do not use IPv6")
1973
 
    parser.add_argument("--no-restore", action="store_false",
1974
 
                        dest="restore", help="Do not restore stored"
1975
 
                        " state", default=True)
1976
 
    
1977
1854
    options = parser.parse_args()
1978
1855
    
1979
1856
    if options.check:
2014
1891
    # options, if set.
2015
1892
    for option in ("interface", "address", "port", "debug",
2016
1893
                   "priority", "servicename", "configdir",
2017
 
                   "use_dbus", "use_ipv6", "debuglevel", "restore"):
 
1894
                   "use_dbus", "use_ipv6", "debuglevel"):
2018
1895
        value = getattr(options, option)
2019
1896
        if value is not None:
2020
1897
            server_settings[option] = value
2033
1910
    use_dbus = server_settings["use_dbus"]
2034
1911
    use_ipv6 = server_settings["use_ipv6"]
2035
1912
    
2036
 
    if debug:
2037
 
        initlogger(logging.DEBUG)
2038
 
    else:
2039
 
        if not debuglevel:
2040
 
            initlogger()
2041
 
        else:
2042
 
            level = getattr(logging, debuglevel.upper())
2043
 
            initlogger(level)
2044
 
    
2045
1913
    if server_settings["servicename"] != "Mandos":
2046
1914
        syslogger.setFormatter(logging.Formatter
2047
1915
                               ('Mandos (%s) [%%(process)d]:'
2101
1969
        if error[0] != errno.EPERM:
2102
1970
            raise error
2103
1971
    
 
1972
    if not debug and not debuglevel:
 
1973
        syslogger.setLevel(logging.WARNING)
 
1974
        console.setLevel(logging.WARNING)
 
1975
    if debuglevel:
 
1976
        level = getattr(logging, debuglevel.upper())
 
1977
        syslogger.setLevel(level)
 
1978
        console.setLevel(level)
 
1979
    
2104
1980
    if debug:
2105
1981
        # Enable all possible GnuTLS debugging
2106
1982
        
2148
2024
            server_settings["use_dbus"] = False
2149
2025
            tcp_server.use_dbus = False
2150
2026
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2151
 
    service = AvahiServiceToSyslog(name =
2152
 
                                   server_settings["servicename"],
2153
 
                                   servicetype = "_mandos._tcp",
2154
 
                                   protocol = protocol, bus = bus)
 
2027
    service = AvahiService(name = server_settings["servicename"],
 
2028
                           servicetype = "_mandos._tcp",
 
2029
                           protocol = protocol, bus = bus)
2155
2030
    if server_settings["interface"]:
2156
2031
        service.interface = (if_nametoindex
2157
2032
                             (str(server_settings["interface"])))
2163
2038
    if use_dbus:
2164
2039
        client_class = functools.partial(ClientDBusTransitional,
2165
2040
                                         bus = bus)
2166
 
    
2167
 
    special_settings = {
2168
 
        # Some settings need to be accessd by special methods;
2169
 
        # booleans need .getboolean(), etc.  Here is a list of them:
2170
 
        "approved_by_default":
2171
 
            lambda section:
2172
 
            client_config.getboolean(section, "approved_by_default"),
2173
 
        }
2174
 
    # Construct a new dict of client settings of this form:
2175
 
    # { client_name: {setting_name: value, ...}, ...}
2176
 
    # with exceptions for any special settings as defined above
2177
 
    client_settings = dict((clientname,
2178
 
                           dict((setting,
2179
 
                                 (value
2180
 
                                  if setting not in special_settings
2181
 
                                  else special_settings[setting]
2182
 
                                  (clientname)))
2183
 
                                for setting, value in
2184
 
                                client_config.items(clientname)))
2185
 
                          for clientname in client_config.sections())
2186
 
    
2187
 
    old_client_settings = {}
2188
 
    clients_data = []
2189
 
    
2190
 
    # Get client data and settings from last running state.
2191
 
    if server_settings["restore"]:
2192
 
        try:
2193
 
            with open(stored_state_path, "rb") as stored_state:
2194
 
                clients_data, old_client_settings = (pickle.load
2195
 
                                                     (stored_state))
2196
 
            os.remove(stored_state_path)
2197
 
        except IOError as e:
2198
 
            logger.warning("Could not load persistent state: {0}"
2199
 
                           .format(e))
2200
 
            if e.errno != errno.ENOENT:
2201
 
                raise
2202
 
    
2203
 
    with Crypto() as crypt:
2204
 
        for client in clients_data:
2205
 
            client_name = client["name"]
2206
 
            
2207
 
            # Decide which value to use after restoring saved state.
2208
 
            # We have three different values: Old config file,
2209
 
            # new config file, and saved state.
2210
 
            # New config value takes precedence if it differs from old
2211
 
            # config value, otherwise use saved state.
2212
 
            for name, value in client_settings[client_name].items():
2213
 
                try:
2214
 
                    # For each value in new config, check if it
2215
 
                    # differs from the old config value (Except for
2216
 
                    # the "secret" attribute)
2217
 
                    if (name != "secret" and
2218
 
                        value != old_client_settings[client_name]
2219
 
                        [name]):
2220
 
                        setattr(client, name, value)
2221
 
                except KeyError:
2222
 
                    pass
2223
 
            
2224
 
            # Clients who has passed its expire date can still be
2225
 
            # enabled if its last checker was sucessful.  Clients
2226
 
            # whose checker failed before we stored its state is
2227
 
            # assumed to have failed all checkers during downtime.
2228
 
            if client["enabled"] and client["last_checked_ok"]:
2229
 
                if ((datetime.datetime.utcnow()
2230
 
                     - client["last_checked_ok"])
2231
 
                    > client["interval"]):
2232
 
                    if client["last_checker_status"] != 0:
2233
 
                        client["enabled"] = False
2234
 
                    else:
2235
 
                        client["expires"] = (datetime.datetime
2236
 
                                             .utcnow()
2237
 
                                             + client["timeout"])
2238
 
            
2239
 
            client["changedstate"] = (multiprocessing_manager
2240
 
                                      .Condition
2241
 
                                      (multiprocessing_manager
2242
 
                                       .Lock()))
2243
 
            if use_dbus:
2244
 
                new_client = (ClientDBusTransitional.__new__
2245
 
                              (ClientDBusTransitional))
2246
 
                tcp_server.clients[client_name] = new_client
2247
 
                new_client.bus = bus
2248
 
                for name, value in client.iteritems():
2249
 
                    setattr(new_client, name, value)
2250
 
                client_object_name = unicode(client_name).translate(
2251
 
                    {ord("."): ord("_"),
2252
 
                     ord("-"): ord("_")})
2253
 
                new_client.dbus_object_path = (dbus.ObjectPath
2254
 
                                               ("/clients/"
2255
 
                                                + client_object_name))
2256
 
                DBusObjectWithProperties.__init__(new_client,
2257
 
                                                  new_client.bus,
2258
 
                                                  new_client
2259
 
                                                  .dbus_object_path)
2260
 
            else:
2261
 
                tcp_server.clients[client_name] = (Client.__new__
2262
 
                                                   (Client))
2263
 
                for name, value in client.iteritems():
2264
 
                    setattr(tcp_server.clients[client_name],
2265
 
                            name, value)
2266
 
            
 
2041
    def client_config_items(config, section):
 
2042
        special_settings = {
 
2043
            "approved_by_default":
 
2044
                lambda: config.getboolean(section,
 
2045
                                          "approved_by_default"),
 
2046
            }
 
2047
        for name, value in config.items(section):
2267
2048
            try:
2268
 
                tcp_server.clients[client_name].secret = (
2269
 
                    crypt.decrypt(tcp_server.clients[client_name]
2270
 
                                  .encrypted_secret,
2271
 
                                  client_settings[client_name]
2272
 
                                  ["secret"]))
2273
 
            except CryptoError:
2274
 
                # If decryption fails, we use secret from new settings
2275
 
                tcp_server.clients[client_name].secret = (
2276
 
                    client_settings[client_name]["secret"])
2277
 
    
2278
 
    # Create/remove clients based on new changes made to config
2279
 
    for clientname in set(old_client_settings) - set(client_settings):
2280
 
        del tcp_server.clients[clientname]
2281
 
    for clientname in set(client_settings) - set(old_client_settings):
2282
 
        tcp_server.clients[clientname] = (client_class(name
2283
 
                                                       = clientname,
2284
 
                                                       config =
2285
 
                                                       client_settings
2286
 
                                                       [clientname]))
2287
 
    
 
2049
                yield (name, special_settings[name]())
 
2050
            except KeyError:
 
2051
                yield (name, value)
 
2052
    
 
2053
    tcp_server.clients.update(set(
 
2054
            client_class(name = section,
 
2055
                         config= dict(client_config_items(
 
2056
                        client_config, section)))
 
2057
            for section in client_config.sections()))
2288
2058
    if not tcp_server.clients:
2289
2059
        logger.warning("No clients defined")
2290
2060
        
2333
2103
            def GetAllClients(self):
2334
2104
                "D-Bus method"
2335
2105
                return dbus.Array(c.dbus_object_path
2336
 
                                  for c in
2337
 
                                  tcp_server.clients.itervalues())
 
2106
                                  for c in tcp_server.clients)
2338
2107
            
2339
2108
            @dbus.service.method(_interface,
2340
2109
                                 out_signature="a{oa{sv}}")
2342
2111
                "D-Bus method"
2343
2112
                return dbus.Dictionary(
2344
2113
                    ((c.dbus_object_path, c.GetAll(""))
2345
 
                     for c in tcp_server.clients.itervalues()),
 
2114
                     for c in tcp_server.clients),
2346
2115
                    signature="oa{sv}")
2347
2116
            
2348
2117
            @dbus.service.method(_interface, in_signature="o")
2349
2118
            def RemoveClient(self, object_path):
2350
2119
                "D-Bus method"
2351
 
                for c in tcp_server.clients.itervalues():
 
2120
                for c in tcp_server.clients:
2352
2121
                    if c.dbus_object_path == object_path:
2353
 
                        del tcp_server.clients[c.name]
 
2122
                        tcp_server.clients.remove(c)
2354
2123
                        c.remove_from_connection()
2355
2124
                        # Don't signal anything except ClientRemoved
2356
2125
                        c.disable(quiet=True)
2370
2139
        service.cleanup()
2371
2140
        
2372
2141
        multiprocessing.active_children()
2373
 
        if not (tcp_server.clients or client_settings):
2374
 
            return
2375
 
        
2376
 
        # Store client before exiting. Secrets are encrypted with key
2377
 
        # based on what config file has. If config file is
2378
 
        # removed/edited, old secret will thus be unrecovable.
2379
 
        clients = []
2380
 
        with Crypto() as crypt:
2381
 
            for client in tcp_server.clients.itervalues():
2382
 
                key = client_settings[client.name]["secret"]
2383
 
                client.encrypted_secret = crypt.encrypt(client.secret,
2384
 
                                                        key)
2385
 
                client_dict = {}
2386
 
                
2387
 
                # A list of attributes that will not be stored when
2388
 
                # shutting down.
2389
 
                exclude = set(("bus", "changedstate", "secret"))
2390
 
                for name, typ in (inspect.getmembers
2391
 
                                  (dbus.service.Object)):
2392
 
                    exclude.add(name)
2393
 
                
2394
 
                client_dict["encrypted_secret"] = (client
2395
 
                                                   .encrypted_secret)
2396
 
                for attr in client.client_structure:
2397
 
                    if attr not in exclude:
2398
 
                        client_dict[attr] = getattr(client, attr)
2399
 
                
2400
 
                clients.append(client_dict)
2401
 
                del client_settings[client.name]["secret"]
2402
 
        
2403
 
        try:
2404
 
            with os.fdopen(os.open(stored_state_path,
2405
 
                                   os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2406
 
                                   0600), "wb") as stored_state:
2407
 
                pickle.dump((clients, client_settings), stored_state)
2408
 
        except (IOError, OSError) as e:
2409
 
            logger.warning("Could not save persistent state: {0}"
2410
 
                           .format(e))
2411
 
            if e.errno not in (errno.ENOENT, errno.EACCES):
2412
 
                raise
2413
 
        
2414
 
        # Delete all clients, and settings from config
2415
2142
        while tcp_server.clients:
2416
 
            name, client = tcp_server.clients.popitem()
 
2143
            client = tcp_server.clients.pop()
2417
2144
            if use_dbus:
2418
2145
                client.remove_from_connection()
 
2146
            client.disable_hook = None
2419
2147
            # Don't signal anything except ClientRemoved
2420
2148
            client.disable(quiet=True)
2421
2149
            if use_dbus:
2423
2151
                mandos_dbus_service.ClientRemoved(client
2424
2152
                                                  .dbus_object_path,
2425
2153
                                                  client.name)
2426
 
        client_settings.clear()
2427
2154
    
2428
2155
    atexit.register(cleanup)
2429
2156
    
2430
 
    for client in tcp_server.clients.itervalues():
 
2157
    for client in tcp_server.clients:
2431
2158
        if use_dbus:
2432
2159
            # Emit D-Bus signal
2433
2160
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
2434
 
        # Need to initiate checking of clients
2435
 
        if client.enabled:
2436
 
            client.init_checker()
 
2161
        client.enable()
2437
2162
    
2438
2163
    tcp_server.enable()
2439
2164
    tcp_server.server_activate()