/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2013-10-28 20:08:32 UTC
  • mto: (237.7.272 trunk)
  • mto: This revision was merged to the branch mainline in revision 307.
  • Revision ID: teddy@recompile.se-20131028200832-80d1k8c5e8mugpkx
Syntax fix; use "raise" better in Mandos server.

* mandos: Syntax fix; use "raise" better in Mandos server; Always
          raise instances, not classes, skip argument when re-raising,
          etc.

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.
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008-2014 Teddy Hogeborn
15
 
# Copyright © 2008-2014 Björn Påhlsson
 
14
# Copyright © 2008-2013 Teddy Hogeborn
 
15
# Copyright © 2008-2013 Björn Påhlsson
16
16
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
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.9"
 
91
version = "1.6.2"
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
275
272
        self.bus = bus
276
273
        self.entry_group_state_changed_match = None
277
274
    
278
 
    def rename(self, remove=True):
 
275
    def rename(self):
279
276
        """Derived from the Avahi example code"""
280
277
        if self.rename_count >= self.max_renames:
281
278
            logger.critical("No suitable Zeroconf service name found"
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))
287
 
        self.rename_count += 1
 
282
        self.name = unicode(self.server
 
283
                            .GetAlternativeServiceName(self.name))
288
284
        logger.info("Changing Zeroconf service name to %r ...",
289
285
                    self.name)
290
 
        if remove:
291
 
            self.remove()
 
286
        self.remove()
292
287
        try:
293
288
            self.add()
294
289
        except dbus.exceptions.DBusException as error:
295
 
            if (error.get_dbus_name()
296
 
                == "org.freedesktop.Avahi.CollisionError"):
297
 
                logger.info("Local Zeroconf service name collision.")
298
 
                return self.rename(remove=False)
299
 
            else:
300
 
                logger.critical("D-Bus Exception", exc_info=error)
301
 
                self.cleanup()
302
 
                os._exit(1)
 
290
            logger.critical("D-Bus Exception", exc_info=error)
 
291
            self.cleanup()
 
292
            os._exit(1)
 
293
        self.rename_count += 1
303
294
    
304
295
    def remove(self):
305
296
        """Derived from the Avahi example code"""
343
334
            self.rename()
344
335
        elif state == avahi.ENTRY_GROUP_FAILURE:
345
336
            logger.critical("Avahi: Error in group state changed %s",
346
 
                            str(error))
347
 
            raise AvahiGroupError("State changed: {!s}"
 
337
                            unicode(error))
 
338
            raise AvahiGroupError("State changed: {0!s}"
348
339
                                  .format(error))
349
340
    
350
341
    def cleanup(self):
397
388
 
398
389
 
399
390
class AvahiServiceToSyslog(AvahiService):
400
 
    def rename(self, *args, **kwargs):
 
391
    def rename(self):
401
392
        """Add the new name to the syslog messages"""
402
 
        ret = AvahiService.rename(self, *args, **kwargs)
 
393
        ret = AvahiService.rename(self)
403
394
        syslogger.setFormatter(logging.Formatter
404
 
                               ('Mandos ({}) [%(process)d]:'
 
395
                               ('Mandos ({0}) [%(process)d]:'
405
396
                                ' %(levelname)s: %(message)s'
406
397
                                .format(self.name)))
407
398
        return ret
408
399
 
409
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
 
410
408
class Client(object):
411
409
    """A representation of a client host served by this server.
412
410
    
467
465
                        "enabled": "True",
468
466
                        }
469
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
    
470
483
    @staticmethod
471
484
    def config_parser(config):
472
485
        """Construct a new dict of client settings of this form:
487
500
            client["enabled"] = config.getboolean(client_name,
488
501
                                                  "enabled")
489
502
            
490
 
            # Uppercase and remove spaces from fingerprint for later
491
 
            # comparison purposes with return value from the
492
 
            # fingerprint() function
493
503
            client["fingerprint"] = (section["fingerprint"].upper()
494
504
                                     .replace(" ", ""))
495
505
            if "secret" in section:
500
510
                          "rb") as secfile:
501
511
                    client["secret"] = secfile.read()
502
512
            else:
503
 
                raise TypeError("No secret or secfile for section {}"
 
513
                raise TypeError("No secret or secfile for section {0}"
504
514
                                .format(section))
505
515
            client["timeout"] = string_to_delta(section["timeout"])
506
516
            client["extended_timeout"] = string_to_delta(
523
533
            server_settings = {}
524
534
        self.server_settings = server_settings
525
535
        # adding all client settings
526
 
        for setting, value in settings.items():
 
536
        for setting, value in settings.iteritems():
527
537
            setattr(self, setting, value)
528
538
        
529
539
        if self.enabled:
537
547
            self.expires = None
538
548
        
539
549
        logger.debug("Creating client %r", self.name)
 
550
        # Uppercase and remove spaces from fingerprint for later
 
551
        # comparison purposes with return value from the fingerprint()
 
552
        # function
540
553
        logger.debug("  Fingerprint: %s", self.fingerprint)
541
554
        self.created = settings.get("created",
542
555
                                    datetime.datetime.utcnow())
609
622
        if self.checker_initiator_tag is not None:
610
623
            gobject.source_remove(self.checker_initiator_tag)
611
624
        self.checker_initiator_tag = (gobject.timeout_add
612
 
                                      (int(self.interval
613
 
                                           .total_seconds() * 1000),
 
625
                                      (self.interval_milliseconds(),
614
626
                                       self.start_checker))
615
627
        # Schedule a disable() when 'timeout' has passed
616
628
        if self.disable_initiator_tag is not None:
617
629
            gobject.source_remove(self.disable_initiator_tag)
618
630
        self.disable_initiator_tag = (gobject.timeout_add
619
 
                                      (int(self.timeout
620
 
                                           .total_seconds() * 1000),
621
 
                                       self.disable))
 
631
                                   (self.timeout_milliseconds(),
 
632
                                    self.disable))
622
633
        # Also start a new checker *right now*.
623
634
        self.start_checker()
624
635
    
655
666
            self.disable_initiator_tag = None
656
667
        if getattr(self, "enabled", False):
657
668
            self.disable_initiator_tag = (gobject.timeout_add
658
 
                                          (int(timeout.total_seconds()
659
 
                                               * 1000), self.disable))
 
669
                                          (timedelta_to_milliseconds
 
670
                                           (timeout), self.disable))
660
671
            self.expires = datetime.datetime.utcnow() + timeout
661
672
    
662
673
    def need_approval(self):
693
704
        # Start a new checker if needed
694
705
        if self.checker is None:
695
706
            # Escape attributes for the shell
696
 
            escaped_attrs = { attr:
697
 
                                  re.escape(str(getattr(self, attr)))
698
 
                              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)
699
711
            try:
700
712
                command = self.checker_command % escaped_attrs
701
713
            except TypeError as error:
782
794
    # "Set" method, so we fail early here:
783
795
    if byte_arrays and signature != "ay":
784
796
        raise ValueError("Byte arrays not supported for non-'ay'"
785
 
                         " signature {!r}".format(signature))
 
797
                         " signature {0!r}".format(signature))
786
798
    def decorator(func):
787
799
        func._dbus_is_property = True
788
800
        func._dbus_interface = dbus_interface
819
831
    """Decorator to annotate D-Bus methods, signals or properties
820
832
    Usage:
821
833
    
822
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true",
823
 
                       "org.freedesktop.DBus.Property."
824
 
                       "EmitsChangedSignal": "false"})
825
834
    @dbus_service_property("org.example.Interface", signature="b",
826
835
                           access="r")
 
836
    @dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true",
 
837
                        "org.freedesktop.DBus.Property."
 
838
                        "EmitsChangedSignal": "false"})
827
839
    def Property_dbus_property(self):
828
840
        return dbus.Boolean(False)
829
841
    """
836
848
class DBusPropertyException(dbus.exceptions.DBusException):
837
849
    """A base class for D-Bus property-related exceptions
838
850
    """
839
 
    pass
 
851
    def __unicode__(self):
 
852
        return unicode(str(self))
 
853
 
840
854
 
841
855
class DBusPropertyAccessException(DBusPropertyException):
842
856
    """A property's access permissions disallows an operation.
865
879
        If called like _is_dbus_thing("method") it returns a function
866
880
        suitable for use as predicate to inspect.getmembers().
867
881
        """
868
 
        return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
 
882
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
869
883
                                   False)
870
884
    
871
885
    def _get_all_dbus_things(self, thing):
920
934
            # The byte_arrays option is not supported yet on
921
935
            # signatures other than "ay".
922
936
            if prop._dbus_signature != "ay":
923
 
                raise ValueError("Byte arrays not supported for non-"
924
 
                                 "'ay' signature {!r}"
925
 
                                 .format(prop._dbus_signature))
 
937
                raise ValueError
926
938
            value = dbus.ByteArray(b''.join(chr(byte)
927
939
                                            for byte in value))
928
940
        prop(value)
952
964
                                           value.variant_level+1)
953
965
        return dbus.Dictionary(properties, signature="sv")
954
966
    
955
 
    @dbus.service.signal(dbus.PROPERTIES_IFACE, signature="sa{sv}as")
956
 
    def PropertiesChanged(self, interface_name, changed_properties,
957
 
                          invalidated_properties):
958
 
        """Standard D-Bus PropertiesChanged() signal, see D-Bus
959
 
        standard.
960
 
        """
961
 
        pass
962
 
    
963
967
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
964
968
                         out_signature="s",
965
969
                         path_keyword='object_path',
1000
1004
                                              (prop,
1001
1005
                                               "_dbus_annotations",
1002
1006
                                               {}))
1003
 
                        for name, value in annots.items():
 
1007
                        for name, value in annots.iteritems():
1004
1008
                            ann_tag = document.createElement(
1005
1009
                                "annotation")
1006
1010
                            ann_tag.setAttribute("name", name)
1009
1013
                # Add interface annotation tags
1010
1014
                for annotation, value in dict(
1011
1015
                    itertools.chain.from_iterable(
1012
 
                        annotations().items()
 
1016
                        annotations().iteritems()
1013
1017
                        for name, annotations in
1014
1018
                        self._get_all_dbus_things("interface")
1015
1019
                        if name == if_tag.getAttribute("name")
1016
 
                        )).items():
 
1020
                        )).iteritems():
1017
1021
                    ann_tag = document.createElement("annotation")
1018
1022
                    ann_tag.setAttribute("name", annotation)
1019
1023
                    ann_tag.setAttribute("value", value)
1075
1079
    """
1076
1080
    def wrapper(cls):
1077
1081
        for orig_interface_name, alt_interface_name in (
1078
 
            alt_interface_names.items()):
 
1082
            alt_interface_names.iteritems()):
1079
1083
            attr = {}
1080
1084
            interface_names = set()
1081
1085
            # Go though all attributes of the class
1198
1202
                                        attribute.func_closure)))
1199
1203
            if deprecate:
1200
1204
                # Deprecate all alternate interfaces
1201
 
                iname="_AlternateDBusNames_interface_annotation{}"
 
1205
                iname="_AlternateDBusNames_interface_annotation{0}"
1202
1206
                for interface_name in interface_names:
1203
1207
                    @dbus_interface_annotations(interface_name)
1204
1208
                    def func(self):
1213
1217
            if interface_names:
1214
1218
                # Replace the class with a new subclass of it with
1215
1219
                # methods, signals, etc. as created above.
1216
 
                cls = type(b"{}Alternate".format(cls.__name__),
 
1220
                cls = type(b"{0}Alternate".format(cls.__name__),
1217
1221
                           (cls,), attr)
1218
1222
        return cls
1219
1223
    return wrapper
1232
1236
    runtime_expansions = (Client.runtime_expansions
1233
1237
                          + ("dbus_object_path",))
1234
1238
    
1235
 
    _interface = "se.recompile.Mandos.Client"
1236
 
    
1237
1239
    # dbus.service.Object doesn't use super(), so we can't either.
1238
1240
    
1239
1241
    def __init__(self, bus = None, *args, **kwargs):
1241
1243
        Client.__init__(self, *args, **kwargs)
1242
1244
        # Only now, when this client is initialized, can it show up on
1243
1245
        # the D-Bus
1244
 
        client_object_name = str(self.name).translate(
 
1246
        client_object_name = unicode(self.name).translate(
1245
1247
            {ord("."): ord("_"),
1246
1248
             ord("-"): ord("_")})
1247
1249
        self.dbus_object_path = (dbus.ObjectPath
1251
1253
    
1252
1254
    def notifychangeproperty(transform_func,
1253
1255
                             dbus_name, type_func=lambda x: x,
1254
 
                             variant_level=1, invalidate_only=False,
1255
 
                             _interface=_interface):
 
1256
                             variant_level=1):
1256
1257
        """ Modify a variable so that it's a property which announces
1257
1258
        its changes to DBus.
1258
1259
        
1263
1264
                   to the D-Bus.  Default: no transform
1264
1265
        variant_level: D-Bus variant level.  Default: 1
1265
1266
        """
1266
 
        attrname = "_{}".format(dbus_name)
 
1267
        attrname = "_{0}".format(dbus_name)
1267
1268
        def setter(self, value):
1268
1269
            if hasattr(self, "dbus_object_path"):
1269
1270
                if (not hasattr(self, attrname) or
1270
1271
                    type_func(getattr(self, attrname, None))
1271
1272
                    != type_func(value)):
1272
 
                    if invalidate_only:
1273
 
                        self.PropertiesChanged(_interface,
1274
 
                                               dbus.Dictionary(),
1275
 
                                               dbus.Array
1276
 
                                               ((dbus_name,)))
1277
 
                    else:
1278
 
                        dbus_value = transform_func(type_func(value),
1279
 
                                                    variant_level
1280
 
                                                    =variant_level)
1281
 
                        self.PropertyChanged(dbus.String(dbus_name),
1282
 
                                             dbus_value)
1283
 
                        self.PropertiesChanged(_interface,
1284
 
                                               dbus.Dictionary({
1285
 
                                    dbus.String(dbus_name):
1286
 
                                        dbus_value }), dbus.Array())
 
1273
                    dbus_value = transform_func(type_func(value),
 
1274
                                                variant_level
 
1275
                                                =variant_level)
 
1276
                    self.PropertyChanged(dbus.String(dbus_name),
 
1277
                                         dbus_value)
1287
1278
            setattr(self, attrname, value)
1288
1279
        
1289
1280
        return property(lambda self: getattr(self, attrname), setter)
1309
1300
    approval_delay = notifychangeproperty(dbus.UInt64,
1310
1301
                                          "ApprovalDelay",
1311
1302
                                          type_func =
1312
 
                                          lambda td: td.total_seconds()
1313
 
                                          * 1000)
 
1303
                                          timedelta_to_milliseconds)
1314
1304
    approval_duration = notifychangeproperty(
1315
1305
        dbus.UInt64, "ApprovalDuration",
1316
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1306
        type_func = timedelta_to_milliseconds)
1317
1307
    host = notifychangeproperty(dbus.String, "Host")
1318
1308
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1319
 
                                   type_func = lambda td:
1320
 
                                       td.total_seconds() * 1000)
 
1309
                                   type_func =
 
1310
                                   timedelta_to_milliseconds)
1321
1311
    extended_timeout = notifychangeproperty(
1322
1312
        dbus.UInt64, "ExtendedTimeout",
1323
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1313
        type_func = timedelta_to_milliseconds)
1324
1314
    interval = notifychangeproperty(dbus.UInt64,
1325
1315
                                    "Interval",
1326
1316
                                    type_func =
1327
 
                                    lambda td: td.total_seconds()
1328
 
                                    * 1000)
 
1317
                                    timedelta_to_milliseconds)
1329
1318
    checker_command = notifychangeproperty(dbus.String, "Checker")
1330
 
    secret = notifychangeproperty(dbus.ByteArray, "Secret",
1331
 
                                  invalidate_only=True)
1332
1319
    
1333
1320
    del notifychangeproperty
1334
1321
    
1361
1348
                                       *args, **kwargs)
1362
1349
    
1363
1350
    def start_checker(self, *args, **kwargs):
1364
 
        old_checker_pid = getattr(self.checker, "pid", None)
 
1351
        old_checker = self.checker
 
1352
        if self.checker is not None:
 
1353
            old_checker_pid = self.checker.pid
 
1354
        else:
 
1355
            old_checker_pid = None
1365
1356
        r = Client.start_checker(self, *args, **kwargs)
1366
1357
        # Only if new checker process was started
1367
1358
        if (self.checker is not None
1376
1367
    
1377
1368
    def approve(self, value=True):
1378
1369
        self.approved = value
1379
 
        gobject.timeout_add(int(self.approval_duration.total_seconds()
1380
 
                                * 1000), self._reset_approved)
 
1370
        gobject.timeout_add(timedelta_to_milliseconds
 
1371
                            (self.approval_duration),
 
1372
                            self._reset_approved)
1381
1373
        self.send_changedstate()
1382
1374
    
1383
1375
    ## D-Bus methods, signals & properties
 
1376
    _interface = "se.recompile.Mandos.Client"
1384
1377
    
1385
1378
    ## Interfaces
1386
1379
    
 
1380
    @dbus_interface_annotations(_interface)
 
1381
    def _foo(self):
 
1382
        return { "org.freedesktop.DBus.Property.EmitsChangedSignal":
 
1383
                     "false"}
 
1384
    
1387
1385
    ## Signals
1388
1386
    
1389
1387
    # CheckerCompleted - signal
1399
1397
        pass
1400
1398
    
1401
1399
    # PropertyChanged - signal
1402
 
    @dbus_annotations({"org.freedesktop.DBus.Deprecated": "true"})
1403
1400
    @dbus.service.signal(_interface, signature="sv")
1404
1401
    def PropertyChanged(self, property, value):
1405
1402
        "D-Bus signal"
1481
1478
                           access="readwrite")
1482
1479
    def ApprovalDelay_dbus_property(self, value=None):
1483
1480
        if value is None:       # get
1484
 
            return dbus.UInt64(self.approval_delay.total_seconds()
1485
 
                               * 1000)
 
1481
            return dbus.UInt64(self.approval_delay_milliseconds())
1486
1482
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1487
1483
    
1488
1484
    # ApprovalDuration - property
1490
1486
                           access="readwrite")
1491
1487
    def ApprovalDuration_dbus_property(self, value=None):
1492
1488
        if value is None:       # get
1493
 
            return dbus.UInt64(self.approval_duration.total_seconds()
1494
 
                               * 1000)
 
1489
            return dbus.UInt64(timedelta_to_milliseconds(
 
1490
                    self.approval_duration))
1495
1491
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1496
1492
    
1497
1493
    # Name - property
1510
1506
    def Host_dbus_property(self, value=None):
1511
1507
        if value is None:       # get
1512
1508
            return dbus.String(self.host)
1513
 
        self.host = str(value)
 
1509
        self.host = unicode(value)
1514
1510
    
1515
1511
    # Created - property
1516
1512
    @dbus_service_property(_interface, signature="s", access="read")
1563
1559
                           access="readwrite")
1564
1560
    def Timeout_dbus_property(self, value=None):
1565
1561
        if value is None:       # get
1566
 
            return dbus.UInt64(self.timeout.total_seconds() * 1000)
 
1562
            return dbus.UInt64(self.timeout_milliseconds())
1567
1563
        old_timeout = self.timeout
1568
1564
        self.timeout = datetime.timedelta(0, 0, 0, value)
1569
1565
        # Reschedule disabling
1580
1576
                gobject.source_remove(self.disable_initiator_tag)
1581
1577
                self.disable_initiator_tag = (
1582
1578
                    gobject.timeout_add(
1583
 
                        int((self.expires - now).total_seconds()
1584
 
                            * 1000), self.disable))
 
1579
                        timedelta_to_milliseconds(self.expires - now),
 
1580
                        self.disable))
1585
1581
    
1586
1582
    # ExtendedTimeout - property
1587
1583
    @dbus_service_property(_interface, signature="t",
1588
1584
                           access="readwrite")
1589
1585
    def ExtendedTimeout_dbus_property(self, value=None):
1590
1586
        if value is None:       # get
1591
 
            return dbus.UInt64(self.extended_timeout.total_seconds()
1592
 
                               * 1000)
 
1587
            return dbus.UInt64(self.extended_timeout_milliseconds())
1593
1588
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1594
1589
    
1595
1590
    # Interval - property
1597
1592
                           access="readwrite")
1598
1593
    def Interval_dbus_property(self, value=None):
1599
1594
        if value is None:       # get
1600
 
            return dbus.UInt64(self.interval.total_seconds() * 1000)
 
1595
            return dbus.UInt64(self.interval_milliseconds())
1601
1596
        self.interval = datetime.timedelta(0, 0, 0, value)
1602
1597
        if getattr(self, "checker_initiator_tag", None) is None:
1603
1598
            return
1614
1609
    def Checker_dbus_property(self, value=None):
1615
1610
        if value is None:       # get
1616
1611
            return dbus.String(self.checker_command)
1617
 
        self.checker_command = str(value)
 
1612
        self.checker_command = unicode(value)
1618
1613
    
1619
1614
    # CheckerRunning - property
1620
1615
    @dbus_service_property(_interface, signature="b",
1636
1631
    @dbus_service_property(_interface, signature="ay",
1637
1632
                           access="write", byte_arrays=True)
1638
1633
    def Secret_dbus_property(self, value):
1639
 
        self.secret = bytes(value)
 
1634
        self.secret = str(value)
1640
1635
    
1641
1636
    del _interface
1642
1637
 
1676
1671
    def handle(self):
1677
1672
        with contextlib.closing(self.server.child_pipe) as child_pipe:
1678
1673
            logger.info("TCP connection from: %s",
1679
 
                        str(self.client_address))
 
1674
                        unicode(self.client_address))
1680
1675
            logger.debug("Pipe FD: %d",
1681
1676
                         self.server.child_pipe.fileno())
1682
1677
            
1763
1758
                        if self.server.use_dbus:
1764
1759
                            # Emit D-Bus signal
1765
1760
                            client.NeedApproval(
1766
 
                                client.approval_delay.total_seconds()
1767
 
                                * 1000, client.approved_by_default)
 
1761
                                client.approval_delay_milliseconds(),
 
1762
                                client.approved_by_default)
1768
1763
                    else:
1769
1764
                        logger.warning("Client %s was not approved",
1770
1765
                                       client.name)
1776
1771
                    #wait until timeout or approved
1777
1772
                    time = datetime.datetime.now()
1778
1773
                    client.changedstate.acquire()
1779
 
                    client.changedstate.wait(delay.total_seconds())
 
1774
                    client.changedstate.wait(
 
1775
                        float(timedelta_to_milliseconds(delay)
 
1776
                              / 1000))
1780
1777
                    client.changedstate.release()
1781
1778
                    time2 = datetime.datetime.now()
1782
1779
                    if (time2 - time) >= delay:
1981
1978
                try:
1982
1979
                    self.socket.setsockopt(socket.SOL_SOCKET,
1983
1980
                                           SO_BINDTODEVICE,
1984
 
                                           (self.interface + "\0")
1985
 
                                           .encode("utf-8"))
 
1981
                                           str(self.interface + '\0'))
1986
1982
                except socket.error as error:
1987
1983
                    if error.errno == errno.EPERM:
1988
1984
                        logger.error("No permission to bind to"
2191
2187
    token_duration = Token(re.compile(r"P"), None,
2192
2188
                           frozenset((token_year, token_month,
2193
2189
                                      token_day, token_time,
2194
 
                                      token_week)))
 
2190
                                      token_week))),
2195
2191
    # Define starting values
2196
2192
    value = datetime.timedelta() # Value so far
2197
2193
    found_token = None
2198
 
    followers = frozenset((token_duration,)) # Following valid tokens
 
2194
    followers = frozenset(token_duration,) # Following valid tokens
2199
2195
    s = duration                # String left to parse
2200
2196
    # Loop until end token is found
2201
2197
    while found_token is not token_end:
2248
2244
    timevalue = datetime.timedelta(0)
2249
2245
    for s in interval.split():
2250
2246
        try:
2251
 
            suffix = s[-1]
 
2247
            suffix = unicode(s[-1])
2252
2248
            value = int(s[:-1])
2253
2249
            if suffix == "d":
2254
2250
                delta = datetime.timedelta(value)
2261
2257
            elif suffix == "w":
2262
2258
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2263
2259
            else:
2264
 
                raise ValueError("Unknown suffix {!r}"
 
2260
                raise ValueError("Unknown suffix {0!r}"
2265
2261
                                 .format(suffix))
2266
2262
        except IndexError as e:
2267
2263
            raise ValueError(*(e.args))
2284
2280
        # Close all standard open file descriptors
2285
2281
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2286
2282
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2287
 
            raise OSError(errno.ENODEV, "{} not a character device"
 
2283
            raise OSError(errno.ENODEV,
 
2284
                          "{0} not a character device"
2288
2285
                          .format(os.devnull))
2289
2286
        os.dup2(null, sys.stdin.fileno())
2290
2287
        os.dup2(null, sys.stdout.fileno())
2300
2297
    
2301
2298
    parser = argparse.ArgumentParser()
2302
2299
    parser.add_argument("-v", "--version", action="version",
2303
 
                        version = "%(prog)s {}".format(version),
 
2300
                        version = "%(prog)s {0}".format(version),
2304
2301
                        help="show version number and exit")
2305
2302
    parser.add_argument("-i", "--interface", metavar="IF",
2306
2303
                        help="Bind to interface IF")
2339
2336
                        help="Directory to save/restore state in")
2340
2337
    parser.add_argument("--foreground", action="store_true",
2341
2338
                        help="Run in foreground", default=None)
2342
 
    parser.add_argument("--no-zeroconf", action="store_false",
2343
 
                        dest="zeroconf", help="Do not use Zeroconf",
2344
 
                        default=None)
2345
2339
    
2346
2340
    options = parser.parse_args()
2347
2341
    
2348
2342
    if options.check:
2349
2343
        import doctest
2350
 
        fail_count, test_count = doctest.testmod()
2351
 
        sys.exit(os.EX_OK if fail_count == 0 else 1)
 
2344
        doctest.testmod()
 
2345
        sys.exit()
2352
2346
    
2353
2347
    # Default values for config file for server-global settings
2354
2348
    server_defaults = { "interface": "",
2356
2350
                        "port": "",
2357
2351
                        "debug": "False",
2358
2352
                        "priority":
2359
 
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA"
2360
 
                        ":+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
 
2353
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
2361
2354
                        "servicename": "Mandos",
2362
2355
                        "use_dbus": "True",
2363
2356
                        "use_ipv6": "True",
2366
2359
                        "socket": "",
2367
2360
                        "statedir": "/var/lib/mandos",
2368
2361
                        "foreground": "False",
2369
 
                        "zeroconf": "True",
2370
2362
                        }
2371
2363
    
2372
2364
    # Parse config file for server-global settings
2399
2391
    for option in ("interface", "address", "port", "debug",
2400
2392
                   "priority", "servicename", "configdir",
2401
2393
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
2402
 
                   "statedir", "socket", "foreground", "zeroconf"):
 
2394
                   "statedir", "socket", "foreground"):
2403
2395
        value = getattr(options, option)
2404
2396
        if value is not None:
2405
2397
            server_settings[option] = value
2406
2398
    del options
2407
2399
    # Force all strings to be unicode
2408
2400
    for option in server_settings.keys():
2409
 
        if isinstance(server_settings[option], bytes):
2410
 
            server_settings[option] = (server_settings[option]
2411
 
                                       .decode("utf-8"))
 
2401
        if type(server_settings[option]) is str:
 
2402
            server_settings[option] = unicode(server_settings[option])
2412
2403
    # Force all boolean options to be boolean
2413
2404
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2414
 
                   "foreground", "zeroconf"):
 
2405
                   "foreground"):
2415
2406
        server_settings[option] = bool(server_settings[option])
2416
2407
    # Debug implies foreground
2417
2408
    if server_settings["debug"]:
2420
2411
    
2421
2412
    ##################################################################
2422
2413
    
2423
 
    if (not server_settings["zeroconf"] and
2424
 
        not (server_settings["port"]
2425
 
             or server_settings["socket"] != "")):
2426
 
            parser.error("Needs port or socket to work without"
2427
 
                         " Zeroconf")
2428
 
    
2429
2414
    # For convenience
2430
2415
    debug = server_settings["debug"]
2431
2416
    debuglevel = server_settings["debuglevel"]
2434
2419
    stored_state_path = os.path.join(server_settings["statedir"],
2435
2420
                                     stored_state_file)
2436
2421
    foreground = server_settings["foreground"]
2437
 
    zeroconf = server_settings["zeroconf"]
2438
2422
    
2439
2423
    if debug:
2440
2424
        initlogger(debug, logging.DEBUG)
2447
2431
    
2448
2432
    if server_settings["servicename"] != "Mandos":
2449
2433
        syslogger.setFormatter(logging.Formatter
2450
 
                               ('Mandos ({}) [%(process)d]:'
 
2434
                               ('Mandos ({0}) [%(process)d]:'
2451
2435
                                ' %(levelname)s: %(message)s'
2452
2436
                                .format(server_settings
2453
2437
                                        ["servicename"])))
2461
2445
    global mandos_dbus_service
2462
2446
    mandos_dbus_service = None
2463
2447
    
2464
 
    socketfd = None
2465
 
    if server_settings["socket"] != "":
2466
 
        socketfd = server_settings["socket"]
2467
2448
    tcp_server = MandosServer((server_settings["address"],
2468
2449
                               server_settings["port"]),
2469
2450
                              ClientHandler,
2473
2454
                              gnutls_priority=
2474
2455
                              server_settings["priority"],
2475
2456
                              use_dbus=use_dbus,
2476
 
                              socketfd=socketfd)
 
2457
                              socketfd=(server_settings["socket"]
 
2458
                                        or None))
2477
2459
    if not foreground:
2478
2460
        pidfilename = "/run/mandos.pid"
2479
2461
        if not os.path.isdir("/run/."):
2549
2531
            use_dbus = False
2550
2532
            server_settings["use_dbus"] = False
2551
2533
            tcp_server.use_dbus = False
2552
 
    if zeroconf:
2553
 
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2554
 
        service = AvahiServiceToSyslog(name =
2555
 
                                       server_settings["servicename"],
2556
 
                                       servicetype = "_mandos._tcp",
2557
 
                                       protocol = protocol, bus = bus)
2558
 
        if server_settings["interface"]:
2559
 
            service.interface = (if_nametoindex
2560
 
                                 (server_settings["interface"]
2561
 
                                  .encode("utf-8")))
 
2534
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
2535
    service = AvahiServiceToSyslog(name =
 
2536
                                   server_settings["servicename"],
 
2537
                                   servicetype = "_mandos._tcp",
 
2538
                                   protocol = protocol, bus = bus)
 
2539
    if server_settings["interface"]:
 
2540
        service.interface = (if_nametoindex
 
2541
                             (str(server_settings["interface"])))
2562
2542
    
2563
2543
    global multiprocessing_manager
2564
2544
    multiprocessing_manager = multiprocessing.Manager()
2588
2568
            os.remove(stored_state_path)
2589
2569
        except IOError as e:
2590
2570
            if e.errno == errno.ENOENT:
2591
 
                logger.warning("Could not load persistent state: {}"
 
2571
                logger.warning("Could not load persistent state: {0}"
2592
2572
                                .format(os.strerror(e.errno)))
2593
2573
            else:
2594
2574
                logger.critical("Could not load persistent state:",
2599
2579
                           "EOFError:", exc_info=e)
2600
2580
    
2601
2581
    with PGPEngine() as pgp:
2602
 
        for client_name, client in clients_data.items():
 
2582
        for client_name, client in clients_data.iteritems():
2603
2583
            # Skip removed clients
2604
2584
            if client_name not in client_settings:
2605
2585
                continue
2630
2610
                if datetime.datetime.utcnow() >= client["expires"]:
2631
2611
                    if not client["last_checked_ok"]:
2632
2612
                        logger.warning(
2633
 
                            "disabling client {} - Client never "
 
2613
                            "disabling client {0} - Client never "
2634
2614
                            "performed a successful checker"
2635
2615
                            .format(client_name))
2636
2616
                        client["enabled"] = False
2637
2617
                    elif client["last_checker_status"] != 0:
2638
2618
                        logger.warning(
2639
 
                            "disabling client {} - Client last"
2640
 
                            " checker failed with error code {}"
 
2619
                            "disabling client {0} - Client "
 
2620
                            "last checker failed with error code {1}"
2641
2621
                            .format(client_name,
2642
2622
                                    client["last_checker_status"]))
2643
2623
                        client["enabled"] = False
2646
2626
                                             .utcnow()
2647
2627
                                             + client["timeout"])
2648
2628
                        logger.debug("Last checker succeeded,"
2649
 
                                     " keeping {} enabled"
 
2629
                                     " keeping {0} enabled"
2650
2630
                                     .format(client_name))
2651
2631
            try:
2652
2632
                client["secret"] = (
2655
2635
                                ["secret"]))
2656
2636
            except PGPError:
2657
2637
                # If decryption fails, we use secret from new settings
2658
 
                logger.debug("Failed to decrypt {} old secret"
 
2638
                logger.debug("Failed to decrypt {0} old secret"
2659
2639
                             .format(client_name))
2660
2640
                client["secret"] = (
2661
2641
                    client_settings[client_name]["secret"])
2669
2649
        clients_data[client_name] = client_settings[client_name]
2670
2650
    
2671
2651
    # Create all client objects
2672
 
    for client_name, client in clients_data.items():
 
2652
    for client_name, client in clients_data.iteritems():
2673
2653
        tcp_server.clients[client_name] = client_class(
2674
2654
            name = client_name, settings = client,
2675
2655
            server_settings = server_settings)
2682
2662
            try:
2683
2663
                with pidfile:
2684
2664
                    pid = os.getpid()
2685
 
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
 
2665
                    pidfile.write(str(pid) + "\n".encode("utf-8"))
2686
2666
            except IOError:
2687
2667
                logger.error("Could not write to file %r with PID %d",
2688
2668
                             pidfilename, pid)
2734
2714
            def GetAllClientsWithProperties(self):
2735
2715
                "D-Bus method"
2736
2716
                return dbus.Dictionary(
2737
 
                    { c.dbus_object_path: c.GetAll("")
2738
 
                      for c in tcp_server.clients.itervalues() },
 
2717
                    ((c.dbus_object_path, c.GetAll(""))
 
2718
                     for c in tcp_server.clients.itervalues()),
2739
2719
                    signature="oa{sv}")
2740
2720
            
2741
2721
            @dbus.service.method(_interface, in_signature="o")
2758
2738
    
2759
2739
    def cleanup():
2760
2740
        "Cleanup function; run on exit"
2761
 
        if zeroconf:
2762
 
            service.cleanup()
 
2741
        service.cleanup()
2763
2742
        
2764
2743
        multiprocessing.active_children()
2765
2744
        wnull.close()
2779
2758
                
2780
2759
                # A list of attributes that can not be pickled
2781
2760
                # + secret.
2782
 
                exclude = { "bus", "changedstate", "secret",
2783
 
                            "checker", "server_settings" }
 
2761
                exclude = set(("bus", "changedstate", "secret",
 
2762
                               "checker", "server_settings"))
2784
2763
                for name, typ in (inspect.getmembers
2785
2764
                                  (dbus.service.Object)):
2786
2765
                    exclude.add(name)
2809
2788
                except NameError:
2810
2789
                    pass
2811
2790
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2812
 
                logger.warning("Could not save persistent state: {}"
 
2791
                logger.warning("Could not save persistent state: {0}"
2813
2792
                               .format(os.strerror(e.errno)))
2814
2793
            else:
2815
2794
                logger.warning("Could not save persistent state:",
2844
2823
    tcp_server.server_activate()
2845
2824
    
2846
2825
    # Find out what port we got
2847
 
    if zeroconf:
2848
 
        service.port = tcp_server.socket.getsockname()[1]
 
2826
    service.port = tcp_server.socket.getsockname()[1]
2849
2827
    if use_ipv6:
2850
2828
        logger.info("Now listening on address %r, port %d,"
2851
2829
                    " flowinfo %d, scope_id %d",
2857
2835
    #service.interface = tcp_server.socket.getsockname()[3]
2858
2836
    
2859
2837
    try:
2860
 
        if zeroconf:
2861
 
            # From the Avahi example code
2862
 
            try:
2863
 
                service.activate()
2864
 
            except dbus.exceptions.DBusException as error:
2865
 
                logger.critical("D-Bus Exception", exc_info=error)
2866
 
                cleanup()
2867
 
                sys.exit(1)
2868
 
            # End of Avahi example code
 
2838
        # From the Avahi example code
 
2839
        try:
 
2840
            service.activate()
 
2841
        except dbus.exceptions.DBusException as error:
 
2842
            logger.critical("D-Bus Exception", exc_info=error)
 
2843
            cleanup()
 
2844
            sys.exit(1)
 
2845
        # End of Avahi example code
2869
2846
        
2870
2847
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2871
2848
                             lambda *args, **kwargs: