/mandos/release

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

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2022-04-24 11:45:13 UTC
  • mto: This revision was merged to the branch mainline in revision 406.
  • Revision ID: teddy@recompile.se-20220424114513-0rvlunnjhgs3deus
mandos-monitor: Update boilerplate code

* mandos-monitor: Show warnings by default.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/python3 -bI
2
 
# -*- coding: utf-8; lexical-binding: t -*-
 
2
# -*- mode: python; after-save-hook: (lambda () (let ((command (if (fboundp 'file-local-name) (file-local-name (buffer-file-name)) (or (file-remote-p (buffer-file-name) 'localname) (buffer-file-name))))) (if (= (progn (if (get-buffer "*Test*") (kill-buffer "*Test*")) (process-file-shell-command (format "%s --check" (shell-quote-argument command)) nil "*Test*")) 0) (let ((w (get-buffer-window "*Test*"))) (if w (delete-window w))) (progn (with-current-buffer "*Test*" (compilation-mode)) (display-buffer "*Test*" '(display-buffer-in-side-window)))))); coding: utf-8 -*-
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-2022 Teddy Hogeborn
15
 
# Copyright © 2008-2022 Björn Påhlsson
 
14
# Copyright © 2008-2020 Teddy Hogeborn
 
15
# Copyright © 2008-2020 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
 
34
35
from __future__ import (division, absolute_import, print_function,
35
36
                        unicode_literals)
36
37
 
39
40
except ImportError:
40
41
    pass
41
42
 
42
 
import sys
43
 
import unittest
44
 
import argparse
45
 
import logging
46
 
import os
47
43
try:
48
44
    import SocketServer as socketserver
49
45
except ImportError:
50
46
    import socketserver
51
47
import socket
 
48
import argparse
52
49
import datetime
53
50
import errno
54
51
try:
55
52
    import ConfigParser as configparser
56
53
except ImportError:
57
54
    import configparser
 
55
import sys
58
56
import re
 
57
import os
59
58
import signal
60
59
import subprocess
61
60
import atexit
62
61
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 unittest
80
81
import random
81
82
import shlex
82
83
 
93
94
if sys.version_info.major == 2:
94
95
    __metaclass__ = type
95
96
    str = unicode
96
 
    input = raw_input
97
97
 
98
98
# Add collections.abc.Callable if it does not exist
99
99
try:
143
143
if sys.version_info < (3, 2):
144
144
    configparser.Configparser = configparser.SafeConfigParser
145
145
 
146
 
version = "1.8.15"
 
146
version = "1.8.14"
147
147
stored_state_file = "clients.pickle"
148
148
 
149
 
log = logging.getLogger(os.path.basename(sys.argv[0]))
 
149
logger = logging.getLogger()
150
150
logging.captureWarnings(True)   # Show warnings via the logging system
151
151
syslogger = None
152
152
 
191
191
    syslogger.setFormatter(logging.Formatter
192
192
                           ("Mandos [%(process)d]: %(levelname)s:"
193
193
                            " %(message)s"))
194
 
    log.addHandler(syslogger)
 
194
    logger.addHandler(syslogger)
195
195
 
196
196
    if debug:
197
197
        console = logging.StreamHandler()
199
199
                                               " [%(process)d]:"
200
200
                                               " %(levelname)s:"
201
201
                                               " %(message)s"))
202
 
        log.addHandler(console)
203
 
    log.setLevel(level)
 
202
        logger.addHandler(console)
 
203
    logger.setLevel(level)
204
204
 
205
205
 
206
206
class PGPError(Exception):
394
394
    def rename(self, remove=True):
395
395
        """Derived from the Avahi example code"""
396
396
        if self.rename_count >= self.max_renames:
397
 
            log.critical("No suitable Zeroconf service name found"
398
 
                         " after %i retries, exiting.",
399
 
                         self.rename_count)
 
397
            logger.critical("No suitable Zeroconf service name found"
 
398
                            " after %i retries, exiting.",
 
399
                            self.rename_count)
400
400
            raise AvahiServiceError("Too many renames")
401
401
        self.name = str(
402
402
            self.server.GetAlternativeServiceName(self.name))
403
403
        self.rename_count += 1
404
 
        log.info("Changing Zeroconf service name to %r ...",
405
 
                 self.name)
 
404
        logger.info("Changing Zeroconf service name to %r ...",
 
405
                    self.name)
406
406
        if remove:
407
407
            self.remove()
408
408
        try:
410
410
        except dbus.exceptions.DBusException as error:
411
411
            if (error.get_dbus_name()
412
412
                == "org.freedesktop.Avahi.CollisionError"):
413
 
                log.info("Local Zeroconf service name collision.")
 
413
                logger.info("Local Zeroconf service name collision.")
414
414
                return self.rename(remove=False)
415
415
            else:
416
 
                log.critical("D-Bus Exception", exc_info=error)
 
416
                logger.critical("D-Bus Exception", exc_info=error)
417
417
                self.cleanup()
418
418
                os._exit(1)
419
419
 
436
436
        self.entry_group_state_changed_match = (
437
437
            self.group.connect_to_signal(
438
438
                "StateChanged", self.entry_group_state_changed))
439
 
        log.debug("Adding Zeroconf service '%s' of type '%s' ...",
440
 
                  self.name, self.type)
 
439
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
 
440
                     self.name, self.type)
441
441
        self.group.AddService(
442
442
            self.interface,
443
443
            self.protocol,
450
450
 
451
451
    def entry_group_state_changed(self, state, error):
452
452
        """Derived from the Avahi example code"""
453
 
        log.debug("Avahi entry group state change: %i", state)
 
453
        logger.debug("Avahi entry group state change: %i", state)
454
454
 
455
455
        if state == avahi.ENTRY_GROUP_ESTABLISHED:
456
 
            log.debug("Zeroconf service established.")
 
456
            logger.debug("Zeroconf service established.")
457
457
        elif state == avahi.ENTRY_GROUP_COLLISION:
458
 
            log.info("Zeroconf service name collision.")
 
458
            logger.info("Zeroconf service name collision.")
459
459
            self.rename()
460
460
        elif state == avahi.ENTRY_GROUP_FAILURE:
461
 
            log.critical("Avahi: Error in group state changed %s",
462
 
                         str(error))
 
461
            logger.critical("Avahi: Error in group state changed %s",
 
462
                            str(error))
463
463
            raise AvahiGroupError("State changed: {!s}".format(error))
464
464
 
465
465
    def cleanup(self):
475
475
 
476
476
    def server_state_changed(self, state, error=None):
477
477
        """Derived from the Avahi example code"""
478
 
        log.debug("Avahi server state change: %i", state)
 
478
        logger.debug("Avahi server state change: %i", state)
479
479
        bad_states = {
480
480
            avahi.SERVER_INVALID: "Zeroconf server invalid",
481
481
            avahi.SERVER_REGISTERING: None,
485
485
        if state in bad_states:
486
486
            if bad_states[state] is not None:
487
487
                if error is None:
488
 
                    log.error(bad_states[state])
 
488
                    logger.error(bad_states[state])
489
489
                else:
490
 
                    log.error(bad_states[state] + ": %r", error)
 
490
                    logger.error(bad_states[state] + ": %r", error)
491
491
            self.cleanup()
492
492
        elif state == avahi.SERVER_RUNNING:
493
493
            try:
495
495
            except dbus.exceptions.DBusException as error:
496
496
                if (error.get_dbus_name()
497
497
                    == "org.freedesktop.Avahi.CollisionError"):
498
 
                    log.info("Local Zeroconf service name collision.")
 
498
                    logger.info("Local Zeroconf service name"
 
499
                                " collision.")
499
500
                    return self.rename(remove=False)
500
501
                else:
501
 
                    log.critical("D-Bus Exception", exc_info=error)
 
502
                    logger.critical("D-Bus Exception", exc_info=error)
502
503
                    self.cleanup()
503
504
                    os._exit(1)
504
505
        else:
505
506
            if error is None:
506
 
                log.debug("Unknown state: %r", state)
 
507
                logger.debug("Unknown state: %r", state)
507
508
            else:
508
 
                log.debug("Unknown state: %r: %r", state, error)
 
509
                logger.debug("Unknown state: %r: %r", state, error)
509
510
 
510
511
    def activate(self):
511
512
        """Derived from the Avahi example code"""
1009
1010
            self.last_enabled = None
1010
1011
            self.expires = None
1011
1012
 
1012
 
        log.debug("Creating client %r", self.name)
1013
 
        log.debug("  Key ID: %s", self.key_id)
1014
 
        log.debug("  Fingerprint: %s", self.fingerprint)
 
1013
        logger.debug("Creating client %r", self.name)
 
1014
        logger.debug("  Key ID: %s", self.key_id)
 
1015
        logger.debug("  Fingerprint: %s", self.fingerprint)
1015
1016
        self.created = settings.get("created",
1016
1017
                                    datetime.datetime.utcnow())
1017
1018
 
1045
1046
        if getattr(self, "enabled", False):
1046
1047
            # Already enabled
1047
1048
            return
 
1049
        self.expires = datetime.datetime.utcnow() + self.timeout
1048
1050
        self.enabled = True
1049
1051
        self.last_enabled = datetime.datetime.utcnow()
1050
1052
        self.init_checker()
1055
1057
        if not getattr(self, "enabled", False):
1056
1058
            return False
1057
1059
        if not quiet:
1058
 
            log.info("Disabling client %s", self.name)
 
1060
            logger.info("Disabling client %s", self.name)
1059
1061
        if getattr(self, "disable_initiator_tag", None) is not None:
1060
1062
            GLib.source_remove(self.disable_initiator_tag)
1061
1063
            self.disable_initiator_tag = None
1073
1075
    def __del__(self):
1074
1076
        self.disable()
1075
1077
 
1076
 
    def init_checker(self, randomize_start=False):
1077
 
        # Schedule a new checker to be started a randomly selected
1078
 
        # time (a fraction of 'interval') from now.  This spreads out
1079
 
        # the startup of checkers over time when the server is
1080
 
        # started.
 
1078
    def init_checker(self):
 
1079
        # Schedule a new checker to be started an 'interval' from now,
 
1080
        # and every interval from then on.
1081
1081
        if self.checker_initiator_tag is not None:
1082
1082
            GLib.source_remove(self.checker_initiator_tag)
1083
 
        interval_milliseconds = int(self.interval.total_seconds()
1084
 
                                    * 1000)
1085
 
        if randomize_start:
1086
 
            delay_milliseconds = random.randrange(
1087
 
                interval_milliseconds + 1)
1088
 
        else:
1089
 
            delay_milliseconds = interval_milliseconds
1090
1083
        self.checker_initiator_tag = GLib.timeout_add(
1091
 
            delay_milliseconds, self.start_checker, randomize_start)
1092
 
        delay = datetime.timedelta(0, 0, 0, delay_milliseconds)
1093
 
        # A checker might take up to an 'interval' of time, so we can
1094
 
        # expire at the soonest one interval after a checker was
1095
 
        # started.  Since the initial checker is delayed, the expire
1096
 
        # time might have to be extended.
1097
 
        now = datetime.datetime.utcnow()
1098
 
        self.expires = now + delay + self.interval
1099
 
        # Schedule a disable() at expire time
 
1084
            random.randrange(int(self.interval.total_seconds() * 1000
 
1085
                                 + 1)),
 
1086
            self.start_checker)
 
1087
        # Schedule a disable() when 'timeout' has passed
1100
1088
        if self.disable_initiator_tag is not None:
1101
1089
            GLib.source_remove(self.disable_initiator_tag)
1102
1090
        self.disable_initiator_tag = GLib.timeout_add(
1103
 
            int((self.expires - now).total_seconds() * 1000),
1104
 
            self.disable)
 
1091
            int(self.timeout.total_seconds() * 1000), self.disable)
 
1092
        # Also start a new checker *right now*.
 
1093
        self.start_checker()
1105
1094
 
1106
1095
    def checker_callback(self, source, condition, connection,
1107
1096
                         command):
1118
1107
            self.last_checker_status = returncode
1119
1108
            self.last_checker_signal = None
1120
1109
            if self.last_checker_status == 0:
1121
 
                log.info("Checker for %(name)s succeeded", vars(self))
 
1110
                logger.info("Checker for %(name)s succeeded",
 
1111
                            vars(self))
1122
1112
                self.checked_ok()
1123
1113
            else:
1124
 
                log.info("Checker for %(name)s failed", vars(self))
 
1114
                logger.info("Checker for %(name)s failed", vars(self))
1125
1115
        else:
1126
1116
            self.last_checker_status = -1
1127
1117
            self.last_checker_signal = -returncode
1128
 
            log.warning("Checker for %(name)s crashed?", vars(self))
 
1118
            logger.warning("Checker for %(name)s crashed?",
 
1119
                           vars(self))
1129
1120
        return False
1130
1121
 
1131
1122
    def checked_ok(self):
1150
1141
    def need_approval(self):
1151
1142
        self.last_approval_request = datetime.datetime.utcnow()
1152
1143
 
1153
 
    def start_checker(self, start_was_randomized=False):
 
1144
    def start_checker(self):
1154
1145
        """Start a new checker subprocess if one is not running.
1155
1146
 
1156
1147
        If a checker already exists, leave it running and do
1165
1156
        # should be.
1166
1157
 
1167
1158
        if self.checker is not None and not self.checker.is_alive():
1168
 
            log.warning("Checker was not alive; joining")
 
1159
            logger.warning("Checker was not alive; joining")
1169
1160
            self.checker.join()
1170
1161
            self.checker = None
1171
1162
        # Start a new checker if needed
1177
1168
            try:
1178
1169
                command = self.checker_command % escaped_attrs
1179
1170
            except TypeError as error:
1180
 
                log.error('Could not format string "%s"',
1181
 
                          self.checker_command, exc_info=error)
 
1171
                logger.error('Could not format string "%s"',
 
1172
                             self.checker_command,
 
1173
                             exc_info=error)
1182
1174
                return True     # Try again later
1183
1175
            self.current_checker_command = command
1184
 
            log.info("Starting checker %r for %s", command, self.name)
 
1176
            logger.info("Starting checker %r for %s", command,
 
1177
                        self.name)
1185
1178
            # We don't need to redirect stdout and stderr, since
1186
1179
            # in normal mode, that is already done by daemon(),
1187
1180
            # and in debug mode we don't want to.  (Stdin is
1206
1199
                GLib.IOChannel.unix_new(pipe[0].fileno()),
1207
1200
                GLib.PRIORITY_DEFAULT, GLib.IO_IN,
1208
1201
                self.checker_callback, pipe[0], command)
1209
 
        if start_was_randomized:
1210
 
            # We were started after a random delay; Schedule a new
1211
 
            # checker to be started an 'interval' from now, and every
1212
 
            # interval from then on.
1213
 
            now = datetime.datetime.utcnow()
1214
 
            self.checker_initiator_tag = GLib.timeout_add(
1215
 
                int(self.interval.total_seconds() * 1000),
1216
 
                self.start_checker)
1217
 
            self.expires = max(self.expires, now + self.interval)
1218
 
            # Don't start a new checker again after same random delay
1219
 
            return False
1220
1202
        # Re-run this periodically if run by GLib.timeout_add
1221
1203
        return True
1222
1204
 
1227
1209
            self.checker_callback_tag = None
1228
1210
        if getattr(self, "checker", None) is None:
1229
1211
            return
1230
 
        log.debug("Stopping checker for %(name)s", vars(self))
 
1212
        logger.debug("Stopping checker for %(name)s", vars(self))
1231
1213
        self.checker.terminate()
1232
1214
        self.checker = None
1233
1215
 
1411
1393
            document.unlink()
1412
1394
        except (AttributeError, xml.dom.DOMException,
1413
1395
                xml.parsers.expat.ExpatError) as error:
1414
 
            log.error("Failed to override Introspection method",
1415
 
                      exc_info=error)
 
1396
            logger.error("Failed to override Introspection method",
 
1397
                         exc_info=error)
1416
1398
        return xmlstring
1417
1399
 
1418
1400
 
1578
1560
            document.unlink()
1579
1561
        except (AttributeError, xml.dom.DOMException,
1580
1562
                xml.parsers.expat.ExpatError) as error:
1581
 
            log.error("Failed to override Introspection method",
1582
 
                      exc_info=error)
 
1563
            logger.error("Failed to override Introspection method",
 
1564
                         exc_info=error)
1583
1565
        return xmlstring
1584
1566
 
1585
1567
 
1649
1631
            document.unlink()
1650
1632
        except (AttributeError, xml.dom.DOMException,
1651
1633
                xml.parsers.expat.ExpatError) as error:
1652
 
            log.error("Failed to override Introspection method",
1653
 
                      exc_info=error)
 
1634
            logger.error("Failed to override Introspection method",
 
1635
                         exc_info=error)
1654
1636
        return xmlstring
1655
1637
 
1656
1638
 
2323
2305
 
2324
2306
    def handle(self):
2325
2307
        with contextlib.closing(self.server.child_pipe) as child_pipe:
2326
 
            log.info("TCP connection from: %s",
2327
 
                     str(self.client_address))
2328
 
            log.debug("Pipe FD: %d", self.server.child_pipe.fileno())
 
2308
            logger.info("TCP connection from: %s",
 
2309
                        str(self.client_address))
 
2310
            logger.debug("Pipe FD: %d",
 
2311
                         self.server.child_pipe.fileno())
2329
2312
 
2330
2313
            session = gnutls.ClientSession(self.request)
2331
2314
 
2343
2326
            # Start communication using the Mandos protocol
2344
2327
            # Get protocol number
2345
2328
            line = self.request.makefile().readline()
2346
 
            log.debug("Protocol version: %r", line)
 
2329
            logger.debug("Protocol version: %r", line)
2347
2330
            try:
2348
2331
                if int(line.strip().split()[0]) > 1:
2349
2332
                    raise RuntimeError(line)
2350
2333
            except (ValueError, IndexError, RuntimeError) as error:
2351
 
                log.error("Unknown protocol version: %s", error)
 
2334
                logger.error("Unknown protocol version: %s", error)
2352
2335
                return
2353
2336
 
2354
2337
            # Start GnuTLS connection
2355
2338
            try:
2356
2339
                session.handshake()
2357
2340
            except gnutls.Error as error:
2358
 
                log.warning("Handshake failed: %s", error)
 
2341
                logger.warning("Handshake failed: %s", error)
2359
2342
                # Do not run session.bye() here: the session is not
2360
2343
                # established.  Just abandon the request.
2361
2344
                return
2362
 
            log.debug("Handshake succeeded")
 
2345
            logger.debug("Handshake succeeded")
2363
2346
 
2364
2347
            approval_required = False
2365
2348
            try:
2369
2352
                        key_id = self.key_id(
2370
2353
                            self.peer_certificate(session))
2371
2354
                    except (TypeError, gnutls.Error) as error:
2372
 
                        log.warning("Bad certificate: %s", error)
 
2355
                        logger.warning("Bad certificate: %s", error)
2373
2356
                        return
2374
 
                    log.debug("Key ID: %s",
2375
 
                              key_id.decode("utf-8",
2376
 
                                            errors="replace"))
 
2357
                    logger.debug("Key ID: %s",
 
2358
                                 key_id.decode("utf-8",
 
2359
                                               errors="replace"))
2377
2360
 
2378
2361
                else:
2379
2362
                    key_id = b""
2381
2364
                        fpr = self.fingerprint(
2382
2365
                            self.peer_certificate(session))
2383
2366
                    except (TypeError, gnutls.Error) as error:
2384
 
                        log.warning("Bad certificate: %s", error)
 
2367
                        logger.warning("Bad certificate: %s", error)
2385
2368
                        return
2386
 
                    log.debug("Fingerprint: %s", fpr)
 
2369
                    logger.debug("Fingerprint: %s", fpr)
2387
2370
 
2388
2371
                try:
2389
2372
                    client = ProxyClient(child_pipe, key_id, fpr,
2398
2381
 
2399
2382
                while True:
2400
2383
                    if not client.enabled:
2401
 
                        log.info("Client %s is disabled", client.name)
 
2384
                        logger.info("Client %s is disabled",
 
2385
                                    client.name)
2402
2386
                        if self.server.use_dbus:
2403
2387
                            # Emit D-Bus signal
2404
2388
                            client.Rejected("Disabled")
2408
2392
                        # We are approved or approval is disabled
2409
2393
                        break
2410
2394
                    elif client.approved is None:
2411
 
                        log.info("Client %s needs approval",
2412
 
                                 client.name)
 
2395
                        logger.info("Client %s needs approval",
 
2396
                                    client.name)
2413
2397
                        if self.server.use_dbus:
2414
2398
                            # Emit D-Bus signal
2415
2399
                            client.NeedApproval(
2416
2400
                                client.approval_delay.total_seconds()
2417
2401
                                * 1000, client.approved_by_default)
2418
2402
                    else:
2419
 
                        log.warning("Client %s was not approved",
2420
 
                                    client.name)
 
2403
                        logger.warning("Client %s was not approved",
 
2404
                                       client.name)
2421
2405
                        if self.server.use_dbus:
2422
2406
                            # Emit D-Bus signal
2423
2407
                            client.Rejected("Denied")
2431
2415
                    time2 = datetime.datetime.now()
2432
2416
                    if (time2 - time) >= delay:
2433
2417
                        if not client.approved_by_default:
2434
 
                            log.warning("Client %s timed out while"
2435
 
                                        " waiting for approval",
2436
 
                                        client.name)
 
2418
                            logger.warning("Client %s timed out while"
 
2419
                                           " waiting for approval",
 
2420
                                           client.name)
2437
2421
                            if self.server.use_dbus:
2438
2422
                                # Emit D-Bus signal
2439
2423
                                client.Rejected("Approval timed out")
2446
2430
                try:
2447
2431
                    session.send(client.secret)
2448
2432
                except gnutls.Error as error:
2449
 
                    log.warning("gnutls send failed", exc_info=error)
 
2433
                    logger.warning("gnutls send failed",
 
2434
                                   exc_info=error)
2450
2435
                    return
2451
2436
 
2452
 
                log.info("Sending secret to %s", client.name)
 
2437
                logger.info("Sending secret to %s", client.name)
2453
2438
                # bump the timeout using extended_timeout
2454
2439
                client.bump_timeout(client.extended_timeout)
2455
2440
                if self.server.use_dbus:
2462
2447
                try:
2463
2448
                    session.bye()
2464
2449
                except gnutls.Error as error:
2465
 
                    log.warning("GnuTLS bye failed", exc_info=error)
 
2450
                    logger.warning("GnuTLS bye failed",
 
2451
                                   exc_info=error)
2466
2452
 
2467
2453
    @staticmethod
2468
2454
    def peer_certificate(session):
2478
2464
            valid_cert_types = frozenset((gnutls.CRT_OPENPGP,))
2479
2465
        # If not a valid certificate type...
2480
2466
        if cert_type not in valid_cert_types:
2481
 
            log.info("Cert type %r not in %r", cert_type,
2482
 
                     valid_cert_types)
 
2467
            logger.info("Cert type %r not in %r", cert_type,
 
2468
                        valid_cert_types)
2483
2469
            # ...return invalid data
2484
2470
            return b""
2485
2471
        list_size = ctypes.c_uint(1)
2661
2647
            if SO_BINDTODEVICE is None:
2662
2648
                # Fall back to a hard-coded value which seems to be
2663
2649
                # common enough.
2664
 
                log.warning("SO_BINDTODEVICE not found, trying 25")
 
2650
                logger.warning("SO_BINDTODEVICE not found, trying 25")
2665
2651
                SO_BINDTODEVICE = 25
2666
2652
            try:
2667
2653
                self.socket.setsockopt(
2669
2655
                    (self.interface + "\0").encode("utf-8"))
2670
2656
            except socket.error as error:
2671
2657
                if error.errno == errno.EPERM:
2672
 
                    log.error("No permission to bind to interface %s",
2673
 
                              self.interface)
 
2658
                    logger.error("No permission to bind to"
 
2659
                                 " interface %s", self.interface)
2674
2660
                elif error.errno == errno.ENOPROTOOPT:
2675
 
                    log.error("SO_BINDTODEVICE not available; cannot"
2676
 
                              " bind to interface %s", self.interface)
 
2661
                    logger.error("SO_BINDTODEVICE not available;"
 
2662
                                 " cannot bind to interface %s",
 
2663
                                 self.interface)
2677
2664
                elif error.errno == errno.ENODEV:
2678
 
                    log.error("Interface %s does not exist, cannot"
2679
 
                              " bind", self.interface)
 
2665
                    logger.error("Interface %s does not exist,"
 
2666
                                 " cannot bind", self.interface)
2680
2667
                else:
2681
2668
                    raise
2682
2669
        # Only bind(2) the socket if we really need to.
2777
2764
                    client = c
2778
2765
                    break
2779
2766
            else:
2780
 
                log.info("Client not found for key ID: %s, address:"
2781
 
                         " %s", key_id or fpr, address)
 
2767
                logger.info("Client not found for key ID: %s, address"
 
2768
                            ": %s", key_id or fpr, address)
2782
2769
                if self.use_dbus:
2783
2770
                    # Emit D-Bus signal
2784
2771
                    mandos_dbus_service.ClientNotFound(key_id or fpr,
3178
3165
        try:
3179
3166
            pidfile = codecs.open(pidfilename, "w", encoding="utf-8")
3180
3167
        except IOError as e:
3181
 
            log.error("Could not open file %r", pidfilename,
3182
 
                      exc_info=e)
 
3168
            logger.error("Could not open file %r", pidfilename,
 
3169
                         exc_info=e)
3183
3170
 
3184
3171
    for name, group in (("_mandos", "_mandos"),
3185
3172
                        ("mandos", "mandos"),
3196
3183
    try:
3197
3184
        os.setgid(gid)
3198
3185
        os.setuid(uid)
3199
 
        log.debug("Did setuid/setgid to %s:%s", uid, gid)
 
3186
        if debug:
 
3187
            logger.debug("Did setuid/setgid to {}:{}".format(uid,
 
3188
                                                             gid))
3200
3189
    except OSError as error:
3201
 
        log.warning("Failed to setuid/setgid to %s:%s: %s", uid, gid,
3202
 
                    os.strerror(error.errno))
 
3190
        logger.warning("Failed to setuid/setgid to {}:{}: {}"
 
3191
                       .format(uid, gid, os.strerror(error.errno)))
3203
3192
        if error.errno != errno.EPERM:
3204
3193
            raise
3205
3194
 
3212
3201
 
3213
3202
        @gnutls.log_func
3214
3203
        def debug_gnutls(level, string):
3215
 
            log.debug("GnuTLS: %s",
3216
 
                      string[:-1].decode("utf-8", errors="replace"))
 
3204
            logger.debug("GnuTLS: %s",
 
3205
                         string[:-1].decode("utf-8",
 
3206
                                            errors="replace"))
3217
3207
 
3218
3208
        gnutls.global_set_log_function(debug_gnutls)
3219
3209
 
3248
3238
                "se.bsnet.fukt.Mandos", bus,
3249
3239
                do_not_queue=True)
3250
3240
        except dbus.exceptions.DBusException as e:
3251
 
            log.error("Disabling D-Bus:", exc_info=e)
 
3241
            logger.error("Disabling D-Bus:", exc_info=e)
3252
3242
            use_dbus = False
3253
3243
            server_settings["use_dbus"] = False
3254
3244
            tcp_server.use_dbus = False
3339
3329
            os.remove(stored_state_path)
3340
3330
        except IOError as e:
3341
3331
            if e.errno == errno.ENOENT:
3342
 
                log.warning("Could not load persistent state:"
3343
 
                            " %s", os.strerror(e.errno))
 
3332
                logger.warning("Could not load persistent state:"
 
3333
                               " {}".format(os.strerror(e.errno)))
3344
3334
            else:
3345
 
                log.critical("Could not load persistent state:",
3346
 
                             exc_info=e)
 
3335
                logger.critical("Could not load persistent state:",
 
3336
                                exc_info=e)
3347
3337
                raise
3348
3338
        except EOFError as e:
3349
 
            log.warning("Could not load persistent state: EOFError:",
3350
 
                        exc_info=e)
 
3339
            logger.warning("Could not load persistent state: "
 
3340
                           "EOFError:",
 
3341
                           exc_info=e)
3351
3342
 
3352
3343
    with PGPEngine() as pgp:
3353
3344
        for client_name, client in clients_data.items():
3380
3371
            if client["enabled"]:
3381
3372
                if datetime.datetime.utcnow() >= client["expires"]:
3382
3373
                    if not client["last_checked_ok"]:
3383
 
                        log.warning("disabling client %s - Client"
3384
 
                                    " never performed a successful"
3385
 
                                    " checker", client_name)
 
3374
                        logger.warning(
 
3375
                            "disabling client {} - Client never "
 
3376
                            "performed a successful checker".format(
 
3377
                                client_name))
3386
3378
                        client["enabled"] = False
3387
3379
                    elif client["last_checker_status"] != 0:
3388
 
                        log.warning("disabling client %s - Client"
3389
 
                                    " last checker failed with error"
3390
 
                                    " code %s", client_name,
3391
 
                                    client["last_checker_status"])
 
3380
                        logger.warning(
 
3381
                            "disabling client {} - Client last"
 
3382
                            " checker failed with error code"
 
3383
                            " {}".format(
 
3384
                                client_name,
 
3385
                                client["last_checker_status"]))
3392
3386
                        client["enabled"] = False
3393
3387
                    else:
3394
3388
                        client["expires"] = (
3395
3389
                            datetime.datetime.utcnow()
3396
3390
                            + client["timeout"])
3397
 
                        log.debug("Last checker succeeded, keeping %s"
3398
 
                                  " enabled", client_name)
 
3391
                        logger.debug("Last checker succeeded,"
 
3392
                                     " keeping {} enabled".format(
 
3393
                                         client_name))
3399
3394
            try:
3400
3395
                client["secret"] = pgp.decrypt(
3401
3396
                    client["encrypted_secret"],
3402
3397
                    client_settings[client_name]["secret"])
3403
3398
            except PGPError:
3404
3399
                # If decryption fails, we use secret from new settings
3405
 
                log.debug("Failed to decrypt %s old secret",
3406
 
                          client_name)
 
3400
                logger.debug("Failed to decrypt {} old secret".format(
 
3401
                    client_name))
3407
3402
                client["secret"] = (client_settings[client_name]
3408
3403
                                    ["secret"])
3409
3404
 
3423
3418
            server_settings=server_settings)
3424
3419
 
3425
3420
    if not tcp_server.clients:
3426
 
        log.warning("No clients defined")
 
3421
        logger.warning("No clients defined")
3427
3422
 
3428
3423
    if not foreground:
3429
3424
        if pidfile is not None:
3432
3427
                with pidfile:
3433
3428
                    print(pid, file=pidfile)
3434
3429
            except IOError:
3435
 
                log.error("Could not write to file %r with PID %d",
3436
 
                          pidfilename, pid)
 
3430
                logger.error("Could not write to file %r with PID %d",
 
3431
                             pidfilename, pid)
3437
3432
        del pidfile
3438
3433
        del pidfilename
3439
3434
 
3605
3600
                except NameError:
3606
3601
                    pass
3607
3602
            if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST):
3608
 
                log.warning("Could not save persistent state: %s",
3609
 
                            os.strerror(e.errno))
 
3603
                logger.warning("Could not save persistent state: {}"
 
3604
                               .format(os.strerror(e.errno)))
3610
3605
            else:
3611
 
                log.warning("Could not save persistent state:",
3612
 
                            exc_info=e)
 
3606
                logger.warning("Could not save persistent state:",
 
3607
                               exc_info=e)
3613
3608
                raise
3614
3609
 
3615
3610
        # Delete all clients, and settings from config
3632
3627
            mandos_dbus_service.client_added_signal(client)
3633
3628
        # Need to initiate checking of clients
3634
3629
        if client.enabled:
3635
 
            client.init_checker(randomize_start=True)
 
3630
            client.init_checker()
3636
3631
 
3637
3632
    tcp_server.enable()
3638
3633
    tcp_server.server_activate()
3641
3636
    if zeroconf:
3642
3637
        service.port = tcp_server.socket.getsockname()[1]
3643
3638
    if use_ipv6:
3644
 
        log.info("Now listening on address %r, port %d, flowinfo %d,"
3645
 
                 " scope_id %d", *tcp_server.socket.getsockname())
 
3639
        logger.info("Now listening on address %r, port %d,"
 
3640
                    " flowinfo %d, scope_id %d",
 
3641
                    *tcp_server.socket.getsockname())
3646
3642
    else:                       # IPv4
3647
 
        log.info("Now listening on address %r, port %d",
3648
 
                 *tcp_server.socket.getsockname())
 
3643
        logger.info("Now listening on address %r, port %d",
 
3644
                    *tcp_server.socket.getsockname())
3649
3645
 
3650
3646
    # service.interface = tcp_server.socket.getsockname()[3]
3651
3647
 
3655
3651
            try:
3656
3652
                service.activate()
3657
3653
            except dbus.exceptions.DBusException as error:
3658
 
                log.critical("D-Bus Exception", exc_info=error)
 
3654
                logger.critical("D-Bus Exception", exc_info=error)
3659
3655
                cleanup()
3660
3656
                sys.exit(1)
3661
3657
            # End of Avahi example code
3666
3662
            lambda *args, **kwargs: (tcp_server.handle_request
3667
3663
                                     (*args[2:], **kwargs) or True))
3668
3664
 
3669
 
        log.debug("Starting main loop")
 
3665
        logger.debug("Starting main loop")
3670
3666
        main_loop.run()
3671
3667
    except AvahiError as error:
3672
 
        log.critical("Avahi Error", exc_info=error)
 
3668
        logger.critical("Avahi Error", exc_info=error)
3673
3669
        cleanup()
3674
3670
        sys.exit(1)
3675
3671
    except KeyboardInterrupt:
3676
3672
        if debug:
3677
3673
            print("", file=sys.stderr)
3678
 
        log.debug("Server received KeyboardInterrupt")
3679
 
    log.debug("Server exiting")
 
3674
        logger.debug("Server received KeyboardInterrupt")
 
3675
    logger.debug("Server exiting")
3680
3676
    # Must run before the D-Bus bus name gets deregistered
3681
3677
    cleanup()
3682
3678
 
3683
3679
 
3684
 
def parse_test_args():
3685
 
    # type: () -> argparse.Namespace
 
3680
def should_only_run_tests():
3686
3681
    parser = argparse.ArgumentParser(add_help=False)
3687
3682
    parser.add_argument("--check", action="store_true")
3688
 
    parser.add_argument("--prefix", )
3689
3683
    args, unknown_args = parser.parse_known_args()
3690
 
    if args.check:
3691
 
        # Remove test options from sys.argv
 
3684
    run_tests = args.check
 
3685
    if run_tests:
 
3686
        # Remove --check argument from sys.argv
3692
3687
        sys.argv[1:] = unknown_args
3693
 
    return args
 
3688
    return run_tests
3694
3689
 
3695
3690
# Add all tests from doctest strings
3696
3691
def load_tests(loader, tests, none):
3699
3694
    return tests
3700
3695
 
3701
3696
if __name__ == "__main__":
3702
 
    options = parse_test_args()
3703
3697
    try:
3704
 
        if options.check:
3705
 
            extra_test_prefix = options.prefix
3706
 
            if extra_test_prefix is not None:
3707
 
                if not (unittest.main(argv=[""], exit=False)
3708
 
                        .result.wasSuccessful()):
3709
 
                    sys.exit(1)
3710
 
                class ExtraTestLoader(unittest.TestLoader):
3711
 
                    testMethodPrefix = extra_test_prefix
3712
 
                # Call using ./scriptname --test [--verbose]
3713
 
                unittest.main(argv=[""], testLoader=ExtraTestLoader())
3714
 
            else:
3715
 
                unittest.main(argv=[""])
 
3698
        if should_only_run_tests():
 
3699
            # Call using ./mandos --check [--verbose]
 
3700
            unittest.main()
3716
3701
        else:
3717
3702
            main()
3718
3703
    finally:
3719
3704
        logging.shutdown()
3720
 
 
3721
 
# Local Variables:
3722
 
# run-tests:
3723
 
# (lambda (&optional extra)
3724
 
#   (if (not (funcall run-tests-in-test-buffer default-directory
3725
 
#             extra))
3726
 
#       (funcall show-test-buffer-in-test-window)
3727
 
#     (funcall remove-test-window)
3728
 
#     (if extra (message "Extra tests run successfully!"))))
3729
 
# run-tests-in-test-buffer:
3730
 
# (lambda (dir &optional extra)
3731
 
#   (with-current-buffer (get-buffer-create "*Test*")
3732
 
#     (setq buffer-read-only nil
3733
 
#           default-directory dir)
3734
 
#     (erase-buffer)
3735
 
#     (compilation-mode))
3736
 
#   (let ((process-result
3737
 
#          (let ((inhibit-read-only t))
3738
 
#            (process-file-shell-command
3739
 
#             (funcall get-command-line extra) nil "*Test*"))))
3740
 
#     (and (numberp process-result)
3741
 
#          (= process-result 0))))
3742
 
# get-command-line:
3743
 
# (lambda (&optional extra)
3744
 
#   (let ((quoted-script
3745
 
#          (shell-quote-argument (funcall get-script-name))))
3746
 
#     (format
3747
 
#      (concat "%s --check" (if extra " --prefix=atest" ""))
3748
 
#      quoted-script)))
3749
 
# get-script-name:
3750
 
# (lambda ()
3751
 
#   (if (fboundp 'file-local-name)
3752
 
#       (file-local-name (buffer-file-name))
3753
 
#     (or (file-remote-p (buffer-file-name) 'localname)
3754
 
#         (buffer-file-name))))
3755
 
# remove-test-window:
3756
 
# (lambda ()
3757
 
#   (let ((test-window (get-buffer-window "*Test*")))
3758
 
#     (if test-window (delete-window test-window))))
3759
 
# show-test-buffer-in-test-window:
3760
 
# (lambda ()
3761
 
#   (when (not (get-buffer-window-list "*Test*"))
3762
 
#     (setq next-error-last-buffer (get-buffer "*Test*"))
3763
 
#     (let* ((side (if (>= (window-width) 146) 'right 'bottom))
3764
 
#            (display-buffer-overriding-action
3765
 
#             `((display-buffer-in-side-window) (side . ,side)
3766
 
#               (window-height . fit-window-to-buffer)
3767
 
#               (window-width . fit-window-to-buffer))))
3768
 
#       (display-buffer "*Test*"))))
3769
 
# eval:
3770
 
# (progn
3771
 
#   (let* ((run-extra-tests (lambda () (interactive)
3772
 
#                             (funcall run-tests t)))
3773
 
#          (inner-keymap `(keymap (116 . ,run-extra-tests))) ; t
3774
 
#          (outer-keymap `(keymap (3 . ,inner-keymap))))     ; C-c
3775
 
#     (setq minor-mode-overriding-map-alist
3776
 
#           (cons `(run-tests . ,outer-keymap)
3777
 
#                 minor-mode-overriding-map-alist)))
3778
 
#   (add-hook 'after-save-hook run-tests 90 t))
3779
 
# End: