/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-ctl

  • Committer: Teddy Hogeborn
  • Date: 2015-07-20 03:03:33 UTC
  • Revision ID: teddy@recompile.se-20150720030333-203m2aeblypcsfte
Bug fix for GnuTLS 3: be compatible with old 2048-bit DSA keys.

The mandos-keygen program in Mandos version 1.6.0 and older generated
2048-bit DSA keys, and when GnuTLS uses these it has trouble
connecting using the Mandos default priority string.  This was
previously fixed in Mandos 1.6.2, but the bug reappeared when using
GnuTLS 3, so the default priority string has to change again; this
time also the Mandos client has to change its default, so now the
server and the client should use the same default priority string:

SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256

* mandos (main/server_defaults): Changed default priority string.
* mandos-options.xml (/section/para[id="priority_compat"]): Removed.
  (/section/para[id="priority"]): Changed default priority string.
* mandos.conf ([DEFAULT]/priority): - '' -
* mandos.conf.xml (OPTIONS/priority): Refer to the id "priority"
                                      instead of "priority_compat".
* mandos.xml (OPTIONS/--priority): - '' -
* plugins.d/mandos-client.c (main): Changed default priority string.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/python
2
2
# -*- mode: python; coding: utf-8 -*-
3
 
#
 
3
4
4
# Mandos Monitor - Control and monitor the Mandos server
5
 
#
6
 
# Copyright © 2008-2017 Teddy Hogeborn
7
 
# Copyright © 2008-2017 Björn Påhlsson
8
 
#
 
5
 
6
# Copyright © 2008-2015 Teddy Hogeborn
 
7
# Copyright © 2008-2015 Björn Påhlsson
 
8
9
9
# This program is free software: you can redistribute it and/or modify
10
10
# it under the terms of the GNU General Public License as published by
11
11
# the Free Software Foundation, either version 3 of the License, or
15
15
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
16
16
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
17
#     GNU General Public License for more details.
18
 
#
 
18
19
19
# You should have received a copy of the GNU General Public License
20
20
# along with this program.  If not, see
21
21
# <http://www.gnu.org/licenses/>.
22
 
#
 
22
23
23
# Contact the authors at <mandos@recompile.se>.
24
 
#
 
24
25
25
 
26
26
from __future__ import (division, absolute_import, print_function,
27
27
                        unicode_literals)
38
38
import re
39
39
import os
40
40
import collections
41
 
import json
 
41
import doctest
42
42
 
43
43
import dbus
44
44
 
64
64
    "ApprovalDelay": "Approval Delay",
65
65
    "ApprovalDuration": "Approval Duration",
66
66
    "Checker": "Checker",
67
 
    "ExtendedTimeout": "Extended Timeout",
68
 
    "Expires": "Expires",
69
 
    "LastCheckerStatus": "Last Checker Status",
 
67
    "ExtendedTimeout": "Extended Timeout"
70
68
}
71
69
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
72
70
domain = "se.recompile"
74
72
server_path = "/"
75
73
server_interface = domain + ".Mandos"
76
74
client_interface = domain + ".Mandos.Client"
77
 
version = "1.7.15"
78
 
 
79
 
 
80
 
try:
81
 
    dbus.OBJECT_MANAGER_IFACE
82
 
except AttributeError:
83
 
    dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
 
75
version = "1.6.9"
84
76
 
85
77
 
86
78
def milliseconds_to_string(ms):
87
79
    td = datetime.timedelta(0, 0, 0, ms)
88
 
    return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
89
 
            .format(days="{}T".format(td.days) if td.days else "",
90
 
                    hours=td.seconds // 3600,
91
 
                    minutes=(td.seconds % 3600) // 60,
92
 
                    seconds=td.seconds % 60))
 
80
    return ("{days}{hours:02}:{minutes:02}:{seconds:02}".format(
 
81
        days = "{}T".format(td.days) if td.days else "",
 
82
        hours = td.seconds // 3600,
 
83
        minutes = (td.seconds % 3600) // 60,
 
84
        seconds = td.seconds % 60))
93
85
 
94
86
 
95
87
def rfc3339_duration_to_delta(duration):
96
88
    """Parse an RFC 3339 "duration" and return a datetime.timedelta
97
 
 
 
89
    
98
90
    >>> rfc3339_duration_to_delta("P7D")
99
91
    datetime.timedelta(7)
100
92
    >>> rfc3339_duration_to_delta("PT60S")
110
102
    >>> rfc3339_duration_to_delta("P1DT3M20S")
111
103
    datetime.timedelta(1, 200)
112
104
    """
113
 
 
 
105
    
114
106
    # Parsing an RFC 3339 duration with regular expressions is not
115
107
    # possible - there would have to be multiple places for the same
116
108
    # values, like seconds.  The current code, while more esoteric, is
117
109
    # cleaner without depending on a parsing library.  If Python had a
118
110
    # built-in library for parsing we would use it, but we'd like to
119
111
    # avoid excessive use of external libraries.
120
 
 
 
112
    
121
113
    # New type for defining tokens, syntax, and semantics all-in-one
122
114
    Token = collections.namedtuple("Token", (
123
115
        "regexp",  # To match token; if "value" is not None, must have
156
148
                           frozenset((token_year, token_month,
157
149
                                      token_day, token_time,
158
150
                                      token_week)))
159
 
    # Define starting values:
160
 
    # Value so far
161
 
    value = datetime.timedelta()
 
151
    # Define starting values
 
152
    value = datetime.timedelta() # Value so far
162
153
    found_token = None
163
 
    # Following valid tokens
164
 
    followers = frozenset((token_duration, ))
165
 
    # String left to parse
166
 
    s = duration
 
154
    followers = frozenset((token_duration, )) # Following valid tokens
 
155
    s = duration                # String left to parse
167
156
    # Loop until end token is found
168
157
    while found_token is not token_end:
169
158
        # Search for any currently valid tokens
193
182
 
194
183
def string_to_delta(interval):
195
184
    """Parse a string and return a datetime.timedelta
196
 
 
 
185
    
197
186
    >>> string_to_delta('7d')
198
187
    datetime.timedelta(7)
199
188
    >>> string_to_delta('60s')
207
196
    >>> string_to_delta('5m 30s')
208
197
    datetime.timedelta(0, 330)
209
198
    """
210
 
 
 
199
    
211
200
    try:
212
201
        return rfc3339_duration_to_delta(interval)
213
202
    except ValueError:
214
203
        pass
215
 
 
 
204
    
216
205
    value = datetime.timedelta(0)
217
206
    regexp = re.compile(r"(\d+)([dsmhw]?)")
218
 
 
 
207
    
219
208
    for num, suffix in regexp.findall(interval):
220
209
        if suffix == "d":
221
210
            value += datetime.timedelta(int(num))
240
229
                       "ApprovalDuration", "ExtendedTimeout"):
241
230
            return milliseconds_to_string(value)
242
231
        return str(value)
243
 
 
 
232
    
244
233
    # Create format string to print table rows
245
234
    format_string = " ".join("{{{key}:{width}}}".format(
246
 
        width=max(len(tablewords[key]),
247
 
                  max(len(valuetostring(client[key], key))
248
 
                      for client in clients)),
249
 
        key=key)
 
235
        width = max(len(tablewords[key]),
 
236
                    max(len(valuetostring(client[key], key))
 
237
                        for client in clients)),
 
238
        key = key)
250
239
                             for key in keywords)
251
240
    # Print header line
252
241
    print(format_string.format(**tablewords))
253
242
    for client in clients:
254
 
        print(format_string
255
 
              .format(**{key: valuetostring(client[key], key)
256
 
                         for key in keywords}))
 
243
        print(format_string.format(**{
 
244
            key: valuetostring(client[key], key)
 
245
            for key in keywords }))
257
246
 
258
247
 
259
248
def has_actions(options):
280
269
def main():
281
270
    parser = argparse.ArgumentParser()
282
271
    parser.add_argument("--version", action="version",
283
 
                        version="%(prog)s {}".format(version),
 
272
                        version = "%(prog)s {}".format(version),
284
273
                        help="show version number and exit")
285
274
    parser.add_argument("-a", "--all", action="store_true",
286
275
                        help="Select all clients")
287
276
    parser.add_argument("-v", "--verbose", action="store_true",
288
277
                        help="Print all fields")
289
 
    parser.add_argument("-j", "--dump-json", action="store_true",
290
 
                        help="Dump client data in JSON format")
291
278
    parser.add_argument("-e", "--enable", action="store_true",
292
279
                        help="Enable client")
293
280
    parser.add_argument("-d", "--disable", action="store_true",
332
319
                        help="Run self-test")
333
320
    parser.add_argument("client", nargs="*", help="Client name")
334
321
    options = parser.parse_args()
335
 
 
 
322
    
336
323
    if has_actions(options) and not (options.client or options.all):
337
324
        parser.error("Options require clients names or --all.")
338
325
    if options.verbose and has_actions(options):
339
 
        parser.error("--verbose can only be used alone.")
340
 
    if options.dump_json and (options.verbose
341
 
                              or has_actions(options)):
342
 
        parser.error("--dump-json can only be used alone.")
 
326
        parser.error("--verbose can only be used alone or with"
 
327
                     " --all.")
343
328
    if options.all and not has_actions(options):
344
329
        parser.error("--all requires an action.")
345
330
 
346
331
    if options.check:
347
 
        import doctest
348
332
        fail_count, test_count = doctest.testmod()
349
333
        sys.exit(os.EX_OK if fail_count == 0 else 1)
350
 
 
 
334
    
351
335
    try:
352
336
        bus = dbus.SystemBus()
353
337
        mandos_dbus_objc = bus.get_object(busname, server_path)
354
338
    except dbus.exceptions.DBusException:
355
339
        print("Could not connect to Mandos server", file=sys.stderr)
356
340
        sys.exit(1)
357
 
 
 
341
    
358
342
    mandos_serv = dbus.Interface(mandos_dbus_objc,
359
 
                                 dbus_interface=server_interface)
360
 
    mandos_serv_object_manager = dbus.Interface(
361
 
        mandos_dbus_objc, dbus_interface=dbus.OBJECT_MANAGER_IFACE)
362
 
 
363
 
    # block stderr since dbus library prints to stderr
 
343
                                 dbus_interface = server_interface)
 
344
    
 
345
    #block stderr since dbus library prints to stderr
364
346
    null = os.open(os.path.devnull, os.O_RDWR)
365
347
    stderrcopy = os.dup(sys.stderr.fileno())
366
348
    os.dup2(null, sys.stderr.fileno())
367
349
    os.close(null)
368
350
    try:
369
351
        try:
370
 
            mandos_clients = {path: ifs_and_props[client_interface]
371
 
                              for path, ifs_and_props in
372
 
                              mandos_serv_object_manager
373
 
                              .GetManagedObjects().items()
374
 
                              if client_interface in ifs_and_props}
 
352
            mandos_clients = mandos_serv.GetAllClientsWithProperties()
375
353
        finally:
376
 
            # restore stderr
 
354
            #restore stderr
377
355
            os.dup2(stderrcopy, sys.stderr.fileno())
378
356
            os.close(stderrcopy)
379
 
    except dbus.exceptions.DBusException as e:
380
 
        print("Access denied: "
381
 
              "Accessing mandos server through D-Bus: {}".format(e),
 
357
    except dbus.exceptions.DBusException:
 
358
        print("Access denied: Accessing mandos server through dbus.",
382
359
              file=sys.stderr)
383
360
        sys.exit(1)
384
 
 
 
361
    
385
362
    # Compile dict of (clients: properties) to process
386
 
    clients = {}
387
 
 
 
363
    clients={}
 
364
    
388
365
    if options.all or not options.client:
389
 
        clients = {bus.get_object(busname, path): properties
390
 
                   for path, properties in mandos_clients.items()}
 
366
        clients = { bus.get_object(busname, path): properties
 
367
                    for path, properties in mandos_clients.items() }
391
368
    else:
392
369
        for name in options.client:
393
370
            for path, client in mandos_clients.items():
399
376
                print("Client not found on server: {!r}"
400
377
                      .format(name), file=sys.stderr)
401
378
                sys.exit(1)
402
 
 
 
379
    
403
380
    if not has_actions(options) and clients:
404
 
        if options.verbose or options.dump_json:
 
381
        if options.verbose:
405
382
            keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
406
383
                        "Created", "Interval", "Host", "Fingerprint",
407
384
                        "CheckerRunning", "LastEnabled",
408
385
                        "ApprovalPending", "ApprovedByDefault",
409
386
                        "LastApprovalRequest", "ApprovalDelay",
410
387
                        "ApprovalDuration", "Checker",
411
 
                        "ExtendedTimeout", "Expires",
412
 
                        "LastCheckerStatus")
 
388
                        "ExtendedTimeout")
413
389
        else:
414
390
            keywords = defaultkeywords
415
 
 
416
 
        if options.dump_json:
417
 
            json.dump({client["Name"]: {key:
418
 
                                        bool(client[key])
419
 
                                        if isinstance(client[key],
420
 
                                                      dbus.Boolean)
421
 
                                        else client[key]
422
 
                                        for key in keywords}
423
 
                       for client in clients.values()},
424
 
                      fp=sys.stdout, indent=4,
425
 
                      separators=(',', ': '))
426
 
            print()
427
 
        else:
428
 
            print_clients(clients.values(), keywords)
 
391
        
 
392
        print_clients(clients.values(), keywords)
429
393
    else:
430
394
        # Process each client in the list by all selected options
431
395
        for client in clients:
432
 
 
 
396
            
433
397
            def set_client_prop(prop, value):
434
398
                """Set a Client D-Bus property"""
435
399
                client.Set(client_interface, prop, value,
436
400
                           dbus_interface=dbus.PROPERTIES_IFACE)
437
 
 
 
401
            
438
402
            def set_client_prop_ms(prop, value):
439
403
                """Set a Client D-Bus property, converted
440
404
                from a string to milliseconds."""
441
405
                set_client_prop(prop,
442
406
                                string_to_delta(value).total_seconds()
443
407
                                * 1000)
444
 
 
 
408
            
445
409
            if options.remove:
446
410
                mandos_serv.RemoveClient(client.__dbus_object_path__)
447
411
            if options.enable:
455
419
            if options.stop_checker:
456
420
                set_client_prop("CheckerRunning", dbus.Boolean(False))
457
421
            if options.is_enabled:
458
 
                if client.Get(client_interface, "Enabled",
459
 
                              dbus_interface=dbus.PROPERTIES_IFACE):
460
 
                    sys.exit(0)
461
 
                else:
462
 
                    sys.exit(1)
 
422
                sys.exit(0 if client.Get(client_interface,
 
423
                                         "Enabled",
 
424
                                         dbus_interface=
 
425
                                         dbus.PROPERTIES_IFACE)
 
426
                         else 1)
463
427
            if options.checker is not None:
464
428
                set_client_prop("Checker", options.checker)
465
429
            if options.host is not None: