/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos

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

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

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008-2012 Teddy Hogeborn
15
 
# Copyright © 2008-2012 Björn Påhlsson
 
14
# Copyright © 2008-2011 Teddy Hogeborn
 
15
# Copyright © 2008-2011 Björn Påhlsson
16
16
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
85
85
    except ImportError:
86
86
        SO_BINDTODEVICE = None
87
87
 
88
 
version = "1.5.1"
 
88
 
 
89
version = "1.4.1"
89
90
stored_state_file = "clients.pickle"
90
91
 
91
92
logger = logging.getLogger()
110
111
        return interface_index
111
112
 
112
113
 
113
 
def initlogger(debug, level=logging.WARNING):
 
114
def initlogger(level=logging.WARNING):
114
115
    """init logger and add loglevel"""
115
116
    
116
117
    syslogger.setFormatter(logging.Formatter
118
119
                            ' %(message)s'))
119
120
    logger.addHandler(syslogger)
120
121
    
121
 
    if debug:
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)
 
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
128
    logger.setLevel(level)
129
129
 
130
130
 
131
 
class PGPError(Exception):
132
 
    """Exception if encryption/decryption fails"""
 
131
class CryptoError(Exception):
133
132
    pass
134
133
 
135
134
 
136
 
class PGPEngine(object):
 
135
class Crypto(object):
137
136
    """A simple class for OpenPGP symmetric encryption & decryption"""
138
137
    def __init__(self):
139
138
        self.gnupg = GnuPGInterface.GnuPG()
142
141
        self.gnupg.options.meta_interactive = False
143
142
        self.gnupg.options.homedir = self.tempdir
144
143
        self.gnupg.options.extra_args.extend(['--force-mdc',
145
 
                                              '--quiet',
146
 
                                              '--no-use-agent'])
 
144
                                              '--quiet'])
147
145
    
148
146
    def __enter__(self):
149
147
        return self
186
184
                    ciphertext = f.read()
187
185
                proc.wait()
188
186
            except IOError as e:
189
 
                raise PGPError(e)
 
187
                raise CryptoError(e)
190
188
        self.gnupg.passphrase = None
191
189
        return ciphertext
192
190
    
203
201
                    decrypted_plaintext = f.read()
204
202
                proc.wait()
205
203
            except IOError as e:
206
 
                raise PGPError(e)
 
204
                raise CryptoError(e)
207
205
        self.gnupg.passphrase = None
208
206
        return decrypted_plaintext
209
207
 
379
377
                                % self.name))
380
378
        return ret
381
379
 
382
 
def timedelta_to_milliseconds(td):
 
380
def _timedelta_to_milliseconds(td):
383
381
    "Convert a datetime.timedelta() to milliseconds"
384
382
    return ((td.days * 24 * 60 * 60 * 1000)
385
383
            + (td.seconds * 1000)
389
387
    """A representation of a client host served by this server.
390
388
    
391
389
    Attributes:
392
 
    approved:   bool(); 'None' if not yet approved/disapproved
 
390
    _approved:   bool(); 'None' if not yet approved/disapproved
393
391
    approval_delay: datetime.timedelta(); Time to wait for approval
394
392
    approval_duration: datetime.timedelta(); Duration of one approval
395
393
    checker:    subprocess.Popen(); a running checker process used
413
411
    interval:   datetime.timedelta(); How often to start a new checker
414
412
    last_approval_request: datetime.datetime(); (UTC) or None
415
413
    last_checked_ok: datetime.datetime(); (UTC) or None
 
414
 
416
415
    last_checker_status: integer between 0 and 255 reflecting exit
417
416
                         status of last checker. -1 reflects crashed
418
417
                         checker, or None.
422
421
    secret:     bytestring; sent verbatim (over TLS) to client
423
422
    timeout:    datetime.timedelta(); How long from last_checked_ok
424
423
                                      until this client is disabled
425
 
    extended_timeout:   extra long timeout when secret has been sent
 
424
    extended_timeout:   extra long timeout when password has been sent
426
425
    runtime_expansions: Allowed attributes for runtime expansion.
427
426
    expires:    datetime.datetime(); time (UTC) when a client will be
428
427
                disabled, or None
432
431
                          "created", "enabled", "fingerprint",
433
432
                          "host", "interval", "last_checked_ok",
434
433
                          "last_enabled", "name", "timeout")
435
 
    client_defaults = { "timeout": "5m",
436
 
                        "extended_timeout": "15m",
437
 
                        "interval": "2m",
438
 
                        "checker": "fping -q -- %%(host)s",
439
 
                        "host": "",
440
 
                        "approval_delay": "0s",
441
 
                        "approval_duration": "1s",
442
 
                        "approved_by_default": "True",
443
 
                        "enabled": "True",
444
 
                        }
445
434
    
446
435
    def timeout_milliseconds(self):
447
436
        "Return the 'timeout' attribute in milliseconds"
448
 
        return timedelta_to_milliseconds(self.timeout)
 
437
        return _timedelta_to_milliseconds(self.timeout)
449
438
    
450
439
    def extended_timeout_milliseconds(self):
451
440
        "Return the 'extended_timeout' attribute in milliseconds"
452
 
        return timedelta_to_milliseconds(self.extended_timeout)
 
441
        return _timedelta_to_milliseconds(self.extended_timeout)
453
442
    
454
443
    def interval_milliseconds(self):
455
444
        "Return the 'interval' attribute in milliseconds"
456
 
        return timedelta_to_milliseconds(self.interval)
 
445
        return _timedelta_to_milliseconds(self.interval)
457
446
    
458
447
    def approval_delay_milliseconds(self):
459
 
        return timedelta_to_milliseconds(self.approval_delay)
460
 
 
461
 
    @staticmethod
462
 
    def config_parser(config):
463
 
        """Construct a new dict of client settings of this form:
464
 
        { client_name: {setting_name: value, ...}, ...}
465
 
        with exceptions for any special settings as defined above.
466
 
        NOTE: Must be a pure function. Must return the same result
467
 
        value given the same arguments.
468
 
        """
469
 
        settings = {}
470
 
        for client_name in config.sections():
471
 
            section = dict(config.items(client_name))
472
 
            client = settings[client_name] = {}
473
 
            
474
 
            client["host"] = section["host"]
475
 
            # Reformat values from string types to Python types
476
 
            client["approved_by_default"] = config.getboolean(
477
 
                client_name, "approved_by_default")
478
 
            client["enabled"] = config.getboolean(client_name,
479
 
                                                  "enabled")
480
 
            
481
 
            client["fingerprint"] = (section["fingerprint"].upper()
482
 
                                     .replace(" ", ""))
483
 
            if "secret" in section:
484
 
                client["secret"] = section["secret"].decode("base64")
485
 
            elif "secfile" in section:
486
 
                with open(os.path.expanduser(os.path.expandvars
487
 
                                             (section["secfile"])),
488
 
                          "rb") as secfile:
489
 
                    client["secret"] = secfile.read()
490
 
            else:
491
 
                raise TypeError("No secret or secfile for section %s"
492
 
                                % section)
493
 
            client["timeout"] = string_to_delta(section["timeout"])
494
 
            client["extended_timeout"] = string_to_delta(
495
 
                section["extended_timeout"])
496
 
            client["interval"] = string_to_delta(section["interval"])
497
 
            client["approval_delay"] = string_to_delta(
498
 
                section["approval_delay"])
499
 
            client["approval_duration"] = string_to_delta(
500
 
                section["approval_duration"])
501
 
            client["checker_command"] = section["checker"]
502
 
            client["last_approval_request"] = None
503
 
            client["last_checked_ok"] = None
504
 
            client["last_checker_status"] = None
505
 
        
506
 
        return settings
507
 
        
508
 
        
509
 
    def __init__(self, settings, name = None):
 
448
        return _timedelta_to_milliseconds(self.approval_delay)
 
449
    
 
450
    def __init__(self, name = None, config=None):
510
451
        """Note: the 'checker' key in 'config' sets the
511
452
        'checker_command' attribute and *not* the 'checker'
512
453
        attribute."""
513
454
        self.name = name
514
 
        # adding all client settings
515
 
        for setting, value in settings.iteritems():
516
 
            setattr(self, setting, value)
517
 
        
518
 
        if self.enabled:
519
 
            if not hasattr(self, "last_enabled"):
520
 
                self.last_enabled = datetime.datetime.utcnow()
521
 
            if not hasattr(self, "expires"):
522
 
                self.expires = (datetime.datetime.utcnow()
523
 
                                + self.timeout)
524
 
        else:
525
 
            self.last_enabled = None
526
 
            self.expires = None
527
 
       
 
455
        if config is None:
 
456
            config = {}
528
457
        logger.debug("Creating client %r", self.name)
529
458
        # Uppercase and remove spaces from fingerprint for later
530
459
        # comparison purposes with return value from the fingerprint()
531
460
        # function
 
461
        self.fingerprint = (config["fingerprint"].upper()
 
462
                            .replace(" ", ""))
532
463
        logger.debug("  Fingerprint: %s", self.fingerprint)
533
 
        self.created = settings.get("created",
534
 
                                    datetime.datetime.utcnow())
535
 
 
536
 
        # attributes specific for this server instance
 
464
        if "secret" in config:
 
465
            self.secret = config["secret"].decode("base64")
 
466
        elif "secfile" in config:
 
467
            with open(os.path.expanduser(os.path.expandvars
 
468
                                         (config["secfile"])),
 
469
                      "rb") as secfile:
 
470
                self.secret = secfile.read()
 
471
        else:
 
472
            raise TypeError("No secret or secfile for client %s"
 
473
                            % self.name)
 
474
        self.host = config.get("host", "")
 
475
        self.created = datetime.datetime.utcnow()
 
476
        self.enabled = config.get("enabled", True)
 
477
        self.last_approval_request = None
 
478
        if self.enabled:
 
479
            self.last_enabled = datetime.datetime.utcnow()
 
480
        else:
 
481
            self.last_enabled = None
 
482
        self.last_checked_ok = None
 
483
        self.last_checker_status = None
 
484
        self.timeout = string_to_delta(config["timeout"])
 
485
        self.extended_timeout = string_to_delta(config
 
486
                                                ["extended_timeout"])
 
487
        self.interval = string_to_delta(config["interval"])
537
488
        self.checker = None
538
489
        self.checker_initiator_tag = None
539
490
        self.disable_initiator_tag = None
 
491
        if self.enabled:
 
492
            self.expires = datetime.datetime.utcnow() + self.timeout
 
493
        else:
 
494
            self.expires = None
540
495
        self.checker_callback_tag = None
 
496
        self.checker_command = config["checker"]
541
497
        self.current_checker_command = None
542
 
        self.approved = None
 
498
        self._approved = None
 
499
        self.approved_by_default = config.get("approved_by_default",
 
500
                                              True)
543
501
        self.approvals_pending = 0
 
502
        self.approval_delay = string_to_delta(
 
503
            config["approval_delay"])
 
504
        self.approval_duration = string_to_delta(
 
505
            config["approval_duration"])
544
506
        self.changedstate = (multiprocessing_manager
545
507
                             .Condition(multiprocessing_manager
546
508
                                        .Lock()))
613
575
        self.checker_callback_tag = None
614
576
        self.checker = None
615
577
        if os.WIFEXITED(condition):
616
 
            self.last_checker_status = os.WEXITSTATUS(condition)
 
578
            self.last_checker_status =  os.WEXITSTATUS(condition)
617
579
            if self.last_checker_status == 0:
618
580
                logger.info("Checker for %(name)s succeeded",
619
581
                            vars(self))
639
601
            gobject.source_remove(self.disable_initiator_tag)
640
602
        if getattr(self, "enabled", False):
641
603
            self.disable_initiator_tag = (gobject.timeout_add
642
 
                                          (timedelta_to_milliseconds
 
604
                                          (_timedelta_to_milliseconds
643
605
                                           (timeout), self.disable))
644
606
            self.expires = datetime.datetime.utcnow() + timeout
645
607
    
850
812
            # signatures other than "ay".
851
813
            if prop._dbus_signature != "ay":
852
814
                raise ValueError
853
 
            value = dbus.ByteArray(b''.join(chr(byte)
854
 
                                            for byte in value))
 
815
            value = dbus.ByteArray(''.join(unichr(byte)
 
816
                                           for byte in value))
855
817
        prop(value)
856
818
    
857
819
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
1049
1011
    def __init__(self, bus = None, *args, **kwargs):
1050
1012
        self.bus = bus
1051
1013
        Client.__init__(self, *args, **kwargs)
 
1014
        
 
1015
        self._approvals_pending = 0
1052
1016
        # Only now, when this client is initialized, can it show up on
1053
1017
        # the D-Bus
1054
1018
        client_object_name = unicode(self.name).translate(
1104
1068
        datetime_to_dbus, "LastApprovalRequest")
1105
1069
    approved_by_default = notifychangeproperty(dbus.Boolean,
1106
1070
                                               "ApprovedByDefault")
1107
 
    approval_delay = notifychangeproperty(dbus.UInt64,
 
1071
    approval_delay = notifychangeproperty(dbus.UInt16,
1108
1072
                                          "ApprovalDelay",
1109
1073
                                          type_func =
1110
 
                                          timedelta_to_milliseconds)
 
1074
                                          _timedelta_to_milliseconds)
1111
1075
    approval_duration = notifychangeproperty(
1112
 
        dbus.UInt64, "ApprovalDuration",
1113
 
        type_func = timedelta_to_milliseconds)
 
1076
        dbus.UInt16, "ApprovalDuration",
 
1077
        type_func = _timedelta_to_milliseconds)
1114
1078
    host = notifychangeproperty(dbus.String, "Host")
1115
 
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
 
1079
    timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1116
1080
                                   type_func =
1117
 
                                   timedelta_to_milliseconds)
 
1081
                                   _timedelta_to_milliseconds)
1118
1082
    extended_timeout = notifychangeproperty(
1119
 
        dbus.UInt64, "ExtendedTimeout",
1120
 
        type_func = timedelta_to_milliseconds)
1121
 
    interval = notifychangeproperty(dbus.UInt64,
 
1083
        dbus.UInt16, "ExtendedTimeout",
 
1084
        type_func = _timedelta_to_milliseconds)
 
1085
    interval = notifychangeproperty(dbus.UInt16,
1122
1086
                                    "Interval",
1123
1087
                                    type_func =
1124
 
                                    timedelta_to_milliseconds)
 
1088
                                    _timedelta_to_milliseconds)
1125
1089
    checker_command = notifychangeproperty(dbus.String, "Checker")
1126
1090
    
1127
1091
    del notifychangeproperty
1169
1133
        return r
1170
1134
    
1171
1135
    def _reset_approved(self):
1172
 
        self.approved = None
 
1136
        self._approved = None
1173
1137
        return False
1174
1138
    
1175
1139
    def approve(self, value=True):
1176
1140
        self.send_changedstate()
1177
 
        self.approved = value
1178
 
        gobject.timeout_add(timedelta_to_milliseconds
 
1141
        self._approved = value
 
1142
        gobject.timeout_add(_timedelta_to_milliseconds
1179
1143
                            (self.approval_duration),
1180
1144
                            self._reset_approved)
1181
1145
    
1224
1188
        "D-Bus signal"
1225
1189
        return self.need_approval()
1226
1190
    
 
1191
    # NeRwequest - signal
 
1192
    @dbus.service.signal(_interface, signature="s")
 
1193
    def NewRequest(self, ip):
 
1194
        """D-Bus signal
 
1195
        Is sent after a client request a password.
 
1196
        """
 
1197
        pass
 
1198
    
1227
1199
    ## Methods
1228
1200
    
1229
1201
    # Approve - method
1287
1259
                           access="readwrite")
1288
1260
    def ApprovalDuration_dbus_property(self, value=None):
1289
1261
        if value is None:       # get
1290
 
            return dbus.UInt64(timedelta_to_milliseconds(
 
1262
            return dbus.UInt64(_timedelta_to_milliseconds(
1291
1263
                    self.approval_duration))
1292
1264
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1293
1265
    
1307
1279
    def Host_dbus_property(self, value=None):
1308
1280
        if value is None:       # get
1309
1281
            return dbus.String(self.host)
1310
 
        self.host = unicode(value)
 
1282
        self.host = value
1311
1283
    
1312
1284
    # Created - property
1313
1285
    @dbus_service_property(_interface, signature="s", access="read")
1356
1328
        if value is None:       # get
1357
1329
            return dbus.UInt64(self.timeout_milliseconds())
1358
1330
        self.timeout = datetime.timedelta(0, 0, 0, value)
 
1331
        if getattr(self, "disable_initiator_tag", None) is None:
 
1332
            return
1359
1333
        # Reschedule timeout
1360
 
        if self.enabled:
1361
 
            now = datetime.datetime.utcnow()
1362
 
            time_to_die = timedelta_to_milliseconds(
1363
 
                (self.last_checked_ok + self.timeout) - now)
1364
 
            if time_to_die <= 0:
1365
 
                # The timeout has passed
1366
 
                self.disable()
1367
 
            else:
1368
 
                self.expires = (now +
1369
 
                                datetime.timedelta(milliseconds =
1370
 
                                                   time_to_die))
1371
 
                if (getattr(self, "disable_initiator_tag", None)
1372
 
                    is None):
1373
 
                    return
1374
 
                gobject.source_remove(self.disable_initiator_tag)
1375
 
                self.disable_initiator_tag = (gobject.timeout_add
1376
 
                                              (time_to_die,
1377
 
                                               self.disable))
 
1334
        gobject.source_remove(self.disable_initiator_tag)
 
1335
        self.disable_initiator_tag = None
 
1336
        self.expires = None
 
1337
        time_to_die = _timedelta_to_milliseconds((self
 
1338
                                                  .last_checked_ok
 
1339
                                                  + self.timeout)
 
1340
                                                 - datetime.datetime
 
1341
                                                 .utcnow())
 
1342
        if time_to_die <= 0:
 
1343
            # The timeout has passed
 
1344
            self.disable()
 
1345
        else:
 
1346
            self.expires = (datetime.datetime.utcnow()
 
1347
                            + datetime.timedelta(milliseconds =
 
1348
                                                 time_to_die))
 
1349
            self.disable_initiator_tag = (gobject.timeout_add
 
1350
                                          (time_to_die, self.disable))
1378
1351
    
1379
1352
    # ExtendedTimeout - property
1380
1353
    @dbus_service_property(_interface, signature="t",
1406
1379
    def Checker_dbus_property(self, value=None):
1407
1380
        if value is None:       # get
1408
1381
            return dbus.String(self.checker_command)
1409
 
        self.checker_command = unicode(value)
 
1382
        self.checker_command = value
1410
1383
    
1411
1384
    # CheckerRunning - property
1412
1385
    @dbus_service_property(_interface, signature="b",
1441
1414
            raise KeyError()
1442
1415
    
1443
1416
    def __getattribute__(self, name):
1444
 
        if name == '_pipe':
 
1417
        if(name == '_pipe'):
1445
1418
            return super(ProxyClient, self).__getattribute__(name)
1446
1419
        self._pipe.send(('getattr', name))
1447
1420
        data = self._pipe.recv()
1454
1427
            return func
1455
1428
    
1456
1429
    def __setattr__(self, name, value):
1457
 
        if name == '_pipe':
 
1430
        if(name == '_pipe'):
1458
1431
            return super(ProxyClient, self).__setattr__(name, value)
1459
1432
        self._pipe.send(('setattr', name, value))
1460
1433
 
1529
1502
                    logger.warning("Bad certificate: %s", error)
1530
1503
                    return
1531
1504
                logger.debug("Fingerprint: %s", fpr)
 
1505
                if self.server.use_dbus:
 
1506
                    # Emit D-Bus signal
 
1507
                    client.NewRequest(str(self.client_address))
1532
1508
                
1533
1509
                try:
1534
1510
                    client = ProxyClient(child_pipe, fpr,
1550
1526
                            client.Rejected("Disabled")
1551
1527
                        return
1552
1528
                    
1553
 
                    if client.approved or not client.approval_delay:
 
1529
                    if client._approved or not client.approval_delay:
1554
1530
                        #We are approved or approval is disabled
1555
1531
                        break
1556
 
                    elif client.approved is None:
 
1532
                    elif client._approved is None:
1557
1533
                        logger.info("Client %s needs approval",
1558
1534
                                    client.name)
1559
1535
                        if self.server.use_dbus:
1573
1549
                    time = datetime.datetime.now()
1574
1550
                    client.changedstate.acquire()
1575
1551
                    (client.changedstate.wait
1576
 
                     (float(client.timedelta_to_milliseconds(delay)
 
1552
                     (float(client._timedelta_to_milliseconds(delay)
1577
1553
                            / 1000)))
1578
1554
                    client.changedstate.release()
1579
1555
                    time2 = datetime.datetime.now()
1687
1663
    def sub_process_main(self, request, address):
1688
1664
        try:
1689
1665
            self.finish_request(request, address)
1690
 
        except Exception:
 
1666
        except:
1691
1667
            self.handle_error(request, address)
1692
1668
        self.close_request(request)
1693
1669
    
2072
2048
                                     stored_state_file)
2073
2049
    
2074
2050
    if debug:
2075
 
        initlogger(debug, logging.DEBUG)
 
2051
        initlogger(logging.DEBUG)
2076
2052
    else:
2077
2053
        if not debuglevel:
2078
 
            initlogger(debug)
 
2054
            initlogger()
2079
2055
        else:
2080
2056
            level = getattr(logging, debuglevel.upper())
2081
 
            initlogger(debug, level)
 
2057
            initlogger(level)
2082
2058
    
2083
2059
    if server_settings["servicename"] != "Mandos":
2084
2060
        syslogger.setFormatter(logging.Formatter
2087
2063
                                % server_settings["servicename"]))
2088
2064
    
2089
2065
    # Parse config file with clients
2090
 
    client_config = configparser.SafeConfigParser(Client
2091
 
                                                  .client_defaults)
 
2066
    client_defaults = { "timeout": "5m",
 
2067
                        "extended_timeout": "15m",
 
2068
                        "interval": "2m",
 
2069
                        "checker": "fping -q -- %%(host)s",
 
2070
                        "host": "",
 
2071
                        "approval_delay": "0s",
 
2072
                        "approval_duration": "1s",
 
2073
                        }
 
2074
    client_config = configparser.SafeConfigParser(client_defaults)
2092
2075
    client_config.read(os.path.join(server_settings["configdir"],
2093
2076
                                    "clients.conf"))
2094
2077
    
2151
2134
        os.dup2(null, sys.stdin.fileno())
2152
2135
        if null > 2:
2153
2136
            os.close(null)
 
2137
    else:
 
2138
        # No console logging
 
2139
        logger.removeHandler(console)
2154
2140
    
2155
2141
    # Need to fork before connecting to D-Bus
2156
2142
    if not debug:
2157
2143
        # Close all input and output, do double fork, etc.
2158
2144
        daemon()
2159
2145
    
2160
 
    gobject.threads_init()
2161
 
    
2162
2146
    global main_loop
2163
2147
    # From the Avahi example code
2164
2148
    DBusGMainLoop(set_as_default=True )
2194
2178
        client_class = functools.partial(ClientDBusTransitional,
2195
2179
                                         bus = bus)
2196
2180
    
2197
 
    client_settings = Client.config_parser(client_config)
 
2181
    special_settings = {
 
2182
        # Some settings need to be accessd by special methods;
 
2183
        # booleans need .getboolean(), etc.  Here is a list of them:
 
2184
        "approved_by_default":
 
2185
            lambda section:
 
2186
            client_config.getboolean(section, "approved_by_default"),
 
2187
        "enabled":
 
2188
            lambda section:
 
2189
            client_config.getboolean(section, "enabled"),
 
2190
        }
 
2191
    # Construct a new dict of client settings of this form:
 
2192
    # { client_name: {setting_name: value, ...}, ...}
 
2193
    # with exceptions for any special settings as defined above
 
2194
    client_settings = dict((clientname,
 
2195
                           dict((setting,
 
2196
                                 (value
 
2197
                                  if setting not in special_settings
 
2198
                                  else special_settings[setting]
 
2199
                                  (clientname)))
 
2200
                                for setting, value in
 
2201
                                client_config.items(clientname)))
 
2202
                          for clientname in client_config.sections())
 
2203
    
2198
2204
    old_client_settings = {}
2199
 
    clients_data = {}
 
2205
    clients_data = []
2200
2206
    
2201
2207
    # Get client data and settings from last running state.
2202
2208
    if server_settings["restore"]:
2210
2216
                           .format(e))
2211
2217
            if e.errno != errno.ENOENT:
2212
2218
                raise
2213
 
        except EOFError as e:
2214
 
            logger.warning("Could not load persistent state: "
2215
 
                           "EOFError: {0}".format(e))
2216
2219
    
2217
 
    with PGPEngine() as pgp:
2218
 
        for client_name, client in clients_data.iteritems():
 
2220
    with Crypto() as crypt:
 
2221
        for client in clients_data:
 
2222
            client_name = client["name"]
 
2223
            
2219
2224
            # Decide which value to use after restoring saved state.
2220
2225
            # We have three different values: Old config file,
2221
2226
            # new config file, and saved state.
2229
2234
                    if (name != "secret" and
2230
2235
                        value != old_client_settings[client_name]
2231
2236
                        [name]):
2232
 
                        client[name] = value
 
2237
                        setattr(client, name, value)
2233
2238
                except KeyError:
2234
2239
                    pass
2235
2240
            
2236
2241
            # Clients who has passed its expire date can still be
2237
 
            # enabled if its last checker was successful.  Clients
2238
 
            # whose checker succeeded before we stored its state is
2239
 
            # assumed to have successfully run all checkers during
2240
 
            # downtime.
2241
 
            if client["enabled"]:
2242
 
                if datetime.datetime.utcnow() >= client["expires"]:
2243
 
                    if not client["last_checked_ok"]:
2244
 
                        logger.warning(
2245
 
                            "disabling client {0} - Client never "
2246
 
                            "performed a successful checker"
2247
 
                            .format(client_name))
2248
 
                        client["enabled"] = False
2249
 
                    elif client["last_checker_status"] != 0:
2250
 
                        logger.warning(
2251
 
                            "disabling client {0} - Client "
2252
 
                            "last checker failed with error code {1}"
2253
 
                            .format(client_name,
2254
 
                                    client["last_checker_status"]))
 
2242
            # enabled if its last checker was sucessful.  Clients
 
2243
            # whose checker failed before we stored its state is
 
2244
            # assumed to have failed all checkers during downtime.
 
2245
            if client["enabled"] and client["last_checked_ok"]:
 
2246
                if ((datetime.datetime.utcnow()
 
2247
                     - client["last_checked_ok"])
 
2248
                    > client["interval"]):
 
2249
                    if client["last_checker_status"] != 0:
2255
2250
                        client["enabled"] = False
2256
2251
                    else:
2257
2252
                        client["expires"] = (datetime.datetime
2258
2253
                                             .utcnow()
2259
2254
                                             + client["timeout"])
2260
 
                        logger.debug("Last checker succeeded,"
2261
 
                                     " keeping {0} enabled"
2262
 
                                     .format(client_name))
 
2255
            
 
2256
            client["changedstate"] = (multiprocessing_manager
 
2257
                                      .Condition
 
2258
                                      (multiprocessing_manager
 
2259
                                       .Lock()))
 
2260
            if use_dbus:
 
2261
                new_client = (ClientDBusTransitional.__new__
 
2262
                              (ClientDBusTransitional))
 
2263
                tcp_server.clients[client_name] = new_client
 
2264
                new_client.bus = bus
 
2265
                for name, value in client.iteritems():
 
2266
                    setattr(new_client, name, value)
 
2267
                client_object_name = unicode(client_name).translate(
 
2268
                    {ord("."): ord("_"),
 
2269
                     ord("-"): ord("_")})
 
2270
                new_client.dbus_object_path = (dbus.ObjectPath
 
2271
                                               ("/clients/"
 
2272
                                                + client_object_name))
 
2273
                DBusObjectWithProperties.__init__(new_client,
 
2274
                                                  new_client.bus,
 
2275
                                                  new_client
 
2276
                                                  .dbus_object_path)
 
2277
            else:
 
2278
                tcp_server.clients[client_name] = (Client.__new__
 
2279
                                                   (Client))
 
2280
                for name, value in client.iteritems():
 
2281
                    setattr(tcp_server.clients[client_name],
 
2282
                            name, value)
 
2283
            
2263
2284
            try:
2264
 
                client["secret"] = (
2265
 
                    pgp.decrypt(client["encrypted_secret"],
2266
 
                                client_settings[client_name]
2267
 
                                ["secret"]))
2268
 
            except PGPError:
 
2285
                tcp_server.clients[client_name].secret = (
 
2286
                    crypt.decrypt(tcp_server.clients[client_name]
 
2287
                                  .encrypted_secret,
 
2288
                                  client_settings[client_name]
 
2289
                                  ["secret"]))
 
2290
            except CryptoError:
2269
2291
                # If decryption fails, we use secret from new settings
2270
 
                logger.debug("Failed to decrypt {0} old secret"
2271
 
                             .format(client_name))
2272
 
                client["secret"] = (
 
2292
                tcp_server.clients[client_name].secret = (
2273
2293
                    client_settings[client_name]["secret"])
2274
 
 
2275
2294
    
2276
 
    # Add/remove clients based on new changes made to config
2277
 
    for client_name in (set(old_client_settings)
2278
 
                        - set(client_settings)):
2279
 
        del clients_data[client_name]
2280
 
    for client_name in (set(client_settings)
2281
 
                        - set(old_client_settings)):
2282
 
        clients_data[client_name] = client_settings[client_name]
2283
 
 
2284
 
    # Create all client objects
2285
 
    for client_name, client in clients_data.iteritems():
2286
 
        tcp_server.clients[client_name] = client_class(
2287
 
            name = client_name, settings = client)
 
2295
    # Create/remove clients based on new changes made to config
 
2296
    for clientname in set(old_client_settings) - set(client_settings):
 
2297
        del tcp_server.clients[clientname]
 
2298
    for clientname in set(client_settings) - set(old_client_settings):
 
2299
        tcp_server.clients[clientname] = (client_class(name
 
2300
                                                       = clientname,
 
2301
                                                       config =
 
2302
                                                       client_settings
 
2303
                                                       [clientname]))
2288
2304
    
2289
2305
    if not tcp_server.clients:
2290
2306
        logger.warning("No clients defined")
2302
2318
            # "pidfile" was never created
2303
2319
            pass
2304
2320
        del pidfilename
 
2321
        
2305
2322
        signal.signal(signal.SIGINT, signal.SIG_IGN)
2306
2323
    
2307
2324
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
2376
2393
        # Store client before exiting. Secrets are encrypted with key
2377
2394
        # based on what config file has. If config file is
2378
2395
        # removed/edited, old secret will thus be unrecovable.
2379
 
        clients = {}
2380
 
        with PGPEngine() as pgp:
 
2396
        clients = []
 
2397
        with Crypto() as crypt:
2381
2398
            for client in tcp_server.clients.itervalues():
2382
2399
                key = client_settings[client.name]["secret"]
2383
 
                client.encrypted_secret = pgp.encrypt(client.secret,
2384
 
                                                      key)
 
2400
                client.encrypted_secret = crypt.encrypt(client.secret,
 
2401
                                                        key)
2385
2402
                client_dict = {}
2386
2403
                
2387
 
                # A list of attributes that can not be pickled
2388
 
                # + secret.
2389
 
                exclude = set(("bus", "changedstate", "secret",
2390
 
                               "checker"))
 
2404
                # A list of attributes that will not be stored when
 
2405
                # shutting down.
 
2406
                exclude = set(("bus", "changedstate", "secret"))
2391
2407
                for name, typ in (inspect.getmembers
2392
2408
                                  (dbus.service.Object)):
2393
2409
                    exclude.add(name)
2398
2414
                    if attr not in exclude:
2399
2415
                        client_dict[attr] = getattr(client, attr)
2400
2416
                
2401
 
                clients[client.name] = client_dict
 
2417
                clients.append(client_dict)
2402
2418
                del client_settings[client.name]["secret"]
2403
2419
        
2404
2420
        try:
2405
 
            tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2406
 
                                                prefix="clients-",
2407
 
                                                dir=os.path.dirname
2408
 
                                                (stored_state_path))
2409
 
            with os.fdopen(tempfd, "wb") as stored_state:
 
2421
            with os.fdopen(os.open(stored_state_path,
 
2422
                                   os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
 
2423
                                   0600), "wb") as stored_state:
2410
2424
                pickle.dump((clients, client_settings), stored_state)
2411
 
            os.rename(tempname, stored_state_path)
2412
2425
        except (IOError, OSError) as e:
2413
2426
            logger.warning("Could not save persistent state: {0}"
2414
2427
                           .format(e))
2415
 
            if not debug:
2416
 
                try:
2417
 
                    os.remove(tempname)
2418
 
                except NameError:
2419
 
                    pass
2420
 
            if e.errno not in set((errno.ENOENT, errno.EACCES,
2421
 
                                   errno.EEXIST)):
2422
 
                raise e
 
2428
            if e.errno not in (errno.ENOENT, errno.EACCES):
 
2429
                raise
2423
2430
        
2424
2431
        # Delete all clients, and settings from config
2425
2432
        while tcp_server.clients:
2489
2496
    # Must run before the D-Bus bus name gets deregistered
2490
2497
    cleanup()
2491
2498
 
 
2499
 
2492
2500
if __name__ == '__main__':
2493
2501
    main()