/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: 2019-08-04 12:42:49 UTC
  • Revision ID: teddy@recompile.se-20190804124249-69cq19d1bgbmm0gh
Describe role of password-agent(8mandos) in intro(8mandos)

Describe the role of password-agent(8mandos) in the intro(8mandos)
manual.

* intro.xml (SYSTEMD): New section.
  (SEE ALSO): Add reference to password-agent(8mandos).

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python3 -bI
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 -*-
 
1
#!/usr/bin/python
 
2
# -*- mode: python; coding: utf-8 -*-
3
3
#
4
4
# Mandos server - give out binary blobs to connecting clients.
5
5
#
77
77
import itertools
78
78
import collections
79
79
import codecs
80
 
import unittest
81
80
 
82
81
import dbus
83
82
import dbus.service
89
88
import xml.dom.minidom
90
89
import inspect
91
90
 
92
 
if sys.version_info.major == 2:
93
 
    __metaclass__ = type
94
 
    str = unicode
95
 
 
96
 
# Show warnings by default
97
 
if not sys.warnoptions:
98
 
    import warnings
99
 
    warnings.simplefilter("default")
100
 
 
101
91
# Try to find the value of SO_BINDTODEVICE:
102
92
try:
103
93
    # This is where SO_BINDTODEVICE is in Python 3.3 (or 3.4?) and
123
113
            # No value found
124
114
            SO_BINDTODEVICE = None
125
115
 
 
116
if sys.version_info.major == 2:
 
117
    str = unicode
 
118
 
126
119
if sys.version_info < (3, 2):
127
120
    configparser.Configparser = configparser.SafeConfigParser
128
121
 
129
 
version = "1.8.9"
 
122
version = "1.8.6"
130
123
stored_state_file = "clients.pickle"
131
124
 
132
125
logger = logging.getLogger()
133
 
logging.captureWarnings(True)   # Show warnings via the logging system
134
126
syslogger = None
135
127
 
136
128
try:
191
183
    pass
192
184
 
193
185
 
194
 
class PGPEngine:
 
186
class PGPEngine(object):
195
187
    """A simple class for OpenPGP symmetric encryption & decryption"""
196
188
 
197
189
    def __init__(self):
201
193
            output = subprocess.check_output(["gpgconf"])
202
194
            for line in output.splitlines():
203
195
                name, text, path = line.split(b":")
204
 
                if name == b"gpg":
 
196
                if name == "gpg":
205
197
                    self.gpg = path
206
198
                    break
207
199
        except OSError as e:
212
204
                          '--force-mdc',
213
205
                          '--quiet']
214
206
        # Only GPG version 1 has the --no-use-agent option.
215
 
        if self.gpg == b"gpg" or self.gpg.endswith(b"/gpg"):
 
207
        if self.gpg == "gpg" or self.gpg.endswith("/gpg"):
216
208
            self.gnupgargs.append("--no-use-agent")
217
209
 
218
210
    def __enter__(self):
287
279
 
288
280
 
289
281
# Pretend that we have an Avahi module
290
 
class avahi:
 
282
class avahi(object):
291
283
    """This isn't so much a class as it is a module-like namespace."""
292
284
    IF_UNSPEC = -1               # avahi-common/address.h
293
285
    PROTO_UNSPEC = -1            # avahi-common/address.h
327
319
    pass
328
320
 
329
321
 
330
 
class AvahiService:
 
322
class AvahiService(object):
331
323
    """An Avahi (Zeroconf) service.
332
324
 
333
325
    Attributes:
515
507
 
516
508
 
517
509
# Pretend that we have a GnuTLS module
518
 
class gnutls:
 
510
class gnutls(object):
519
511
    """This isn't so much a class as it is a module-like namespace."""
520
512
 
521
513
    library = ctypes.util.find_library("gnutls")
584
576
        pass
585
577
 
586
578
    # Classes
587
 
    class Credentials:
 
579
    class Credentials(object):
588
580
        def __init__(self):
589
581
            self._c_object = gnutls.certificate_credentials_t()
590
582
            gnutls.certificate_allocate_credentials(
594
586
        def __del__(self):
595
587
            gnutls.certificate_free_credentials(self._c_object)
596
588
 
597
 
    class ClientSession:
 
589
    class ClientSession(object):
598
590
        def __init__(self, socket, credentials=None):
599
591
            self._c_object = gnutls.session_t()
600
592
            gnutls_flags = gnutls.CLIENT
826
818
    connection.close()
827
819
 
828
820
 
829
 
class Client:
 
821
class Client(object):
830
822
    """A representation of a client host served by this server.
831
823
 
832
824
    Attributes:
1051
1043
        # Read return code from connection (see call_pipe)
1052
1044
        returncode = connection.recv()
1053
1045
        connection.close()
1054
 
        if self.checker is not None:
1055
 
            self.checker.join()
 
1046
        self.checker.join()
1056
1047
        self.checker_callback_tag = None
1057
1048
        self.checker = None
1058
1049
 
1149
1140
                kwargs=popen_args)
1150
1141
            self.checker.start()
1151
1142
            self.checker_callback_tag = GLib.io_add_watch(
1152
 
                GLib.IOChannel.unix_new(pipe[0].fileno()),
1153
 
                GLib.PRIORITY_DEFAULT, GLib.IO_IN,
 
1143
                pipe[0].fileno(), GLib.IO_IN,
1154
1144
                self.checker_callback, pipe[0], command)
1155
1145
        # Re-run this periodically if run by GLib.timeout_add
1156
1146
        return True
1411
1401
                raise ValueError("Byte arrays not supported for non-"
1412
1402
                                 "'ay' signature {!r}"
1413
1403
                                 .format(prop._dbus_signature))
1414
 
            value = dbus.ByteArray(bytes(value))
 
1404
            value = dbus.ByteArray(b''.join(chr(byte)
 
1405
                                            for byte in value))
1415
1406
        prop(value)
1416
1407
 
1417
1408
    @dbus.service.method(dbus.PROPERTIES_IFACE,
2222
2213
    del _interface
2223
2214
 
2224
2215
 
2225
 
class ProxyClient:
 
2216
class ProxyClient(object):
2226
2217
    def __init__(self, child_pipe, key_id, fpr, address):
2227
2218
        self._pipe = child_pipe
2228
2219
        self._pipe.send(('init', key_id, fpr, address))
2501
2492
        return hex_fpr
2502
2493
 
2503
2494
 
2504
 
class MultiprocessingMixIn:
 
2495
class MultiprocessingMixIn(object):
2505
2496
    """Like socketserver.ThreadingMixIn, but with multiprocessing"""
2506
2497
 
2507
2498
    def sub_process_main(self, request, address):
2519
2510
        return proc
2520
2511
 
2521
2512
 
2522
 
class MultiprocessingMixInWithPipe(MultiprocessingMixIn):
 
2513
class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object):
2523
2514
    """ adds a pipe to the MixIn """
2524
2515
 
2525
2516
    def process_request(self, request, client_address):
2540
2531
 
2541
2532
 
2542
2533
class IPv6_TCPServer(MultiprocessingMixInWithPipe,
2543
 
                     socketserver.TCPServer):
 
2534
                     socketserver.TCPServer, object):
2544
2535
    """IPv6-capable TCP server.  Accepts 'None' as address and/or port
2545
2536
 
2546
2537
    Attributes:
2679
2670
    def add_pipe(self, parent_pipe, proc):
2680
2671
        # Call "handle_ipc" for both data and EOF events
2681
2672
        GLib.io_add_watch(
2682
 
            GLib.IOChannel.unix_new(parent_pipe.fileno()),
2683
 
            GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_HUP,
 
2673
            parent_pipe.fileno(),
 
2674
            GLib.IO_IN | GLib.IO_HUP,
2684
2675
            functools.partial(self.handle_ipc,
2685
2676
                              parent_pipe=parent_pipe,
2686
2677
                              proc=proc))
2724
2715
                return False
2725
2716
 
2726
2717
            GLib.io_add_watch(
2727
 
                GLib.IOChannel.unix_new(parent_pipe.fileno()),
2728
 
                GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_HUP,
 
2718
                parent_pipe.fileno(),
 
2719
                GLib.IO_IN | GLib.IO_HUP,
2729
2720
                functools.partial(self.handle_ipc,
2730
2721
                                  parent_pipe=parent_pipe,
2731
2722
                                  proc=proc,
2763
2754
def rfc3339_duration_to_delta(duration):
2764
2755
    """Parse an RFC 3339 "duration" and return a datetime.timedelta
2765
2756
 
2766
 
    >>> rfc3339_duration_to_delta("P7D") == datetime.timedelta(7)
2767
 
    True
2768
 
    >>> rfc3339_duration_to_delta("PT60S") == datetime.timedelta(0, 60)
2769
 
    True
2770
 
    >>> rfc3339_duration_to_delta("PT60M") == datetime.timedelta(0, 3600)
2771
 
    True
2772
 
    >>> rfc3339_duration_to_delta("PT24H") == datetime.timedelta(1)
2773
 
    True
2774
 
    >>> rfc3339_duration_to_delta("P1W") == datetime.timedelta(7)
2775
 
    True
2776
 
    >>> rfc3339_duration_to_delta("PT5M30S") == datetime.timedelta(0, 330)
2777
 
    True
2778
 
    >>> rfc3339_duration_to_delta("P1DT3M20S") == datetime.timedelta(1, 200)
2779
 
    True
 
2757
    >>> rfc3339_duration_to_delta("P7D")
 
2758
    datetime.timedelta(7)
 
2759
    >>> rfc3339_duration_to_delta("PT60S")
 
2760
    datetime.timedelta(0, 60)
 
2761
    >>> rfc3339_duration_to_delta("PT60M")
 
2762
    datetime.timedelta(0, 3600)
 
2763
    >>> rfc3339_duration_to_delta("PT24H")
 
2764
    datetime.timedelta(1)
 
2765
    >>> rfc3339_duration_to_delta("P1W")
 
2766
    datetime.timedelta(7)
 
2767
    >>> rfc3339_duration_to_delta("PT5M30S")
 
2768
    datetime.timedelta(0, 330)
 
2769
    >>> rfc3339_duration_to_delta("P1DT3M20S")
 
2770
    datetime.timedelta(1, 200)
2780
2771
    """
2781
2772
 
2782
2773
    # Parsing an RFC 3339 duration with regular expressions is not
2862
2853
def string_to_delta(interval):
2863
2854
    """Parse a string and return a datetime.timedelta
2864
2855
 
2865
 
    >>> string_to_delta('7d') == datetime.timedelta(7)
2866
 
    True
2867
 
    >>> string_to_delta('60s') == datetime.timedelta(0, 60)
2868
 
    True
2869
 
    >>> string_to_delta('60m') == datetime.timedelta(0, 3600)
2870
 
    True
2871
 
    >>> string_to_delta('24h') == datetime.timedelta(1)
2872
 
    True
2873
 
    >>> string_to_delta('1w') == datetime.timedelta(7)
2874
 
    True
2875
 
    >>> string_to_delta('5m 30s') == datetime.timedelta(0, 330)
2876
 
    True
 
2856
    >>> string_to_delta('7d')
 
2857
    datetime.timedelta(7)
 
2858
    >>> string_to_delta('60s')
 
2859
    datetime.timedelta(0, 60)
 
2860
    >>> string_to_delta('60m')
 
2861
    datetime.timedelta(0, 3600)
 
2862
    >>> string_to_delta('24h')
 
2863
    datetime.timedelta(1)
 
2864
    >>> string_to_delta('1w')
 
2865
    datetime.timedelta(7)
 
2866
    >>> string_to_delta('5m 30s')
 
2867
    datetime.timedelta(0, 330)
2877
2868
    """
2878
2869
 
2879
2870
    try:
2981
2972
 
2982
2973
    options = parser.parse_args()
2983
2974
 
 
2975
    if options.check:
 
2976
        import doctest
 
2977
        fail_count, test_count = doctest.testmod()
 
2978
        sys.exit(os.EX_OK if fail_count == 0 else 1)
 
2979
 
2984
2980
    # Default values for config file for server-global settings
2985
2981
    if gnutls.has_rawpk:
2986
2982
        priority = ("SECURE128:!CTYPE-X.509:+CTYPE-RAWPK:!RSA"
3249
3245
                             if isinstance(s, bytes)
3250
3246
                             else s) for s in
3251
3247
                            value["client_structure"]]
3252
 
                        # .name, .host, and .checker_command
3253
 
                        for k in ("name", "host", "checker_command"):
 
3248
                        # .name & .host
 
3249
                        for k in ("name", "host"):
3254
3250
                            if isinstance(value[k], bytes):
3255
3251
                                value[k] = value[k].decode("utf-8")
3256
3252
                        if "key_id" not in value:
3266
3262
                        for key, value in
3267
3263
                        bytes_old_client_settings.items()}
3268
3264
                    del bytes_old_client_settings
3269
 
                    # .host and .checker_command
 
3265
                    # .host
3270
3266
                    for value in old_client_settings.values():
3271
 
                        for attribute in ("host", "checker_command"):
3272
 
                            if isinstance(value[attribute], bytes):
3273
 
                                value[attribute] = (value[attribute]
3274
 
                                                    .decode("utf-8"))
 
3267
                        if isinstance(value["host"], bytes):
 
3268
                            value["host"] = (value["host"]
 
3269
                                             .decode("utf-8"))
3275
3270
            os.remove(stored_state_path)
3276
3271
        except IOError as e:
3277
3272
            if e.errno == errno.ENOENT:
3602
3597
                sys.exit(1)
3603
3598
            # End of Avahi example code
3604
3599
 
3605
 
        GLib.io_add_watch(
3606
 
            GLib.IOChannel.unix_new(tcp_server.fileno()),
3607
 
            GLib.PRIORITY_DEFAULT, GLib.IO_IN,
3608
 
            lambda *args, **kwargs: (tcp_server.handle_request
3609
 
                                     (*args[2:], **kwargs) or True))
 
3600
        GLib.io_add_watch(tcp_server.fileno(), GLib.IO_IN,
 
3601
                          lambda *args, **kwargs:
 
3602
                          (tcp_server.handle_request
 
3603
                           (*args[2:], **kwargs) or True))
3610
3604
 
3611
3605
        logger.debug("Starting main loop")
3612
3606
        main_loop.run()
3622
3616
    # Must run before the D-Bus bus name gets deregistered
3623
3617
    cleanup()
3624
3618
 
3625
 
 
3626
 
def should_only_run_tests():
3627
 
    parser = argparse.ArgumentParser(add_help=False)
3628
 
    parser.add_argument("--check", action='store_true')
3629
 
    args, unknown_args = parser.parse_known_args()
3630
 
    run_tests = args.check
3631
 
    if run_tests:
3632
 
        # Remove --check argument from sys.argv
3633
 
        sys.argv[1:] = unknown_args
3634
 
    return run_tests
3635
 
 
3636
 
# Add all tests from doctest strings
3637
 
def load_tests(loader, tests, none):
3638
 
    import doctest
3639
 
    tests.addTests(doctest.DocTestSuite())
3640
 
    return tests
3641
3619
 
3642
3620
if __name__ == '__main__':
3643
 
    try:
3644
 
        if should_only_run_tests():
3645
 
            # Call using ./mandos --check [--verbose]
3646
 
            unittest.main()
3647
 
        else:
3648
 
            main()
3649
 
    finally:
3650
 
        logging.shutdown()
 
3621
    main()