/mandos/trunk

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2014-08-09 13:12:55 UTC
  • Revision ID: teddy@recompile.se-20140809131255-lp31j98u2pl0xpe6
mandos: Stop using str() and remove unnecessary unicode() calls.

* mandos (if_nametoindex): Use "bytes" literal instead of str().
  (initlogger): Use a unicode string for log device.
  (AvahiError.__unicode__): Removed.
  (DBusPropertyException.__unicode__): - '' -
  (ClientDBus.Secret_dbus_property): Use bytes() instead of str().
  (IPv6_TCPServer.server_bind): Use .encode() instead of str().
  (string_to_delta): Removed unnecessary unicode() call.
  (main): Use "isinstance(x, bytes)" instead of "type(x) is str", use
          .decode() instead of unicode(), and use .encode() instead of
          str().

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.
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008-2013 Teddy Hogeborn
15
 
# Copyright © 2008-2013 Björn Påhlsson
 
14
# Copyright © 2008-2014 Teddy Hogeborn
 
15
# Copyright © 2008-2014 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
 
version = "1.6.1"
 
91
version = "1.6.8"
92
92
stored_state_file = "clients.pickle"
93
93
 
94
94
logger = logging.getLogger()
95
 
syslogger = (logging.handlers.SysLogHandler
96
 
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
97
 
              address = str("/dev/log")))
 
95
syslogger = None
98
96
 
99
97
try:
100
98
    if_nametoindex = (ctypes.cdll.LoadLibrary
106
104
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
107
105
        with contextlib.closing(socket.socket()) as s:
108
106
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
109
 
                                struct.pack(str("16s16x"),
110
 
                                            interface))
111
 
        interface_index = struct.unpack(str("I"),
112
 
                                        ifreq[16:20])[0]
 
107
                                struct.pack(b"16s16x", interface))
 
108
        interface_index = struct.unpack("I", ifreq[16:20])[0]
113
109
        return interface_index
114
110
 
115
111
 
116
112
def initlogger(debug, level=logging.WARNING):
117
113
    """init logger and add loglevel"""
118
114
    
 
115
    global syslogger
 
116
    syslogger = (logging.handlers.SysLogHandler
 
117
                 (facility =
 
118
                  logging.handlers.SysLogHandler.LOG_DAEMON,
 
119
                  address = "/dev/log"))
119
120
    syslogger.setFormatter(logging.Formatter
120
121
                           ('Mandos [%(process)d]: %(levelname)s:'
121
122
                            ' %(message)s'))
172
173
    def password_encode(self, password):
173
174
        # Passphrase can not be empty and can not contain newlines or
174
175
        # NUL bytes.  So we prefix it and hex encode it.
175
 
        return b"mandos" + binascii.hexlify(password)
 
176
        encoded = b"mandos" + binascii.hexlify(password)
 
177
        if len(encoded) > 2048:
 
178
            # GnuPG can't handle long passwords, so encode differently
 
179
            encoded = (b"mandos" + password.replace(b"\\", b"\\\\")
 
180
                       .replace(b"\n", b"\\n")
 
181
                       .replace(b"\0", b"\\x00"))
 
182
        return encoded
176
183
    
177
184
    def encrypt(self, data, password):
178
185
        passphrase = self.password_encode(password)
215
222
class AvahiError(Exception):
216
223
    def __init__(self, value, *args, **kwargs):
217
224
        self.value = value
218
 
        super(AvahiError, self).__init__(value, *args, **kwargs)
219
 
    def __unicode__(self):
220
 
        return unicode(repr(self.value))
 
225
        return super(AvahiError, self).__init__(value, *args,
 
226
                                                **kwargs)
221
227
 
222
228
class AvahiServiceError(AvahiError):
223
229
    pass
329
335
        elif state == avahi.ENTRY_GROUP_FAILURE:
330
336
            logger.critical("Avahi: Error in group state changed %s",
331
337
                            unicode(error))
332
 
            raise AvahiGroupError("State changed: {0!s}"
 
338
            raise AvahiGroupError("State changed: {!s}"
333
339
                                  .format(error))
334
340
    
335
341
    def cleanup(self):
386
392
        """Add the new name to the syslog messages"""
387
393
        ret = AvahiService.rename(self)
388
394
        syslogger.setFormatter(logging.Formatter
389
 
                               ('Mandos ({0}) [%(process)d]:'
 
395
                               ('Mandos ({}) [%(process)d]:'
390
396
                                ' %(levelname)s: %(message)s'
391
397
                                .format(self.name)))
392
398
        return ret
393
399
 
394
400
 
395
 
def timedelta_to_milliseconds(td):
396
 
    "Convert a datetime.timedelta() to milliseconds"
397
 
    return ((td.days * 24 * 60 * 60 * 1000)
398
 
            + (td.seconds * 1000)
399
 
            + (td.microseconds // 1000))
400
 
 
401
 
 
402
401
class Client(object):
403
402
    """A representation of a client host served by this server.
404
403
    
459
458
                        "enabled": "True",
460
459
                        }
461
460
    
462
 
    def timeout_milliseconds(self):
463
 
        "Return the 'timeout' attribute in milliseconds"
464
 
        return timedelta_to_milliseconds(self.timeout)
465
 
    
466
 
    def extended_timeout_milliseconds(self):
467
 
        "Return the 'extended_timeout' attribute in milliseconds"
468
 
        return timedelta_to_milliseconds(self.extended_timeout)
469
 
    
470
 
    def interval_milliseconds(self):
471
 
        "Return the 'interval' attribute in milliseconds"
472
 
        return timedelta_to_milliseconds(self.interval)
473
 
    
474
 
    def approval_delay_milliseconds(self):
475
 
        return timedelta_to_milliseconds(self.approval_delay)
476
 
    
477
461
    @staticmethod
478
462
    def config_parser(config):
479
463
        """Construct a new dict of client settings of this form:
504
488
                          "rb") as secfile:
505
489
                    client["secret"] = secfile.read()
506
490
            else:
507
 
                raise TypeError("No secret or secfile for section {0}"
 
491
                raise TypeError("No secret or secfile for section {}"
508
492
                                .format(section))
509
493
            client["timeout"] = string_to_delta(section["timeout"])
510
494
            client["extended_timeout"] = string_to_delta(
527
511
            server_settings = {}
528
512
        self.server_settings = server_settings
529
513
        # adding all client settings
530
 
        for setting, value in settings.iteritems():
 
514
        for setting, value in settings.items():
531
515
            setattr(self, setting, value)
532
516
        
533
517
        if self.enabled:
616
600
        if self.checker_initiator_tag is not None:
617
601
            gobject.source_remove(self.checker_initiator_tag)
618
602
        self.checker_initiator_tag = (gobject.timeout_add
619
 
                                      (self.interval_milliseconds(),
 
603
                                      (int(self.interval
 
604
                                           .total_seconds() * 1000),
620
605
                                       self.start_checker))
621
606
        # Schedule a disable() when 'timeout' has passed
622
607
        if self.disable_initiator_tag is not None:
623
608
            gobject.source_remove(self.disable_initiator_tag)
624
609
        self.disable_initiator_tag = (gobject.timeout_add
625
 
                                   (self.timeout_milliseconds(),
626
 
                                    self.disable))
 
610
                                      (int(self.timeout
 
611
                                           .total_seconds() * 1000),
 
612
                                       self.disable))
627
613
        # Also start a new checker *right now*.
628
614
        self.start_checker()
629
615
    
660
646
            self.disable_initiator_tag = None
661
647
        if getattr(self, "enabled", False):
662
648
            self.disable_initiator_tag = (gobject.timeout_add
663
 
                                          (timedelta_to_milliseconds
664
 
                                           (timeout), self.disable))
 
649
                                          (int(timeout.total_seconds()
 
650
                                               * 1000), self.disable))
665
651
            self.expires = datetime.datetime.utcnow() + timeout
666
652
    
667
653
    def need_approval(self):
684
670
        # If a checker exists, make sure it is not a zombie
685
671
        try:
686
672
            pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
687
 
        except (AttributeError, OSError) as error:
688
 
            if (isinstance(error, OSError)
689
 
                and error.errno != errno.ECHILD):
690
 
                raise error
 
673
        except AttributeError:
 
674
            pass
 
675
        except OSError as error:
 
676
            if error.errno != errno.ECHILD:
 
677
                raise
691
678
        else:
692
679
            if pid:
693
680
                logger.warning("Checker was a zombie")
697
684
        # Start a new checker if needed
698
685
        if self.checker is None:
699
686
            # Escape attributes for the shell
700
 
            escaped_attrs = dict(
701
 
                (attr, re.escape(unicode(getattr(self, attr))))
702
 
                for attr in
703
 
                self.runtime_expansions)
 
687
            escaped_attrs = { attr:
 
688
                                  re.escape(unicode(getattr(self,
 
689
                                                            attr)))
 
690
                              for attr in self.runtime_expansions }
704
691
            try:
705
692
                command = self.checker_command % escaped_attrs
706
693
            except TypeError as error:
787
774
    # "Set" method, so we fail early here:
788
775
    if byte_arrays and signature != "ay":
789
776
        raise ValueError("Byte arrays not supported for non-'ay'"
790
 
                         " signature {0!r}".format(signature))
 
777
                         " signature {!r}".format(signature))
791
778
    def decorator(func):
792
779
        func._dbus_is_property = True
793
780
        func._dbus_interface = dbus_interface
841
828
class DBusPropertyException(dbus.exceptions.DBusException):
842
829
    """A base class for D-Bus property-related exceptions
843
830
    """
844
 
    def __unicode__(self):
845
 
        return unicode(str(self))
846
 
 
 
831
    pass
847
832
 
848
833
class DBusPropertyAccessException(DBusPropertyException):
849
834
    """A property's access permissions disallows an operation.
872
857
        If called like _is_dbus_thing("method") it returns a function
873
858
        suitable for use as predicate to inspect.getmembers().
874
859
        """
875
 
        return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing),
 
860
        return lambda obj: getattr(obj, "_dbus_is_{}".format(thing),
876
861
                                   False)
877
862
    
878
863
    def _get_all_dbus_things(self, thing):
927
912
            # The byte_arrays option is not supported yet on
928
913
            # signatures other than "ay".
929
914
            if prop._dbus_signature != "ay":
930
 
                raise ValueError
 
915
                raise ValueError("Byte arrays not supported for non-"
 
916
                                 "'ay' signature {!r}"
 
917
                                 .format(prop._dbus_signature))
931
918
            value = dbus.ByteArray(b''.join(chr(byte)
932
919
                                            for byte in value))
933
920
        prop(value)
997
984
                                              (prop,
998
985
                                               "_dbus_annotations",
999
986
                                               {}))
1000
 
                        for name, value in annots.iteritems():
 
987
                        for name, value in annots.items():
1001
988
                            ann_tag = document.createElement(
1002
989
                                "annotation")
1003
990
                            ann_tag.setAttribute("name", name)
1006
993
                # Add interface annotation tags
1007
994
                for annotation, value in dict(
1008
995
                    itertools.chain.from_iterable(
1009
 
                        annotations().iteritems()
 
996
                        annotations().items()
1010
997
                        for name, annotations in
1011
998
                        self._get_all_dbus_things("interface")
1012
999
                        if name == if_tag.getAttribute("name")
1013
 
                        )).iteritems():
 
1000
                        )).items():
1014
1001
                    ann_tag = document.createElement("annotation")
1015
1002
                    ann_tag.setAttribute("name", annotation)
1016
1003
                    ann_tag.setAttribute("value", value)
1072
1059
    """
1073
1060
    def wrapper(cls):
1074
1061
        for orig_interface_name, alt_interface_name in (
1075
 
            alt_interface_names.iteritems()):
 
1062
            alt_interface_names.items()):
1076
1063
            attr = {}
1077
1064
            interface_names = set()
1078
1065
            # Go though all attributes of the class
1195
1182
                                        attribute.func_closure)))
1196
1183
            if deprecate:
1197
1184
                # Deprecate all alternate interfaces
1198
 
                iname="_AlternateDBusNames_interface_annotation{0}"
 
1185
                iname="_AlternateDBusNames_interface_annotation{}"
1199
1186
                for interface_name in interface_names:
1200
1187
                    @dbus_interface_annotations(interface_name)
1201
1188
                    def func(self):
1210
1197
            if interface_names:
1211
1198
                # Replace the class with a new subclass of it with
1212
1199
                # methods, signals, etc. as created above.
1213
 
                cls = type(b"{0}Alternate".format(cls.__name__),
 
1200
                cls = type(b"{}Alternate".format(cls.__name__),
1214
1201
                           (cls,), attr)
1215
1202
        return cls
1216
1203
    return wrapper
1257
1244
                   to the D-Bus.  Default: no transform
1258
1245
        variant_level: D-Bus variant level.  Default: 1
1259
1246
        """
1260
 
        attrname = "_{0}".format(dbus_name)
 
1247
        attrname = "_{}".format(dbus_name)
1261
1248
        def setter(self, value):
1262
1249
            if hasattr(self, "dbus_object_path"):
1263
1250
                if (not hasattr(self, attrname) or
1293
1280
    approval_delay = notifychangeproperty(dbus.UInt64,
1294
1281
                                          "ApprovalDelay",
1295
1282
                                          type_func =
1296
 
                                          timedelta_to_milliseconds)
 
1283
                                          lambda td: td.total_seconds()
 
1284
                                          * 1000)
1297
1285
    approval_duration = notifychangeproperty(
1298
1286
        dbus.UInt64, "ApprovalDuration",
1299
 
        type_func = timedelta_to_milliseconds)
 
1287
        type_func = lambda td: td.total_seconds() * 1000)
1300
1288
    host = notifychangeproperty(dbus.String, "Host")
1301
1289
    timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1302
 
                                   type_func =
1303
 
                                   timedelta_to_milliseconds)
 
1290
                                   type_func = lambda td:
 
1291
                                       td.total_seconds() * 1000)
1304
1292
    extended_timeout = notifychangeproperty(
1305
1293
        dbus.UInt64, "ExtendedTimeout",
1306
 
        type_func = timedelta_to_milliseconds)
 
1294
        type_func = lambda td: td.total_seconds() * 1000)
1307
1295
    interval = notifychangeproperty(dbus.UInt64,
1308
1296
                                    "Interval",
1309
1297
                                    type_func =
1310
 
                                    timedelta_to_milliseconds)
 
1298
                                    lambda td: td.total_seconds()
 
1299
                                    * 1000)
1311
1300
    checker_command = notifychangeproperty(dbus.String, "Checker")
1312
1301
    
1313
1302
    del notifychangeproperty
1341
1330
                                       *args, **kwargs)
1342
1331
    
1343
1332
    def start_checker(self, *args, **kwargs):
1344
 
        old_checker = self.checker
1345
 
        if self.checker is not None:
1346
 
            old_checker_pid = self.checker.pid
1347
 
        else:
1348
 
            old_checker_pid = None
 
1333
        old_checker_pid = getattr(self.checker, "pid", None)
1349
1334
        r = Client.start_checker(self, *args, **kwargs)
1350
1335
        # Only if new checker process was started
1351
1336
        if (self.checker is not None
1360
1345
    
1361
1346
    def approve(self, value=True):
1362
1347
        self.approved = value
1363
 
        gobject.timeout_add(timedelta_to_milliseconds
1364
 
                            (self.approval_duration),
1365
 
                            self._reset_approved)
 
1348
        gobject.timeout_add(int(self.approval_duration.total_seconds()
 
1349
                                * 1000), self._reset_approved)
1366
1350
        self.send_changedstate()
1367
1351
    
1368
1352
    ## D-Bus methods, signals & properties
1471
1455
                           access="readwrite")
1472
1456
    def ApprovalDelay_dbus_property(self, value=None):
1473
1457
        if value is None:       # get
1474
 
            return dbus.UInt64(self.approval_delay_milliseconds())
 
1458
            return dbus.UInt64(self.approval_delay.total_seconds()
 
1459
                               * 1000)
1475
1460
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
1476
1461
    
1477
1462
    # ApprovalDuration - property
1479
1464
                           access="readwrite")
1480
1465
    def ApprovalDuration_dbus_property(self, value=None):
1481
1466
        if value is None:       # get
1482
 
            return dbus.UInt64(timedelta_to_milliseconds(
1483
 
                    self.approval_duration))
 
1467
            return dbus.UInt64(self.approval_duration.total_seconds()
 
1468
                               * 1000)
1484
1469
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1485
1470
    
1486
1471
    # Name - property
1552
1537
                           access="readwrite")
1553
1538
    def Timeout_dbus_property(self, value=None):
1554
1539
        if value is None:       # get
1555
 
            return dbus.UInt64(self.timeout_milliseconds())
 
1540
            return dbus.UInt64(self.timeout.total_seconds() * 1000)
1556
1541
        old_timeout = self.timeout
1557
1542
        self.timeout = datetime.timedelta(0, 0, 0, value)
1558
1543
        # Reschedule disabling
1569
1554
                gobject.source_remove(self.disable_initiator_tag)
1570
1555
                self.disable_initiator_tag = (
1571
1556
                    gobject.timeout_add(
1572
 
                        timedelta_to_milliseconds(self.expires - now),
1573
 
                        self.disable))
 
1557
                        int((self.expires - now).total_seconds()
 
1558
                            * 1000), self.disable))
1574
1559
    
1575
1560
    # ExtendedTimeout - property
1576
1561
    @dbus_service_property(_interface, signature="t",
1577
1562
                           access="readwrite")
1578
1563
    def ExtendedTimeout_dbus_property(self, value=None):
1579
1564
        if value is None:       # get
1580
 
            return dbus.UInt64(self.extended_timeout_milliseconds())
 
1565
            return dbus.UInt64(self.extended_timeout.total_seconds()
 
1566
                               * 1000)
1581
1567
        self.extended_timeout = datetime.timedelta(0, 0, 0, value)
1582
1568
    
1583
1569
    # Interval - property
1585
1571
                           access="readwrite")
1586
1572
    def Interval_dbus_property(self, value=None):
1587
1573
        if value is None:       # get
1588
 
            return dbus.UInt64(self.interval_milliseconds())
 
1574
            return dbus.UInt64(self.interval.total_seconds() * 1000)
1589
1575
        self.interval = datetime.timedelta(0, 0, 0, value)
1590
1576
        if getattr(self, "checker_initiator_tag", None) is None:
1591
1577
            return
1624
1610
    @dbus_service_property(_interface, signature="ay",
1625
1611
                           access="write", byte_arrays=True)
1626
1612
    def Secret_dbus_property(self, value):
1627
 
        self.secret = str(value)
 
1613
        self.secret = bytes(value)
1628
1614
    
1629
1615
    del _interface
1630
1616
 
1696
1682
            logger.debug("Protocol version: %r", line)
1697
1683
            try:
1698
1684
                if int(line.strip().split()[0]) > 1:
1699
 
                    raise RuntimeError
 
1685
                    raise RuntimeError(line)
1700
1686
            except (ValueError, IndexError, RuntimeError) as error:
1701
1687
                logger.error("Unknown protocol version: %s", error)
1702
1688
                return
1751
1737
                        if self.server.use_dbus:
1752
1738
                            # Emit D-Bus signal
1753
1739
                            client.NeedApproval(
1754
 
                                client.approval_delay_milliseconds(),
1755
 
                                client.approved_by_default)
 
1740
                                client.approval_delay.total_seconds()
 
1741
                                * 1000, client.approved_by_default)
1756
1742
                    else:
1757
1743
                        logger.warning("Client %s was not approved",
1758
1744
                                       client.name)
1764
1750
                    #wait until timeout or approved
1765
1751
                    time = datetime.datetime.now()
1766
1752
                    client.changedstate.acquire()
1767
 
                    client.changedstate.wait(
1768
 
                        float(timedelta_to_milliseconds(delay)
1769
 
                              / 1000))
 
1753
                    client.changedstate.wait(delay.total_seconds())
1770
1754
                    client.changedstate.release()
1771
1755
                    time2 = datetime.datetime.now()
1772
1756
                    if (time2 - time) >= delay:
1909
1893
    
1910
1894
    def add_pipe(self, parent_pipe, proc):
1911
1895
        """Dummy function; override as necessary"""
1912
 
        raise NotImplementedError
 
1896
        raise NotImplementedError()
1913
1897
 
1914
1898
 
1915
1899
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
1971
1955
                try:
1972
1956
                    self.socket.setsockopt(socket.SOL_SOCKET,
1973
1957
                                           SO_BINDTODEVICE,
1974
 
                                           str(self.interface + '\0'))
 
1958
                                           (self.interface + "\0")
 
1959
                                           .encode("utf-8"))
1975
1960
                except socket.error as error:
1976
1961
                    if error.errno == errno.EPERM:
1977
1962
                        logger.error("No permission to bind to"
2180
2165
    token_duration = Token(re.compile(r"P"), None,
2181
2166
                           frozenset((token_year, token_month,
2182
2167
                                      token_day, token_time,
2183
 
                                      token_week))),
 
2168
                                      token_week)))
2184
2169
    # Define starting values
2185
2170
    value = datetime.timedelta() # Value so far
2186
2171
    found_token = None
2187
 
    followers = frozenset(token_duration,) # Following valid tokens
 
2172
    followers = frozenset((token_duration,)) # Following valid tokens
2188
2173
    s = duration                # String left to parse
2189
2174
    # Loop until end token is found
2190
2175
    while found_token is not token_end:
2237
2222
    timevalue = datetime.timedelta(0)
2238
2223
    for s in interval.split():
2239
2224
        try:
2240
 
            suffix = unicode(s[-1])
 
2225
            suffix = s[-1]
2241
2226
            value = int(s[:-1])
2242
2227
            if suffix == "d":
2243
2228
                delta = datetime.timedelta(value)
2250
2235
            elif suffix == "w":
2251
2236
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
2252
2237
            else:
2253
 
                raise ValueError("Unknown suffix {0!r}"
 
2238
                raise ValueError("Unknown suffix {!r}"
2254
2239
                                 .format(suffix))
2255
 
        except (ValueError, IndexError) as e:
 
2240
        except IndexError as e:
2256
2241
            raise ValueError(*(e.args))
2257
2242
        timevalue += delta
2258
2243
    return timevalue
2273
2258
        # Close all standard open file descriptors
2274
2259
        null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR)
2275
2260
        if not stat.S_ISCHR(os.fstat(null).st_mode):
2276
 
            raise OSError(errno.ENODEV,
2277
 
                          "{0} not a character device"
 
2261
            raise OSError(errno.ENODEV, "{} not a character device"
2278
2262
                          .format(os.devnull))
2279
2263
        os.dup2(null, sys.stdin.fileno())
2280
2264
        os.dup2(null, sys.stdout.fileno())
2290
2274
    
2291
2275
    parser = argparse.ArgumentParser()
2292
2276
    parser.add_argument("-v", "--version", action="version",
2293
 
                        version = "%(prog)s {0}".format(version),
 
2277
                        version = "%(prog)s {}".format(version),
2294
2278
                        help="show version number and exit")
2295
2279
    parser.add_argument("-i", "--interface", metavar="IF",
2296
2280
                        help="Bind to interface IF")
2329
2313
                        help="Directory to save/restore state in")
2330
2314
    parser.add_argument("--foreground", action="store_true",
2331
2315
                        help="Run in foreground", default=None)
 
2316
    parser.add_argument("--no-zeroconf", action="store_false",
 
2317
                        dest="zeroconf", help="Do not use Zeroconf",
 
2318
                        default=None)
2332
2319
    
2333
2320
    options = parser.parse_args()
2334
2321
    
2335
2322
    if options.check:
2336
2323
        import doctest
2337
 
        doctest.testmod()
2338
 
        sys.exit()
 
2324
        fail_count, test_count = doctest.testmod()
 
2325
        sys.exit(os.EX_OK if fail_count == 0 else 1)
2339
2326
    
2340
2327
    # Default values for config file for server-global settings
2341
2328
    server_defaults = { "interface": "",
2343
2330
                        "port": "",
2344
2331
                        "debug": "False",
2345
2332
                        "priority":
2346
 
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:+SIGN-RSA-SHA224",
 
2333
                        "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:+SIGN-RSA-SHA224:+SIGN-RSA-RMD160",
2347
2334
                        "servicename": "Mandos",
2348
2335
                        "use_dbus": "True",
2349
2336
                        "use_ipv6": "True",
2352
2339
                        "socket": "",
2353
2340
                        "statedir": "/var/lib/mandos",
2354
2341
                        "foreground": "False",
 
2342
                        "zeroconf": "True",
2355
2343
                        }
2356
2344
    
2357
2345
    # Parse config file for server-global settings
2384
2372
    for option in ("interface", "address", "port", "debug",
2385
2373
                   "priority", "servicename", "configdir",
2386
2374
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
2387
 
                   "statedir", "socket", "foreground"):
 
2375
                   "statedir", "socket", "foreground", "zeroconf"):
2388
2376
        value = getattr(options, option)
2389
2377
        if value is not None:
2390
2378
            server_settings[option] = value
2391
2379
    del options
2392
2380
    # Force all strings to be unicode
2393
2381
    for option in server_settings.keys():
2394
 
        if type(server_settings[option]) is str:
2395
 
            server_settings[option] = unicode(server_settings[option])
 
2382
        if isinstance(server_settings[option], bytes):
 
2383
            server_settings[option] = (server_settings[option]
 
2384
                                       .decode("utf-8"))
2396
2385
    # Force all boolean options to be boolean
2397
2386
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
2398
 
                   "foreground"):
 
2387
                   "foreground", "zeroconf"):
2399
2388
        server_settings[option] = bool(server_settings[option])
2400
2389
    # Debug implies foreground
2401
2390
    if server_settings["debug"]:
2404
2393
    
2405
2394
    ##################################################################
2406
2395
    
 
2396
    if (not server_settings["zeroconf"] and
 
2397
        not (server_settings["port"]
 
2398
             or server_settings["socket"] != "")):
 
2399
            parser.error("Needs port or socket to work without"
 
2400
                         " Zeroconf")
 
2401
    
2407
2402
    # For convenience
2408
2403
    debug = server_settings["debug"]
2409
2404
    debuglevel = server_settings["debuglevel"]
2412
2407
    stored_state_path = os.path.join(server_settings["statedir"],
2413
2408
                                     stored_state_file)
2414
2409
    foreground = server_settings["foreground"]
 
2410
    zeroconf = server_settings["zeroconf"]
2415
2411
    
2416
2412
    if debug:
2417
2413
        initlogger(debug, logging.DEBUG)
2424
2420
    
2425
2421
    if server_settings["servicename"] != "Mandos":
2426
2422
        syslogger.setFormatter(logging.Formatter
2427
 
                               ('Mandos ({0}) [%(process)d]:'
 
2423
                               ('Mandos ({}) [%(process)d]:'
2428
2424
                                ' %(levelname)s: %(message)s'
2429
2425
                                .format(server_settings
2430
2426
                                        ["servicename"])))
2438
2434
    global mandos_dbus_service
2439
2435
    mandos_dbus_service = None
2440
2436
    
 
2437
    socketfd = None
 
2438
    if server_settings["socket"] != "":
 
2439
        socketfd = server_settings["socket"]
2441
2440
    tcp_server = MandosServer((server_settings["address"],
2442
2441
                               server_settings["port"]),
2443
2442
                              ClientHandler,
2447
2446
                              gnutls_priority=
2448
2447
                              server_settings["priority"],
2449
2448
                              use_dbus=use_dbus,
2450
 
                              socketfd=(server_settings["socket"]
2451
 
                                        or None))
 
2449
                              socketfd=socketfd)
2452
2450
    if not foreground:
2453
2451
        pidfilename = "/run/mandos.pid"
 
2452
        if not os.path.isdir("/run/."):
 
2453
            pidfilename = "/var/run/mandos.pid"
2454
2454
        pidfile = None
2455
2455
        try:
2456
2456
            pidfile = open(pidfilename, "w")
2473
2473
        os.setuid(uid)
2474
2474
    except OSError as error:
2475
2475
        if error.errno != errno.EPERM:
2476
 
            raise error
 
2476
            raise
2477
2477
    
2478
2478
    if debug:
2479
2479
        # Enable all possible GnuTLS debugging
2522
2522
            use_dbus = False
2523
2523
            server_settings["use_dbus"] = False
2524
2524
            tcp_server.use_dbus = False
2525
 
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2526
 
    service = AvahiServiceToSyslog(name =
2527
 
                                   server_settings["servicename"],
2528
 
                                   servicetype = "_mandos._tcp",
2529
 
                                   protocol = protocol, bus = bus)
2530
 
    if server_settings["interface"]:
2531
 
        service.interface = (if_nametoindex
2532
 
                             (str(server_settings["interface"])))
 
2525
    if zeroconf:
 
2526
        protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
 
2527
        service = AvahiServiceToSyslog(name =
 
2528
                                       server_settings["servicename"],
 
2529
                                       servicetype = "_mandos._tcp",
 
2530
                                       protocol = protocol, bus = bus)
 
2531
        if server_settings["interface"]:
 
2532
            service.interface = (if_nametoindex
 
2533
                                 (server_settings["interface"]
 
2534
                                  .encode("utf-8")))
2533
2535
    
2534
2536
    global multiprocessing_manager
2535
2537
    multiprocessing_manager = multiprocessing.Manager()
2559
2561
            os.remove(stored_state_path)
2560
2562
        except IOError as e:
2561
2563
            if e.errno == errno.ENOENT:
2562
 
                logger.warning("Could not load persistent state: {0}"
 
2564
                logger.warning("Could not load persistent state: {}"
2563
2565
                                .format(os.strerror(e.errno)))
2564
2566
            else:
2565
2567
                logger.critical("Could not load persistent state:",
2570
2572
                           "EOFError:", exc_info=e)
2571
2573
    
2572
2574
    with PGPEngine() as pgp:
2573
 
        for client_name, client in clients_data.iteritems():
 
2575
        for client_name, client in clients_data.items():
2574
2576
            # Skip removed clients
2575
2577
            if client_name not in client_settings:
2576
2578
                continue
2601
2603
                if datetime.datetime.utcnow() >= client["expires"]:
2602
2604
                    if not client["last_checked_ok"]:
2603
2605
                        logger.warning(
2604
 
                            "disabling client {0} - Client never "
 
2606
                            "disabling client {} - Client never "
2605
2607
                            "performed a successful checker"
2606
2608
                            .format(client_name))
2607
2609
                        client["enabled"] = False
2608
2610
                    elif client["last_checker_status"] != 0:
2609
2611
                        logger.warning(
2610
 
                            "disabling client {0} - Client "
2611
 
                            "last checker failed with error code {1}"
 
2612
                            "disabling client {} - Client last"
 
2613
                            " checker failed with error code {}"
2612
2614
                            .format(client_name,
2613
2615
                                    client["last_checker_status"]))
2614
2616
                        client["enabled"] = False
2617
2619
                                             .utcnow()
2618
2620
                                             + client["timeout"])
2619
2621
                        logger.debug("Last checker succeeded,"
2620
 
                                     " keeping {0} enabled"
 
2622
                                     " keeping {} enabled"
2621
2623
                                     .format(client_name))
2622
2624
            try:
2623
2625
                client["secret"] = (
2626
2628
                                ["secret"]))
2627
2629
            except PGPError:
2628
2630
                # If decryption fails, we use secret from new settings
2629
 
                logger.debug("Failed to decrypt {0} old secret"
 
2631
                logger.debug("Failed to decrypt {} old secret"
2630
2632
                             .format(client_name))
2631
2633
                client["secret"] = (
2632
2634
                    client_settings[client_name]["secret"])
2640
2642
        clients_data[client_name] = client_settings[client_name]
2641
2643
    
2642
2644
    # Create all client objects
2643
 
    for client_name, client in clients_data.iteritems():
 
2645
    for client_name, client in clients_data.items():
2644
2646
        tcp_server.clients[client_name] = client_class(
2645
2647
            name = client_name, settings = client,
2646
2648
            server_settings = server_settings)
2653
2655
            try:
2654
2656
                with pidfile:
2655
2657
                    pid = os.getpid()
2656
 
                    pidfile.write(str(pid) + "\n".encode("utf-8"))
 
2658
                    pidfile.write("{}\n".format(pid).encode("utf-8"))
2657
2659
            except IOError:
2658
2660
                logger.error("Could not write to file %r with PID %d",
2659
2661
                             pidfilename, pid)
2729
2731
    
2730
2732
    def cleanup():
2731
2733
        "Cleanup function; run on exit"
2732
 
        service.cleanup()
 
2734
        if zeroconf:
 
2735
            service.cleanup()
2733
2736
        
2734
2737
        multiprocessing.active_children()
2735
2738
        wnull.close()
2749
2752
                
2750
2753
                # A list of attributes that can not be pickled
2751
2754
                # + secret.
2752
 
                exclude = set(("bus", "changedstate", "secret",
2753
 
                               "checker", "server_settings"))
 
2755
                exclude = { "bus", "changedstate", "secret",
 
2756
                            "checker", "server_settings" }
2754
2757
                for name, typ in (inspect.getmembers
2755
2758
                                  (dbus.service.Object)):
2756
2759
                    exclude.add(name)
2779
2782
                except NameError:
2780
2783
                    pass
2781
2784
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
2782
 
                logger.warning("Could not save persistent state: {0}"
 
2785
                logger.warning("Could not save persistent state: {}"
2783
2786
                               .format(os.strerror(e.errno)))
2784
2787
            else:
2785
2788
                logger.warning("Could not save persistent state:",
2786
2789
                               exc_info=e)
2787
 
                raise e
 
2790
                raise
2788
2791
        
2789
2792
        # Delete all clients, and settings from config
2790
2793
        while tcp_server.clients:
2814
2817
    tcp_server.server_activate()
2815
2818
    
2816
2819
    # Find out what port we got
2817
 
    service.port = tcp_server.socket.getsockname()[1]
 
2820
    if zeroconf:
 
2821
        service.port = tcp_server.socket.getsockname()[1]
2818
2822
    if use_ipv6:
2819
2823
        logger.info("Now listening on address %r, port %d,"
2820
2824
                    " flowinfo %d, scope_id %d",
2826
2830
    #service.interface = tcp_server.socket.getsockname()[3]
2827
2831
    
2828
2832
    try:
2829
 
        # From the Avahi example code
2830
 
        try:
2831
 
            service.activate()
2832
 
        except dbus.exceptions.DBusException as error:
2833
 
            logger.critical("D-Bus Exception", exc_info=error)
2834
 
            cleanup()
2835
 
            sys.exit(1)
2836
 
        # End of Avahi example code
 
2833
        if zeroconf:
 
2834
            # From the Avahi example code
 
2835
            try:
 
2836
                service.activate()
 
2837
            except dbus.exceptions.DBusException as error:
 
2838
                logger.critical("D-Bus Exception", exc_info=error)
 
2839
                cleanup()
 
2840
                sys.exit(1)
 
2841
            # End of Avahi example code
2837
2842
        
2838
2843
        gobject.io_add_watch(tcp_server.fileno(), gobject.IO_IN,
2839
2844
                             lambda *args, **kwargs: