/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: 2014-08-20 21:46:38 UTC
  • mto: (237.7.304 trunk)
  • mto: This revision was merged to the branch mainline in revision 323.
  • Revision ID: teddy@recompile.se-20140820214638-k4naueej6hffdgfg
mandos-client: Bug fix: Check fork() return value.

When executing network hook scripts, check fork() return value.

* plugins.d/mandos-client.c (run_network_hooks): Bug fix: check if
                                                 fork() returns -1.

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