/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2013-10-26 19:05:21 UTC
  • Revision ID: teddy@recompile.se-20131026190521-giagilisbyciox2h
Fall back to /var/run for pidfile if /run is not a directory.

This is for old (possibly non-Debian) systems which have not migrated
from /var/run to /run yet.

* init.d-mandos (PIDFILE): Fall back to /var/run/mandos.pid if /run is
                           not a directory.
* mandos (pidfilename): - '' -
* mandos.xml (FILES): Document fallback to /var/run/mandos.pid if /run
                      is not a directory.

Reported-by: Nathanael D. Noblet <nathanael@gnat.ca>
Suggested-by: Nathanael D. Noblet <nathanael@gnat.ca>

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.8"
 
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
282
279
                            " after %i retries, exiting.",
283
280
                            self.rename_count)
284
281
            raise AvahiServiceError("Too many renames")
285
 
        self.name = str(self.server
286
 
                        .GetAlternativeServiceName(self.name))
 
282
        self.name = unicode(self.server
 
283
                            .GetAlternativeServiceName(self.name))
287
284
        logger.info("Changing Zeroconf service name to %r ...",
288
285
                    self.name)
289
286
        self.remove()
337
334
            self.rename()
338
335
        elif state == avahi.ENTRY_GROUP_FAILURE:
339
336
            logger.critical("Avahi: Error in group state changed %s",
340
 
                            str(error))
341
 
            raise AvahiGroupError("State changed: {!s}"
 
337
                            unicode(error))
 
338
            raise AvahiGroupError("State changed: {0!s}"
342
339
                                  .format(error))
343
340
    
344
341
    def cleanup(self):
395
392
        """Add the new name to the syslog messages"""
396
393
        ret = AvahiService.rename(self)
397
394
        syslogger.setFormatter(logging.Formatter
398
 
                               ('Mandos ({}) [%(process)d]:'
 
395
                               ('Mandos ({0}) [%(process)d]:'
399
396
                                ' %(levelname)s: %(message)s'
400
397
                                .format(self.name)))
401
398
        return ret
402
399
 
403
400
 
 
401
def timedelta_to_milliseconds(td):
 
402
    "Convert a datetime.timedelta() to milliseconds"
 
403
    return ((td.days * 24 * 60 * 60 * 1000)
 
404
            + (td.seconds * 1000)
 
405
            + (td.microseconds // 1000))
 
406
 
 
407
 
404
408
class Client(object):
405
409
    """A representation of a client host served by this server.
406
410
    
461
465
                        "enabled": "True",
462
466
                        }
463
467
    
 
468
    def timeout_milliseconds(self):
 
469
        "Return the 'timeout' attribute in milliseconds"
 
470
        return timedelta_to_milliseconds(self.timeout)
 
471
    
 
472
    def extended_timeout_milliseconds(self):
 
473
        "Return the 'extended_timeout' attribute in milliseconds"
 
474
        return timedelta_to_milliseconds(self.extended_timeout)
 
475
    
 
476
    def interval_milliseconds(self):
 
477
        "Return the 'interval' attribute in milliseconds"
 
478
        return timedelta_to_milliseconds(self.interval)
 
479
    
 
480
    def approval_delay_milliseconds(self):
 
481
        return timedelta_to_milliseconds(self.approval_delay)
 
482
    
464
483
    @staticmethod
465
484
    def config_parser(config):
466
485
        """Construct a new dict of client settings of this form:
491
510
                          "rb") as secfile:
492
511
                    client["secret"] = secfile.read()
493
512
            else:
494
 
                raise TypeError("No secret or secfile for section {}"
 
513
                raise TypeError("No secret or secfile for section {0}"
495
514
                                .format(section))
496
515
            client["timeout"] = string_to_delta(section["timeout"])
497
516
            client["extended_timeout"] = string_to_delta(
514
533
            server_settings = {}
515
534
        self.server_settings = server_settings
516
535
        # adding all client settings
517
 
        for setting, value in settings.items():
 
536
        for setting, value in settings.iteritems():
518
537
            setattr(self, setting, value)
519
538
        
520
539
        if self.enabled:
603
622
        if self.checker_initiator_tag is not None:
604
623
            gobject.source_remove(self.checker_initiator_tag)
605
624
        self.checker_initiator_tag = (gobject.timeout_add
606
 
                                      (int(self.interval
607
 
                                           .total_seconds() * 1000),
 
625
                                      (self.interval_milliseconds(),
608
626
                                       self.start_checker))
609
627
        # Schedule a disable() when 'timeout' has passed
610
628
        if self.disable_initiator_tag is not None:
611
629
            gobject.source_remove(self.disable_initiator_tag)
612
630
        self.disable_initiator_tag = (gobject.timeout_add
613
 
                                      (int(self.timeout
614
 
                                           .total_seconds() * 1000),
615
 
                                       self.disable))
 
631
                                   (self.timeout_milliseconds(),
 
632
                                    self.disable))
616
633
        # Also start a new checker *right now*.
617
634
        self.start_checker()
618
635
    
649
666
            self.disable_initiator_tag = None
650
667
        if getattr(self, "enabled", False):
651
668
            self.disable_initiator_tag = (gobject.timeout_add
652
 
                                          (int(timeout.total_seconds()
653
 
                                               * 1000), self.disable))
 
669
                                          (timedelta_to_milliseconds
 
670
                                           (timeout), self.disable))
654
671
            self.expires = datetime.datetime.utcnow() + timeout
655
672
    
656
673
    def need_approval(self):
673
690
        # If a checker exists, make sure it is not a zombie
674
691
        try:
675
692
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
676
 
        except AttributeError:
677
 
            pass
678
 
        except OSError as error:
679
 
            if error.errno != errno.ECHILD:
680
 
                raise
 
693
        except (AttributeError, OSError) as error:
 
694
            if (isinstance(error, OSError)
 
695
                and error.errno != errno.ECHILD):
 
696
                raise error
681
697
        else:
682
698
            if pid:
683
699
                logger.warning("Checker was a zombie")
687
703
        # Start a new checker if needed
688
704
        if self.checker is None:
689
705
            # Escape attributes for the shell
690
 
            escaped_attrs = { attr:
691
 
                                  re.escape(str(getattr(self, attr)))
692
 
                              for attr in self.runtime_expansions }
 
706
            escaped_attrs = dict(
 
707
                (attr, re.escape(unicode(getattr(self, attr))))
 
708
                for attr in
 
709
                self.runtime_expansions)
693
710
            try:
694
711
                command = self.checker_command % escaped_attrs
695
712
            except TypeError as error:
776
793
    # "Set" method, so we fail early here:
777
794
    if byte_arrays and signature != "ay":
778
795
        raise ValueError("Byte arrays not supported for non-'ay'"
779
 
                         " signature {!r}".format(signature))
 
796
                         " signature {0!r}".format(signature))
780
797
    def decorator(func):
781
798
        func._dbus_is_property = True
782
799
        func._dbus_interface = dbus_interface
830
847
class DBusPropertyException(dbus.exceptions.DBusException):
831
848
    """A base class for D-Bus property-related exceptions
832
849
    """
833
 
    pass
 
850
    def __unicode__(self):
 
851
        return unicode(str(self))
 
852
 
834
853
 
835
854
class DBusPropertyAccessException(DBusPropertyException):
836
855
    """A property's access permissions disallows an operation.
859
878
        If called like _is_dbus_thing("method") it returns a function
860
879
        suitable for use as predicate to inspect.getmembers().
861
880
        """
862
 
        return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
 
881
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
863
882
                                   False)
864
883
    
865
884
    def _get_all_dbus_things(self, thing):
914
933
            # The byte_arrays option is not supported yet on
915
934
            # signatures other than "ay".
916
935
            if prop._dbus_signature != "ay":
917
 
                raise ValueError("Byte arrays not supported for non-"
918
 
                                 "'ay' signature {!r}"
919
 
                                 .format(prop._dbus_signature))
 
936
                raise ValueError
920
937
            value = dbus.ByteArray(b''.join(chr(byte)
921
938
                                            for byte in value))
922
939
        prop(value)
986
1003
                                              (prop,
987
1004
                                               "_dbus_annotations",
988
1005
                                               {}))
989
 
                        for name, value in annots.items():
 
1006
                        for name, value in annots.iteritems():
990
1007
                            ann_tag = document.createElement(
991
1008
                                "annotation")
992
1009
                            ann_tag.setAttribute("name", name)
995
1012
                # Add interface annotation tags
996
1013
                for annotation, value in dict(
997
1014
                    itertools.chain.from_iterable(
998
 
                        annotations().items()
 
1015
                        annotations().iteritems()
999
1016
                        for name, annotations in
1000
1017
                        self._get_all_dbus_things("interface")
1001
1018
                        if name == if_tag.getAttribute("name")
1002
 
                        )).items():
 
1019
                        )).iteritems():
1003
1020
                    ann_tag = document.createElement("annotation")
1004
1021
                    ann_tag.setAttribute("name", annotation)
1005
1022
                    ann_tag.setAttribute("value", value)
1061
1078
    """
1062
1079
    def wrapper(cls):
1063
1080
        for orig_interface_name, alt_interface_name in (
1064
 
            alt_interface_names.items()):
 
1081
            alt_interface_names.iteritems()):
1065
1082
            attr = {}
1066
1083
            interface_names = set()
1067
1084
            # Go though all attributes of the class
1184
1201
                                        attribute.func_closure)))
1185
1202
            if deprecate:
1186
1203
                # Deprecate all alternate interfaces
1187
 
                iname="_AlternateDBusNames_interface_annotation{}"
 
1204
                iname="_AlternateDBusNames_interface_annotation{0}"
1188
1205
                for interface_name in interface_names:
1189
1206
                    @dbus_interface_annotations(interface_name)
1190
1207
                    def func(self):
1199
1216
            if interface_names:
1200
1217
                # Replace the class with a new subclass of it with
1201
1218
                # methods, signals, etc. as created above.
1202
 
                cls = type(b"{}Alternate".format(cls.__name__),
 
1219
                cls = type(b"{0}Alternate".format(cls.__name__),
1203
1220
                           (cls,), attr)
1204
1221
        return cls
1205
1222
    return wrapper
1225
1242
        Client.__init__(self, *args, **kwargs)
1226
1243
        # Only now, when this client is initialized, can it show up on
1227
1244
        # the D-Bus
1228
 
        client_object_name = str(self.name).translate(
 
1245
        client_object_name = unicode(self.name).translate(
1229
1246
            {ord("."): ord("_"),
1230
1247
             ord("-"): ord("_")})
1231
1248
        self.dbus_object_path = (dbus.ObjectPath
1246
1263
                   to the D-Bus.  Default: no transform
1247
1264
        variant_level: D-Bus variant level.  Default: 1
1248
1265
        """
1249
 
        attrname = "_{}".format(dbus_name)
 
1266
        attrname = "_{0}".format(dbus_name)
1250
1267
        def setter(self, value):
1251
1268
            if hasattr(self, "dbus_object_path"):
1252
1269
                if (not hasattr(self, attrname) or
1282
1299
    approval_delay = notifychangeproperty(dbus.UInt64,
1283
1300
                                          "ApprovalDelay",
1284
1301
                                          type_func =
1285
 
                                          lambda td: td.total_seconds()
1286
 
                                          * 1000)
 
1302
                                          timedelta_to_milliseconds)
1287
1303
    approval_duration = notifychangeproperty(
1288
1304
        dbus.UInt64, "ApprovalDuration",
1289
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1305
        type_func = timedelta_to_milliseconds)
1290
1306
    host = notifychangeproperty(dbus.String, "Host")
1291
1307
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1292
 
                                   type_func = lambda td:
1293
 
                                       td.total_seconds() * 1000)
 
1308
                                   type_func =
 
1309
                                   timedelta_to_milliseconds)
1294
1310
    extended_timeout = notifychangeproperty(
1295
1311
        dbus.UInt64, "ExtendedTimeout",
1296
 
        type_func = lambda td: td.total_seconds() * 1000)
 
1312
        type_func = timedelta_to_milliseconds)
1297
1313
    interval = notifychangeproperty(dbus.UInt64,
1298
1314
                                    "Interval",
1299
1315
                                    type_func =
1300
 
                                    lambda td: td.total_seconds()
1301
 
                                    * 1000)
 
1316
                                    timedelta_to_milliseconds)
1302
1317
    checker_command = notifychangeproperty(dbus.String, "Checker")
1303
1318
    
1304
1319
    del notifychangeproperty
1332
1347
                                       *args, **kwargs)
1333
1348
    
1334
1349
    def start_checker(self, *args, **kwargs):
1335
 
        old_checker_pid = getattr(self.checker, "pid", None)
 
1350
        old_checker = self.checker
 
1351
        if self.checker is not None:
 
1352
            old_checker_pid = self.checker.pid
 
1353
        else:
 
1354
            old_checker_pid = None
1336
1355
        r = Client.start_checker(self, *args, **kwargs)
1337
1356
        # Only if new checker process was started
1338
1357
        if (self.checker is not None
1347
1366
    
1348
1367
    def approve(self, value=True):
1349
1368
        self.approved = value
1350
 
        gobject.timeout_add(int(self.approval_duration.total_seconds()
1351
 
                                * 1000), self._reset_approved)
 
1369
        gobject.timeout_add(timedelta_to_milliseconds
 
1370
                            (self.approval_duration),
 
1371
                            self._reset_approved)
1352
1372
        self.send_changedstate()
1353
1373
    
1354
1374
    ## D-Bus methods, signals & properties
1457
1477
                           access="readwrite")
1458
1478
    def ApprovalDelay_dbus_property(self, value=None):
1459
1479
        if value is None:       # get
1460
 
            return dbus.UInt64(self.approval_delay.total_seconds()
1461
 
                               * 1000)
 
1480
            return dbus.UInt64(self.approval_delay_milliseconds())
1462
1481
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1463
1482
    
1464
1483
    # ApprovalDuration - property
1466
1485
                           access="readwrite")
1467
1486
    def ApprovalDuration_dbus_property(self, value=None):
1468
1487
        if value is None:       # get
1469
 
            return dbus.UInt64(self.approval_duration.total_seconds()
1470
 
                               * 1000)
 
1488
            return dbus.UInt64(timedelta_to_milliseconds(
 
1489
                    self.approval_duration))
1471
1490
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1472
1491
    
1473
1492
    # Name - property
1486
1505
    def Host_dbus_property(self, value=None):
1487
1506
        if value is None:       # get
1488
1507
            return dbus.String(self.host)
1489
 
        self.host = str(value)
 
1508
        self.host = unicode(value)
1490
1509
    
1491
1510
    # Created - property
1492
1511
    @dbus_service_property(_interface, signature="s", access="read")
1539
1558
                           access="readwrite")
1540
1559
    def Timeout_dbus_property(self, value=None):
1541
1560
        if value is None:       # get
1542
 
            return dbus.UInt64(self.timeout.total_seconds() * 1000)
 
1561
            return dbus.UInt64(self.timeout_milliseconds())
1543
1562
        old_timeout = self.timeout
1544
1563
        self.timeout = datetime.timedelta(0, 0, 0, value)
1545
1564
        # Reschedule disabling
1556
1575
                gobject.source_remove(self.disable_initiator_tag)
1557
1576
                self.disable_initiator_tag = (
1558
1577
                    gobject.timeout_add(
1559
 
                        int((self.expires - now).total_seconds()
1560
 
                            * 1000), self.disable))
 
1578
                        timedelta_to_milliseconds(self.expires - now),
 
1579
                        self.disable))
1561
1580
    
1562
1581
    # ExtendedTimeout - property
1563
1582
    @dbus_service_property(_interface, signature="t",
1564
1583
                           access="readwrite")
1565
1584
    def ExtendedTimeout_dbus_property(self, value=None):
1566
1585
        if value is None:       # get
1567
 
            return dbus.UInt64(self.extended_timeout.total_seconds()
1568
 
                               * 1000)
 
1586
            return dbus.UInt64(self.extended_timeout_milliseconds())
1569
1587
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1570
1588
    
1571
1589
    # Interval - property
1573
1591
                           access="readwrite")
1574
1592
    def Interval_dbus_property(self, value=None):
1575
1593
        if value is None:       # get
1576
 
            return dbus.UInt64(self.interval.total_seconds() * 1000)
 
1594
            return dbus.UInt64(self.interval_milliseconds())
1577
1595
        self.interval = datetime.timedelta(0, 0, 0, value)
1578
1596
        if getattr(self, "checker_initiator_tag", None) is None:
1579
1597
            return
1590
1608
    def Checker_dbus_property(self, value=None):
1591
1609
        if value is None:       # get
1592
1610
            return dbus.String(self.checker_command)
1593
 
        self.checker_command = str(value)
 
1611
        self.checker_command = unicode(value)
1594
1612
    
1595
1613
    # CheckerRunning - property
1596
1614
    @dbus_service_property(_interface, signature="b",
1612
1630
    @dbus_service_property(_interface, signature="ay",
1613
1631
                           access="write", byte_arrays=True)
1614
1632
    def Secret_dbus_property(self, value):
1615
 
        self.secret = bytes(value)
 
1633
        self.secret = str(value)
1616
1634
    
1617
1635
    del _interface
1618
1636
 
1652
1670
    def handle(self):
1653
1671
        with contextlib.closing(self.server.child_pipe) as child_pipe:
1654
1672
            logger.info("TCP connection from: %s",
1655
 
                        str(self.client_address))
 
1673
                        unicode(self.client_address))
1656
1674
            logger.debug("Pipe FD: %d",
1657
1675
                         self.server.child_pipe.fileno())
1658
1676
            
1684
1702
            logger.debug("Protocol version: %r", line)
1685
1703
            try:
1686
1704
                if int(line.strip().split()[0]) > 1:
1687
 
                    raise RuntimeError(line)
 
1705
                    raise RuntimeError
1688
1706
            except (ValueError, IndexError, RuntimeError) as error:
1689
1707
                logger.error("Unknown protocol version: %s", error)
1690
1708
                return
1739
1757
                        if self.server.use_dbus:
1740
1758
                            # Emit D-Bus signal
1741
1759
                            client.NeedApproval(
1742
 
                                client.approval_delay.total_seconds()
1743
 
                                * 1000, client.approved_by_default)
 
1760
                                client.approval_delay_milliseconds(),
 
1761
                                client.approved_by_default)
1744
1762
                    else:
1745
1763
                        logger.warning("Client %s was not approved",
1746
1764
                                       client.name)
1752
1770
                    #wait until timeout or approved
1753
1771
                    time = datetime.datetime.now()
1754
1772
                    client.changedstate.acquire()
1755
 
                    client.changedstate.wait(delay.total_seconds())
 
1773
                    client.changedstate.wait(
 
1774
                        float(timedelta_to_milliseconds(delay)
 
1775
                              / 1000))
1756
1776
                    client.changedstate.release()
1757
1777
                    time2 = datetime.datetime.now()
1758
1778
                    if (time2 - time) >= delay:
1895
1915
    
1896
1916
    def add_pipe(self, parent_pipe, proc):
1897
1917
        """Dummy function; override as necessary"""
1898
 
        raise NotImplementedError()
 
1918
        raise NotImplementedError
1899
1919
 
1900
1920
 
1901
1921
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1957
1977
                try:
1958
1978
                    self.socket.setsockopt(socket.SOL_SOCKET,
1959
1979
                                           SO_BINDTODEVICE,
1960
 
                                           (self.interface + "\0")
1961
 
                                           .encode("utf-8"))
 
1980
                                           str(self.interface + '\0'))
1962
1981
                except socket.error as error:
1963
1982
                    if error.errno == errno.EPERM:
1964
1983
                        logger.error("No permission to bind to"
2167
2186
    token_duration = Token(re.compile(r"P"), None,
2168
2187
                           frozenset((token_year, token_month,
2169
2188
                                      token_day, token_time,
2170
 
                                      token_week)))
 
2189
                                      token_week))),
2171
2190
    # Define starting values
2172
2191
    value = datetime.timedelta() # Value so far
2173
2192
    found_token = None
2174
 
    followers = frozenset((token_duration,)) # Following valid tokens
 
2193
    followers = frozenset(token_duration,) # Following valid tokens
2175
2194
    s = duration                # String left to parse
2176
2195
    # Loop until end token is found
2177
2196
    while found_token is not token_end:
2224
2243
    timevalue = datetime.timedelta(0)
2225
2244
    for s in interval.split():
2226
2245
        try:
2227
 
            suffix = s[-1]
 
2246
            suffix = unicode(s[-1])
2228
2247
            value = int(s[:-1])
2229
2248
            if suffix == "d":
2230
2249
                delta = datetime.timedelta(value)
2237
2256
            elif suffix == "w":
2238
2257
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2239
2258
            else:
2240
 
                raise ValueError("Unknown suffix {!r}"
 
2259
                raise ValueError("Unknown suffix {0!r}"
2241
2260
                                 .format(suffix))
2242
 
        except IndexError as e:
 
2261
        except (ValueError, IndexError) as e:
2243
2262
            raise ValueError(*(e.args))
2244
2263
        timevalue += delta
2245
2264
    return timevalue
2260
2279
        # Close all standard open file descriptors
2261
2280
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2262
2281
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2263
 
            raise OSError(errno.ENODEV, "{} not a character device"
 
2282
            raise OSError(errno.ENODEV,
 
2283
                          "{0} not a character device"
2264
2284
                          .format(os.devnull))
2265
2285
        os.dup2(null, sys.stdin.fileno())
2266
2286
        os.dup2(null, sys.stdout.fileno())
2276
2296
    
2277
2297
    parser = argparse.ArgumentParser()
2278
2298
    parser.add_argument("-v", "--version", action="version",
2279
 
                        version = "%(prog)s {}".format(version),
 
2299
                        version = "%(prog)s {0}".format(version),
2280
2300
                        help="show version number and exit")
2281
2301
    parser.add_argument("-i", "--interface", metavar="IF",
2282
2302
                        help="Bind to interface IF")
2315
2335
                        help="Directory to save/restore state in")
2316
2336
    parser.add_argument("--foreground", action="store_true",
2317
2337
                        help="Run in foreground", default=None)
2318
 
    parser.add_argument("--no-zeroconf", action="store_false",
2319
 
                        dest="zeroconf", help="Do not use Zeroconf",
2320
 
                        default=None)
2321
2338
    
2322
2339
    options = parser.parse_args()
2323
2340
    
2324
2341
    if options.check:
2325
2342
        import doctest
2326
 
        fail_count, test_count = doctest.testmod()
2327
 
        sys.exit(os.EX_OK if fail_count == 0 else 1)
 
2343
        doctest.testmod()
 
2344
        sys.exit()
2328
2345
    
2329
2346
    # Default values for config file for server-global settings
2330
2347
    server_defaults = { "interface": "",
2341
2358
                        "socket": "",
2342
2359
                        "statedir": "/var/lib/mandos",
2343
2360
                        "foreground": "False",
2344
 
                        "zeroconf": "True",
2345
2361
                        }
2346
2362
    
2347
2363
    # Parse config file for server-global settings
2374
2390
    for option in ("interface", "address", "port", "debug",
2375
2391
                   "priority", "servicename", "configdir",
2376
2392
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
2377
 
                   "statedir", "socket", "foreground", "zeroconf"):
 
2393
                   "statedir", "socket", "foreground"):
2378
2394
        value = getattr(options, option)
2379
2395
        if value is not None:
2380
2396
            server_settings[option] = value
2381
2397
    del options
2382
2398
    # Force all strings to be unicode
2383
2399
    for option in server_settings.keys():
2384
 
        if isinstance(server_settings[option], bytes):
2385
 
            server_settings[option] = (server_settings[option]
2386
 
                                       .decode("utf-8"))
 
2400
        if type(server_settings[option]) is str:
 
2401
            server_settings[option] = unicode(server_settings[option])
2387
2402
    # Force all boolean options to be boolean
2388
2403
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2389
 
                   "foreground", "zeroconf"):
 
2404
                   "foreground"):
2390
2405
        server_settings[option] = bool(server_settings[option])
2391
2406
    # Debug implies foreground
2392
2407
    if server_settings["debug"]:
2395
2410
    
2396
2411
    ##################################################################
2397
2412
    
2398
 
    if (not server_settings["zeroconf"] and
2399
 
        not (server_settings["port"]
2400
 
             or server_settings["socket"] != "")):
2401
 
            parser.error("Needs port or socket to work without"
2402
 
                         " Zeroconf")
2403
 
    
2404
2413
    # For convenience
2405
2414
    debug = server_settings["debug"]
2406
2415
    debuglevel = server_settings["debuglevel"]
2409
2418
    stored_state_path = os.path.join(server_settings["statedir"],
2410
2419
                                     stored_state_file)
2411
2420
    foreground = server_settings["foreground"]
2412
 
    zeroconf = server_settings["zeroconf"]
2413
2421
    
2414
2422
    if debug:
2415
2423
        initlogger(debug, logging.DEBUG)
2422
2430
    
2423
2431
    if server_settings["servicename"] != "Mandos":
2424
2432
        syslogger.setFormatter(logging.Formatter
2425
 
                               ('Mandos ({}) [%(process)d]:'
 
2433
                               ('Mandos ({0}) [%(process)d]:'
2426
2434
                                ' %(levelname)s: %(message)s'
2427
2435
                                .format(server_settings
2428
2436
                                        ["servicename"])))
2436
2444
    global mandos_dbus_service
2437
2445
    mandos_dbus_service = None
2438
2446
    
2439
 
    socketfd = None
2440
 
    if server_settings["socket"] != "":
2441
 
        socketfd = server_settings["socket"]
2442
2447
    tcp_server = MandosServer((server_settings["address"],
2443
2448
                               server_settings["port"]),
2444
2449
                              ClientHandler,
2448
2453
                              gnutls_priority=
2449
2454
                              server_settings["priority"],
2450
2455
                              use_dbus=use_dbus,
2451
 
                              socketfd=socketfd)
 
2456
                              socketfd=(server_settings["socket"]
 
2457
                                        or None))
2452
2458
    if not foreground:
2453
2459
        pidfilename = "/run/mandos.pid"
2454
2460
        if not os.path.isdir("/run/."):
2475
2481
        os.setuid(uid)
2476
2482
    except OSError as error:
2477
2483
        if error.errno != errno.EPERM:
2478
 
            raise
 
2484
            raise error
2479
2485
    
2480
2486
    if debug:
2481
2487
        # Enable all possible GnuTLS debugging
2524
2530
            use_dbus = False
2525
2531
            server_settings["use_dbus"] = False
2526
2532
            tcp_server.use_dbus = False
2527
 
    if zeroconf:
2528
 
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2529
 
        service = AvahiServiceToSyslog(name =
2530
 
                                       server_settings["servicename"],
2531
 
                                       servicetype = "_mandos._tcp",
2532
 
                                       protocol = protocol, bus = bus)
2533
 
        if server_settings["interface"]:
2534
 
            service.interface = (if_nametoindex
2535
 
                                 (server_settings["interface"]
2536
 
                                  .encode("utf-8")))
 
2533
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
2534
    service = AvahiServiceToSyslog(name =
 
2535
                                   server_settings["servicename"],
 
2536
                                   servicetype = "_mandos._tcp",
 
2537
                                   protocol = protocol, bus = bus)
 
2538
    if server_settings["interface"]:
 
2539
        service.interface = (if_nametoindex
 
2540
                             (str(server_settings["interface"])))
2537
2541
    
2538
2542
    global multiprocessing_manager
2539
2543
    multiprocessing_manager = multiprocessing.Manager()
2563
2567
            os.remove(stored_state_path)
2564
2568
        except IOError as e:
2565
2569
            if e.errno == errno.ENOENT:
2566
 
                logger.warning("Could not load persistent state: {}"
 
2570
                logger.warning("Could not load persistent state: {0}"
2567
2571
                                .format(os.strerror(e.errno)))
2568
2572
            else:
2569
2573
                logger.critical("Could not load persistent state:",
2574
2578
                           "EOFError:", exc_info=e)
2575
2579
    
2576
2580
    with PGPEngine() as pgp:
2577
 
        for client_name, client in clients_data.items():
 
2581
        for client_name, client in clients_data.iteritems():
2578
2582
            # Skip removed clients
2579
2583
            if client_name not in client_settings:
2580
2584
                continue
2605
2609
                if datetime.datetime.utcnow() >= client["expires"]:
2606
2610
                    if not client["last_checked_ok"]:
2607
2611
                        logger.warning(
2608
 
                            "disabling client {} - Client never "
 
2612
                            "disabling client {0} - Client never "
2609
2613
                            "performed a successful checker"
2610
2614
                            .format(client_name))
2611
2615
                        client["enabled"] = False
2612
2616
                    elif client["last_checker_status"] != 0:
2613
2617
                        logger.warning(
2614
 
                            "disabling client {} - Client last"
2615
 
                            " checker failed with error code {}"
 
2618
                            "disabling client {0} - Client "
 
2619
                            "last checker failed with error code {1}"
2616
2620
                            .format(client_name,
2617
2621
                                    client["last_checker_status"]))
2618
2622
                        client["enabled"] = False
2621
2625
                                             .utcnow()
2622
2626
                                             + client["timeout"])
2623
2627
                        logger.debug("Last checker succeeded,"
2624
 
                                     " keeping {} enabled"
 
2628
                                     " keeping {0} enabled"
2625
2629
                                     .format(client_name))
2626
2630
            try:
2627
2631
                client["secret"] = (
2630
2634
                                ["secret"]))
2631
2635
            except PGPError:
2632
2636
                # If decryption fails, we use secret from new settings
2633
 
                logger.debug("Failed to decrypt {} old secret"
 
2637
                logger.debug("Failed to decrypt {0} old secret"
2634
2638
                             .format(client_name))
2635
2639
                client["secret"] = (
2636
2640
                    client_settings[client_name]["secret"])
2644
2648
        clients_data[client_name] = client_settings[client_name]
2645
2649
    
2646
2650
    # Create all client objects
2647
 
    for client_name, client in clients_data.items():
 
2651
    for client_name, client in clients_data.iteritems():
2648
2652
        tcp_server.clients[client_name] = client_class(
2649
2653
            name = client_name, settings = client,
2650
2654
            server_settings = server_settings)
2657
2661
            try:
2658
2662
                with pidfile:
2659
2663
                    pid = os.getpid()
2660
 
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
 
2664
                    pidfile.write(str(pid) + "\n".encode("utf-8"))
2661
2665
            except IOError:
2662
2666
                logger.error("Could not write to file %r with PID %d",
2663
2667
                             pidfilename, pid)
2733
2737
    
2734
2738
    def cleanup():
2735
2739
        "Cleanup function; run on exit"
2736
 
        if zeroconf:
2737
 
            service.cleanup()
 
2740
        service.cleanup()
2738
2741
        
2739
2742
        multiprocessing.active_children()
2740
2743
        wnull.close()
2754
2757
                
2755
2758
                # A list of attributes that can not be pickled
2756
2759
                # + secret.
2757
 
                exclude = { "bus", "changedstate", "secret",
2758
 
                            "checker", "server_settings" }
 
2760
                exclude = set(("bus", "changedstate", "secret",
 
2761
                               "checker", "server_settings"))
2759
2762
                for name, typ in (inspect.getmembers
2760
2763
                                  (dbus.service.Object)):
2761
2764
                    exclude.add(name)
2784
2787
                except NameError:
2785
2788
                    pass
2786
2789
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2787
 
                logger.warning("Could not save persistent state: {}"
 
2790
                logger.warning("Could not save persistent state: {0}"
2788
2791
                               .format(os.strerror(e.errno)))
2789
2792
            else:
2790
2793
                logger.warning("Could not save persistent state:",
2791
2794
                               exc_info=e)
2792
 
                raise
 
2795
                raise e
2793
2796
        
2794
2797
        # Delete all clients, and settings from config
2795
2798
        while tcp_server.clients:
2819
2822
    tcp_server.server_activate()
2820
2823
    
2821
2824
    # Find out what port we got
2822
 
    if zeroconf:
2823
 
        service.port = tcp_server.socket.getsockname()[1]
 
2825
    service.port = tcp_server.socket.getsockname()[1]
2824
2826
    if use_ipv6:
2825
2827
        logger.info("Now listening on address %r, port %d,"
2826
2828
                    " flowinfo %d, scope_id %d",
2832
2834
    #service.interface = tcp_server.socket.getsockname()[3]
2833
2835
    
2834
2836
    try:
2835
 
        if zeroconf:
2836
 
            # From the Avahi example code
2837
 
            try:
2838
 
                service.activate()
2839
 
            except dbus.exceptions.DBusException as error:
2840
 
                logger.critical("D-Bus Exception", exc_info=error)
2841
 
                cleanup()
2842
 
                sys.exit(1)
2843
 
            # End of Avahi example code
 
2837
        # From the Avahi example code
 
2838
        try:
 
2839
            service.activate()
 
2840
        except dbus.exceptions.DBusException as error:
 
2841
            logger.critical("D-Bus Exception", exc_info=error)
 
2842
            cleanup()
 
2843
            sys.exit(1)
 
2844
        # End of Avahi example code
2844
2845
        
2845
2846
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2846
2847
                             lambda *args, **kwargs: