/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-02-16 02:42:42 UTC
  • Revision ID: teddy@recompile.se-20140216024242-9wiw1nkxgt7ohovj
Fix running of self-tests.

* debian/control (Build-Depends): Add Python dependencies to
                                  successfully run self-tests.
* debian/copyright: GPLv3 now has its own license file - use it.
* debian/watch: Set PGP signature URL.
* mandos (main): Bug fix: When running self-tests, set exit code.
* mandos-ctl (main): Cosmetic fix; use os.EX_OK instead of plain 0.

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
 
if sys.version_info.major == 2:
92
 
    str = unicode
93
 
 
94
 
version = "1.6.8"
 
91
version = "1.6.3"
95
92
stored_state_file = "clients.pickle"
96
93
 
97
94
logger = logging.getLogger()
98
 
syslogger = None
 
95
syslogger = (logging.handlers.SysLogHandler
 
96
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
 
97
              address = str("/dev/log")))
99
98
 
100
99
try:
101
100
    if_nametoindex = (ctypes.cdll.LoadLibrary
107
106
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
108
107
        with contextlib.closing(socket.socket()) as s:
109
108
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
110
 
                                struct.pack(b"16s16x", interface))
111
 
        interface_index = struct.unpack("I", ifreq[16:20])[0]
 
109
                                struct.pack(str("16s16x"),
 
110
                                            interface))
 
111
        interface_index = struct.unpack(str("I"),
 
112
                                        ifreq[16:20])[0]
112
113
        return interface_index
113
114
 
114
115
 
115
116
def initlogger(debug, level=logging.WARNING):
116
117
    """init logger and add loglevel"""
117
118
    
118
 
    global syslogger
119
 
    syslogger = (logging.handlers.SysLogHandler
120
 
                 (facility =
121
 
                  logging.handlers.SysLogHandler.LOG_DAEMON,
122
 
                  address = "/dev/log"))
123
119
    syslogger.setFormatter(logging.Formatter
124
120
                           ('Mandos [%(process)d]: %(levelname)s:'
125
121
                            ' %(message)s'))
225
221
class AvahiError(Exception):
226
222
    def __init__(self, value, *args, **kwargs):
227
223
        self.value = value
228
 
        return super(AvahiError, self).__init__(value, *args,
229
 
                                                **kwargs)
 
224
        super(AvahiError, self).__init__(value, *args, **kwargs)
 
225
    def __unicode__(self):
 
226
        return unicode(repr(self.value))
230
227
 
231
228
class AvahiServiceError(AvahiError):
232
229
    pass
282
279
                            " after %i retries, exiting.",
283
280
                            self.rename_count)
284
281
            raise AvahiServiceError("Too many renames")
285
 
        self.name = str(self.server
286
 
                        .GetAlternativeServiceName(self.name))
 
282
        self.name = unicode(self.server
 
283
                            .GetAlternativeServiceName(self.name))
287
284
        logger.info("Changing Zeroconf service name to %r ...",
288
285
                    self.name)
289
286
        self.remove()
337
334
            self.rename()
338
335
        elif state == avahi.ENTRY_GROUP_FAILURE:
339
336
            logger.critical("Avahi: Error in group state changed %s",
340
 
                            str(error))
341
 
            raise AvahiGroupError("State changed: {!s}"
 
337
                            unicode(error))
 
338
            raise AvahiGroupError("State changed: {0!s}"
342
339
                                  .format(error))
343
340
    
344
341
    def cleanup(self):
395
392
        """Add the new name to the syslog messages"""
396
393
        ret = AvahiService.rename(self)
397
394
        syslogger.setFormatter(logging.Formatter
398
 
                               ('Mandos ({}) [%(process)d]:'
 
395
                               ('Mandos ({0}) [%(process)d]:'
399
396
                                ' %(levelname)s: %(message)s'
400
397
                                .format(self.name)))
401
398
        return ret
402
399
 
403
400
 
 
401
def timedelta_to_milliseconds(td):
 
402
    "Convert a datetime.timedelta() to milliseconds"
 
403
    return ((td.days * 24 * 60 * 60 * 1000)
 
404
            + (td.seconds * 1000)
 
405
            + (td.microseconds // 1000))
 
406
 
 
407
 
404
408
class Client(object):
405
409
    """A representation of a client host served by this server.
406
410
    
461
465
                        "enabled": "True",
462
466
                        }
463
467
    
 
468
    def timeout_milliseconds(self):
 
469
        "Return the 'timeout' attribute in milliseconds"
 
470
        return timedelta_to_milliseconds(self.timeout)
 
471
    
 
472
    def extended_timeout_milliseconds(self):
 
473
        "Return the 'extended_timeout' attribute in milliseconds"
 
474
        return timedelta_to_milliseconds(self.extended_timeout)
 
475
    
 
476
    def interval_milliseconds(self):
 
477
        "Return the 'interval' attribute in milliseconds"
 
478
        return timedelta_to_milliseconds(self.interval)
 
479
    
 
480
    def approval_delay_milliseconds(self):
 
481
        return timedelta_to_milliseconds(self.approval_delay)
 
482
    
464
483
    @staticmethod
465
484
    def config_parser(config):
466
485
        """Construct a new dict of client settings of this form:
491
510
                          "rb") as secfile:
492
511
                    client["secret"] = secfile.read()
493
512
            else:
494
 
                raise TypeError("No secret or secfile for section {}"
 
513
                raise TypeError("No secret or secfile for section {0}"
495
514
                                .format(section))
496
515
            client["timeout"] = string_to_delta(section["timeout"])
497
516
            client["extended_timeout"] = string_to_delta(
514
533
            server_settings = {}
515
534
        self.server_settings = server_settings
516
535
        # adding all client settings
517
 
        for setting, value in settings.items():
 
536
        for setting, value in settings.iteritems():
518
537
            setattr(self, setting, value)
519
538
        
520
539
        if self.enabled:
603
622
        if self.checker_initiator_tag is not None:
604
623
            gobject.source_remove(self.checker_initiator_tag)
605
624
        self.checker_initiator_tag = (gobject.timeout_add
606
 
                                      (int(self.interval
607
 
                                           .total_seconds() * 1000),
 
625
                                      (self.interval_milliseconds(),
608
626
                                       self.start_checker))
609
627
        # Schedule a disable() when 'timeout' has passed
610
628
        if self.disable_initiator_tag is not None:
611
629
            gobject.source_remove(self.disable_initiator_tag)
612
630
        self.disable_initiator_tag = (gobject.timeout_add
613
 
                                      (int(self.timeout
614
 
                                           .total_seconds() * 1000),
615
 
                                       self.disable))
 
631
                                   (self.timeout_milliseconds(),
 
632
                                    self.disable))
616
633
        # Also start a new checker *right now*.
617
634
        self.start_checker()
618
635
    
649
666
            self.disable_initiator_tag = None
650
667
        if getattr(self, "enabled", False):
651
668
            self.disable_initiator_tag = (gobject.timeout_add
652
 
                                          (int(timeout.total_seconds()
653
 
                                               * 1000), self.disable))
 
669
                                          (timedelta_to_milliseconds
 
670
                                           (timeout), self.disable))
654
671
            self.expires = datetime.datetime.utcnow() + timeout
655
672
    
656
673
    def need_approval(self):
687
704
        # Start a new checker if needed
688
705
        if self.checker is None:
689
706
            # Escape attributes for the shell
690
 
            escaped_attrs = { attr:
691
 
                                  re.escape(str(getattr(self, attr)))
692
 
                              for attr in self.runtime_expansions }
 
707
            escaped_attrs = dict(
 
708
                (attr, re.escape(unicode(getattr(self, attr))))
 
709
                for attr in
 
710
                self.runtime_expansions)
693
711
            try:
694
712
                command = self.checker_command % escaped_attrs
695
713
            except TypeError as error:
776
794
    # "Set" method, so we fail early here:
777
795
    if byte_arrays and signature != "ay":
778
796
        raise ValueError("Byte arrays not supported for non-'ay'"
779
 
                         " signature {!r}".format(signature))
 
797
                         " signature {0!r}".format(signature))
780
798
    def decorator(func):
781
799
        func._dbus_is_property = True
782
800
        func._dbus_interface = dbus_interface
813
831
    """Decorator to annotate D-Bus methods, signals or properties
814
832
    Usage:
815
833
    
816
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
817
 
                       "org.freedesktop.DBus.Property."
818
 
                       "EmitsChangedSignal": "false"})
819
834
    @dbus_service_property("org.example.Interface", signature="b",
820
835
                           access="r")
 
836
    @dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
 
837
                        "org.freedesktop.DBus.Property."
 
838
                        "EmitsChangedSignal": "false"})
821
839
    def Property_dbus_property(self):
822
840
        return dbus.Boolean(False)
823
841
    """
830
848
class DBusPropertyException(dbus.exceptions.DBusException):
831
849
    """A base class for D-Bus property-related exceptions
832
850
    """
833
 
    pass
 
851
    def __unicode__(self):
 
852
        return unicode(str(self))
 
853
 
834
854
 
835
855
class DBusPropertyAccessException(DBusPropertyException):
836
856
    """A property's access permissions disallows an operation.
859
879
        If called like _is_dbus_thing("method") it returns a function
860
880
        suitable for use as predicate to inspect.getmembers().
861
881
        """
862
 
        return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
 
882
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
863
883
                                   False)
864
884
    
865
885
    def _get_all_dbus_things(self, thing):
915
935
            # signatures other than "ay".
916
936
            if prop._dbus_signature != "ay":
917
937
                raise ValueError("Byte arrays not supported for non-"
918
 
                                 "'ay' signature {!r}"
 
938
                                 "'ay' signature {0!r}"
919
939
                                 .format(prop._dbus_signature))
920
940
            value = dbus.ByteArray(b''.join(chr(byte)
921
941
                                            for byte in value))
946
966
                                           value.variant_level+1)
947
967
        return dbus.Dictionary(properties, signature="sv")
948
968
    
949
 
    @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
950
 
    def PropertiesChanged(self, interface_name, changed_properties,
951
 
                          invalidated_properties):
952
 
        """Standard D-Bus PropertiesChanged() signal, see D-Bus
953
 
        standard.
954
 
        """
955
 
        pass
956
 
    
957
969
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
958
970
                         out_signature="s",
959
971
                         path_keyword='object_path',
994
1006
                                              (prop,
995
1007
                                               "_dbus_annotations",
996
1008
                                               {}))
997
 
                        for name, value in annots.items():
 
1009
                        for name, value in annots.iteritems():
998
1010
                            ann_tag = document.createElement(
999
1011
                                "annotation")
1000
1012
                            ann_tag.setAttribute("name", name)
1003
1015
                # Add interface annotation tags
1004
1016
                for annotation, value in dict(
1005
1017
                    itertools.chain.from_iterable(
1006
 
                        annotations().items()
 
1018
                        annotations().iteritems()
1007
1019
                        for name, annotations in
1008
1020
                        self._get_all_dbus_things("interface")
1009
1021
                        if name == if_tag.getAttribute("name")
1010
 
                        )).items():
 
1022
                        )).iteritems():
1011
1023
                    ann_tag = document.createElement("annotation")
1012
1024
                    ann_tag.setAttribute("name", annotation)
1013
1025
                    ann_tag.setAttribute("value", value)
1069
1081
    """
1070
1082
    def wrapper(cls):
1071
1083
        for orig_interface_name, alt_interface_name in (
1072
 
            alt_interface_names.items()):
 
1084
            alt_interface_names.iteritems()):
1073
1085
            attr = {}
1074
1086
            interface_names = set()
1075
1087
            # Go though all attributes of the class
1192
1204
                                        attribute.func_closure)))
1193
1205
            if deprecate:
1194
1206
                # Deprecate all alternate interfaces
1195
 
                iname="_AlternateDBusNames_interface_annotation{}"
 
1207
                iname="_AlternateDBusNames_interface_annotation{0}"
1196
1208
                for interface_name in interface_names:
1197
1209
                    @dbus_interface_annotations(interface_name)
1198
1210
                    def func(self):
1207
1219
            if interface_names:
1208
1220
                # Replace the class with a new subclass of it with
1209
1221
                # methods, signals, etc. as created above.
1210
 
                cls = type(b"{}Alternate".format(cls.__name__),
 
1222
                cls = type(b"{0}Alternate".format(cls.__name__),
1211
1223
                           (cls,), attr)
1212
1224
        return cls
1213
1225
    return wrapper
1226
1238
    runtime_expansions = (Client.runtime_expansions
1227
1239
                          + ("dbus_object_path",))
1228
1240
    
1229
 
    _interface = "se.recompile.Mandos.Client"
1230
 
    
1231
1241
    # dbus.service.Object doesn't use super(), so we can't either.
1232
1242
    
1233
1243
    def __init__(self, bus = None, *args, **kwargs):
1235
1245
        Client.__init__(self, *args, **kwargs)
1236
1246
        # Only now, when this client is initialized, can it show up on
1237
1247
        # the D-Bus
1238
 
        client_object_name = str(self.name).translate(
 
1248
        client_object_name = unicode(self.name).translate(
1239
1249
            {ord("."): ord("_"),
1240
1250
             ord("-"): ord("_")})
1241
1251
        self.dbus_object_path = (dbus.ObjectPath
1245
1255
    
1246
1256
    def notifychangeproperty(transform_func,
1247
1257
                             dbus_name, type_func=lambda x: x,
1248
 
                             variant_level=1, invalidate_only=False,
1249
 
                             _interface=_interface):
 
1258
                             variant_level=1):
1250
1259
        """ Modify a variable so that it's a property which announces
1251
1260
        its changes to DBus.
1252
1261
        
1257
1266
                   to the D-Bus.  Default: no transform
1258
1267
        variant_level: D-Bus variant level.  Default: 1
1259
1268
        """
1260
 
        attrname = "_{}".format(dbus_name)
 
1269
        attrname = "_{0}".format(dbus_name)
1261
1270
        def setter(self, value):
1262
1271
            if hasattr(self, "dbus_object_path"):
1263
1272
                if (not hasattr(self, attrname) or
1264
1273
                    type_func(getattr(self, attrname, None))
1265
1274
                    != type_func(value)):
1266
 
                    if invalidate_only:
1267
 
                        self.PropertiesChanged(_interface,
1268
 
                                               dbus.Dictionary(),
1269
 
                                               dbus.Array
1270
 
                                               ((dbus_name,)))
1271
 
                    else:
1272
 
                        dbus_value = transform_func(type_func(value),
1273
 
                                                    variant_level
1274
 
                                                    =variant_level)
1275
 
                        self.PropertyChanged(dbus.String(dbus_name),
1276
 
                                             dbus_value)
1277
 
                        self.PropertiesChanged(_interface,
1278
 
                                               dbus.Dictionary({
1279
 
                                    dbus.String(dbus_name):
1280
 
                                        dbus_value }), dbus.Array())
 
1275
                    dbus_value = transform_func(type_func(value),
 
1276
                                                variant_level
 
1277
                                                =variant_level)
 
1278
                    self.PropertyChanged(dbus.String(dbus_name),
 
1279
                                         dbus_value)
1281
1280
            setattr(self, attrname, value)
1282
1281
        
1283
1282
        return property(lambda self: getattr(self, attrname), setter)
1303
1302
    approval_delay = notifychangeproperty(dbus.UInt64,
1304
1303
                                          "ApprovalDelay",
1305
1304
                                          type_func =
1306
 
                                          lambda td: td.total_seconds()
1307
 
                                          * 1000)
 
1305
                                          timedelta_to_milliseconds)
1308
1306
    approval_duration = notifychangeproperty(
1309
1307
        dbus.UInt64, "ApprovalDuration",
1310
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1308
        type_func = timedelta_to_milliseconds)
1311
1309
    host = notifychangeproperty(dbus.String, "Host")
1312
1310
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1313
 
                                   type_func = lambda td:
1314
 
                                       td.total_seconds() * 1000)
 
1311
                                   type_func =
 
1312
                                   timedelta_to_milliseconds)
1315
1313
    extended_timeout = notifychangeproperty(
1316
1314
        dbus.UInt64, "ExtendedTimeout",
1317
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1315
        type_func = timedelta_to_milliseconds)
1318
1316
    interval = notifychangeproperty(dbus.UInt64,
1319
1317
                                    "Interval",
1320
1318
                                    type_func =
1321
 
                                    lambda td: td.total_seconds()
1322
 
                                    * 1000)
 
1319
                                    timedelta_to_milliseconds)
1323
1320
    checker_command = notifychangeproperty(dbus.String, "Checker")
1324
 
    secret = notifychangeproperty(dbus.ByteArray, "Secret",
1325
 
                                  invalidate_only=True)
1326
1321
    
1327
1322
    del notifychangeproperty
1328
1323
    
1355
1350
                                       *args, **kwargs)
1356
1351
    
1357
1352
    def start_checker(self, *args, **kwargs):
1358
 
        old_checker_pid = getattr(self.checker, "pid", None)
 
1353
        old_checker = self.checker
 
1354
        if self.checker is not None:
 
1355
            old_checker_pid = self.checker.pid
 
1356
        else:
 
1357
            old_checker_pid = None
1359
1358
        r = Client.start_checker(self, *args, **kwargs)
1360
1359
        # Only if new checker process was started
1361
1360
        if (self.checker is not None
1370
1369
    
1371
1370
    def approve(self, value=True):
1372
1371
        self.approved = value
1373
 
        gobject.timeout_add(int(self.approval_duration.total_seconds()
1374
 
                                * 1000), self._reset_approved)
 
1372
        gobject.timeout_add(timedelta_to_milliseconds
 
1373
                            (self.approval_duration),
 
1374
                            self._reset_approved)
1375
1375
        self.send_changedstate()
1376
1376
    
1377
1377
    ## D-Bus methods, signals & properties
 
1378
    _interface = "se.recompile.Mandos.Client"
1378
1379
    
1379
1380
    ## Interfaces
1380
1381
    
 
1382
    @dbus_interface_annotations(_interface)
 
1383
    def _foo(self):
 
1384
        return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
 
1385
                     "false"}
 
1386
    
1381
1387
    ## Signals
1382
1388
    
1383
1389
    # CheckerCompleted - signal
1393
1399
        pass
1394
1400
    
1395
1401
    # PropertyChanged - signal
1396
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1397
1402
    @dbus.service.signal(_interface, signature="sv")
1398
1403
    def PropertyChanged(self, property, value):
1399
1404
        "D-Bus signal"
1475
1480
                           access="readwrite")
1476
1481
    def ApprovalDelay_dbus_property(self, value=None):
1477
1482
        if value is None:       # get
1478
 
            return dbus.UInt64(self.approval_delay.total_seconds()
1479
 
                               * 1000)
 
1483
            return dbus.UInt64(self.approval_delay_milliseconds())
1480
1484
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1481
1485
    
1482
1486
    # ApprovalDuration - property
1484
1488
                           access="readwrite")
1485
1489
    def ApprovalDuration_dbus_property(self, value=None):
1486
1490
        if value is None:       # get
1487
 
            return dbus.UInt64(self.approval_duration.total_seconds()
1488
 
                               * 1000)
 
1491
            return dbus.UInt64(timedelta_to_milliseconds(
 
1492
                    self.approval_duration))
1489
1493
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1490
1494
    
1491
1495
    # Name - property
1504
1508
    def Host_dbus_property(self, value=None):
1505
1509
        if value is None:       # get
1506
1510
            return dbus.String(self.host)
1507
 
        self.host = str(value)
 
1511
        self.host = unicode(value)
1508
1512
    
1509
1513
    # Created - property
1510
1514
    @dbus_service_property(_interface, signature="s", access="read")
1557
1561
                           access="readwrite")
1558
1562
    def Timeout_dbus_property(self, value=None):
1559
1563
        if value is None:       # get
1560
 
            return dbus.UInt64(self.timeout.total_seconds() * 1000)
 
1564
            return dbus.UInt64(self.timeout_milliseconds())
1561
1565
        old_timeout = self.timeout
1562
1566
        self.timeout = datetime.timedelta(0, 0, 0, value)
1563
1567
        # Reschedule disabling
1574
1578
                gobject.source_remove(self.disable_initiator_tag)
1575
1579
                self.disable_initiator_tag = (
1576
1580
                    gobject.timeout_add(
1577
 
                        int((self.expires - now).total_seconds()
1578
 
                            * 1000), self.disable))
 
1581
                        timedelta_to_milliseconds(self.expires - now),
 
1582
                        self.disable))
1579
1583
    
1580
1584
    # ExtendedTimeout - property
1581
1585
    @dbus_service_property(_interface, signature="t",
1582
1586
                           access="readwrite")
1583
1587
    def ExtendedTimeout_dbus_property(self, value=None):
1584
1588
        if value is None:       # get
1585
 
            return dbus.UInt64(self.extended_timeout.total_seconds()
1586
 
                               * 1000)
 
1589
            return dbus.UInt64(self.extended_timeout_milliseconds())
1587
1590
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1588
1591
    
1589
1592
    # Interval - property
1591
1594
                           access="readwrite")
1592
1595
    def Interval_dbus_property(self, value=None):
1593
1596
        if value is None:       # get
1594
 
            return dbus.UInt64(self.interval.total_seconds() * 1000)
 
1597
            return dbus.UInt64(self.interval_milliseconds())
1595
1598
        self.interval = datetime.timedelta(0, 0, 0, value)
1596
1599
        if getattr(self, "checker_initiator_tag", None) is None:
1597
1600
            return
1608
1611
    def Checker_dbus_property(self, value=None):
1609
1612
        if value is None:       # get
1610
1613
            return dbus.String(self.checker_command)
1611
 
        self.checker_command = str(value)
 
1614
        self.checker_command = unicode(value)
1612
1615
    
1613
1616
    # CheckerRunning - property
1614
1617
    @dbus_service_property(_interface, signature="b",
1630
1633
    @dbus_service_property(_interface, signature="ay",
1631
1634
                           access="write", byte_arrays=True)
1632
1635
    def Secret_dbus_property(self, value):
1633
 
        self.secret = bytes(value)
 
1636
        self.secret = str(value)
1634
1637
    
1635
1638
    del _interface
1636
1639
 
1670
1673
    def handle(self):
1671
1674
        with contextlib.closing(self.server.child_pipe) as child_pipe:
1672
1675
            logger.info("TCP connection from: %s",
1673
 
                        str(self.client_address))
 
1676
                        unicode(self.client_address))
1674
1677
            logger.debug("Pipe FD: %d",
1675
1678
                         self.server.child_pipe.fileno())
1676
1679
            
1757
1760
                        if self.server.use_dbus:
1758
1761
                            # Emit D-Bus signal
1759
1762
                            client.NeedApproval(
1760
 
                                client.approval_delay.total_seconds()
1761
 
                                * 1000, client.approved_by_default)
 
1763
                                client.approval_delay_milliseconds(),
 
1764
                                client.approved_by_default)
1762
1765
                    else:
1763
1766
                        logger.warning("Client %s was not approved",
1764
1767
                                       client.name)
1770
1773
                    #wait until timeout or approved
1771
1774
                    time = datetime.datetime.now()
1772
1775
                    client.changedstate.acquire()
1773
 
                    client.changedstate.wait(delay.total_seconds())
 
1776
                    client.changedstate.wait(
 
1777
                        float(timedelta_to_milliseconds(delay)
 
1778
                              / 1000))
1774
1779
                    client.changedstate.release()
1775
1780
                    time2 = datetime.datetime.now()
1776
1781
                    if (time2 - time) >= delay:
1975
1980
                try:
1976
1981
                    self.socket.setsockopt(socket.SOL_SOCKET,
1977
1982
                                           SO_BINDTODEVICE,
1978
 
                                           (self.interface + "\0")
1979
 
                                           .encode("utf-8"))
 
1983
                                           str(self.interface + '\0'))
1980
1984
                except socket.error as error:
1981
1985
                    if error.errno == errno.EPERM:
1982
1986
                        logger.error("No permission to bind to"
2185
2189
    token_duration = Token(re.compile(r"P"), None,
2186
2190
                           frozenset((token_year, token_month,
2187
2191
                                      token_day, token_time,
2188
 
                                      token_week)))
 
2192
                                      token_week))),
2189
2193
    # Define starting values
2190
2194
    value = datetime.timedelta() # Value so far
2191
2195
    found_token = None
2192
 
    followers = frozenset((token_duration,)) # Following valid tokens
 
2196
    followers = frozenset(token_duration,) # Following valid tokens
2193
2197
    s = duration                # String left to parse
2194
2198
    # Loop until end token is found
2195
2199
    while found_token is not token_end:
2242
2246
    timevalue = datetime.timedelta(0)
2243
2247
    for s in interval.split():
2244
2248
        try:
2245
 
            suffix = s[-1]
 
2249
            suffix = unicode(s[-1])
2246
2250
            value = int(s[:-1])
2247
2251
            if suffix == "d":
2248
2252
                delta = datetime.timedelta(value)
2255
2259
            elif suffix == "w":
2256
2260
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2257
2261
            else:
2258
 
                raise ValueError("Unknown suffix {!r}"
 
2262
                raise ValueError("Unknown suffix {0!r}"
2259
2263
                                 .format(suffix))
2260
2264
        except IndexError as e:
2261
2265
            raise ValueError(*(e.args))
2278
2282
        # Close all standard open file descriptors
2279
2283
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2280
2284
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2281
 
            raise OSError(errno.ENODEV, "{} not a character device"
 
2285
            raise OSError(errno.ENODEV,
 
2286
                          "{0} not a character device"
2282
2287
                          .format(os.devnull))
2283
2288
        os.dup2(null, sys.stdin.fileno())
2284
2289
        os.dup2(null, sys.stdout.fileno())
2294
2299
    
2295
2300
    parser = argparse.ArgumentParser()
2296
2301
    parser.add_argument("-v", "--version", action="version",
2297
 
                        version = "%(prog)s {}".format(version),
 
2302
                        version = "%(prog)s {0}".format(version),
2298
2303
                        help="show version number and exit")
2299
2304
    parser.add_argument("-i", "--interface", metavar="IF",
2300
2305
                        help="Bind to interface IF")
2333
2338
                        help="Directory to save/restore state in")
2334
2339
    parser.add_argument("--foreground", action="store_true",
2335
2340
                        help="Run in foreground", default=None)
2336
 
    parser.add_argument("--no-zeroconf", action="store_false",
2337
 
                        dest="zeroconf", help="Do not use Zeroconf",
2338
 
                        default=None)
2339
2341
    
2340
2342
    options = parser.parse_args()
2341
2343
    
2359
2361
                        "socket": "",
2360
2362
                        "statedir": "/var/lib/mandos",
2361
2363
                        "foreground": "False",
2362
 
                        "zeroconf": "True",
2363
2364
                        }
2364
2365
    
2365
2366
    # Parse config file for server-global settings
2392
2393
    for option in ("interface", "address", "port", "debug",
2393
2394
                   "priority", "servicename", "configdir",
2394
2395
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
2395
 
                   "statedir", "socket", "foreground", "zeroconf"):
 
2396
                   "statedir", "socket", "foreground"):
2396
2397
        value = getattr(options, option)
2397
2398
        if value is not None:
2398
2399
            server_settings[option] = value
2399
2400
    del options
2400
2401
    # Force all strings to be unicode
2401
2402
    for option in server_settings.keys():
2402
 
        if isinstance(server_settings[option], bytes):
2403
 
            server_settings[option] = (server_settings[option]
2404
 
                                       .decode("utf-8"))
 
2403
        if type(server_settings[option]) is str:
 
2404
            server_settings[option] = unicode(server_settings[option])
2405
2405
    # Force all boolean options to be boolean
2406
2406
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2407
 
                   "foreground", "zeroconf"):
 
2407
                   "foreground"):
2408
2408
        server_settings[option] = bool(server_settings[option])
2409
2409
    # Debug implies foreground
2410
2410
    if server_settings["debug"]:
2413
2413
    
2414
2414
    ##################################################################
2415
2415
    
2416
 
    if (not server_settings["zeroconf"] and
2417
 
        not (server_settings["port"]
2418
 
             or server_settings["socket"] != "")):
2419
 
            parser.error("Needs port or socket to work without"
2420
 
                         " Zeroconf")
2421
 
    
2422
2416
    # For convenience
2423
2417
    debug = server_settings["debug"]
2424
2418
    debuglevel = server_settings["debuglevel"]
2427
2421
    stored_state_path = os.path.join(server_settings["statedir"],
2428
2422
                                     stored_state_file)
2429
2423
    foreground = server_settings["foreground"]
2430
 
    zeroconf = server_settings["zeroconf"]
2431
2424
    
2432
2425
    if debug:
2433
2426
        initlogger(debug, logging.DEBUG)
2440
2433
    
2441
2434
    if server_settings["servicename"] != "Mandos":
2442
2435
        syslogger.setFormatter(logging.Formatter
2443
 
                               ('Mandos ({}) [%(process)d]:'
 
2436
                               ('Mandos ({0}) [%(process)d]:'
2444
2437
                                ' %(levelname)s: %(message)s'
2445
2438
                                .format(server_settings
2446
2439
                                        ["servicename"])))
2454
2447
    global mandos_dbus_service
2455
2448
    mandos_dbus_service = None
2456
2449
    
2457
 
    socketfd = None
2458
 
    if server_settings["socket"] != "":
2459
 
        socketfd = server_settings["socket"]
2460
2450
    tcp_server = MandosServer((server_settings["address"],
2461
2451
                               server_settings["port"]),
2462
2452
                              ClientHandler,
2466
2456
                              gnutls_priority=
2467
2457
                              server_settings["priority"],
2468
2458
                              use_dbus=use_dbus,
2469
 
                              socketfd=socketfd)
 
2459
                              socketfd=(server_settings["socket"]
 
2460
                                        or None))
2470
2461
    if not foreground:
2471
2462
        pidfilename = "/run/mandos.pid"
2472
2463
        if not os.path.isdir("/run/."):
2542
2533
            use_dbus = False
2543
2534
            server_settings["use_dbus"] = False
2544
2535
            tcp_server.use_dbus = False
2545
 
    if zeroconf:
2546
 
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2547
 
        service = AvahiServiceToSyslog(name =
2548
 
                                       server_settings["servicename"],
2549
 
                                       servicetype = "_mandos._tcp",
2550
 
                                       protocol = protocol, bus = bus)
2551
 
        if server_settings["interface"]:
2552
 
            service.interface = (if_nametoindex
2553
 
                                 (server_settings["interface"]
2554
 
                                  .encode("utf-8")))
 
2536
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
2537
    service = AvahiServiceToSyslog(name =
 
2538
                                   server_settings["servicename"],
 
2539
                                   servicetype = "_mandos._tcp",
 
2540
                                   protocol = protocol, bus = bus)
 
2541
    if server_settings["interface"]:
 
2542
        service.interface = (if_nametoindex
 
2543
                             (str(server_settings["interface"])))
2555
2544
    
2556
2545
    global multiprocessing_manager
2557
2546
    multiprocessing_manager = multiprocessing.Manager()
2581
2570
            os.remove(stored_state_path)
2582
2571
        except IOError as e:
2583
2572
            if e.errno == errno.ENOENT:
2584
 
                logger.warning("Could not load persistent state: {}"
 
2573
                logger.warning("Could not load persistent state: {0}"
2585
2574
                                .format(os.strerror(e.errno)))
2586
2575
            else:
2587
2576
                logger.critical("Could not load persistent state:",
2592
2581
                           "EOFError:", exc_info=e)
2593
2582
    
2594
2583
    with PGPEngine() as pgp:
2595
 
        for client_name, client in clients_data.items():
 
2584
        for client_name, client in clients_data.iteritems():
2596
2585
            # Skip removed clients
2597
2586
            if client_name not in client_settings:
2598
2587
                continue
2623
2612
                if datetime.datetime.utcnow() >= client["expires"]:
2624
2613
                    if not client["last_checked_ok"]:
2625
2614
                        logger.warning(
2626
 
                            "disabling client {} - Client never "
 
2615
                            "disabling client {0} - Client never "
2627
2616
                            "performed a successful checker"
2628
2617
                            .format(client_name))
2629
2618
                        client["enabled"] = False
2630
2619
                    elif client["last_checker_status"] != 0:
2631
2620
                        logger.warning(
2632
 
                            "disabling client {} - Client last"
2633
 
                            " checker failed with error code {}"
 
2621
                            "disabling client {0} - Client "
 
2622
                            "last checker failed with error code {1}"
2634
2623
                            .format(client_name,
2635
2624
                                    client["last_checker_status"]))
2636
2625
                        client["enabled"] = False
2639
2628
                                             .utcnow()
2640
2629
                                             + client["timeout"])
2641
2630
                        logger.debug("Last checker succeeded,"
2642
 
                                     " keeping {} enabled"
 
2631
                                     " keeping {0} enabled"
2643
2632
                                     .format(client_name))
2644
2633
            try:
2645
2634
                client["secret"] = (
2648
2637
                                ["secret"]))
2649
2638
            except PGPError:
2650
2639
                # If decryption fails, we use secret from new settings
2651
 
                logger.debug("Failed to decrypt {} old secret"
 
2640
                logger.debug("Failed to decrypt {0} old secret"
2652
2641
                             .format(client_name))
2653
2642
                client["secret"] = (
2654
2643
                    client_settings[client_name]["secret"])
2662
2651
        clients_data[client_name] = client_settings[client_name]
2663
2652
    
2664
2653
    # Create all client objects
2665
 
    for client_name, client in clients_data.items():
 
2654
    for client_name, client in clients_data.iteritems():
2666
2655
        tcp_server.clients[client_name] = client_class(
2667
2656
            name = client_name, settings = client,
2668
2657
            server_settings = server_settings)
2675
2664
            try:
2676
2665
                with pidfile:
2677
2666
                    pid = os.getpid()
2678
 
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
 
2667
                    pidfile.write(str(pid) + "\n".encode("utf-8"))
2679
2668
            except IOError:
2680
2669
                logger.error("Could not write to file %r with PID %d",
2681
2670
                             pidfilename, pid)
2727
2716
            def GetAllClientsWithProperties(self):
2728
2717
                "D-Bus method"
2729
2718
                return dbus.Dictionary(
2730
 
                    { c.dbus_object_path: c.GetAll("")
2731
 
                      for c in tcp_server.clients.itervalues() },
 
2719
                    ((c.dbus_object_path, c.GetAll(""))
 
2720
                     for c in tcp_server.clients.itervalues()),
2732
2721
                    signature="oa{sv}")
2733
2722
            
2734
2723
            @dbus.service.method(_interface, in_signature="o")
2751
2740
    
2752
2741
    def cleanup():
2753
2742
        "Cleanup function; run on exit"
2754
 
        if zeroconf:
2755
 
            service.cleanup()
 
2743
        service.cleanup()
2756
2744
        
2757
2745
        multiprocessing.active_children()
2758
2746
        wnull.close()
2772
2760
                
2773
2761
                # A list of attributes that can not be pickled
2774
2762
                # + secret.
2775
 
                exclude = { "bus", "changedstate", "secret",
2776
 
                            "checker", "server_settings" }
 
2763
                exclude = set(("bus", "changedstate", "secret",
 
2764
                               "checker", "server_settings"))
2777
2765
                for name, typ in (inspect.getmembers
2778
2766
                                  (dbus.service.Object)):
2779
2767
                    exclude.add(name)
2802
2790
                except NameError:
2803
2791
                    pass
2804
2792
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2805
 
                logger.warning("Could not save persistent state: {}"
 
2793
                logger.warning("Could not save persistent state: {0}"
2806
2794
                               .format(os.strerror(e.errno)))
2807
2795
            else:
2808
2796
                logger.warning("Could not save persistent state:",
2837
2825
    tcp_server.server_activate()
2838
2826
    
2839
2827
    # Find out what port we got
2840
 
    if zeroconf:
2841
 
        service.port = tcp_server.socket.getsockname()[1]
 
2828
    service.port = tcp_server.socket.getsockname()[1]
2842
2829
    if use_ipv6:
2843
2830
        logger.info("Now listening on address %r, port %d,"
2844
2831
                    " flowinfo %d, scope_id %d",
2850
2837
    #service.interface = tcp_server.socket.getsockname()[3]
2851
2838
    
2852
2839
    try:
2853
 
        if zeroconf:
2854
 
            # From the Avahi example code
2855
 
            try:
2856
 
                service.activate()
2857
 
            except dbus.exceptions.DBusException as error:
2858
 
                logger.critical("D-Bus Exception", exc_info=error)
2859
 
                cleanup()
2860
 
                sys.exit(1)
2861
 
            # End of Avahi example code
 
2840
        # From the Avahi example code
 
2841
        try:
 
2842
            service.activate()
 
2843
        except dbus.exceptions.DBusException as error:
 
2844
            logger.critical("D-Bus Exception", exc_info=error)
 
2845
            cleanup()
 
2846
            sys.exit(1)
 
2847
        # End of Avahi example code
2862
2848
        
2863
2849
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2864
2850
                             lambda *args, **kwargs: