/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: 2015-04-02 18:59:29 UTC
  • mto: (237.7.304 trunk)
  • mto: This revision was merged to the branch mainline in revision 325.
  • Revision ID: teddy@recompile.se-20150402185929-1q1rf1zelbpzzn74
Add "!RSA" also to examples/documentation.

* mandos.conf (priority): Add "!RSA" to default commented-out value.
* mandos.conf.xml (EXAMPLE): Add "!RSA" to example priority setting.

Show diffs side-by-side

added added

removed removed

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