/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2011-11-26 22:22:20 UTC
  • mto: (518.1.8 mandos-persistent)
  • mto: This revision was merged to the branch mainline in revision 524.
  • Revision ID: teddy@recompile.se-20111126222220-1ubwjpb5ugqnrhec
Directory with persistent state can now be changed with the "statedir"
option.  The state directory /var/lib/mandos now gets created on
installation.  Added documentation about "restore" and "statedir"
options.

* Makefile (USER, GROUP, STATEDIR): New.
  (maintainer-clean): Also remove "statedir".
  (run-server): Replaced "--no-restore" with "--statedir=statedir".
  (statedir): New.
  (install-server): Make $(STATEDIR) directory.
* debian/mandos.dirs (var/lib/mandos): Added.
* debian/mandos.postinst: Fix ownership of /var/lib/mandos.
* mandos: New --statedir option.
  (stored_state_path): Not global anymore.
  (stored_state_file): New global.
* mandos.conf: Fix whitespace.
  (restore, statedir): Added.
* mandos.conf.xml (OPTIONS, EXAMPLE): Added "restore" and "statedir".
  mandos.xml (SYNOPSIS, OPTIONS): Added "--statedir".
  (FILES): Added "/var/lib/mandos".

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
66
68
 
67
69
import dbus
68
70
import dbus.service
73
75
import ctypes.util
74
76
import xml.dom.minidom
75
77
import inspect
 
78
import GnuPGInterface
76
79
 
77
80
try:
78
81
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
84
87
 
85
88
 
86
89
version = "1.4.1"
 
90
stored_state_file = "clients.pickle"
87
91
 
88
 
#logger = logging.getLogger('mandos')
89
 
logger = logging.Logger('mandos')
 
92
logger = logging.getLogger()
90
93
syslogger = (logging.handlers.SysLogHandler
91
94
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
92
95
              address = str("/dev/log")))
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)
 
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
 
103
209
 
104
210
class AvahiError(Exception):
105
211
    def __init__(self, value, *args, **kwargs):
164
270
                            .GetAlternativeServiceName(self.name))
165
271
        logger.info("Changing Zeroconf service name to %r ...",
166
272
                    self.name)
167
 
        syslogger.setFormatter(logging.Formatter
168
 
                               ('Mandos (%s) [%%(process)d]:'
169
 
                                ' %%(levelname)s: %%(message)s'
170
 
                                % self.name))
171
273
        self.remove()
172
274
        try:
173
275
            self.add()
193
295
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
194
296
        self.entry_group_state_changed_match = (
195
297
            self.group.connect_to_signal(
196
 
                'StateChanged', self .entry_group_state_changed))
 
298
                'StateChanged', self.entry_group_state_changed))
197
299
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
198
300
                     self.name, self.type)
199
301
        self.group.AddService(
225
327
            try:
226
328
                self.group.Free()
227
329
            except (dbus.exceptions.UnknownMethodException,
228
 
                    dbus.exceptions.DBusException) as e:
 
330
                    dbus.exceptions.DBusException):
229
331
                pass
230
332
            self.group = None
231
333
        self.remove()
265
367
                                 self.server_state_changed)
266
368
        self.server_state_changed(self.server.GetState())
267
369
 
 
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
268
379
 
269
380
def _timedelta_to_milliseconds(td):
270
381
    "Convert a datetime.timedelta() to milliseconds"
289
400
                     instance %(name)s can be used in the command.
290
401
    checker_initiator_tag: a gobject event source tag, or None
291
402
    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
292
405
    current_checker_command: string; current running checker_command
293
 
    disable_hook:  If set, called by disable() as disable_hook(self)
294
406
    disable_initiator_tag: a gobject event source tag, or None
295
407
    enabled:    bool()
296
408
    fingerprint: string (40 or 32 hexadecimal digits); used to
299
411
    interval:   datetime.timedelta(); How often to start a new checker
300
412
    last_approval_request: datetime.datetime(); (UTC) or None
301
413
    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.
302
418
    last_enabled: datetime.datetime(); (UTC)
303
419
    name:       string; from the config file, used in log messages and
304
420
                        D-Bus identifiers
331
447
    def approval_delay_milliseconds(self):
332
448
        return _timedelta_to_milliseconds(self.approval_delay)
333
449
    
334
 
    def __init__(self, name = None, disable_hook=None, config=None):
 
450
    def __init__(self, name = None, config=None):
335
451
        """Note: the 'checker' key in 'config' sets the
336
452
        'checker_command' attribute and *not* the 'checker'
337
453
        attribute."""
357
473
                            % self.name)
358
474
        self.host = config.get("host", "")
359
475
        self.created = datetime.datetime.utcnow()
360
 
        self.enabled = False
 
476
        self.enabled = True
361
477
        self.last_approval_request = None
362
 
        self.last_enabled = None
 
478
        self.last_enabled = datetime.datetime.utcnow()
363
479
        self.last_checked_ok = None
 
480
        self.last_checker_status = None
364
481
        self.timeout = string_to_delta(config["timeout"])
365
482
        self.extended_timeout = string_to_delta(config
366
483
                                                ["extended_timeout"])
367
484
        self.interval = string_to_delta(config["interval"])
368
 
        self.disable_hook = disable_hook
369
485
        self.checker = None
370
486
        self.checker_initiator_tag = None
371
487
        self.disable_initiator_tag = None
372
 
        self.expires = None
 
488
        self.expires = datetime.datetime.utcnow() + self.timeout
373
489
        self.checker_callback_tag = None
374
490
        self.checker_command = config["checker"]
375
491
        self.current_checker_command = None
376
 
        self.last_connect = None
377
492
        self._approved = None
378
493
        self.approved_by_default = config.get("approved_by_default",
379
494
                                              True)
385
500
        self.changedstate = (multiprocessing_manager
386
501
                             .Condition(multiprocessing_manager
387
502
                                        .Lock()))
 
503
        self.client_structure = [attr for attr in
 
504
                                 self.__dict__.iterkeys()
 
505
                                 if not attr.startswith("_")]
 
506
        self.client_structure.append("client_structure")
 
507
        
 
508
        for name, t in inspect.getmembers(type(self),
 
509
                                          lambda obj:
 
510
                                              isinstance(obj,
 
511
                                                         property)):
 
512
            if not name.startswith("_"):
 
513
                self.client_structure.append(name)
388
514
    
 
515
    # Send notice to process children that client state has changed
389
516
    def send_changedstate(self):
390
 
        self.changedstate.acquire()
391
 
        self.changedstate.notify_all()
392
 
        self.changedstate.release()
 
517
        with self.changedstate:
 
518
            self.changedstate.notify_all()
393
519
    
394
520
    def enable(self):
395
521
        """Start this client's checker and timeout hooks"""
397
523
            # Already enabled
398
524
            return
399
525
        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
406
526
        self.expires = datetime.datetime.utcnow() + self.timeout
407
 
        self.disable_initiator_tag = (gobject.timeout_add
408
 
                                   (self.timeout_milliseconds(),
409
 
                                    self.disable))
410
527
        self.enabled = True
411
528
        self.last_enabled = datetime.datetime.utcnow()
412
 
        # Also start a new checker *right now*.
413
 
        self.start_checker()
 
529
        self.init_checker()
414
530
    
415
531
    def disable(self, quiet=True):
416
532
        """Disable this client."""
428
544
            gobject.source_remove(self.checker_initiator_tag)
429
545
            self.checker_initiator_tag = None
430
546
        self.stop_checker()
431
 
        if self.disable_hook:
432
 
            self.disable_hook(self)
433
547
        self.enabled = False
434
548
        # Do not run this again if called by a gobject.timeout_add
435
549
        return False
436
550
    
437
551
    def __del__(self):
438
 
        self.disable_hook = None
439
552
        self.disable()
440
553
    
 
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
    
441
567
    def checker_callback(self, pid, condition, command):
442
568
        """The checker has completed, so take appropriate actions."""
443
569
        self.checker_callback_tag = None
444
570
        self.checker = None
445
571
        if os.WIFEXITED(condition):
446
 
            exitstatus = os.WEXITSTATUS(condition)
447
 
            if exitstatus == 0:
 
572
            self.last_checker_status =  os.WEXITSTATUS(condition)
 
573
            if self.last_checker_status == 0:
448
574
                logger.info("Checker for %(name)s succeeded",
449
575
                            vars(self))
450
576
                self.checked_ok()
452
578
                logger.info("Checker for %(name)s failed",
453
579
                            vars(self))
454
580
        else:
 
581
            self.last_checker_status = -1
455
582
            logger.warning("Checker for %(name)s crashed?",
456
583
                           vars(self))
457
584
    
691
818
        
692
819
        Note: Will not include properties with access="write".
693
820
        """
694
 
        all = {}
 
821
        properties = {}
695
822
        for name, prop in self._get_all_dbus_properties():
696
823
            if (interface_name
697
824
                and interface_name != prop._dbus_interface):
702
829
                continue
703
830
            value = prop()
704
831
            if not hasattr(value, "variant_level"):
705
 
                all[name] = value
 
832
                properties[name] = value
706
833
                continue
707
 
            all[name] = type(value)(value, variant_level=
708
 
                                    value.variant_level+1)
709
 
        return dbus.Dictionary(all, signature="sv")
 
834
            properties[name] = type(value)(value, variant_level=
 
835
                                           value.variant_level+1)
 
836
        return dbus.Dictionary(properties, signature="sv")
710
837
    
711
838
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
712
839
                         out_signature="s",
763
890
    return dbus.String(dt.isoformat(),
764
891
                       variant_level=variant_level)
765
892
 
 
893
 
766
894
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
767
895
                                  .__metaclass__):
768
896
    """Applied to an empty subclass of a D-Bus object, this metaclass
860
988
                                        attribute.func_closure)))
861
989
        return type.__new__(mcs, name, bases, attr)
862
990
 
 
991
 
863
992
class ClientDBus(Client, DBusObjectWithProperties):
864
993
    """A Client class using D-Bus
865
994
    
874
1003
    # dbus.service.Object doesn't use super(), so we can't either.
875
1004
    
876
1005
    def __init__(self, bus = None, *args, **kwargs):
 
1006
        self.bus = bus
 
1007
        Client.__init__(self, *args, **kwargs)
 
1008
        
877
1009
        self._approvals_pending = 0
878
 
        self.bus = bus
879
 
        Client.__init__(self, *args, **kwargs)
880
1010
        # Only now, when this client is initialized, can it show up on
881
1011
        # the D-Bus
882
1012
        client_object_name = unicode(self.name).translate(
892
1022
                             variant_level=1):
893
1023
        """ Modify a variable so that it's a property which announces
894
1024
        its changes to DBus.
895
 
 
 
1025
        
896
1026
        transform_fun: Function that takes a value and a variant_level
897
1027
                       and transforms it to a D-Bus type.
898
1028
        dbus_name: D-Bus name of the variable
1052
1182
        "D-Bus signal"
1053
1183
        return self.need_approval()
1054
1184
    
 
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
    
1055
1193
    ## Methods
1056
1194
    
1057
1195
    # Approve - method
1286
1424
            return super(ProxyClient, self).__setattr__(name, value)
1287
1425
        self._pipe.send(('setattr', name, value))
1288
1426
 
 
1427
 
1289
1428
class ClientDBusTransitional(ClientDBus):
1290
1429
    __metaclass__ = AlternateDBusNamesMetaclass
1291
1430
 
 
1431
 
1292
1432
class ClientHandler(socketserver.BaseRequestHandler, object):
1293
1433
    """A class to handle client connections.
1294
1434
    
1355
1495
                    logger.warning("Bad certificate: %s", error)
1356
1496
                    return
1357
1497
                logger.debug("Fingerprint: %s", fpr)
 
1498
                if self.server.use_dbus:
 
1499
                    # Emit D-Bus signal
 
1500
                    client.NewRequest(str(self.client_address))
1358
1501
                
1359
1502
                try:
1360
1503
                    client = ProxyClient(child_pipe, fpr,
1504
1647
        # Convert the buffer to a Python bytestring
1505
1648
        fpr = ctypes.string_at(buf, buf_len.value)
1506
1649
        # Convert the bytestring to hexadecimal notation
1507
 
        hex_fpr = ''.join("%02X" % ord(char) for char in fpr)
 
1650
        hex_fpr = binascii.hexlify(fpr).upper()
1508
1651
        return hex_fpr
1509
1652
 
1510
1653
 
1624
1767
        self.enabled = False
1625
1768
        self.clients = clients
1626
1769
        if self.clients is None:
1627
 
            self.clients = set()
 
1770
            self.clients = {}
1628
1771
        self.use_dbus = use_dbus
1629
1772
        self.gnutls_priority = gnutls_priority
1630
1773
        IPv6_TCPServer.__init__(self, server_address,
1677
1820
            fpr = request[1]
1678
1821
            address = request[2]
1679
1822
            
1680
 
            for c in self.clients:
 
1823
            for c in self.clients.itervalues():
1681
1824
                if c.fingerprint == fpr:
1682
1825
                    client = c
1683
1826
                    break
1767
1910
    return timevalue
1768
1911
 
1769
1912
 
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
 
 
1794
1913
def daemon(nochdir = False, noclose = False):
1795
1914
    """See daemon(3).  Standard BSD Unix function.
1796
1915
    
1851
1970
                        " system bus interface")
1852
1971
    parser.add_argument("--no-ipv6", action="store_false",
1853
1972
                        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")
 
1976
    parser.add_argument("--statedir", metavar="DIR",
 
1977
                        help="Directory to save/restore state in")
 
1978
    
1854
1979
    options = parser.parse_args()
1855
1980
    
1856
1981
    if options.check:
1869
1994
                        "use_dbus": "True",
1870
1995
                        "use_ipv6": "True",
1871
1996
                        "debuglevel": "",
 
1997
                        "restore": "True",
 
1998
                        "statedir": "/var/lib/mandos"
1872
1999
                        }
1873
2000
    
1874
2001
    # Parse config file for server-global settings
1891
2018
    # options, if set.
1892
2019
    for option in ("interface", "address", "port", "debug",
1893
2020
                   "priority", "servicename", "configdir",
1894
 
                   "use_dbus", "use_ipv6", "debuglevel"):
 
2021
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
 
2022
                   "statedir"):
1895
2023
        value = getattr(options, option)
1896
2024
        if value is not None:
1897
2025
            server_settings[option] = value
1909
2037
    debuglevel = server_settings["debuglevel"]
1910
2038
    use_dbus = server_settings["use_dbus"]
1911
2039
    use_ipv6 = server_settings["use_ipv6"]
 
2040
    stored_state_path = os.path.join(server_settings["statedir"],
 
2041
                                     stored_state_file)
 
2042
    
 
2043
    if debug:
 
2044
        initlogger(logging.DEBUG)
 
2045
    else:
 
2046
        if not debuglevel:
 
2047
            initlogger()
 
2048
        else:
 
2049
            level = getattr(logging, debuglevel.upper())
 
2050
            initlogger(level)
1912
2051
    
1913
2052
    if server_settings["servicename"] != "Mandos":
1914
2053
        syslogger.setFormatter(logging.Formatter
1969
2108
        if error[0] != errno.EPERM:
1970
2109
            raise error
1971
2110
    
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
 
    
1980
2111
    if debug:
1981
2112
        # Enable all possible GnuTLS debugging
1982
2113
        
2024
2155
            server_settings["use_dbus"] = False
2025
2156
            tcp_server.use_dbus = False
2026
2157
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2027
 
    service = AvahiService(name = server_settings["servicename"],
2028
 
                           servicetype = "_mandos._tcp",
2029
 
                           protocol = protocol, bus = bus)
 
2158
    service = AvahiServiceToSyslog(name =
 
2159
                                   server_settings["servicename"],
 
2160
                                   servicetype = "_mandos._tcp",
 
2161
                                   protocol = protocol, bus = bus)
2030
2162
    if server_settings["interface"]:
2031
2163
        service.interface = (if_nametoindex
2032
2164
                             (str(server_settings["interface"])))
2038
2170
    if use_dbus:
2039
2171
        client_class = functools.partial(ClientDBusTransitional,
2040
2172
                                         bus = bus)
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):
 
2173
    
 
2174
    special_settings = {
 
2175
        # Some settings need to be accessd by special methods;
 
2176
        # booleans need .getboolean(), etc.  Here is a list of them:
 
2177
        "approved_by_default":
 
2178
            lambda section:
 
2179
            client_config.getboolean(section, "approved_by_default"),
 
2180
        }
 
2181
    # Construct a new dict of client settings of this form:
 
2182
    # { client_name: {setting_name: value, ...}, ...}
 
2183
    # with exceptions for any special settings as defined above
 
2184
    client_settings = dict((clientname,
 
2185
                           dict((setting,
 
2186
                                 (value
 
2187
                                  if setting not in special_settings
 
2188
                                  else special_settings[setting]
 
2189
                                  (clientname)))
 
2190
                                for setting, value in
 
2191
                                client_config.items(clientname)))
 
2192
                          for clientname in client_config.sections())
 
2193
    
 
2194
    old_client_settings = {}
 
2195
    clients_data = []
 
2196
    
 
2197
    # Get client data and settings from last running state.
 
2198
    if server_settings["restore"]:
 
2199
        try:
 
2200
            with open(stored_state_path, "rb") as stored_state:
 
2201
                clients_data, old_client_settings = (pickle.load
 
2202
                                                     (stored_state))
 
2203
            os.remove(stored_state_path)
 
2204
        except IOError as e:
 
2205
            logger.warning("Could not load persistent state: {0}"
 
2206
                           .format(e))
 
2207
            if e.errno != errno.ENOENT:
 
2208
                raise
 
2209
    
 
2210
    with Crypto() as crypt:
 
2211
        for client in clients_data:
 
2212
            client_name = client["name"]
 
2213
            
 
2214
            # Decide which value to use after restoring saved state.
 
2215
            # We have three different values: Old config file,
 
2216
            # new config file, and saved state.
 
2217
            # New config value takes precedence if it differs from old
 
2218
            # config value, otherwise use saved state.
 
2219
            for name, value in client_settings[client_name].items():
 
2220
                try:
 
2221
                    # For each value in new config, check if it
 
2222
                    # differs from the old config value (Except for
 
2223
                    # the "secret" attribute)
 
2224
                    if (name != "secret" and
 
2225
                        value != old_client_settings[client_name]
 
2226
                        [name]):
 
2227
                        setattr(client, name, value)
 
2228
                except KeyError:
 
2229
                    pass
 
2230
            
 
2231
            # Clients who has passed its expire date can still be
 
2232
            # enabled if its last checker was sucessful.  Clients
 
2233
            # whose checker failed before we stored its state is
 
2234
            # assumed to have failed all checkers during downtime.
 
2235
            if client["enabled"] and client["last_checked_ok"]:
 
2236
                if ((datetime.datetime.utcnow()
 
2237
                     - client["last_checked_ok"])
 
2238
                    > client["interval"]):
 
2239
                    if client["last_checker_status"] != 0:
 
2240
                        client["enabled"] = False
 
2241
                    else:
 
2242
                        client["expires"] = (datetime.datetime
 
2243
                                             .utcnow()
 
2244
                                             + client["timeout"])
 
2245
            
 
2246
            client["changedstate"] = (multiprocessing_manager
 
2247
                                      .Condition
 
2248
                                      (multiprocessing_manager
 
2249
                                       .Lock()))
 
2250
            if use_dbus:
 
2251
                new_client = (ClientDBusTransitional.__new__
 
2252
                              (ClientDBusTransitional))
 
2253
                tcp_server.clients[client_name] = new_client
 
2254
                new_client.bus = bus
 
2255
                for name, value in client.iteritems():
 
2256
                    setattr(new_client, name, value)
 
2257
                client_object_name = unicode(client_name).translate(
 
2258
                    {ord("."): ord("_"),
 
2259
                     ord("-"): ord("_")})
 
2260
                new_client.dbus_object_path = (dbus.ObjectPath
 
2261
                                               ("/clients/"
 
2262
                                                + client_object_name))
 
2263
                DBusObjectWithProperties.__init__(new_client,
 
2264
                                                  new_client.bus,
 
2265
                                                  new_client
 
2266
                                                  .dbus_object_path)
 
2267
            else:
 
2268
                tcp_server.clients[client_name] = (Client.__new__
 
2269
                                                   (Client))
 
2270
                for name, value in client.iteritems():
 
2271
                    setattr(tcp_server.clients[client_name],
 
2272
                            name, value)
 
2273
            
2048
2274
            try:
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()))
 
2275
                tcp_server.clients[client_name].secret = (
 
2276
                    crypt.decrypt(tcp_server.clients[client_name]
 
2277
                                  .encrypted_secret,
 
2278
                                  client_settings[client_name]
 
2279
                                  ["secret"]))
 
2280
            except CryptoError:
 
2281
                # If decryption fails, we use secret from new settings
 
2282
                tcp_server.clients[client_name].secret = (
 
2283
                    client_settings[client_name]["secret"])
 
2284
    
 
2285
    # Create/remove clients based on new changes made to config
 
2286
    for clientname in set(old_client_settings) - set(client_settings):
 
2287
        del tcp_server.clients[clientname]
 
2288
    for clientname in set(client_settings) - set(old_client_settings):
 
2289
        tcp_server.clients[clientname] = (client_class(name
 
2290
                                                       = clientname,
 
2291
                                                       config =
 
2292
                                                       client_settings
 
2293
                                                       [clientname]))
 
2294
    
2058
2295
    if not tcp_server.clients:
2059
2296
        logger.warning("No clients defined")
2060
2297
        
2103
2340
            def GetAllClients(self):
2104
2341
                "D-Bus method"
2105
2342
                return dbus.Array(c.dbus_object_path
2106
 
                                  for c in tcp_server.clients)
 
2343
                                  for c in
 
2344
                                  tcp_server.clients.itervalues())
2107
2345
            
2108
2346
            @dbus.service.method(_interface,
2109
2347
                                 out_signature="a{oa{sv}}")
2111
2349
                "D-Bus method"
2112
2350
                return dbus.Dictionary(
2113
2351
                    ((c.dbus_object_path, c.GetAll(""))
2114
 
                     for c in tcp_server.clients),
 
2352
                     for c in tcp_server.clients.itervalues()),
2115
2353
                    signature="oa{sv}")
2116
2354
            
2117
2355
            @dbus.service.method(_interface, in_signature="o")
2118
2356
            def RemoveClient(self, object_path):
2119
2357
                "D-Bus method"
2120
 
                for c in tcp_server.clients:
 
2358
                for c in tcp_server.clients.itervalues():
2121
2359
                    if c.dbus_object_path == object_path:
2122
 
                        tcp_server.clients.remove(c)
 
2360
                        del tcp_server.clients[c.name]
2123
2361
                        c.remove_from_connection()
2124
2362
                        # Don't signal anything except ClientRemoved
2125
2363
                        c.disable(quiet=True)
2139
2377
        service.cleanup()
2140
2378
        
2141
2379
        multiprocessing.active_children()
 
2380
        if not (tcp_server.clients or client_settings):
 
2381
            return
 
2382
        
 
2383
        # Store client before exiting. Secrets are encrypted with key
 
2384
        # based on what config file has. If config file is
 
2385
        # removed/edited, old secret will thus be unrecovable.
 
2386
        clients = []
 
2387
        with Crypto() as crypt:
 
2388
            for client in tcp_server.clients.itervalues():
 
2389
                key = client_settings[client.name]["secret"]
 
2390
                client.encrypted_secret = crypt.encrypt(client.secret,
 
2391
                                                        key)
 
2392
                client_dict = {}
 
2393
                
 
2394
                # A list of attributes that will not be stored when
 
2395
                # shutting down.
 
2396
                exclude = set(("bus", "changedstate", "secret"))
 
2397
                for name, typ in (inspect.getmembers
 
2398
                                  (dbus.service.Object)):
 
2399
                    exclude.add(name)
 
2400
                
 
2401
                client_dict["encrypted_secret"] = (client
 
2402
                                                   .encrypted_secret)
 
2403
                for attr in client.client_structure:
 
2404
                    if attr not in exclude:
 
2405
                        client_dict[attr] = getattr(client, attr)
 
2406
                
 
2407
                clients.append(client_dict)
 
2408
                del client_settings[client.name]["secret"]
 
2409
        
 
2410
        try:
 
2411
            with os.fdopen(os.open(stored_state_path,
 
2412
                                   os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
 
2413
                                   0600), "wb") as stored_state:
 
2414
                pickle.dump((clients, client_settings), stored_state)
 
2415
        except (IOError, OSError) as e:
 
2416
            logger.warning("Could not save persistent state: {0}"
 
2417
                           .format(e))
 
2418
            if e.errno not in (errno.ENOENT, errno.EACCES):
 
2419
                raise
 
2420
        
 
2421
        # Delete all clients, and settings from config
2142
2422
        while tcp_server.clients:
2143
 
            client = tcp_server.clients.pop()
 
2423
            name, client = tcp_server.clients.popitem()
2144
2424
            if use_dbus:
2145
2425
                client.remove_from_connection()
2146
 
            client.disable_hook = None
2147
2426
            # Don't signal anything except ClientRemoved
2148
2427
            client.disable(quiet=True)
2149
2428
            if use_dbus:
2151
2430
                mandos_dbus_service.ClientRemoved(client
2152
2431
                                                  .dbus_object_path,
2153
2432
                                                  client.name)
 
2433
        client_settings.clear()
2154
2434
    
2155
2435
    atexit.register(cleanup)
2156
2436
    
2157
 
    for client in tcp_server.clients:
 
2437
    for client in tcp_server.clients.itervalues():
2158
2438
        if use_dbus:
2159
2439
            # Emit D-Bus signal
2160
2440
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
2161
 
        client.enable()
 
2441
        # Need to initiate checking of clients
 
2442
        if client.enabled:
 
2443
            client.init_checker()
2162
2444
    
2163
2445
    tcp_server.enable()
2164
2446
    tcp_server.server_activate()