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

  • Committer: Teddy Hogeborn
  • Date: 2016-06-27 20:21:50 UTC
  • mto: (237.7.594 trunk)
  • mto: This revision was merged to the branch mainline in revision 350.
  • Revision ID: teddy@recompile.se-20160627202150-ml201ilxwjf1g29w
mandos-ctl: Implement --dump-json option

* mandos-ctl (main): Implement --dump-json option
* mandos-ctl.xml (NAME, DESCRIPTION): Change description to the more
                                      accurate "control or query".
  (SYNOPSIS): Add required group around action options and add new
              "--dump-json" option.
  (OPTIONS): Document new "--dump-json" option.

Show diffs side-by-side

added added

removed removed

Lines of Context:
3
3
4
4
# Mandos Monitor - Control and monitor the Mandos server
5
5
6
 
# Copyright © 2008-2014 Teddy Hogeborn
7
 
# Copyright © 2008-2014 Björn Påhlsson
 
6
# Copyright © 2008-2016 Teddy Hogeborn
 
7
# Copyright © 2008-2016 Björn Påhlsson
8
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
26
26
from __future__ import (division, absolute_import, print_function,
27
27
                        unicode_literals)
28
28
 
29
 
from future_builtins import *
 
29
try:
 
30
    from future_builtins import *
 
31
except ImportError:
 
32
    pass
30
33
 
31
34
import sys
32
35
import argparse
36
39
import os
37
40
import collections
38
41
import doctest
 
42
import json
39
43
 
40
44
import dbus
41
45
 
 
46
if sys.version_info.major == 2:
 
47
    str = unicode
 
48
 
42
49
locale.setlocale(locale.LC_ALL, "")
43
50
 
44
51
tablewords = {
58
65
    "ApprovalDelay": "Approval Delay",
59
66
    "ApprovalDuration": "Approval Duration",
60
67
    "Checker": "Checker",
61
 
    "ExtendedTimeout" : "Extended Timeout"
62
 
    }
 
68
    "ExtendedTimeout": "Extended Timeout"
 
69
}
63
70
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
64
71
domain = "se.recompile"
65
72
busname = domain + ".Mandos"
66
73
server_path = "/"
67
74
server_interface = domain + ".Mandos"
68
75
client_interface = domain + ".Mandos.Client"
69
 
version = "1.6.4"
70
 
 
71
 
def timedelta_to_milliseconds(td):
72
 
    """Convert a datetime.timedelta object to milliseconds"""
73
 
    return ((td.days * 24 * 60 * 60 * 1000)
74
 
            + (td.seconds * 1000)
75
 
            + (td.microseconds // 1000))
 
76
version = "1.7.10"
 
77
 
 
78
 
 
79
try:
 
80
    dbus.OBJECT_MANAGER_IFACE
 
81
except AttributeError:
 
82
    dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
76
83
 
77
84
def milliseconds_to_string(ms):
78
85
    td = datetime.timedelta(0, 0, 0, ms)
79
 
    return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
80
 
            .format(days = "{0}T".format(td.days) if td.days else "",
81
 
                    hours = td.seconds // 3600,
82
 
                    minutes = (td.seconds % 3600) // 60,
83
 
                    seconds = td.seconds % 60,
84
 
                    ))
 
86
    return ("{days}{hours:02}:{minutes:02}:{seconds:02}".format(
 
87
        days = "{}T".format(td.days) if td.days else "",
 
88
        hours = td.seconds // 3600,
 
89
        minutes = (td.seconds % 3600) // 60,
 
90
        seconds = td.seconds % 60))
85
91
 
86
92
 
87
93
def rfc3339_duration_to_delta(duration):
111
117
    # avoid excessive use of external libraries.
112
118
    
113
119
    # New type for defining tokens, syntax, and semantics all-in-one
114
 
    Token = collections.namedtuple("Token",
115
 
                                   ("regexp", # To match token; if
116
 
                                              # "value" is not None,
117
 
                                              # must have a "group"
118
 
                                              # containing digits
119
 
                                    "value",  # datetime.timedelta or
120
 
                                              # None
121
 
                                    "followers")) # Tokens valid after
122
 
                                                  # this token
 
120
    Token = collections.namedtuple("Token", (
 
121
        "regexp",  # To match token; if "value" is not None, must have
 
122
                   # a "group" containing digits
 
123
        "value",   # datetime.timedelta or None
 
124
        "followers"))           # Tokens valid after this token
123
125
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
124
126
    # the "duration" ABNF definition in RFC 3339, Appendix A.
125
127
    token_end = Token(re.compile(r"$"), None, frozenset())
126
128
    token_second = Token(re.compile(r"(\d+)S"),
127
129
                         datetime.timedelta(seconds=1),
128
 
                         frozenset((token_end,)))
 
130
                         frozenset((token_end, )))
129
131
    token_minute = Token(re.compile(r"(\d+)M"),
130
132
                         datetime.timedelta(minutes=1),
131
133
                         frozenset((token_second, token_end)))
147
149
                       frozenset((token_month, token_end)))
148
150
    token_week = Token(re.compile(r"(\d+)W"),
149
151
                       datetime.timedelta(weeks=1),
150
 
                       frozenset((token_end,)))
 
152
                       frozenset((token_end, )))
151
153
    token_duration = Token(re.compile(r"P"), None,
152
154
                           frozenset((token_year, token_month,
153
155
                                      token_day, token_time,
154
 
                                      token_week))),
 
156
                                      token_week)))
155
157
    # Define starting values
156
158
    value = datetime.timedelta() # Value so far
157
159
    found_token = None
158
 
    followers = frozenset(token_duration,) # Following valid tokens
 
160
    followers = frozenset((token_duration, )) # Following valid tokens
159
161
    s = duration                # String left to parse
160
162
    # Loop until end token is found
161
163
    while found_token is not token_end:
178
180
                break
179
181
        else:
180
182
            # No currently valid tokens were found
181
 
            raise ValueError("Invalid RFC 3339 duration")
 
183
            raise ValueError("Invalid RFC 3339 duration: {!r}"
 
184
                             .format(duration))
182
185
    # End token found
183
186
    return value
184
187
 
186
189
def string_to_delta(interval):
187
190
    """Parse a string and return a datetime.timedelta
188
191
    
189
 
    >>> string_to_delta("7d")
 
192
    >>> string_to_delta('7d')
190
193
    datetime.timedelta(7)
191
 
    >>> string_to_delta("60s")
 
194
    >>> string_to_delta('60s')
192
195
    datetime.timedelta(0, 60)
193
 
    >>> string_to_delta("60m")
 
196
    >>> string_to_delta('60m')
194
197
    datetime.timedelta(0, 3600)
195
 
    >>> string_to_delta("24h")
 
198
    >>> string_to_delta('24h')
196
199
    datetime.timedelta(1)
197
 
    >>> string_to_delta("1w")
 
200
    >>> string_to_delta('1w')
198
201
    datetime.timedelta(7)
199
 
    >>> string_to_delta("5m 30s")
 
202
    >>> string_to_delta('5m 30s')
200
203
    datetime.timedelta(0, 330)
201
204
    """
202
205
    
223
226
            value += datetime.timedelta(0, 0, 0, int(num))
224
227
    return value
225
228
 
 
229
 
226
230
def print_clients(clients, keywords):
227
231
    def valuetostring(value, keyword):
228
232
        if type(value) is dbus.Boolean:
230
234
        if keyword in ("Timeout", "Interval", "ApprovalDelay",
231
235
                       "ApprovalDuration", "ExtendedTimeout"):
232
236
            return milliseconds_to_string(value)
233
 
        return unicode(value)
 
237
        return str(value)
234
238
    
235
239
    # Create format string to print table rows
236
240
    format_string = " ".join("{{{key}:{width}}}".format(
237
 
            width = max(len(tablewords[key]),
238
 
                        max(len(valuetostring(client[key],
239
 
                                              key))
240
 
                            for client in
241
 
                            clients)),
242
 
            key = key) for key in keywords)
 
241
        width = max(len(tablewords[key]),
 
242
                    max(len(valuetostring(client[key], key))
 
243
                        for client in clients)),
 
244
        key = key)
 
245
                             for key in keywords)
243
246
    # Print header line
244
247
    print(format_string.format(**tablewords))
245
248
    for client in clients:
246
 
        print(format_string.format(**dict((key,
247
 
                                           valuetostring(client[key],
248
 
                                                         key))
249
 
                                          for key in keywords)))
 
249
        print(format_string.format(**{
 
250
            key: valuetostring(client[key], key)
 
251
            for key in keywords }))
 
252
 
250
253
 
251
254
def has_actions(options):
252
255
    return any((options.enable,
268
271
                options.approve,
269
272
                options.deny))
270
273
 
 
274
 
271
275
def main():
272
276
    parser = argparse.ArgumentParser()
273
277
    parser.add_argument("--version", action="version",
274
 
                        version = "%(prog)s {0}".format(version),
 
278
                        version = "%(prog)s {}".format(version),
275
279
                        help="show version number and exit")
276
280
    parser.add_argument("-a", "--all", action="store_true",
277
281
                        help="Select all clients")
278
282
    parser.add_argument("-v", "--verbose", action="store_true",
279
283
                        help="Print all fields")
 
284
    parser.add_argument("-j", "--dump-json", action="store_true",
 
285
                        help="Dump client data in JSON format")
280
286
    parser.add_argument("-e", "--enable", action="store_true",
281
287
                        help="Enable client")
282
288
    parser.add_argument("-d", "--disable", action="store_true",
310
316
    parser.add_argument("--approval-duration",
311
317
                        help="Set duration of one client approval")
312
318
    parser.add_argument("-H", "--host", help="Set host for client")
313
 
    parser.add_argument("-s", "--secret", type=file,
 
319
    parser.add_argument("-s", "--secret",
 
320
                        type=argparse.FileType(mode="rb"),
314
321
                        help="Set password blob (file) for client")
315
322
    parser.add_argument("-A", "--approve", action="store_true",
316
323
                        help="Approve any current client request")
324
331
    if has_actions(options) and not (options.client or options.all):
325
332
        parser.error("Options require clients names or --all.")
326
333
    if options.verbose and has_actions(options):
327
 
        parser.error("--verbose can only be used alone or with"
328
 
                     " --all.")
 
334
        parser.error("--verbose can only be used alone.")
 
335
    if options.dump_json and (options.verbose or has_actions(options)):
 
336
        parser.error("--dump-json can only be used alone.")
329
337
    if options.all and not has_actions(options):
330
338
        parser.error("--all requires an action.")
331
 
 
 
339
    
332
340
    if options.check:
333
341
        fail_count, test_count = doctest.testmod()
334
342
        sys.exit(os.EX_OK if fail_count == 0 else 1)
337
345
        bus = dbus.SystemBus()
338
346
        mandos_dbus_objc = bus.get_object(busname, server_path)
339
347
    except dbus.exceptions.DBusException:
340
 
        print("Could not connect to Mandos server",
341
 
              file=sys.stderr)
 
348
        print("Could not connect to Mandos server", file=sys.stderr)
342
349
        sys.exit(1)
343
350
    
344
351
    mandos_serv = dbus.Interface(mandos_dbus_objc,
345
352
                                 dbus_interface = server_interface)
 
353
    mandos_serv_object_manager = dbus.Interface(
 
354
        mandos_dbus_objc, dbus_interface = dbus.OBJECT_MANAGER_IFACE)
346
355
    
347
356
    #block stderr since dbus library prints to stderr
348
357
    null = os.open(os.path.devnull, os.O_RDWR)
351
360
    os.close(null)
352
361
    try:
353
362
        try:
354
 
            mandos_clients = mandos_serv.GetAllClientsWithProperties()
 
363
            mandos_clients = { path: ifs_and_props[client_interface]
 
364
                               for path, ifs_and_props in
 
365
                               mandos_serv_object_manager
 
366
                               .GetManagedObjects().items()
 
367
                               if client_interface in ifs_and_props }
355
368
        finally:
356
369
            #restore stderr
357
370
            os.dup2(stderrcopy, sys.stderr.fileno())
358
371
            os.close(stderrcopy)
359
 
    except dbus.exceptions.DBusException:
360
 
        print("Access denied: Accessing mandos server through dbus.",
361
 
              file=sys.stderr)
 
372
    except dbus.exceptions.DBusException as e:
 
373
        print("Access denied: Accessing mandos server through D-Bus: {}"
 
374
              .format(e), file=sys.stderr)
362
375
        sys.exit(1)
363
376
    
364
377
    # Compile dict of (clients: properties) to process
365
378
    clients={}
366
379
    
367
380
    if options.all or not options.client:
368
 
        clients = dict((bus.get_object(busname, path), properties)
369
 
                       for path, properties in
370
 
                       mandos_clients.iteritems())
 
381
        clients = { bus.get_object(busname, path): properties
 
382
                    for path, properties in mandos_clients.items() }
371
383
    else:
372
384
        for name in options.client:
373
 
            for path, client in mandos_clients.iteritems():
 
385
            for path, client in mandos_clients.items():
374
386
                if client["Name"] == name:
375
387
                    client_objc = bus.get_object(busname, path)
376
388
                    clients[client_objc] = client
377
389
                    break
378
390
            else:
379
 
                print("Client not found on server: {0!r}"
 
391
                print("Client not found on server: {!r}"
380
392
                      .format(name), file=sys.stderr)
381
393
                sys.exit(1)
382
394
    
383
395
    if not has_actions(options) and clients:
384
 
        if options.verbose:
385
 
            keywords = ("Name", "Enabled", "Timeout",
386
 
                        "LastCheckedOK", "Created", "Interval",
387
 
                        "Host", "Fingerprint", "CheckerRunning",
388
 
                        "LastEnabled", "ApprovalPending",
389
 
                        "ApprovedByDefault",
 
396
        if options.verbose or options.dump_json:
 
397
            keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
 
398
                        "Created", "Interval", "Host", "Fingerprint",
 
399
                        "CheckerRunning", "LastEnabled",
 
400
                        "ApprovalPending", "ApprovedByDefault",
390
401
                        "LastApprovalRequest", "ApprovalDelay",
391
402
                        "ApprovalDuration", "Checker",
392
403
                        "ExtendedTimeout")
393
404
        else:
394
405
            keywords = defaultkeywords
395
406
        
396
 
        print_clients(clients.values(), keywords)
 
407
        if options.dump_json:
 
408
            json.dump({client["Name"]: {key: client[key]
 
409
                                        for key in keywords }
 
410
                       for client in clients.values() },
 
411
                      fp = sys.stdout, indent = 4,
 
412
                      separators = (',', ': '))
 
413
            print()
 
414
        else:
 
415
            print_clients(clients.values(), keywords)
397
416
    else:
398
417
        # Process each client in the list by all selected options
399
418
        for client in clients:
 
419
            
400
420
            def set_client_prop(prop, value):
401
421
                """Set a Client D-Bus property"""
402
422
                client.Set(client_interface, prop, value,
403
423
                           dbus_interface=dbus.PROPERTIES_IFACE)
 
424
            
404
425
            def set_client_prop_ms(prop, value):
405
426
                """Set a Client D-Bus property, converted
406
427
                from a string to milliseconds."""
407
428
                set_client_prop(prop,
408
 
                                timedelta_to_milliseconds
409
 
                                (string_to_delta(value)))
 
429
                                string_to_delta(value).total_seconds()
 
430
                                * 1000)
 
431
            
410
432
            if options.remove:
411
433
                mandos_serv.RemoveClient(client.__dbus_object_path__)
412
434
            if options.enable:
456
478
                client.Approve(dbus.Boolean(False),
457
479
                               dbus_interface=client_interface)
458
480
 
 
481
 
459
482
if __name__ == "__main__":
460
483
    main()