/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: 2025-06-14 15:37:45 UTC
  • Revision ID: teddy@recompile.se-20250614153745-1labvcqq11fuijy4
debian/control: Require cryptsetup support in systemd

* debian/control (Package: mandos-client/Depends): Add dependency on
  "systemd-cryptsetup" (for newer systemd), or "systemd (<< 256-2)"
  for when cryptsetup support was included in the systemd package
  itself, or "sysvinit-core" for installations without systemd.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python
2
 
# -*- mode: python; coding: utf-8 -*-
 
1
#!/usr/bin/python3 -bI
 
2
# -*- coding: utf-8; lexical-binding: t -*-
3
3
#
4
4
# Mandos server - give out binary blobs to connecting clients.
5
5
#
11
11
# "AvahiService" class, and some lines in "main".
12
12
#
13
13
# Everything else is
14
 
# Copyright © 2008-2019 Teddy Hogeborn
15
 
# Copyright © 2008-2019 Björn Påhlsson
 
14
# Copyright © 2008-2022 Teddy Hogeborn
 
15
# Copyright © 2008-2022 Björn Påhlsson
16
16
#
17
17
# This file is part of Mandos.
18
18
#
31
31
#
32
32
# Contact the authors at <mandos@recompile.se>.
33
33
#
34
 
 
35
34
from __future__ import (division, absolute_import, print_function,
36
35
                        unicode_literals)
37
36
 
40
39
except ImportError:
41
40
    pass
42
41
 
 
42
import sys
 
43
import unittest
 
44
import argparse
 
45
import logging
 
46
import os
43
47
try:
44
48
    import SocketServer as socketserver
45
49
except ImportError:
46
50
    import socketserver
47
51
import socket
48
 
import argparse
49
52
import datetime
50
53
import errno
51
54
try:
52
55
    import ConfigParser as configparser
53
56
except ImportError:
54
57
    import configparser
55
 
import sys
56
58
import re
57
 
import os
58
59
import signal
59
60
import subprocess
60
61
import atexit
61
62
import stat
62
 
import logging
63
63
import logging.handlers
64
64
import pwd
65
65
import contextlib
77
77
import itertools
78
78
import collections
79
79
import codecs
 
80
import random
 
81
import shlex
80
82
 
81
83
import dbus
82
84
import dbus.service
 
85
import gi
83
86
from gi.repository import GLib
84
87
from dbus.mainloop.glib import DBusGMainLoop
85
88
import ctypes
87
90
import xml.dom.minidom
88
91
import inspect
89
92
 
 
93
if sys.version_info.major == 2:
 
94
    __metaclass__ = type
 
95
    str = unicode
 
96
    input = raw_input
 
97
 
 
98
# Add collections.abc.Callable if it does not exist
 
99
try:
 
100
    collections.abc.Callable
 
101
except AttributeError:
 
102
    class abc:
 
103
        Callable = collections.Callable
 
104
    collections.abc = abc
 
105
    del abc
 
106
 
 
107
# Add shlex.quote if it does not exist
 
108
try:
 
109
    shlex.quote
 
110
except AttributeError:
 
111
    shlex.quote = re.escape
 
112
 
 
113
# Add os.set_inheritable if it does not exist
 
114
try:
 
115
    os.set_inheritable
 
116
except AttributeError:
 
117
    def set_inheritable(fd, inheritable):
 
118
        flags = fcntl.fcntl(fd, fcntl.F_GETFD)
 
119
        if inheritable and ((flags & fcntl.FD_CLOEXEC) != 0):
 
120
            fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~fcntl.FD_CLOEXEC)
 
121
        elif (not inheritable) and ((flags & fcntl.FD_CLOEXEC) == 0):
 
122
            fcntl.fcntl(fd, fcntl.F_SETFL, flags | fcntl.FD_CLOEXEC)
 
123
    os.set_inheritable = set_inheritable
 
124
    del set_inheritable
 
125
 
 
126
# Show warnings by default
 
127
if not sys.warnoptions:
 
128
    import warnings
 
129
    warnings.simplefilter("default")
 
130
 
90
131
# Try to find the value of SO_BINDTODEVICE:
91
132
try:
92
133
    # This is where SO_BINDTODEVICE is in Python 3.3 (or 3.4?) and
112
153
            # No value found
113
154
            SO_BINDTODEVICE = None
114
155
 
115
 
if sys.version_info.major == 2:
116
 
    str = unicode
 
156
if sys.version_info < (3, 2):
 
157
    configparser.Configparser = configparser.SafeConfigParser
117
158
 
118
 
version = "1.8.3"
 
159
version = "1.8.18"
119
160
stored_state_file = "clients.pickle"
120
161
 
121
 
logger = logging.getLogger()
 
162
log = logging.getLogger(os.path.basename(sys.argv[0]))
 
163
logging.captureWarnings(True)   # Show warnings via the logging system
122
164
syslogger = None
123
165
 
124
166
try:
160
202
        facility=logging.handlers.SysLogHandler.LOG_DAEMON,
161
203
        address="/dev/log"))
162
204
    syslogger.setFormatter(logging.Formatter
163
 
                           ('Mandos [%(process)d]: %(levelname)s:'
164
 
                            ' %(message)s'))
165
 
    logger.addHandler(syslogger)
 
205
                           ("Mandos [%(process)d]: %(levelname)s:"
 
206
                            " %(message)s"))
 
207
    log.addHandler(syslogger)
166
208
 
167
209
    if debug:
168
210
        console = logging.StreamHandler()
169
 
        console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
170
 
                                               ' [%(process)d]:'
171
 
                                               ' %(levelname)s:'
172
 
                                               ' %(message)s'))
173
 
        logger.addHandler(console)
174
 
    logger.setLevel(level)
 
211
        console.setFormatter(logging.Formatter("%(asctime)s %(name)s"
 
212
                                               " [%(process)d]:"
 
213
                                               " %(levelname)s:"
 
214
                                               " %(message)s"))
 
215
        log.addHandler(console)
 
216
    log.setLevel(level)
175
217
 
176
218
 
177
219
class PGPError(Exception):
179
221
    pass
180
222
 
181
223
 
182
 
class PGPEngine(object):
 
224
class PGPEngine:
183
225
    """A simple class for OpenPGP symmetric encryption & decryption"""
184
226
 
185
227
    def __init__(self):
189
231
            output = subprocess.check_output(["gpgconf"])
190
232
            for line in output.splitlines():
191
233
                name, text, path = line.split(b":")
192
 
                if name == "gpg":
 
234
                if name == b"gpg":
193
235
                    self.gpg = path
194
236
                    break
195
237
        except OSError as e:
196
238
            if e.errno != errno.ENOENT:
197
239
                raise
198
 
        self.gnupgargs = ['--batch',
199
 
                          '--homedir', self.tempdir,
200
 
                          '--force-mdc',
201
 
                          '--quiet']
 
240
        self.gnupgargs = ["--batch",
 
241
                          "--homedir", self.tempdir,
 
242
                          "--force-mdc",
 
243
                          "--quiet"]
202
244
        # Only GPG version 1 has the --no-use-agent option.
203
 
        if self.gpg == "gpg" or self.gpg.endswith("/gpg"):
 
245
        if self.gpg == b"gpg" or self.gpg.endswith(b"/gpg"):
204
246
            self.gnupgargs.append("--no-use-agent")
205
247
 
206
248
    def __enter__(self):
243
285
                dir=self.tempdir) as passfile:
244
286
            passfile.write(passphrase)
245
287
            passfile.flush()
246
 
            proc = subprocess.Popen([self.gpg, '--symmetric',
247
 
                                     '--passphrase-file',
 
288
            proc = subprocess.Popen([self.gpg, "--symmetric",
 
289
                                     "--passphrase-file",
248
290
                                     passfile.name]
249
291
                                    + self.gnupgargs,
250
292
                                    stdin=subprocess.PIPE,
261
303
                dir=self.tempdir) as passfile:
262
304
            passfile.write(passphrase)
263
305
            passfile.flush()
264
 
            proc = subprocess.Popen([self.gpg, '--decrypt',
265
 
                                     '--passphrase-file',
 
306
            proc = subprocess.Popen([self.gpg, "--decrypt",
 
307
                                     "--passphrase-file",
266
308
                                     passfile.name]
267
309
                                    + self.gnupgargs,
268
310
                                    stdin=subprocess.PIPE,
275
317
 
276
318
 
277
319
# Pretend that we have an Avahi module
278
 
class Avahi(object):
279
 
    """This isn't so much a class as it is a module-like namespace.
280
 
    It is instantiated once, and simulates having an Avahi module."""
 
320
class avahi:
 
321
    """This isn't so much a class as it is a module-like namespace."""
281
322
    IF_UNSPEC = -1               # avahi-common/address.h
282
323
    PROTO_UNSPEC = -1            # avahi-common/address.h
283
324
    PROTO_INET = 0               # avahi-common/address.h
287
328
    DBUS_INTERFACE_SERVER = DBUS_NAME + ".Server"
288
329
    DBUS_PATH_SERVER = "/"
289
330
 
290
 
    def string_array_to_txt_array(self, t):
 
331
    @staticmethod
 
332
    def string_array_to_txt_array(t):
291
333
        return dbus.Array((dbus.ByteArray(s.encode("utf-8"))
292
334
                           for s in t), signature="ay")
293
335
    ENTRY_GROUP_ESTABLISHED = 2  # avahi-common/defs.h
298
340
    SERVER_RUNNING = 2           # avahi-common/defs.h
299
341
    SERVER_COLLISION = 3         # avahi-common/defs.h
300
342
    SERVER_FAILURE = 4           # avahi-common/defs.h
301
 
avahi = Avahi()
302
343
 
303
344
 
304
345
class AvahiError(Exception):
316
357
    pass
317
358
 
318
359
 
319
 
class AvahiService(object):
 
360
class AvahiService:
320
361
    """An Avahi (Zeroconf) service.
321
362
 
322
363
    Attributes:
323
364
    interface: integer; avahi.IF_UNSPEC or an interface index.
324
365
               Used to optionally bind to the specified interface.
325
 
    name: string; Example: 'Mandos'
326
 
    type: string; Example: '_mandos._tcp'.
 
366
    name: string; Example: "Mandos"
 
367
    type: string; Example: "_mandos._tcp".
327
368
     See <https://www.iana.org/assignments/service-names-port-numbers>
328
369
    port: integer; what port to announce
329
370
    TXT: list of strings; TXT record for the service
366
407
    def rename(self, remove=True):
367
408
        """Derived from the Avahi example code"""
368
409
        if self.rename_count >= self.max_renames:
369
 
            logger.critical("No suitable Zeroconf service name found"
370
 
                            " after %i retries, exiting.",
371
 
                            self.rename_count)
 
410
            log.critical("No suitable Zeroconf service name found"
 
411
                         " after %i retries, exiting.",
 
412
                         self.rename_count)
372
413
            raise AvahiServiceError("Too many renames")
373
414
        self.name = str(
374
415
            self.server.GetAlternativeServiceName(self.name))
375
416
        self.rename_count += 1
376
 
        logger.info("Changing Zeroconf service name to %r ...",
377
 
                    self.name)
 
417
        log.info("Changing Zeroconf service name to %r ...",
 
418
                 self.name)
378
419
        if remove:
379
420
            self.remove()
380
421
        try:
382
423
        except dbus.exceptions.DBusException as error:
383
424
            if (error.get_dbus_name()
384
425
                == "org.freedesktop.Avahi.CollisionError"):
385
 
                logger.info("Local Zeroconf service name collision.")
 
426
                log.info("Local Zeroconf service name collision.")
386
427
                return self.rename(remove=False)
387
428
            else:
388
 
                logger.critical("D-Bus Exception", exc_info=error)
 
429
                log.critical("D-Bus Exception", exc_info=error)
389
430
                self.cleanup()
390
431
                os._exit(1)
391
432
 
407
448
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
408
449
        self.entry_group_state_changed_match = (
409
450
            self.group.connect_to_signal(
410
 
                'StateChanged', self.entry_group_state_changed))
411
 
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
412
 
                     self.name, self.type)
 
451
                "StateChanged", self.entry_group_state_changed))
 
452
        log.debug("Adding Zeroconf service '%s' of type '%s' ...",
 
453
                  self.name, self.type)
413
454
        self.group.AddService(
414
455
            self.interface,
415
456
            self.protocol,
422
463
 
423
464
    def entry_group_state_changed(self, state, error):
424
465
        """Derived from the Avahi example code"""
425
 
        logger.debug("Avahi entry group state change: %i", state)
 
466
        log.debug("Avahi entry group state change: %i", state)
426
467
 
427
468
        if state == avahi.ENTRY_GROUP_ESTABLISHED:
428
 
            logger.debug("Zeroconf service established.")
 
469
            log.debug("Zeroconf service established.")
429
470
        elif state == avahi.ENTRY_GROUP_COLLISION:
430
 
            logger.info("Zeroconf service name collision.")
 
471
            log.info("Zeroconf service name collision.")
431
472
            self.rename()
432
473
        elif state == avahi.ENTRY_GROUP_FAILURE:
433
 
            logger.critical("Avahi: Error in group state changed %s",
434
 
                            str(error))
 
474
            log.critical("Avahi: Error in group state changed %s",
 
475
                         str(error))
435
476
            raise AvahiGroupError("State changed: {!s}".format(error))
436
477
 
437
478
    def cleanup(self):
447
488
 
448
489
    def server_state_changed(self, state, error=None):
449
490
        """Derived from the Avahi example code"""
450
 
        logger.debug("Avahi server state change: %i", state)
 
491
        log.debug("Avahi server state change: %i", state)
451
492
        bad_states = {
452
493
            avahi.SERVER_INVALID: "Zeroconf server invalid",
453
494
            avahi.SERVER_REGISTERING: None,
457
498
        if state in bad_states:
458
499
            if bad_states[state] is not None:
459
500
                if error is None:
460
 
                    logger.error(bad_states[state])
 
501
                    log.error(bad_states[state])
461
502
                else:
462
 
                    logger.error(bad_states[state] + ": %r", error)
 
503
                    log.error(bad_states[state] + ": %r", error)
463
504
            self.cleanup()
464
505
        elif state == avahi.SERVER_RUNNING:
465
506
            try:
467
508
            except dbus.exceptions.DBusException as error:
468
509
                if (error.get_dbus_name()
469
510
                    == "org.freedesktop.Avahi.CollisionError"):
470
 
                    logger.info("Local Zeroconf service name"
471
 
                                " collision.")
 
511
                    log.info("Local Zeroconf service name collision.")
472
512
                    return self.rename(remove=False)
473
513
                else:
474
 
                    logger.critical("D-Bus Exception", exc_info=error)
 
514
                    log.critical("D-Bus Exception", exc_info=error)
475
515
                    self.cleanup()
476
516
                    os._exit(1)
477
517
        else:
478
518
            if error is None:
479
 
                logger.debug("Unknown state: %r", state)
 
519
                log.debug("Unknown state: %r", state)
480
520
            else:
481
 
                logger.debug("Unknown state: %r: %r", state, error)
 
521
                log.debug("Unknown state: %r: %r", state, error)
482
522
 
483
523
    def activate(self):
484
524
        """Derived from the Avahi example code"""
496
536
class AvahiServiceToSyslog(AvahiService):
497
537
    def rename(self, *args, **kwargs):
498
538
        """Add the new name to the syslog messages"""
499
 
        ret = super(AvahiServiceToSyslog, self).rename(*args, **kwargs)
 
539
        ret = super(AvahiServiceToSyslog, self).rename(*args,
 
540
                                                       **kwargs)
500
541
        syslogger.setFormatter(logging.Formatter(
501
 
            'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
 
542
            "Mandos ({}) [%(process)d]: %(levelname)s: %(message)s"
502
543
            .format(self.name)))
503
544
        return ret
504
545
 
505
546
 
506
547
# Pretend that we have a GnuTLS module
507
 
class GnuTLS(object):
508
 
    """This isn't so much a class as it is a module-like namespace.
509
 
    It is instantiated once, and simulates having a GnuTLS module."""
 
548
class gnutls:
 
549
    """This isn't so much a class as it is a module-like namespace."""
510
550
 
511
551
    library = ctypes.util.find_library("gnutls")
512
552
    if library is None:
513
553
        library = ctypes.util.find_library("gnutls-deb0")
514
554
    _library = ctypes.cdll.LoadLibrary(library)
515
555
    del library
516
 
    _need_version = b"3.3.0"
517
 
    _tls_rawpk_version = b"3.6.6"
518
 
 
519
 
    def __init__(self):
520
 
        # Need to use "self" here, since this method is called before
521
 
        # the assignment to the "gnutls" global variable happens.
522
 
        if self.check_version(self._need_version) is None:
523
 
            raise self.Error("Needs GnuTLS {} or later"
524
 
                             .format(self._need_version))
525
556
 
526
557
    # Unless otherwise indicated, the constants and types below are
527
558
    # all from the gnutls/gnutls.h C header file.
544
575
    OPENPGP_FMT_RAW = 0         # gnutls/openpgp.h
545
576
 
546
577
    # Types
547
 
    class session_int(ctypes.Structure):
 
578
    class _session_int(ctypes.Structure):
548
579
        _fields_ = []
549
 
    session_t = ctypes.POINTER(session_int)
 
580
    session_t = ctypes.POINTER(_session_int)
550
581
 
551
582
    class certificate_credentials_st(ctypes.Structure):
552
583
        _fields_ = []
555
586
    certificate_type_t = ctypes.c_int
556
587
 
557
588
    class datum_t(ctypes.Structure):
558
 
        _fields_ = [('data', ctypes.POINTER(ctypes.c_ubyte)),
559
 
                    ('size', ctypes.c_uint)]
 
589
        _fields_ = [("data", ctypes.POINTER(ctypes.c_ubyte)),
 
590
                    ("size", ctypes.c_uint)]
560
591
 
561
 
    class openpgp_crt_int(ctypes.Structure):
 
592
    class _openpgp_crt_int(ctypes.Structure):
562
593
        _fields_ = []
563
 
    openpgp_crt_t = ctypes.POINTER(openpgp_crt_int)
 
594
    openpgp_crt_t = ctypes.POINTER(_openpgp_crt_int)
564
595
    openpgp_crt_fmt_t = ctypes.c_int  # gnutls/openpgp.h
565
596
    log_func = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
566
597
    credentials_type_t = ctypes.c_int
569
600
 
570
601
    # Exceptions
571
602
    class Error(Exception):
572
 
        # We need to use the class name "GnuTLS" here, since this
573
 
        # exception might be raised from within GnuTLS.__init__,
574
 
        # which is called before the assignment to the "gnutls"
575
 
        # global variable has happened.
576
603
        def __init__(self, message=None, code=None, args=()):
577
604
            # Default usage is by a message string, but if a return
578
605
            # code is passed, convert it to a string with
579
606
            # gnutls.strerror()
580
607
            self.code = code
581
608
            if message is None and code is not None:
582
 
                message = GnuTLS.strerror(code)
583
 
            return super(GnuTLS.Error, self).__init__(
 
609
                message = gnutls.strerror(code).decode(
 
610
                    "utf-8", errors="replace")
 
611
            return super(gnutls.Error, self).__init__(
584
612
                message, *args)
585
613
 
586
614
    class CertificateSecurityError(Error):
587
615
        pass
588
616
 
 
617
    class PointerTo:
 
618
        def __init__(self, cls):
 
619
            self.cls = cls
 
620
 
 
621
        def from_param(self, obj):
 
622
            if not isinstance(obj, self.cls):
 
623
                raise TypeError("Not of type {}: {!r}"
 
624
                                .format(self.cls.__name__, obj))
 
625
            return ctypes.byref(obj.from_param(obj))
 
626
 
 
627
    class CastToVoidPointer:
 
628
        def __init__(self, cls):
 
629
            self.cls = cls
 
630
 
 
631
        def from_param(self, obj):
 
632
            if not isinstance(obj, self.cls):
 
633
                raise TypeError("Not of type {}: {!r}"
 
634
                                .format(self.cls.__name__, obj))
 
635
            return ctypes.cast(obj.from_param(obj), ctypes.c_void_p)
 
636
 
 
637
    class With_from_param:
 
638
        @classmethod
 
639
        def from_param(cls, obj):
 
640
            return obj._as_parameter_
 
641
 
589
642
    # Classes
590
 
    class Credentials(object):
 
643
    class Credentials(With_from_param):
591
644
        def __init__(self):
592
 
            self._c_object = gnutls.certificate_credentials_t()
593
 
            gnutls.certificate_allocate_credentials(
594
 
                ctypes.byref(self._c_object))
 
645
            self._as_parameter_ = gnutls.certificate_credentials_t()
 
646
            gnutls.certificate_allocate_credentials(self)
595
647
            self.type = gnutls.CRD_CERTIFICATE
596
648
 
597
649
        def __del__(self):
598
 
            gnutls.certificate_free_credentials(self._c_object)
 
650
            gnutls.certificate_free_credentials(self)
599
651
 
600
 
    class ClientSession(object):
 
652
    class ClientSession(With_from_param):
601
653
        def __init__(self, socket, credentials=None):
602
 
            self._c_object = gnutls.session_t()
 
654
            self._as_parameter_ = gnutls.session_t()
603
655
            gnutls_flags = gnutls.CLIENT
604
 
            if gnutls.check_version("3.5.6"):
 
656
            if gnutls.check_version(b"3.5.6"):
605
657
                gnutls_flags |= gnutls.NO_TICKETS
606
658
            if gnutls.has_rawpk:
607
659
                gnutls_flags |= gnutls.ENABLE_RAWPK
608
 
            gnutls.init(ctypes.byref(self._c_object), gnutls_flags)
 
660
            gnutls.init(self, gnutls_flags)
609
661
            del gnutls_flags
610
 
            gnutls.set_default_priority(self._c_object)
611
 
            gnutls.transport_set_ptr(self._c_object, socket.fileno())
612
 
            gnutls.handshake_set_private_extensions(self._c_object,
613
 
                                                    True)
 
662
            gnutls.set_default_priority(self)
 
663
            gnutls.transport_set_ptr(self, socket.fileno())
 
664
            gnutls.handshake_set_private_extensions(self, True)
614
665
            self.socket = socket
615
666
            if credentials is None:
616
667
                credentials = gnutls.Credentials()
617
 
            gnutls.credentials_set(self._c_object, credentials.type,
618
 
                                   ctypes.cast(credentials._c_object,
619
 
                                               ctypes.c_void_p))
 
668
            gnutls.credentials_set(self, credentials.type,
 
669
                                   credentials)
620
670
            self.credentials = credentials
621
671
 
622
672
        def __del__(self):
623
 
            gnutls.deinit(self._c_object)
 
673
            gnutls.deinit(self)
624
674
 
625
675
        def handshake(self):
626
 
            return gnutls.handshake(self._c_object)
 
676
            return gnutls.handshake(self)
627
677
 
628
678
        def send(self, data):
629
679
            data = bytes(data)
630
680
            data_len = len(data)
631
681
            while data_len > 0:
632
 
                data_len -= gnutls.record_send(self._c_object,
633
 
                                               data[-data_len:],
 
682
                data_len -= gnutls.record_send(self, data[-data_len:],
634
683
                                               data_len)
635
684
 
636
685
        def bye(self):
637
 
            return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
 
686
            return gnutls.bye(self, gnutls.SHUT_RDWR)
638
687
 
639
688
    # Error handling functions
640
689
    def _error_code(result):
641
690
        """A function to raise exceptions on errors, suitable
642
 
        for the 'restype' attribute on ctypes functions"""
643
 
        if result >= 0:
 
691
        for the "restype" attribute on ctypes functions"""
 
692
        if result >= gnutls.E_SUCCESS:
644
693
            return result
645
694
        if result == gnutls.E_NO_CERTIFICATE_FOUND:
646
695
            raise gnutls.CertificateSecurityError(code=result)
647
696
        raise gnutls.Error(code=result)
648
697
 
649
 
    def _retry_on_error(result, func, arguments):
 
698
    def _retry_on_error(result, func, arguments,
 
699
                        _error_code=_error_code):
650
700
        """A function to retry on some errors, suitable
651
 
        for the 'errcheck' attribute on ctypes functions"""
652
 
        while result < 0:
 
701
        for the "errcheck" attribute on ctypes functions"""
 
702
        while result < gnutls.E_SUCCESS:
653
703
            if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
654
704
                return _error_code(result)
655
705
            result = func(*arguments)
660
710
 
661
711
    # Functions
662
712
    priority_set_direct = _library.gnutls_priority_set_direct
663
 
    priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
 
713
    priority_set_direct.argtypes = [ClientSession, ctypes.c_char_p,
664
714
                                    ctypes.POINTER(ctypes.c_char_p)]
665
715
    priority_set_direct.restype = _error_code
666
716
 
667
717
    init = _library.gnutls_init
668
 
    init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
 
718
    init.argtypes = [PointerTo(ClientSession), ctypes.c_int]
669
719
    init.restype = _error_code
670
720
 
671
721
    set_default_priority = _library.gnutls_set_default_priority
672
 
    set_default_priority.argtypes = [session_t]
 
722
    set_default_priority.argtypes = [ClientSession]
673
723
    set_default_priority.restype = _error_code
674
724
 
675
725
    record_send = _library.gnutls_record_send
676
 
    record_send.argtypes = [session_t, ctypes.c_void_p,
 
726
    record_send.argtypes = [ClientSession, ctypes.c_void_p,
677
727
                            ctypes.c_size_t]
678
728
    record_send.restype = ctypes.c_ssize_t
679
729
    record_send.errcheck = _retry_on_error
681
731
    certificate_allocate_credentials = (
682
732
        _library.gnutls_certificate_allocate_credentials)
683
733
    certificate_allocate_credentials.argtypes = [
684
 
        ctypes.POINTER(certificate_credentials_t)]
 
734
        PointerTo(Credentials)]
685
735
    certificate_allocate_credentials.restype = _error_code
686
736
 
687
737
    certificate_free_credentials = (
688
738
        _library.gnutls_certificate_free_credentials)
689
 
    certificate_free_credentials.argtypes = [
690
 
        certificate_credentials_t]
 
739
    certificate_free_credentials.argtypes = [Credentials]
691
740
    certificate_free_credentials.restype = None
692
741
 
693
742
    handshake_set_private_extensions = (
694
743
        _library.gnutls_handshake_set_private_extensions)
695
 
    handshake_set_private_extensions.argtypes = [session_t,
 
744
    handshake_set_private_extensions.argtypes = [ClientSession,
696
745
                                                 ctypes.c_int]
697
746
    handshake_set_private_extensions.restype = None
698
747
 
699
748
    credentials_set = _library.gnutls_credentials_set
700
 
    credentials_set.argtypes = [session_t, credentials_type_t,
701
 
                                ctypes.c_void_p]
 
749
    credentials_set.argtypes = [ClientSession, credentials_type_t,
 
750
                                CastToVoidPointer(Credentials)]
702
751
    credentials_set.restype = _error_code
703
752
 
704
753
    strerror = _library.gnutls_strerror
706
755
    strerror.restype = ctypes.c_char_p
707
756
 
708
757
    certificate_type_get = _library.gnutls_certificate_type_get
709
 
    certificate_type_get.argtypes = [session_t]
 
758
    certificate_type_get.argtypes = [ClientSession]
710
759
    certificate_type_get.restype = _error_code
711
760
 
712
761
    certificate_get_peers = _library.gnutls_certificate_get_peers
713
 
    certificate_get_peers.argtypes = [session_t,
 
762
    certificate_get_peers.argtypes = [ClientSession,
714
763
                                      ctypes.POINTER(ctypes.c_uint)]
715
764
    certificate_get_peers.restype = ctypes.POINTER(datum_t)
716
765
 
723
772
    global_set_log_function.restype = None
724
773
 
725
774
    deinit = _library.gnutls_deinit
726
 
    deinit.argtypes = [session_t]
 
775
    deinit.argtypes = [ClientSession]
727
776
    deinit.restype = None
728
777
 
729
778
    handshake = _library.gnutls_handshake
730
 
    handshake.argtypes = [session_t]
731
 
    handshake.restype = _error_code
 
779
    handshake.argtypes = [ClientSession]
 
780
    handshake.restype = ctypes.c_int
732
781
    handshake.errcheck = _retry_on_error
733
782
 
734
783
    transport_set_ptr = _library.gnutls_transport_set_ptr
735
 
    transport_set_ptr.argtypes = [session_t, transport_ptr_t]
 
784
    transport_set_ptr.argtypes = [ClientSession, transport_ptr_t]
736
785
    transport_set_ptr.restype = None
737
786
 
738
787
    bye = _library.gnutls_bye
739
 
    bye.argtypes = [session_t, close_request_t]
740
 
    bye.restype = _error_code
 
788
    bye.argtypes = [ClientSession, close_request_t]
 
789
    bye.restype = ctypes.c_int
741
790
    bye.errcheck = _retry_on_error
742
791
 
743
792
    check_version = _library.gnutls_check_version
744
793
    check_version.argtypes = [ctypes.c_char_p]
745
794
    check_version.restype = ctypes.c_char_p
746
795
 
 
796
    _need_version = b"3.3.0"
 
797
    if check_version(_need_version) is None:
 
798
        raise self.Error("Needs GnuTLS {} or later"
 
799
                         .format(_need_version))
 
800
 
 
801
    _tls_rawpk_version = b"3.6.6"
747
802
    has_rawpk = bool(check_version(_tls_rawpk_version))
748
803
 
749
804
    if has_rawpk:
754
809
 
755
810
        x509_crt_fmt_t = ctypes.c_int
756
811
 
757
 
        # All the function declarations below are from gnutls/abstract.h
 
812
        # All the function declarations below are from
 
813
        # gnutls/abstract.h
758
814
        pubkey_init = _library.gnutls_pubkey_init
759
815
        pubkey_init.argtypes = [ctypes.POINTER(pubkey_t)]
760
816
        pubkey_init.restype = _error_code
774
830
        pubkey_deinit.argtypes = [pubkey_t]
775
831
        pubkey_deinit.restype = None
776
832
    else:
777
 
        # All the function declarations below are from gnutls/openpgp.h
 
833
        # All the function declarations below are from
 
834
        # gnutls/openpgp.h
778
835
 
779
836
        openpgp_crt_init = _library.gnutls_openpgp_crt_init
780
837
        openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
786
843
                                       openpgp_crt_fmt_t]
787
844
        openpgp_crt_import.restype = _error_code
788
845
 
789
 
        openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
790
 
        openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
791
 
                                            ctypes.POINTER(ctypes.c_uint)]
 
846
        openpgp_crt_verify_self = \
 
847
            _library.gnutls_openpgp_crt_verify_self
 
848
        openpgp_crt_verify_self.argtypes = [
 
849
            openpgp_crt_t,
 
850
            ctypes.c_uint,
 
851
            ctypes.POINTER(ctypes.c_uint),
 
852
        ]
792
853
        openpgp_crt_verify_self.restype = _error_code
793
854
 
794
855
        openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
803
864
                                                    ctypes.c_size_t)]
804
865
        openpgp_crt_get_fingerprint.restype = _error_code
805
866
 
806
 
    if check_version("3.6.4"):
 
867
    if check_version(b"3.6.4"):
807
868
        certificate_type_get2 = _library.gnutls_certificate_type_get2
808
 
        certificate_type_get2.argtypes = [session_t, ctypes.c_int]
 
869
        certificate_type_get2.argtypes = [ClientSession, ctypes.c_int]
809
870
        certificate_type_get2.restype = _error_code
810
871
 
811
872
    # Remove non-public functions
812
873
    del _error_code, _retry_on_error
813
 
# Create the global "gnutls" object, simulating a module
814
 
gnutls = GnuTLS()
815
874
 
816
875
 
817
876
def call_pipe(connection,       # : multiprocessing.Connection
825
884
    connection.close()
826
885
 
827
886
 
828
 
class Client(object):
 
887
class Client:
829
888
    """A representation of a client host served by this server.
830
889
 
831
890
    Attributes:
832
 
    approved:   bool(); 'None' if not yet approved/disapproved
 
891
    approved:   bool(); None if not yet approved/disapproved
833
892
    approval_delay: datetime.timedelta(); Time to wait for approval
834
893
    approval_duration: datetime.timedelta(); Duration of one approval
835
 
    checker:    subprocess.Popen(); a running checker process used
836
 
                                    to see if the client lives.
837
 
                                    'None' if no process is running.
 
894
    checker: multiprocessing.Process(); a running checker process used
 
895
             to see if the client lives. None if no process is
 
896
             running.
838
897
    checker_callback_tag: a GLib event source tag, or None
839
898
    checker_command: string; External command which is run to check
840
899
                     if client lives.  %() expansions are done at
915
974
            # key_id() and fingerprint() functions
916
975
            client["key_id"] = (section.get("key_id", "").upper()
917
976
                                .replace(" ", ""))
918
 
            client["fingerprint"] = (section["fingerprint"].upper()
 
977
            client["fingerprint"] = (section.get("fingerprint",
 
978
                                                 "").upper()
919
979
                                     .replace(" ", ""))
 
980
            if not (client["key_id"] or client["fingerprint"]):
 
981
                log.error("Skipping client %s without key_id or"
 
982
                          " fingerprint", client_name)
 
983
                del settings[client_name]
 
984
                continue
920
985
            if "secret" in section:
921
986
                client["secret"] = codecs.decode(section["secret"]
922
987
                                                 .encode("utf-8"),
963
1028
            self.last_enabled = None
964
1029
            self.expires = None
965
1030
 
966
 
        logger.debug("Creating client %r", self.name)
967
 
        logger.debug("  Key ID: %s", self.key_id)
968
 
        logger.debug("  Fingerprint: %s", self.fingerprint)
 
1031
        log.debug("Creating client %r", self.name)
 
1032
        log.debug("  Key ID: %s", self.key_id)
 
1033
        log.debug("  Fingerprint: %s", self.fingerprint)
969
1034
        self.created = settings.get("created",
970
1035
                                    datetime.datetime.utcnow())
971
1036
 
999
1064
        if getattr(self, "enabled", False):
1000
1065
            # Already enabled
1001
1066
            return
1002
 
        self.expires = datetime.datetime.utcnow() + self.timeout
1003
1067
        self.enabled = True
1004
1068
        self.last_enabled = datetime.datetime.utcnow()
1005
1069
        self.init_checker()
1010
1074
        if not getattr(self, "enabled", False):
1011
1075
            return False
1012
1076
        if not quiet:
1013
 
            logger.info("Disabling client %s", self.name)
 
1077
            log.info("Disabling client %s", self.name)
1014
1078
        if getattr(self, "disable_initiator_tag", None) is not None:
1015
1079
            GLib.source_remove(self.disable_initiator_tag)
1016
1080
            self.disable_initiator_tag = None
1028
1092
    def __del__(self):
1029
1093
        self.disable()
1030
1094
 
1031
 
    def init_checker(self):
1032
 
        # Schedule a new checker to be started an 'interval' from now,
1033
 
        # and every interval from then on.
 
1095
    def init_checker(self, randomize_start=False):
 
1096
        # Schedule a new checker to be started a randomly selected
 
1097
        # time (a fraction of 'interval') from now.  This spreads out
 
1098
        # the startup of checkers over time when the server is
 
1099
        # started.
1034
1100
        if self.checker_initiator_tag is not None:
1035
1101
            GLib.source_remove(self.checker_initiator_tag)
 
1102
        interval_milliseconds = int(self.interval.total_seconds()
 
1103
                                    * 1000)
 
1104
        if randomize_start:
 
1105
            delay_milliseconds = random.randrange(
 
1106
                interval_milliseconds + 1)
 
1107
        else:
 
1108
            delay_milliseconds = interval_milliseconds
1036
1109
        self.checker_initiator_tag = GLib.timeout_add(
1037
 
            int(self.interval.total_seconds() * 1000),
1038
 
            self.start_checker)
1039
 
        # Schedule a disable() when 'timeout' has passed
 
1110
            delay_milliseconds, self.start_checker, randomize_start)
 
1111
        delay = datetime.timedelta(0, 0, 0, delay_milliseconds)
 
1112
        # A checker might take up to an 'interval' of time, so we can
 
1113
        # expire at the soonest one interval after a checker was
 
1114
        # started.  Since the initial checker is delayed, the expire
 
1115
        # time might have to be extended.
 
1116
        now = datetime.datetime.utcnow()
 
1117
        self.expires = now + delay + self.interval
 
1118
        # Schedule a disable() at expire time
1040
1119
        if self.disable_initiator_tag is not None:
1041
1120
            GLib.source_remove(self.disable_initiator_tag)
1042
1121
        self.disable_initiator_tag = GLib.timeout_add(
1043
 
            int(self.timeout.total_seconds() * 1000), self.disable)
1044
 
        # Also start a new checker *right now*.
1045
 
        self.start_checker()
 
1122
            int((self.expires - now).total_seconds() * 1000),
 
1123
            self.disable)
1046
1124
 
1047
1125
    def checker_callback(self, source, condition, connection,
1048
1126
                         command):
1049
1127
        """The checker has completed, so take appropriate actions."""
1050
 
        self.checker_callback_tag = None
1051
 
        self.checker = None
1052
1128
        # Read return code from connection (see call_pipe)
1053
1129
        returncode = connection.recv()
1054
1130
        connection.close()
 
1131
        if self.checker is not None:
 
1132
            self.checker.join()
 
1133
        self.checker_callback_tag = None
 
1134
        self.checker = None
1055
1135
 
1056
1136
        if returncode >= 0:
1057
1137
            self.last_checker_status = returncode
1058
1138
            self.last_checker_signal = None
1059
1139
            if self.last_checker_status == 0:
1060
 
                logger.info("Checker for %(name)s succeeded",
1061
 
                            vars(self))
 
1140
                log.info("Checker for %(name)s succeeded", vars(self))
1062
1141
                self.checked_ok()
1063
1142
            else:
1064
 
                logger.info("Checker for %(name)s failed", vars(self))
 
1143
                log.info("Checker for %(name)s failed", vars(self))
1065
1144
        else:
1066
1145
            self.last_checker_status = -1
1067
1146
            self.last_checker_signal = -returncode
1068
 
            logger.warning("Checker for %(name)s crashed?",
1069
 
                           vars(self))
 
1147
            log.warning("Checker for %(name)s crashed?", vars(self))
1070
1148
        return False
1071
1149
 
1072
1150
    def checked_ok(self):
1091
1169
    def need_approval(self):
1092
1170
        self.last_approval_request = datetime.datetime.utcnow()
1093
1171
 
1094
 
    def start_checker(self):
 
1172
    def start_checker(self, start_was_randomized=False):
1095
1173
        """Start a new checker subprocess if one is not running.
1096
1174
 
1097
1175
        If a checker already exists, leave it running and do
1106
1184
        # should be.
1107
1185
 
1108
1186
        if self.checker is not None and not self.checker.is_alive():
1109
 
            logger.warning("Checker was not alive; joining")
 
1187
            log.warning("Checker was not alive; joining")
1110
1188
            self.checker.join()
1111
1189
            self.checker = None
1112
1190
        # Start a new checker if needed
1113
1191
        if self.checker is None:
1114
1192
            # Escape attributes for the shell
1115
1193
            escaped_attrs = {
1116
 
                attr: re.escape(str(getattr(self, attr)))
 
1194
                attr: shlex.quote(str(getattr(self, attr)))
1117
1195
                for attr in self.runtime_expansions}
1118
1196
            try:
1119
1197
                command = self.checker_command % escaped_attrs
1120
1198
            except TypeError as error:
1121
 
                logger.error('Could not format string "%s"',
1122
 
                             self.checker_command,
1123
 
                             exc_info=error)
 
1199
                log.error('Could not format string "%s"',
 
1200
                          self.checker_command, exc_info=error)
1124
1201
                return True     # Try again later
1125
1202
            self.current_checker_command = command
1126
 
            logger.info("Starting checker %r for %s", command,
1127
 
                        self.name)
 
1203
            log.info("Starting checker %r for %s", command, self.name)
1128
1204
            # We don't need to redirect stdout and stderr, since
1129
1205
            # in normal mode, that is already done by daemon(),
1130
1206
            # and in debug mode we don't want to.  (Stdin is
1146
1222
                kwargs=popen_args)
1147
1223
            self.checker.start()
1148
1224
            self.checker_callback_tag = GLib.io_add_watch(
1149
 
                pipe[0].fileno(), GLib.IO_IN,
 
1225
                GLib.IOChannel.unix_new(pipe[0].fileno()),
 
1226
                GLib.PRIORITY_DEFAULT, GLib.IO_IN,
1150
1227
                self.checker_callback, pipe[0], command)
 
1228
        if start_was_randomized:
 
1229
            # We were started after a random delay; Schedule a new
 
1230
            # checker to be started an 'interval' from now, and every
 
1231
            # interval from then on.
 
1232
            now = datetime.datetime.utcnow()
 
1233
            self.checker_initiator_tag = GLib.timeout_add(
 
1234
                int(self.interval.total_seconds() * 1000),
 
1235
                self.start_checker)
 
1236
            self.expires = max(self.expires, now + self.interval)
 
1237
            # Don't start a new checker again after same random delay
 
1238
            return False
1151
1239
        # Re-run this periodically if run by GLib.timeout_add
1152
1240
        return True
1153
1241
 
1158
1246
            self.checker_callback_tag = None
1159
1247
        if getattr(self, "checker", None) is None:
1160
1248
            return
1161
 
        logger.debug("Stopping checker for %(name)s", vars(self))
 
1249
        log.debug("Stopping checker for %(name)s", vars(self))
1162
1250
        self.checker.terminate()
1163
1251
        self.checker = None
1164
1252
 
1191
1279
        func._dbus_name = func.__name__
1192
1280
        if func._dbus_name.endswith("_dbus_property"):
1193
1281
            func._dbus_name = func._dbus_name[:-14]
1194
 
        func._dbus_get_args_options = {'byte_arrays': byte_arrays}
 
1282
        func._dbus_get_args_options = {"byte_arrays": byte_arrays}
1195
1283
        return func
1196
1284
 
1197
1285
    return decorator
1286
1374
 
1287
1375
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1288
1376
                         out_signature="s",
1289
 
                         path_keyword='object_path',
1290
 
                         connection_keyword='connection')
 
1377
                         path_keyword="object_path",
 
1378
                         connection_keyword="connection")
1291
1379
    def Introspect(self, object_path, connection):
1292
1380
        """Overloading of standard D-Bus method.
1293
1381
 
1342
1430
            document.unlink()
1343
1431
        except (AttributeError, xml.dom.DOMException,
1344
1432
                xml.parsers.expat.ExpatError) as error:
1345
 
            logger.error("Failed to override Introspection method",
1346
 
                         exc_info=error)
 
1433
            log.error("Failed to override Introspection method",
 
1434
                      exc_info=error)
1347
1435
        return xmlstring
1348
1436
 
1349
1437
 
1407
1495
                raise ValueError("Byte arrays not supported for non-"
1408
1496
                                 "'ay' signature {!r}"
1409
1497
                                 .format(prop._dbus_signature))
1410
 
            value = dbus.ByteArray(b''.join(chr(byte)
1411
 
                                            for byte in value))
 
1498
            value = dbus.ByteArray(bytes(value))
1412
1499
        prop(value)
1413
1500
 
1414
1501
    @dbus.service.method(dbus.PROPERTIES_IFACE,
1447
1534
 
1448
1535
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1449
1536
                         out_signature="s",
1450
 
                         path_keyword='object_path',
1451
 
                         connection_keyword='connection')
 
1537
                         path_keyword="object_path",
 
1538
                         connection_keyword="connection")
1452
1539
    def Introspect(self, object_path, connection):
1453
1540
        """Overloading of standard D-Bus method.
1454
1541
 
1510
1597
            document.unlink()
1511
1598
        except (AttributeError, xml.dom.DOMException,
1512
1599
                xml.parsers.expat.ExpatError) as error:
1513
 
            logger.error("Failed to override Introspection method",
1514
 
                         exc_info=error)
 
1600
            log.error("Failed to override Introspection method",
 
1601
                      exc_info=error)
1515
1602
        return xmlstring
1516
1603
 
1517
1604
 
1549
1636
 
1550
1637
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
1551
1638
                         out_signature="s",
1552
 
                         path_keyword='object_path',
1553
 
                         connection_keyword='connection')
 
1639
                         path_keyword="object_path",
 
1640
                         connection_keyword="connection")
1554
1641
    def Introspect(self, object_path, connection):
1555
1642
        """Overloading of standard D-Bus method.
1556
1643
 
1581
1668
            document.unlink()
1582
1669
        except (AttributeError, xml.dom.DOMException,
1583
1670
                xml.parsers.expat.ExpatError) as error:
1584
 
            logger.error("Failed to override Introspection method",
1585
 
                         exc_info=error)
 
1671
            log.error("Failed to override Introspection method",
 
1672
                      exc_info=error)
1586
1673
        return xmlstring
1587
1674
 
1588
1675
 
2219
2306
    del _interface
2220
2307
 
2221
2308
 
2222
 
class ProxyClient(object):
 
2309
class ProxyClient:
2223
2310
    def __init__(self, child_pipe, key_id, fpr, address):
2224
2311
        self._pipe = child_pipe
2225
 
        self._pipe.send(('init', key_id, fpr, address))
 
2312
        self._pipe.send(("init", key_id, fpr, address))
2226
2313
        if not self._pipe.recv():
2227
2314
            raise KeyError(key_id or fpr)
2228
2315
 
2229
2316
    def __getattribute__(self, name):
2230
 
        if name == '_pipe':
 
2317
        if name == "_pipe":
2231
2318
            return super(ProxyClient, self).__getattribute__(name)
2232
 
        self._pipe.send(('getattr', name))
 
2319
        self._pipe.send(("getattr", name))
2233
2320
        data = self._pipe.recv()
2234
 
        if data[0] == 'data':
 
2321
        if data[0] == "data":
2235
2322
            return data[1]
2236
 
        if data[0] == 'function':
 
2323
        if data[0] == "function":
2237
2324
 
2238
2325
            def func(*args, **kwargs):
2239
 
                self._pipe.send(('funcall', name, args, kwargs))
 
2326
                self._pipe.send(("funcall", name, args, kwargs))
2240
2327
                return self._pipe.recv()[1]
2241
2328
 
2242
2329
            return func
2243
2330
 
2244
2331
    def __setattr__(self, name, value):
2245
 
        if name == '_pipe':
 
2332
        if name == "_pipe":
2246
2333
            return super(ProxyClient, self).__setattr__(name, value)
2247
 
        self._pipe.send(('setattr', name, value))
 
2334
        self._pipe.send(("setattr", name, value))
2248
2335
 
2249
2336
 
2250
2337
class ClientHandler(socketserver.BaseRequestHandler, object):
2255
2342
 
2256
2343
    def handle(self):
2257
2344
        with contextlib.closing(self.server.child_pipe) as child_pipe:
2258
 
            logger.info("TCP connection from: %s",
2259
 
                        str(self.client_address))
2260
 
            logger.debug("Pipe FD: %d",
2261
 
                         self.server.child_pipe.fileno())
 
2345
            log.info("TCP connection from: %s",
 
2346
                     str(self.client_address))
 
2347
            log.debug("Pipe FD: %d", self.server.child_pipe.fileno())
2262
2348
 
2263
2349
            session = gnutls.ClientSession(self.request)
2264
2350
 
2265
 
            # priority = ':'.join(("NONE", "+VERS-TLS1.1",
 
2351
            # priority = ":".join(("NONE", "+VERS-TLS1.1",
2266
2352
            #                       "+AES-256-CBC", "+SHA1",
2267
2353
            #                       "+COMP-NULL", "+CTYPE-OPENPGP",
2268
2354
            #                       "+DHE-DSS"))
2270
2356
            priority = self.server.gnutls_priority
2271
2357
            if priority is None:
2272
2358
                priority = "NORMAL"
2273
 
            gnutls.priority_set_direct(session._c_object,
2274
 
                                       priority.encode("utf-8"),
2275
 
                                       None)
 
2359
            gnutls.priority_set_direct(session,
 
2360
                                       priority.encode("utf-8"), None)
2276
2361
 
2277
2362
            # Start communication using the Mandos protocol
2278
2363
            # Get protocol number
2279
2364
            line = self.request.makefile().readline()
2280
 
            logger.debug("Protocol version: %r", line)
 
2365
            log.debug("Protocol version: %r", line)
2281
2366
            try:
2282
2367
                if int(line.strip().split()[0]) > 1:
2283
2368
                    raise RuntimeError(line)
2284
2369
            except (ValueError, IndexError, RuntimeError) as error:
2285
 
                logger.error("Unknown protocol version: %s", error)
 
2370
                log.error("Unknown protocol version: %s", error)
2286
2371
                return
2287
2372
 
2288
2373
            # Start GnuTLS connection
2289
2374
            try:
2290
2375
                session.handshake()
2291
2376
            except gnutls.Error as error:
2292
 
                logger.warning("Handshake failed: %s", error)
 
2377
                log.warning("Handshake failed: %s", error)
2293
2378
                # Do not run session.bye() here: the session is not
2294
2379
                # established.  Just abandon the request.
2295
2380
                return
2296
 
            logger.debug("Handshake succeeded")
 
2381
            log.debug("Handshake succeeded")
2297
2382
 
2298
2383
            approval_required = False
2299
2384
            try:
2300
2385
                if gnutls.has_rawpk:
2301
 
                    fpr = ""
 
2386
                    fpr = b""
2302
2387
                    try:
2303
2388
                        key_id = self.key_id(
2304
2389
                            self.peer_certificate(session))
2305
2390
                    except (TypeError, gnutls.Error) as error:
2306
 
                        logger.warning("Bad certificate: %s", error)
 
2391
                        log.warning("Bad certificate: %s", error)
2307
2392
                        return
2308
 
                    logger.debug("Key ID: %s", key_id)
 
2393
                    log.debug("Key ID: %s",
 
2394
                              key_id.decode("utf-8",
 
2395
                                            errors="replace"))
2309
2396
 
2310
2397
                else:
2311
 
                    key_id = ""
 
2398
                    key_id = b""
2312
2399
                    try:
2313
2400
                        fpr = self.fingerprint(
2314
2401
                            self.peer_certificate(session))
2315
2402
                    except (TypeError, gnutls.Error) as error:
2316
 
                        logger.warning("Bad certificate: %s", error)
 
2403
                        log.warning("Bad certificate: %s", error)
2317
2404
                        return
2318
 
                    logger.debug("Fingerprint: %s", fpr)
 
2405
                    log.debug("Fingerprint: %s", fpr)
2319
2406
 
2320
2407
                try:
2321
2408
                    client = ProxyClient(child_pipe, key_id, fpr,
2330
2417
 
2331
2418
                while True:
2332
2419
                    if not client.enabled:
2333
 
                        logger.info("Client %s is disabled",
2334
 
                                    client.name)
 
2420
                        log.info("Client %s is disabled", client.name)
2335
2421
                        if self.server.use_dbus:
2336
2422
                            # Emit D-Bus signal
2337
2423
                            client.Rejected("Disabled")
2341
2427
                        # We are approved or approval is disabled
2342
2428
                        break
2343
2429
                    elif client.approved is None:
2344
 
                        logger.info("Client %s needs approval",
2345
 
                                    client.name)
 
2430
                        log.info("Client %s needs approval",
 
2431
                                 client.name)
2346
2432
                        if self.server.use_dbus:
2347
2433
                            # Emit D-Bus signal
2348
2434
                            client.NeedApproval(
2349
2435
                                client.approval_delay.total_seconds()
2350
2436
                                * 1000, client.approved_by_default)
2351
2437
                    else:
2352
 
                        logger.warning("Client %s was not approved",
2353
 
                                       client.name)
 
2438
                        log.warning("Client %s was not approved",
 
2439
                                    client.name)
2354
2440
                        if self.server.use_dbus:
2355
2441
                            # Emit D-Bus signal
2356
2442
                            client.Rejected("Denied")
2364
2450
                    time2 = datetime.datetime.now()
2365
2451
                    if (time2 - time) >= delay:
2366
2452
                        if not client.approved_by_default:
2367
 
                            logger.warning("Client %s timed out while"
2368
 
                                           " waiting for approval",
2369
 
                                           client.name)
 
2453
                            log.warning("Client %s timed out while"
 
2454
                                        " waiting for approval",
 
2455
                                        client.name)
2370
2456
                            if self.server.use_dbus:
2371
2457
                                # Emit D-Bus signal
2372
2458
                                client.Rejected("Approval timed out")
2379
2465
                try:
2380
2466
                    session.send(client.secret)
2381
2467
                except gnutls.Error as error:
2382
 
                    logger.warning("gnutls send failed",
2383
 
                                   exc_info=error)
 
2468
                    log.warning("gnutls send failed", exc_info=error)
2384
2469
                    return
2385
2470
 
2386
 
                logger.info("Sending secret to %s", client.name)
 
2471
                log.info("Sending secret to %s", client.name)
2387
2472
                # bump the timeout using extended_timeout
2388
2473
                client.bump_timeout(client.extended_timeout)
2389
2474
                if self.server.use_dbus:
2396
2481
                try:
2397
2482
                    session.bye()
2398
2483
                except gnutls.Error as error:
2399
 
                    logger.warning("GnuTLS bye failed",
2400
 
                                   exc_info=error)
 
2484
                    log.warning("GnuTLS bye failed", exc_info=error)
2401
2485
 
2402
2486
    @staticmethod
2403
2487
    def peer_certificate(session):
2404
2488
        "Return the peer's certificate as a bytestring"
2405
2489
        try:
2406
 
            cert_type = gnutls.certificate_type_get2(session._c_object,
2407
 
                                                     gnutls.CTYPE_PEERS)
 
2490
            cert_type = gnutls.certificate_type_get2(
 
2491
                session, gnutls.CTYPE_PEERS)
2408
2492
        except AttributeError:
2409
 
            cert_type = gnutls.certificate_type_get(session._c_object)
 
2493
            cert_type = gnutls.certificate_type_get(session)
2410
2494
        if gnutls.has_rawpk:
2411
2495
            valid_cert_types = frozenset((gnutls.CRT_RAWPK,))
2412
2496
        else:
2413
2497
            valid_cert_types = frozenset((gnutls.CRT_OPENPGP,))
2414
2498
        # If not a valid certificate type...
2415
2499
        if cert_type not in valid_cert_types:
2416
 
            logger.info("Cert type %r not in %r", cert_type,
2417
 
                        valid_cert_types)
 
2500
            log.info("Cert type %r not in %r", cert_type,
 
2501
                     valid_cert_types)
2418
2502
            # ...return invalid data
2419
2503
            return b""
2420
2504
        list_size = ctypes.c_uint(1)
2421
2505
        cert_list = (gnutls.certificate_get_peers
2422
 
                     (session._c_object, ctypes.byref(list_size)))
 
2506
                     (session, ctypes.byref(list_size)))
2423
2507
        if not bool(cert_list) and list_size.value != 0:
2424
2508
            raise gnutls.Error("error getting peer certificate")
2425
2509
        if list_size.value == 0:
2447
2531
        buf = ctypes.create_string_buffer(32)
2448
2532
        buf_len = ctypes.c_size_t(len(buf))
2449
2533
        # Get the key ID from the raw public key into the buffer
2450
 
        gnutls.pubkey_get_key_id(pubkey,
2451
 
                                 gnutls.KEYID_USE_SHA256,
2452
 
                                 ctypes.cast(ctypes.byref(buf),
2453
 
                                             ctypes.POINTER(ctypes.c_ubyte)),
2454
 
                                 ctypes.byref(buf_len))
 
2534
        gnutls.pubkey_get_key_id(
 
2535
            pubkey,
 
2536
            gnutls.KEYID_USE_SHA256,
 
2537
            ctypes.cast(ctypes.byref(buf),
 
2538
                        ctypes.POINTER(ctypes.c_ubyte)),
 
2539
            ctypes.byref(buf_len))
2455
2540
        # Deinit the certificate
2456
2541
        gnutls.pubkey_deinit(pubkey)
2457
2542
 
2498
2583
        return hex_fpr
2499
2584
 
2500
2585
 
2501
 
class MultiprocessingMixIn(object):
 
2586
class MultiprocessingMixIn:
2502
2587
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
2503
2588
 
2504
2589
    def sub_process_main(self, request, address):
2516
2601
        return proc
2517
2602
 
2518
2603
 
2519
 
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
 
2604
class MultiprocessingMixInWithPipe(MultiprocessingMixIn):
2520
2605
    """ adds a pipe to the MixIn """
2521
2606
 
2522
2607
    def process_request(self, request, client_address):
2537
2622
 
2538
2623
 
2539
2624
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
2540
 
                     socketserver.TCPServer, object):
2541
 
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
 
2625
                     socketserver.TCPServer):
 
2626
    """IPv6-capable TCP server.  Accepts None as address and/or port
2542
2627
 
2543
2628
    Attributes:
2544
2629
        enabled:        Boolean; whether this server is activated yet
2595
2680
            if SO_BINDTODEVICE is None:
2596
2681
                # Fall back to a hard-coded value which seems to be
2597
2682
                # common enough.
2598
 
                logger.warning("SO_BINDTODEVICE not found, trying 25")
 
2683
                log.warning("SO_BINDTODEVICE not found, trying 25")
2599
2684
                SO_BINDTODEVICE = 25
2600
2685
            try:
2601
2686
                self.socket.setsockopt(
2603
2688
                    (self.interface + "\0").encode("utf-8"))
2604
2689
            except socket.error as error:
2605
2690
                if error.errno == errno.EPERM:
2606
 
                    logger.error("No permission to bind to"
2607
 
                                 " interface %s", self.interface)
 
2691
                    log.error("No permission to bind to interface %s",
 
2692
                              self.interface)
2608
2693
                elif error.errno == errno.ENOPROTOOPT:
2609
 
                    logger.error("SO_BINDTODEVICE not available;"
2610
 
                                 " cannot bind to interface %s",
2611
 
                                 self.interface)
 
2694
                    log.error("SO_BINDTODEVICE not available; cannot"
 
2695
                              " bind to interface %s", self.interface)
2612
2696
                elif error.errno == errno.ENODEV:
2613
 
                    logger.error("Interface %s does not exist,"
2614
 
                                 " cannot bind", self.interface)
 
2697
                    log.error("Interface %s does not exist, cannot"
 
2698
                              " bind", self.interface)
2615
2699
                else:
2616
2700
                    raise
2617
2701
        # Only bind(2) the socket if we really need to.
2618
2702
        if self.server_address[0] or self.server_address[1]:
 
2703
            if self.server_address[1]:
 
2704
                self.allow_reuse_address = True
2619
2705
            if not self.server_address[0]:
2620
2706
                if self.address_family == socket.AF_INET6:
2621
2707
                    any_address = "::"  # in6addr_any
2674
2760
    def add_pipe(self, parent_pipe, proc):
2675
2761
        # Call "handle_ipc" for both data and EOF events
2676
2762
        GLib.io_add_watch(
2677
 
            parent_pipe.fileno(),
2678
 
            GLib.IO_IN | GLib.IO_HUP,
 
2763
            GLib.IOChannel.unix_new(parent_pipe.fileno()),
 
2764
            GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_HUP,
2679
2765
            functools.partial(self.handle_ipc,
2680
2766
                              parent_pipe=parent_pipe,
2681
2767
                              proc=proc))
2694
2780
        request = parent_pipe.recv()
2695
2781
        command = request[0]
2696
2782
 
2697
 
        if command == 'init':
 
2783
        if command == "init":
2698
2784
            key_id = request[1].decode("ascii")
2699
2785
            fpr = request[2].decode("ascii")
2700
2786
            address = request[3]
2701
2787
 
2702
2788
            for c in self.clients.values():
2703
 
                if key_id == "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855":
 
2789
                if key_id == ("E3B0C44298FC1C149AFBF4C8996FB924"
 
2790
                              "27AE41E4649B934CA495991B7852B855"):
2704
2791
                    continue
2705
2792
                if key_id and c.key_id == key_id:
2706
2793
                    client = c
2709
2796
                    client = c
2710
2797
                    break
2711
2798
            else:
2712
 
                logger.info("Client not found for key ID: %s, address"
2713
 
                            ": %s", key_id or fpr, address)
 
2799
                log.info("Client not found for key ID: %s, address:"
 
2800
                         " %s", key_id or fpr, address)
2714
2801
                if self.use_dbus:
2715
2802
                    # Emit D-Bus signal
2716
2803
                    mandos_dbus_service.ClientNotFound(key_id or fpr,
2719
2806
                return False
2720
2807
 
2721
2808
            GLib.io_add_watch(
2722
 
                parent_pipe.fileno(),
2723
 
                GLib.IO_IN | GLib.IO_HUP,
 
2809
                GLib.IOChannel.unix_new(parent_pipe.fileno()),
 
2810
                GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_HUP,
2724
2811
                functools.partial(self.handle_ipc,
2725
2812
                                  parent_pipe=parent_pipe,
2726
2813
                                  proc=proc,
2729
2816
            # remove the old hook in favor of the new above hook on
2730
2817
            # same fileno
2731
2818
            return False
2732
 
        if command == 'funcall':
 
2819
        if command == "funcall":
2733
2820
            funcname = request[1]
2734
2821
            args = request[2]
2735
2822
            kwargs = request[3]
2736
2823
 
2737
 
            parent_pipe.send(('data', getattr(client_object,
 
2824
            parent_pipe.send(("data", getattr(client_object,
2738
2825
                                              funcname)(*args,
2739
2826
                                                        **kwargs)))
2740
2827
 
2741
 
        if command == 'getattr':
 
2828
        if command == "getattr":
2742
2829
            attrname = request[1]
2743
2830
            if isinstance(client_object.__getattribute__(attrname),
2744
 
                          collections.Callable):
2745
 
                parent_pipe.send(('function', ))
 
2831
                          collections.abc.Callable):
 
2832
                parent_pipe.send(("function", ))
2746
2833
            else:
2747
2834
                parent_pipe.send((
2748
 
                    'data', client_object.__getattribute__(attrname)))
 
2835
                    "data", client_object.__getattribute__(attrname)))
2749
2836
 
2750
 
        if command == 'setattr':
 
2837
        if command == "setattr":
2751
2838
            attrname = request[1]
2752
2839
            value = request[2]
2753
2840
            setattr(client_object, attrname, value)
2758
2845
def rfc3339_duration_to_delta(duration):
2759
2846
    """Parse an RFC 3339 "duration" and return a datetime.timedelta
2760
2847
 
2761
 
    >>> rfc3339_duration_to_delta("P7D")
2762
 
    datetime.timedelta(7)
2763
 
    >>> rfc3339_duration_to_delta("PT60S")
2764
 
    datetime.timedelta(0, 60)
2765
 
    >>> rfc3339_duration_to_delta("PT60M")
2766
 
    datetime.timedelta(0, 3600)
2767
 
    >>> rfc3339_duration_to_delta("PT24H")
2768
 
    datetime.timedelta(1)
2769
 
    >>> rfc3339_duration_to_delta("P1W")
2770
 
    datetime.timedelta(7)
2771
 
    >>> rfc3339_duration_to_delta("PT5M30S")
2772
 
    datetime.timedelta(0, 330)
2773
 
    >>> rfc3339_duration_to_delta("P1DT3M20S")
2774
 
    datetime.timedelta(1, 200)
 
2848
    >>> timedelta = datetime.timedelta
 
2849
    >>> rfc3339_duration_to_delta("P7D") == timedelta(7)
 
2850
    True
 
2851
    >>> rfc3339_duration_to_delta("PT60S") == timedelta(0, 60)
 
2852
    True
 
2853
    >>> rfc3339_duration_to_delta("PT60M") == timedelta(0, 3600)
 
2854
    True
 
2855
    >>> rfc3339_duration_to_delta("PT24H") == timedelta(1)
 
2856
    True
 
2857
    >>> rfc3339_duration_to_delta("P1W") == timedelta(7)
 
2858
    True
 
2859
    >>> rfc3339_duration_to_delta("PT5M30S") == timedelta(0, 330)
 
2860
    True
 
2861
    >>> rfc3339_duration_to_delta("P1DT3M20S") == timedelta(1, 200)
 
2862
    True
 
2863
    >>> del timedelta
2775
2864
    """
2776
2865
 
2777
2866
    # Parsing an RFC 3339 duration with regular expressions is not
2857
2946
def string_to_delta(interval):
2858
2947
    """Parse a string and return a datetime.timedelta
2859
2948
 
2860
 
    >>> string_to_delta('7d')
2861
 
    datetime.timedelta(7)
2862
 
    >>> string_to_delta('60s')
2863
 
    datetime.timedelta(0, 60)
2864
 
    >>> string_to_delta('60m')
2865
 
    datetime.timedelta(0, 3600)
2866
 
    >>> string_to_delta('24h')
2867
 
    datetime.timedelta(1)
2868
 
    >>> string_to_delta('1w')
2869
 
    datetime.timedelta(7)
2870
 
    >>> string_to_delta('5m 30s')
2871
 
    datetime.timedelta(0, 330)
 
2949
    >>> string_to_delta("7d") == datetime.timedelta(7)
 
2950
    True
 
2951
    >>> string_to_delta("60s") == datetime.timedelta(0, 60)
 
2952
    True
 
2953
    >>> string_to_delta("60m") == datetime.timedelta(0, 3600)
 
2954
    True
 
2955
    >>> string_to_delta("24h") == datetime.timedelta(1)
 
2956
    True
 
2957
    >>> string_to_delta("1w") == datetime.timedelta(7)
 
2958
    True
 
2959
    >>> string_to_delta("5m 30s") == datetime.timedelta(0, 330)
 
2960
    True
2872
2961
    """
2873
2962
 
2874
2963
    try:
2976
3065
 
2977
3066
    options = parser.parse_args()
2978
3067
 
2979
 
    if options.check:
2980
 
        import doctest
2981
 
        fail_count, test_count = doctest.testmod()
2982
 
        sys.exit(os.EX_OK if fail_count == 0 else 1)
2983
 
 
2984
3068
    # Default values for config file for server-global settings
2985
3069
    if gnutls.has_rawpk:
2986
3070
        priority = ("SECURE128:!CTYPE-X.509:+CTYPE-RAWPK:!RSA"
3006
3090
    del priority
3007
3091
 
3008
3092
    # Parse config file for server-global settings
3009
 
    server_config = configparser.SafeConfigParser(server_defaults)
 
3093
    server_config = configparser.ConfigParser(server_defaults)
3010
3094
    del server_defaults
3011
3095
    server_config.read(os.path.join(options.configdir, "mandos.conf"))
3012
 
    # Convert the SafeConfigParser object to a dict
 
3096
    # Convert the ConfigParser object to a dict
3013
3097
    server_settings = server_config.defaults()
3014
3098
    # Use the appropriate methods on the non-string config options
3015
3099
    for option in ("debug", "use_dbus", "use_ipv6", "restore",
3025
3109
        # Later, stdin will, and stdout and stderr might, be dup'ed
3026
3110
        # over with an opened os.devnull.  But we don't want this to
3027
3111
        # happen with a supplied network socket.
3028
 
        if 0 <= server_settings["socket"] <= 2:
 
3112
        while 0 <= server_settings["socket"] <= 2:
3029
3113
            server_settings["socket"] = os.dup(server_settings
3030
3114
                                               ["socket"])
 
3115
        os.set_inheritable(server_settings["socket"], False)
3031
3116
    del server_config
3032
3117
 
3033
3118
    # Override the settings from the config file with command line
3082
3167
 
3083
3168
    if server_settings["servicename"] != "Mandos":
3084
3169
        syslogger.setFormatter(
3085
 
            logging.Formatter('Mandos ({}) [%(process)d]:'
3086
 
                              ' %(levelname)s: %(message)s'.format(
 
3170
            logging.Formatter("Mandos ({}) [%(process)d]:"
 
3171
                              " %(levelname)s: %(message)s".format(
3087
3172
                                  server_settings["servicename"])))
3088
3173
 
3089
3174
    # Parse config file with clients
3090
 
    client_config = configparser.SafeConfigParser(Client
3091
 
                                                  .client_defaults)
 
3175
    client_config = configparser.ConfigParser(Client.client_defaults)
3092
3176
    client_config.read(os.path.join(server_settings["configdir"],
3093
3177
                                    "clients.conf"))
3094
3178
 
3114
3198
        try:
3115
3199
            pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
3116
3200
        except IOError as e:
3117
 
            logger.error("Could not open file %r", pidfilename,
3118
 
                         exc_info=e)
 
3201
            log.error("Could not open file %r", pidfilename,
 
3202
                      exc_info=e)
3119
3203
 
3120
3204
    for name, group in (("_mandos", "_mandos"),
3121
3205
                        ("mandos", "mandos"),
3132
3216
    try:
3133
3217
        os.setgid(gid)
3134
3218
        os.setuid(uid)
3135
 
        if debug:
3136
 
            logger.debug("Did setuid/setgid to {}:{}".format(uid,
3137
 
                                                             gid))
 
3219
        log.debug("Did setuid/setgid to %s:%s", uid, gid)
3138
3220
    except OSError as error:
3139
 
        logger.warning("Failed to setuid/setgid to {}:{}: {}"
3140
 
                       .format(uid, gid, os.strerror(error.errno)))
 
3221
        log.warning("Failed to setuid/setgid to %s:%s: %s", uid, gid,
 
3222
                    os.strerror(error.errno))
3141
3223
        if error.errno != errno.EPERM:
3142
3224
            raise
3143
3225
 
3150
3232
 
3151
3233
        @gnutls.log_func
3152
3234
        def debug_gnutls(level, string):
3153
 
            logger.debug("GnuTLS: %s", string[:-1])
 
3235
            log.debug("GnuTLS: %s",
 
3236
                      string[:-1].decode("utf-8", errors="replace"))
3154
3237
 
3155
3238
        gnutls.global_set_log_function(debug_gnutls)
3156
3239
 
3165
3248
        # Close all input and output, do double fork, etc.
3166
3249
        daemon()
3167
3250
 
3168
 
    # multiprocessing will use threads, so before we use GLib we need
3169
 
    # to inform GLib that threads will be used.
3170
 
    GLib.threads_init()
 
3251
    if gi.version_info < (3, 10, 2):
 
3252
        # multiprocessing will use threads, so before we use GLib we
 
3253
        # need to inform GLib that threads will be used.
 
3254
        GLib.threads_init()
3171
3255
 
3172
3256
    global main_loop
3173
3257
    # From the Avahi example code
3174
3258
    DBusGMainLoop(set_as_default=True)
3175
3259
    main_loop = GLib.MainLoop()
3176
 
    bus = dbus.SystemBus()
 
3260
    if use_dbus or zeroconf:
 
3261
        bus = dbus.SystemBus()
3177
3262
    # End of Avahi example code
3178
3263
    if use_dbus:
3179
3264
        try:
3184
3269
                "se.bsnet.fukt.Mandos", bus,
3185
3270
                do_not_queue=True)
3186
3271
        except dbus.exceptions.DBusException as e:
3187
 
            logger.error("Disabling D-Bus:", exc_info=e)
 
3272
            log.error("Disabling D-Bus:", exc_info=e)
3188
3273
            use_dbus = False
3189
3274
            server_settings["use_dbus"] = False
3190
3275
            tcp_server.use_dbus = False
3249
3334
                             if isinstance(s, bytes)
3250
3335
                             else s) for s in
3251
3336
                            value["client_structure"]]
3252
 
                        # .name & .host
3253
 
                        for k in ("name", "host"):
 
3337
                        # .name, .host, and .checker_command
 
3338
                        for k in ("name", "host", "checker_command"):
3254
3339
                            if isinstance(value[k], bytes):
3255
3340
                                value[k] = value[k].decode("utf-8")
3256
 
                        if not value.has_key("key_id"):
 
3341
                        if "key_id" not in value:
3257
3342
                            value["key_id"] = ""
3258
 
                        elif not value.has_key("fingerprint"):
 
3343
                        elif "fingerprint" not in value:
3259
3344
                            value["fingerprint"] = ""
3260
3345
                    #  old_client_settings
3261
3346
                    # .keys()
3266
3351
                        for key, value in
3267
3352
                        bytes_old_client_settings.items()}
3268
3353
                    del bytes_old_client_settings
3269
 
                    # .host
 
3354
                    # .host and .checker_command
3270
3355
                    for value in old_client_settings.values():
3271
 
                        if isinstance(value["host"], bytes):
3272
 
                            value["host"] = (value["host"]
3273
 
                                             .decode("utf-8"))
 
3356
                        for attribute in ("host", "checker_command"):
 
3357
                            if isinstance(value[attribute], bytes):
 
3358
                                value[attribute] = (value[attribute]
 
3359
                                                    .decode("utf-8"))
3274
3360
            os.remove(stored_state_path)
3275
3361
        except IOError as e:
3276
3362
            if e.errno == errno.ENOENT:
3277
 
                logger.warning("Could not load persistent state:"
3278
 
                               " {}".format(os.strerror(e.errno)))
 
3363
                log.warning("Could not load persistent state:"
 
3364
                            " %s", os.strerror(e.errno))
3279
3365
            else:
3280
 
                logger.critical("Could not load persistent state:",
3281
 
                                exc_info=e)
 
3366
                log.critical("Could not load persistent state:",
 
3367
                             exc_info=e)
3282
3368
                raise
3283
3369
        except EOFError as e:
3284
 
            logger.warning("Could not load persistent state: "
3285
 
                           "EOFError:",
3286
 
                           exc_info=e)
 
3370
            log.warning("Could not load persistent state: EOFError:",
 
3371
                        exc_info=e)
3287
3372
 
3288
3373
    with PGPEngine() as pgp:
3289
3374
        for client_name, client in clients_data.items():
3316
3401
            if client["enabled"]:
3317
3402
                if datetime.datetime.utcnow() >= client["expires"]:
3318
3403
                    if not client["last_checked_ok"]:
3319
 
                        logger.warning(
3320
 
                            "disabling client {} - Client never "
3321
 
                            "performed a successful checker".format(
3322
 
                                client_name))
 
3404
                        log.warning("disabling client %s - Client"
 
3405
                                    " never performed a successful"
 
3406
                                    " checker", client_name)
3323
3407
                        client["enabled"] = False
3324
3408
                    elif client["last_checker_status"] != 0:
3325
 
                        logger.warning(
3326
 
                            "disabling client {} - Client last"
3327
 
                            " checker failed with error code"
3328
 
                            " {}".format(
3329
 
                                client_name,
3330
 
                                client["last_checker_status"]))
 
3409
                        log.warning("disabling client %s - Client"
 
3410
                                    " last checker failed with error"
 
3411
                                    " code %s", client_name,
 
3412
                                    client["last_checker_status"])
3331
3413
                        client["enabled"] = False
3332
3414
                    else:
3333
3415
                        client["expires"] = (
3334
3416
                            datetime.datetime.utcnow()
3335
3417
                            + client["timeout"])
3336
 
                        logger.debug("Last checker succeeded,"
3337
 
                                     " keeping {} enabled".format(
3338
 
                                         client_name))
 
3418
                        log.debug("Last checker succeeded, keeping %s"
 
3419
                                  " enabled", client_name)
3339
3420
            try:
3340
3421
                client["secret"] = pgp.decrypt(
3341
3422
                    client["encrypted_secret"],
3342
3423
                    client_settings[client_name]["secret"])
3343
3424
            except PGPError:
3344
3425
                # If decryption fails, we use secret from new settings
3345
 
                logger.debug("Failed to decrypt {} old secret".format(
3346
 
                    client_name))
 
3426
                log.debug("Failed to decrypt %s old secret",
 
3427
                          client_name)
3347
3428
                client["secret"] = (client_settings[client_name]
3348
3429
                                    ["secret"])
3349
3430
 
3363
3444
            server_settings=server_settings)
3364
3445
 
3365
3446
    if not tcp_server.clients:
3366
 
        logger.warning("No clients defined")
 
3447
        log.warning("No clients defined")
3367
3448
 
3368
3449
    if not foreground:
3369
3450
        if pidfile is not None:
3372
3453
                with pidfile:
3373
3454
                    print(pid, file=pidfile)
3374
3455
            except IOError:
3375
 
                logger.error("Could not write to file %r with PID %d",
3376
 
                             pidfilename, pid)
 
3456
                log.error("Could not write to file %r with PID %d",
 
3457
                          pidfilename, pid)
3377
3458
        del pidfile
3378
3459
        del pidfilename
3379
3460
 
3529
3610
 
3530
3611
        try:
3531
3612
            with tempfile.NamedTemporaryFile(
3532
 
                    mode='wb',
 
3613
                    mode="wb",
3533
3614
                    suffix=".pickle",
3534
 
                    prefix='clients-',
 
3615
                    prefix="clients-",
3535
3616
                    dir=os.path.dirname(stored_state_path),
3536
3617
                    delete=False) as stored_state:
3537
3618
                pickle.dump((clients, client_settings), stored_state,
3545
3626
                except NameError:
3546
3627
                    pass
3547
3628
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
3548
 
                logger.warning("Could not save persistent state: {}"
3549
 
                               .format(os.strerror(e.errno)))
 
3629
                log.warning("Could not save persistent state: %s",
 
3630
                            os.strerror(e.errno))
3550
3631
            else:
3551
 
                logger.warning("Could not save persistent state:",
3552
 
                               exc_info=e)
 
3632
                log.warning("Could not save persistent state:",
 
3633
                            exc_info=e)
3553
3634
                raise
3554
3635
 
3555
3636
        # Delete all clients, and settings from config
3572
3653
            mandos_dbus_service.client_added_signal(client)
3573
3654
        # Need to initiate checking of clients
3574
3655
        if client.enabled:
3575
 
            client.init_checker()
 
3656
            client.init_checker(randomize_start=True)
3576
3657
 
3577
3658
    tcp_server.enable()
3578
3659
    tcp_server.server_activate()
3581
3662
    if zeroconf:
3582
3663
        service.port = tcp_server.socket.getsockname()[1]
3583
3664
    if use_ipv6:
3584
 
        logger.info("Now listening on address %r, port %d,"
3585
 
                    " flowinfo %d, scope_id %d",
3586
 
                    *tcp_server.socket.getsockname())
 
3665
        log.info("Now listening on address %r, port %d, flowinfo %d,"
 
3666
                 " scope_id %d", *tcp_server.socket.getsockname())
3587
3667
    else:                       # IPv4
3588
 
        logger.info("Now listening on address %r, port %d",
3589
 
                    *tcp_server.socket.getsockname())
 
3668
        log.info("Now listening on address %r, port %d",
 
3669
                 *tcp_server.socket.getsockname())
3590
3670
 
3591
3671
    # service.interface = tcp_server.socket.getsockname()[3]
3592
3672
 
3596
3676
            try:
3597
3677
                service.activate()
3598
3678
            except dbus.exceptions.DBusException as error:
3599
 
                logger.critical("D-Bus Exception", exc_info=error)
 
3679
                log.critical("D-Bus Exception", exc_info=error)
3600
3680
                cleanup()
3601
3681
                sys.exit(1)
3602
3682
            # End of Avahi example code
3603
3683
 
3604
 
        GLib.io_add_watch(tcp_server.fileno(), GLib.IO_IN,
3605
 
                          lambda *args, **kwargs:
3606
 
                          (tcp_server.handle_request
3607
 
                           (*args[2:], **kwargs) or True))
 
3684
        GLib.io_add_watch(
 
3685
            GLib.IOChannel.unix_new(tcp_server.fileno()),
 
3686
            GLib.PRIORITY_DEFAULT, GLib.IO_IN,
 
3687
            lambda *args, **kwargs: (tcp_server.handle_request
 
3688
                                     (*args[2:], **kwargs) or True))
3608
3689
 
3609
 
        logger.debug("Starting main loop")
 
3690
        log.debug("Starting main loop")
3610
3691
        main_loop.run()
3611
3692
    except AvahiError as error:
3612
 
        logger.critical("Avahi Error", exc_info=error)
 
3693
        log.critical("Avahi Error", exc_info=error)
3613
3694
        cleanup()
3614
3695
        sys.exit(1)
3615
3696
    except KeyboardInterrupt:
3616
3697
        if debug:
3617
3698
            print("", file=sys.stderr)
3618
 
        logger.debug("Server received KeyboardInterrupt")
3619
 
    logger.debug("Server exiting")
 
3699
        log.debug("Server received KeyboardInterrupt")
 
3700
    log.debug("Server exiting")
3620
3701
    # Must run before the D-Bus bus name gets deregistered
3621
3702
    cleanup()
3622
3703
 
3623
 
 
3624
 
if __name__ == '__main__':
3625
 
    main()
 
3704
 
 
3705
def parse_test_args():
 
3706
    # type: () -> argparse.Namespace
 
3707
    parser = argparse.ArgumentParser(add_help=False)
 
3708
    parser.add_argument("--check", action="store_true")
 
3709
    parser.add_argument("--prefix", )
 
3710
    args, unknown_args = parser.parse_known_args()
 
3711
    if args.check:
 
3712
        # Remove test options from sys.argv
 
3713
        sys.argv[1:] = unknown_args
 
3714
    return args
 
3715
 
 
3716
# Add all tests from doctest strings
 
3717
def load_tests(loader, tests, none):
 
3718
    import doctest
 
3719
    tests.addTests(doctest.DocTestSuite())
 
3720
    return tests
 
3721
 
 
3722
if __name__ == "__main__":
 
3723
    options = parse_test_args()
 
3724
    try:
 
3725
        if options.check:
 
3726
            extra_test_prefix = options.prefix
 
3727
            if extra_test_prefix is not None:
 
3728
                if not (unittest.main(argv=[""], exit=False)
 
3729
                        .result.wasSuccessful()):
 
3730
                    sys.exit(1)
 
3731
                class ExtraTestLoader(unittest.TestLoader):
 
3732
                    testMethodPrefix = extra_test_prefix
 
3733
                # Call using ./scriptname --test [--verbose]
 
3734
                unittest.main(argv=[""], testLoader=ExtraTestLoader())
 
3735
            else:
 
3736
                unittest.main(argv=[""])
 
3737
        else:
 
3738
            main()
 
3739
    finally:
 
3740
        logging.shutdown()
 
3741
 
 
3742
# Local Variables:
 
3743
# run-tests:
 
3744
# (lambda (&optional extra)
 
3745
#   (if (not (funcall run-tests-in-test-buffer default-directory
 
3746
#             extra))
 
3747
#       (funcall show-test-buffer-in-test-window)
 
3748
#     (funcall remove-test-window)
 
3749
#     (if extra (message "Extra tests run successfully!"))))
 
3750
# run-tests-in-test-buffer:
 
3751
# (lambda (dir &optional extra)
 
3752
#   (with-current-buffer (get-buffer-create "*Test*")
 
3753
#     (setq buffer-read-only nil
 
3754
#           default-directory dir)
 
3755
#     (erase-buffer)
 
3756
#     (compilation-mode))
 
3757
#   (let ((process-result
 
3758
#          (let ((inhibit-read-only t))
 
3759
#            (process-file-shell-command
 
3760
#             (funcall get-command-line extra) nil "*Test*"))))
 
3761
#     (and (numberp process-result)
 
3762
#          (= process-result 0))))
 
3763
# get-command-line:
 
3764
# (lambda (&optional extra)
 
3765
#   (let ((quoted-script
 
3766
#          (shell-quote-argument (funcall get-script-name))))
 
3767
#     (format
 
3768
#      (concat "%s --check" (if extra " --prefix=atest" ""))
 
3769
#      quoted-script)))
 
3770
# get-script-name:
 
3771
# (lambda ()
 
3772
#   (if (fboundp 'file-local-name)
 
3773
#       (file-local-name (buffer-file-name))
 
3774
#     (or (file-remote-p (buffer-file-name) 'localname)
 
3775
#         (buffer-file-name))))
 
3776
# remove-test-window:
 
3777
# (lambda ()
 
3778
#   (let ((test-window (get-buffer-window "*Test*")))
 
3779
#     (if test-window (delete-window test-window))))
 
3780
# show-test-buffer-in-test-window:
 
3781
# (lambda ()
 
3782
#   (when (not (get-buffer-window-list "*Test*"))
 
3783
#     (setq next-error-last-buffer (get-buffer "*Test*"))
 
3784
#     (let* ((side (if (>= (window-width) 146) 'right 'bottom))
 
3785
#            (display-buffer-overriding-action
 
3786
#             `((display-buffer-in-side-window) (side . ,side)
 
3787
#               (window-height . fit-window-to-buffer)
 
3788
#               (window-width . fit-window-to-buffer))))
 
3789
#       (display-buffer "*Test*"))))
 
3790
# eval:
 
3791
# (progn
 
3792
#   (let* ((run-extra-tests (lambda () (interactive)
 
3793
#                             (funcall run-tests t)))
 
3794
#          (inner-keymap `(keymap (116 . ,run-extra-tests))) ; t
 
3795
#          (outer-keymap `(keymap (3 . ,inner-keymap))))     ; C-c
 
3796
#     (setq minor-mode-overriding-map-alist
 
3797
#           (cons `(run-tests . ,outer-keymap)
 
3798
#                 minor-mode-overriding-map-alist)))
 
3799
#   (add-hook 'after-save-hook run-tests 90 t))
 
3800
# End: