/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: 2014-07-25 23:44:04 UTC
  • mfrom: (723.1.7 python27)
  • Revision ID: teddy@recompile.se-20140725234404-m6c733af4i3zs0la
Merge from Python 2.7 branch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python
 
1
#!/usr/bin/python2.7
2
2
# -*- mode: python; coding: utf-8 -*-
3
3
4
4
# Mandos server - give out binary blobs to connecting clients.
338
338
        elif state == avahi.ENTRY_GROUP_FAILURE:
339
339
            logger.critical("Avahi: Error in group state changed %s",
340
340
                            unicode(error))
341
 
            raise AvahiGroupError("State changed: {0!s}"
 
341
            raise AvahiGroupError("State changed: {!s}"
342
342
                                  .format(error))
343
343
    
344
344
    def cleanup(self):
395
395
        """Add the new name to the syslog messages"""
396
396
        ret = AvahiService.rename(self)
397
397
        syslogger.setFormatter(logging.Formatter
398
 
                               ('Mandos ({0}) [%(process)d]:'
 
398
                               ('Mandos ({}) [%(process)d]:'
399
399
                                ' %(levelname)s: %(message)s'
400
400
                                .format(self.name)))
401
401
        return ret
402
402
 
403
403
 
404
 
def timedelta_to_milliseconds(td):
405
 
    "Convert a datetime.timedelta() to milliseconds"
406
 
    return ((td.days * 24 * 60 * 60 * 1000)
407
 
            + (td.seconds * 1000)
408
 
            + (td.microseconds // 1000))
409
 
 
410
 
 
411
404
class Client(object):
412
405
    """A representation of a client host served by this server.
413
406
    
468
461
                        "enabled": "True",
469
462
                        }
470
463
    
471
 
    def timeout_milliseconds(self):
472
 
        "Return the 'timeout' attribute in milliseconds"
473
 
        return timedelta_to_milliseconds(self.timeout)
474
 
    
475
 
    def extended_timeout_milliseconds(self):
476
 
        "Return the 'extended_timeout' attribute in milliseconds"
477
 
        return timedelta_to_milliseconds(self.extended_timeout)
478
 
    
479
 
    def interval_milliseconds(self):
480
 
        "Return the 'interval' attribute in milliseconds"
481
 
        return timedelta_to_milliseconds(self.interval)
482
 
    
483
 
    def approval_delay_milliseconds(self):
484
 
        return timedelta_to_milliseconds(self.approval_delay)
485
 
    
486
464
    @staticmethod
487
465
    def config_parser(config):
488
466
        """Construct a new dict of client settings of this form:
513
491
                          "rb") as secfile:
514
492
                    client["secret"] = secfile.read()
515
493
            else:
516
 
                raise TypeError("No secret or secfile for section {0}"
 
494
                raise TypeError("No secret or secfile for section {}"
517
495
                                .format(section))
518
496
            client["timeout"] = string_to_delta(section["timeout"])
519
497
            client["extended_timeout"] = string_to_delta(
536
514
            server_settings = {}
537
515
        self.server_settings = server_settings
538
516
        # adding all client settings
539
 
        for setting, value in settings.iteritems():
 
517
        for setting, value in settings.items():
540
518
            setattr(self, setting, value)
541
519
        
542
520
        if self.enabled:
625
603
        if self.checker_initiator_tag is not None:
626
604
            gobject.source_remove(self.checker_initiator_tag)
627
605
        self.checker_initiator_tag = (gobject.timeout_add
628
 
                                      (self.interval_milliseconds(),
 
606
                                      (int(self.interval
 
607
                                           .total_seconds() * 1000),
629
608
                                       self.start_checker))
630
609
        # Schedule a disable() when 'timeout' has passed
631
610
        if self.disable_initiator_tag is not None:
632
611
            gobject.source_remove(self.disable_initiator_tag)
633
612
        self.disable_initiator_tag = (gobject.timeout_add
634
 
                                   (self.timeout_milliseconds(),
635
 
                                    self.disable))
 
613
                                      (int(self.timeout
 
614
                                           .total_seconds() * 1000),
 
615
                                       self.disable))
636
616
        # Also start a new checker *right now*.
637
617
        self.start_checker()
638
618
    
669
649
            self.disable_initiator_tag = None
670
650
        if getattr(self, "enabled", False):
671
651
            self.disable_initiator_tag = (gobject.timeout_add
672
 
                                          (timedelta_to_milliseconds
673
 
                                           (timeout), self.disable))
 
652
                                          (int(timeout.total_seconds()
 
653
                                               * 1000), self.disable))
674
654
            self.expires = datetime.datetime.utcnow() + timeout
675
655
    
676
656
    def need_approval(self):
707
687
        # Start a new checker if needed
708
688
        if self.checker is None:
709
689
            # Escape attributes for the shell
710
 
            escaped_attrs = dict(
711
 
                (attr, re.escape(unicode(getattr(self, attr))))
712
 
                for attr in
713
 
                self.runtime_expansions)
 
690
            escaped_attrs = { attr:
 
691
                                  re.escape(unicode(getattr(self,
 
692
                                                            attr)))
 
693
                              for attr in self.runtime_expansions }
714
694
            try:
715
695
                command = self.checker_command % escaped_attrs
716
696
            except TypeError as error:
797
777
    # "Set" method, so we fail early here:
798
778
    if byte_arrays and signature != "ay":
799
779
        raise ValueError("Byte arrays not supported for non-'ay'"
800
 
                         " signature {0!r}".format(signature))
 
780
                         " signature {!r}".format(signature))
801
781
    def decorator(func):
802
782
        func._dbus_is_property = True
803
783
        func._dbus_interface = dbus_interface
882
862
        If called like _is_dbus_thing("method") it returns a function
883
863
        suitable for use as predicate to inspect.getmembers().
884
864
        """
885
 
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
 
865
        return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
886
866
                                   False)
887
867
    
888
868
    def _get_all_dbus_things(self, thing):
938
918
            # signatures other than "ay".
939
919
            if prop._dbus_signature != "ay":
940
920
                raise ValueError("Byte arrays not supported for non-"
941
 
                                 "'ay' signature {0!r}"
 
921
                                 "'ay' signature {!r}"
942
922
                                 .format(prop._dbus_signature))
943
923
            value = dbus.ByteArray(b''.join(chr(byte)
944
924
                                            for byte in value))
1009
989
                                              (prop,
1010
990
                                               "_dbus_annotations",
1011
991
                                               {}))
1012
 
                        for name, value in annots.iteritems():
 
992
                        for name, value in annots.items():
1013
993
                            ann_tag = document.createElement(
1014
994
                                "annotation")
1015
995
                            ann_tag.setAttribute("name", name)
1018
998
                # Add interface annotation tags
1019
999
                for annotation, value in dict(
1020
1000
                    itertools.chain.from_iterable(
1021
 
                        annotations().iteritems()
 
1001
                        annotations().items()
1022
1002
                        for name, annotations in
1023
1003
                        self._get_all_dbus_things("interface")
1024
1004
                        if name == if_tag.getAttribute("name")
1025
 
                        )).iteritems():
 
1005
                        )).items():
1026
1006
                    ann_tag = document.createElement("annotation")
1027
1007
                    ann_tag.setAttribute("name", annotation)
1028
1008
                    ann_tag.setAttribute("value", value)
1084
1064
    """
1085
1065
    def wrapper(cls):
1086
1066
        for orig_interface_name, alt_interface_name in (
1087
 
            alt_interface_names.iteritems()):
 
1067
            alt_interface_names.items()):
1088
1068
            attr = {}
1089
1069
            interface_names = set()
1090
1070
            # Go though all attributes of the class
1207
1187
                                        attribute.func_closure)))
1208
1188
            if deprecate:
1209
1189
                # Deprecate all alternate interfaces
1210
 
                iname="_AlternateDBusNames_interface_annotation{0}"
 
1190
                iname="_AlternateDBusNames_interface_annotation{}"
1211
1191
                for interface_name in interface_names:
1212
1192
                    @dbus_interface_annotations(interface_name)
1213
1193
                    def func(self):
1222
1202
            if interface_names:
1223
1203
                # Replace the class with a new subclass of it with
1224
1204
                # methods, signals, etc. as created above.
1225
 
                cls = type(b"{0}Alternate".format(cls.__name__),
 
1205
                cls = type(b"{}Alternate".format(cls.__name__),
1226
1206
                           (cls,), attr)
1227
1207
        return cls
1228
1208
    return wrapper
1269
1249
                   to the D-Bus.  Default: no transform
1270
1250
        variant_level: D-Bus variant level.  Default: 1
1271
1251
        """
1272
 
        attrname = "_{0}".format(dbus_name)
 
1252
        attrname = "_{}".format(dbus_name)
1273
1253
        def setter(self, value):
1274
1254
            if hasattr(self, "dbus_object_path"):
1275
1255
                if (not hasattr(self, attrname) or
1305
1285
    approval_delay = notifychangeproperty(dbus.UInt64,
1306
1286
                                          "ApprovalDelay",
1307
1287
                                          type_func =
1308
 
                                          timedelta_to_milliseconds)
 
1288
                                          lambda td: td.total_seconds()
 
1289
                                          * 1000)
1309
1290
    approval_duration = notifychangeproperty(
1310
1291
        dbus.UInt64, "ApprovalDuration",
1311
 
        type_func = timedelta_to_milliseconds)
 
1292
        type_func = lambda td: td.total_seconds() * 1000)
1312
1293
    host = notifychangeproperty(dbus.String, "Host")
1313
1294
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1314
 
                                   type_func =
1315
 
                                   timedelta_to_milliseconds)
 
1295
                                   type_func = lambda td:
 
1296
                                       td.total_seconds() * 1000)
1316
1297
    extended_timeout = notifychangeproperty(
1317
1298
        dbus.UInt64, "ExtendedTimeout",
1318
 
        type_func = timedelta_to_milliseconds)
 
1299
        type_func = lambda td: td.total_seconds() * 1000)
1319
1300
    interval = notifychangeproperty(dbus.UInt64,
1320
1301
                                    "Interval",
1321
1302
                                    type_func =
1322
 
                                    timedelta_to_milliseconds)
 
1303
                                    lambda td: td.total_seconds()
 
1304
                                    * 1000)
1323
1305
    checker_command = notifychangeproperty(dbus.String, "Checker")
1324
1306
    
1325
1307
    del notifychangeproperty
1368
1350
    
1369
1351
    def approve(self, value=True):
1370
1352
        self.approved = value
1371
 
        gobject.timeout_add(timedelta_to_milliseconds
1372
 
                            (self.approval_duration),
1373
 
                            self._reset_approved)
 
1353
        gobject.timeout_add(int(self.approval_duration.total_seconds()
 
1354
                                * 1000), self._reset_approved)
1374
1355
        self.send_changedstate()
1375
1356
    
1376
1357
    ## D-Bus methods, signals & properties
1479
1460
                           access="readwrite")
1480
1461
    def ApprovalDelay_dbus_property(self, value=None):
1481
1462
        if value is None:       # get
1482
 
            return dbus.UInt64(self.approval_delay_milliseconds())
 
1463
            return dbus.UInt64(self.approval_delay.total_seconds()
 
1464
                               * 1000)
1483
1465
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1484
1466
    
1485
1467
    # ApprovalDuration - property
1487
1469
                           access="readwrite")
1488
1470
    def ApprovalDuration_dbus_property(self, value=None):
1489
1471
        if value is None:       # get
1490
 
            return dbus.UInt64(timedelta_to_milliseconds(
1491
 
                    self.approval_duration))
 
1472
            return dbus.UInt64(self.approval_duration.total_seconds()
 
1473
                               * 1000)
1492
1474
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1493
1475
    
1494
1476
    # Name - property
1560
1542
                           access="readwrite")
1561
1543
    def Timeout_dbus_property(self, value=None):
1562
1544
        if value is None:       # get
1563
 
            return dbus.UInt64(self.timeout_milliseconds())
 
1545
            return dbus.UInt64(self.timeout.total_seconds() * 1000)
1564
1546
        old_timeout = self.timeout
1565
1547
        self.timeout = datetime.timedelta(0, 0, 0, value)
1566
1548
        # Reschedule disabling
1577
1559
                gobject.source_remove(self.disable_initiator_tag)
1578
1560
                self.disable_initiator_tag = (
1579
1561
                    gobject.timeout_add(
1580
 
                        timedelta_to_milliseconds(self.expires - now),
1581
 
                        self.disable))
 
1562
                        int((self.expires - now).total_seconds()
 
1563
                            * 1000), self.disable))
1582
1564
    
1583
1565
    # ExtendedTimeout - property
1584
1566
    @dbus_service_property(_interface, signature="t",
1585
1567
                           access="readwrite")
1586
1568
    def ExtendedTimeout_dbus_property(self, value=None):
1587
1569
        if value is None:       # get
1588
 
            return dbus.UInt64(self.extended_timeout_milliseconds())
 
1570
            return dbus.UInt64(self.extended_timeout.total_seconds()
 
1571
                               * 1000)
1589
1572
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1590
1573
    
1591
1574
    # Interval - property
1593
1576
                           access="readwrite")
1594
1577
    def Interval_dbus_property(self, value=None):
1595
1578
        if value is None:       # get
1596
 
            return dbus.UInt64(self.interval_milliseconds())
 
1579
            return dbus.UInt64(self.interval.total_seconds() * 1000)
1597
1580
        self.interval = datetime.timedelta(0, 0, 0, value)
1598
1581
        if getattr(self, "checker_initiator_tag", None) is None:
1599
1582
            return
1759
1742
                        if self.server.use_dbus:
1760
1743
                            # Emit D-Bus signal
1761
1744
                            client.NeedApproval(
1762
 
                                client.approval_delay_milliseconds(),
1763
 
                                client.approved_by_default)
 
1745
                                client.approval_delay.total_seconds()
 
1746
                                * 1000, client.approved_by_default)
1764
1747
                    else:
1765
1748
                        logger.warning("Client %s was not approved",
1766
1749
                                       client.name)
1772
1755
                    #wait until timeout or approved
1773
1756
                    time = datetime.datetime.now()
1774
1757
                    client.changedstate.acquire()
1775
 
                    client.changedstate.wait(
1776
 
                        float(timedelta_to_milliseconds(delay)
1777
 
                              / 1000))
 
1758
                    client.changedstate.wait(delay.total_seconds())
1778
1759
                    client.changedstate.release()
1779
1760
                    time2 = datetime.datetime.now()
1780
1761
                    if (time2 - time) >= delay:
2258
2239
            elif suffix == "w":
2259
2240
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2260
2241
            else:
2261
 
                raise ValueError("Unknown suffix {0!r}"
 
2242
                raise ValueError("Unknown suffix {!r}"
2262
2243
                                 .format(suffix))
2263
2244
        except IndexError as e:
2264
2245
            raise ValueError(*(e.args))
2281
2262
        # Close all standard open file descriptors
2282
2263
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2283
2264
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2284
 
            raise OSError(errno.ENODEV,
2285
 
                          "{0} not a character device"
 
2265
            raise OSError(errno.ENODEV, "{} not a character device"
2286
2266
                          .format(os.devnull))
2287
2267
        os.dup2(null, sys.stdin.fileno())
2288
2268
        os.dup2(null, sys.stdout.fileno())
2298
2278
    
2299
2279
    parser = argparse.ArgumentParser()
2300
2280
    parser.add_argument("-v", "--version", action="version",
2301
 
                        version = "%(prog)s {0}".format(version),
 
2281
                        version = "%(prog)s {}".format(version),
2302
2282
                        help="show version number and exit")
2303
2283
    parser.add_argument("-i", "--interface", metavar="IF",
2304
2284
                        help="Bind to interface IF")
2443
2423
    
2444
2424
    if server_settings["servicename"] != "Mandos":
2445
2425
        syslogger.setFormatter(logging.Formatter
2446
 
                               ('Mandos ({0}) [%(process)d]:'
 
2426
                               ('Mandos ({}) [%(process)d]:'
2447
2427
                                ' %(levelname)s: %(message)s'
2448
2428
                                .format(server_settings
2449
2429
                                        ["servicename"])))
2583
2563
            os.remove(stored_state_path)
2584
2564
        except IOError as e:
2585
2565
            if e.errno == errno.ENOENT:
2586
 
                logger.warning("Could not load persistent state: {0}"
 
2566
                logger.warning("Could not load persistent state: {}"
2587
2567
                                .format(os.strerror(e.errno)))
2588
2568
            else:
2589
2569
                logger.critical("Could not load persistent state:",
2594
2574
                           "EOFError:", exc_info=e)
2595
2575
    
2596
2576
    with PGPEngine() as pgp:
2597
 
        for client_name, client in clients_data.iteritems():
 
2577
        for client_name, client in clients_data.items():
2598
2578
            # Skip removed clients
2599
2579
            if client_name not in client_settings:
2600
2580
                continue
2625
2605
                if datetime.datetime.utcnow() >= client["expires"]:
2626
2606
                    if not client["last_checked_ok"]:
2627
2607
                        logger.warning(
2628
 
                            "disabling client {0} - Client never "
 
2608
                            "disabling client {} - Client never "
2629
2609
                            "performed a successful checker"
2630
2610
                            .format(client_name))
2631
2611
                        client["enabled"] = False
2632
2612
                    elif client["last_checker_status"] != 0:
2633
2613
                        logger.warning(
2634
 
                            "disabling client {0} - Client "
2635
 
                            "last checker failed with error code {1}"
 
2614
                            "disabling client {} - Client last"
 
2615
                            " checker failed with error code {}"
2636
2616
                            .format(client_name,
2637
2617
                                    client["last_checker_status"]))
2638
2618
                        client["enabled"] = False
2641
2621
                                             .utcnow()
2642
2622
                                             + client["timeout"])
2643
2623
                        logger.debug("Last checker succeeded,"
2644
 
                                     " keeping {0} enabled"
 
2624
                                     " keeping {} enabled"
2645
2625
                                     .format(client_name))
2646
2626
            try:
2647
2627
                client["secret"] = (
2650
2630
                                ["secret"]))
2651
2631
            except PGPError:
2652
2632
                # If decryption fails, we use secret from new settings
2653
 
                logger.debug("Failed to decrypt {0} old secret"
 
2633
                logger.debug("Failed to decrypt {} old secret"
2654
2634
                             .format(client_name))
2655
2635
                client["secret"] = (
2656
2636
                    client_settings[client_name]["secret"])
2664
2644
        clients_data[client_name] = client_settings[client_name]
2665
2645
    
2666
2646
    # Create all client objects
2667
 
    for client_name, client in clients_data.iteritems():
 
2647
    for client_name, client in clients_data.items():
2668
2648
        tcp_server.clients[client_name] = client_class(
2669
2649
            name = client_name, settings = client,
2670
2650
            server_settings = server_settings)
2774
2754
                
2775
2755
                # A list of attributes that can not be pickled
2776
2756
                # + secret.
2777
 
                exclude = set(("bus", "changedstate", "secret",
2778
 
                               "checker", "server_settings"))
 
2757
                exclude = { "bus", "changedstate", "secret",
 
2758
                            "checker", "server_settings" }
2779
2759
                for name, typ in (inspect.getmembers
2780
2760
                                  (dbus.service.Object)):
2781
2761
                    exclude.add(name)
2804
2784
                except NameError:
2805
2785
                    pass
2806
2786
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2807
 
                logger.warning("Could not save persistent state: {0}"
 
2787
                logger.warning("Could not save persistent state: {}"
2808
2788
                               .format(os.strerror(e.errno)))
2809
2789
            else:
2810
2790
                logger.warning("Could not save persistent state:",