/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-05 14:31:51 UTC
  • Revision ID: teddy@recompile.se-20190805143151-lt5d97wqif3t8250
Client: Debian package fix: Make uninstall when using dracut(8) work

Use the same logic to rebuild the initramfs image when uninstalling as
when installing the package.

* debian/mandos-client.postrm (update_initramfs): Use the same logic
  as the update_initramfs function in debian/mandos-client.postinst.

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