/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-15 23:52:00 UTC
  • Revision ID: teddy@recompile.se-20140715235200-4dukd7i2tvbcix61
mandos-client: Bug Fix: Fix some memory leaks.

* plugins.d/mandos-client.c (resolve_callback): Always free resolver.
  (run_network_hooks): Free the individual direntries.
  (main): When listing network interfaces and when removing the GPGME
          temp directory, free the individual direntries.

Show diffs side-by-side

added added

removed removed

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