/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: 2016-06-28 18:46:40 UTC
  • Revision ID: teddy@recompile.se-20160628184640-22uh54op9nw0908b
mandos-ctl: Dump booleans as booleans in --dump-json output.

* mandos-ctl (main): Detect dbus.Boolean objects and recast them to
                     regular Python bool() objects to make them show
                     as boolean values in dump output.

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
39
39
import os
40
40
import collections
41
41
import doctest
 
42
import json
42
43
 
43
44
import dbus
44
45
 
45
 
if sys.version_info[0] == 2:
 
46
if sys.version_info.major == 2:
46
47
    str = unicode
47
48
 
48
49
locale.setlocale(locale.LC_ALL, "")
64
65
    "ApprovalDelay": "Approval Delay",
65
66
    "ApprovalDuration": "Approval Duration",
66
67
    "Checker": "Checker",
67
 
    "ExtendedTimeout" : "Extended Timeout"
68
 
    }
 
68
    "ExtendedTimeout": "Extended Timeout"
 
69
}
69
70
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
70
71
domain = "se.recompile"
71
72
busname = domain + ".Mandos"
72
73
server_path = "/"
73
74
server_interface = domain + ".Mandos"
74
75
client_interface = domain + ".Mandos.Client"
75
 
version = "1.6.7"
76
 
 
77
 
def timedelta_to_milliseconds(td):
78
 
    """Convert a datetime.timedelta object to milliseconds"""
79
 
    return ((td.days * 24 * 60 * 60 * 1000)
80
 
            + (td.seconds * 1000)
81
 
            + (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"
82
83
 
83
84
def milliseconds_to_string(ms):
84
85
    td = datetime.timedelta(0, 0, 0, ms)
85
 
    return ("{days}{hours:02}:{minutes:02}:{seconds:02}"
86
 
            .format(days = "{0}T".format(td.days) if td.days else "",
87
 
                    hours = td.seconds // 3600,
88
 
                    minutes = (td.seconds % 3600) // 60,
89
 
                    seconds = td.seconds % 60,
90
 
                    ))
 
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))
91
91
 
92
92
 
93
93
def rfc3339_duration_to_delta(duration):
117
117
    # avoid excessive use of external libraries.
118
118
    
119
119
    # New type for defining tokens, syntax, and semantics all-in-one
120
 
    Token = collections.namedtuple("Token",
121
 
                                   ("regexp", # To match token; if
122
 
                                              # "value" is not None,
123
 
                                              # must have a "group"
124
 
                                              # containing digits
125
 
                                    "value",  # datetime.timedelta or
126
 
                                              # None
127
 
                                    "followers")) # Tokens valid after
128
 
                                                  # 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
129
125
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
130
126
    # the "duration" ABNF definition in RFC 3339, Appendix A.
131
127
    token_end = Token(re.compile(r"$"), None, frozenset())
132
128
    token_second = Token(re.compile(r"(\d+)S"),
133
129
                         datetime.timedelta(seconds=1),
134
 
                         frozenset((token_end,)))
 
130
                         frozenset((token_end, )))
135
131
    token_minute = Token(re.compile(r"(\d+)M"),
136
132
                         datetime.timedelta(minutes=1),
137
133
                         frozenset((token_second, token_end)))
153
149
                       frozenset((token_month, token_end)))
154
150
    token_week = Token(re.compile(r"(\d+)W"),
155
151
                       datetime.timedelta(weeks=1),
156
 
                       frozenset((token_end,)))
 
152
                       frozenset((token_end, )))
157
153
    token_duration = Token(re.compile(r"P"), None,
158
154
                           frozenset((token_year, token_month,
159
155
                                      token_day, token_time,
161
157
    # Define starting values
162
158
    value = datetime.timedelta() # Value so far
163
159
    found_token = None
164
 
    followers = frozenset((token_duration,)) # Following valid tokens
 
160
    followers = frozenset((token_duration, )) # Following valid tokens
165
161
    s = duration                # String left to parse
166
162
    # Loop until end token is found
167
163
    while found_token is not token_end:
184
180
                break
185
181
        else:
186
182
            # No currently valid tokens were found
187
 
            raise ValueError("Invalid RFC 3339 duration")
 
183
            raise ValueError("Invalid RFC 3339 duration: {!r}"
 
184
                             .format(duration))
188
185
    # End token found
189
186
    return value
190
187
 
192
189
def string_to_delta(interval):
193
190
    """Parse a string and return a datetime.timedelta
194
191
    
195
 
    >>> string_to_delta("7d")
 
192
    >>> string_to_delta('7d')
196
193
    datetime.timedelta(7)
197
 
    >>> string_to_delta("60s")
 
194
    >>> string_to_delta('60s')
198
195
    datetime.timedelta(0, 60)
199
 
    >>> string_to_delta("60m")
 
196
    >>> string_to_delta('60m')
200
197
    datetime.timedelta(0, 3600)
201
 
    >>> string_to_delta("24h")
 
198
    >>> string_to_delta('24h')
202
199
    datetime.timedelta(1)
203
 
    >>> string_to_delta("1w")
 
200
    >>> string_to_delta('1w')
204
201
    datetime.timedelta(7)
205
 
    >>> string_to_delta("5m 30s")
 
202
    >>> string_to_delta('5m 30s')
206
203
    datetime.timedelta(0, 330)
207
204
    """
208
205
    
229
226
            value += datetime.timedelta(0, 0, 0, int(num))
230
227
    return value
231
228
 
 
229
 
232
230
def print_clients(clients, keywords):
233
231
    def valuetostring(value, keyword):
234
232
        if type(value) is dbus.Boolean:
240
238
    
241
239
    # Create format string to print table rows
242
240
    format_string = " ".join("{{{key}:{width}}}".format(
243
 
            width = max(len(tablewords[key]),
244
 
                        max(len(valuetostring(client[key],
245
 
                                              key))
246
 
                            for client in
247
 
                            clients)),
248
 
            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)
249
246
    # Print header line
250
247
    print(format_string.format(**tablewords))
251
248
    for client in clients:
252
 
        print(format_string.format(**dict((key,
253
 
                                           valuetostring(client[key],
254
 
                                                         key))
255
 
                                          for key in keywords)))
 
249
        print(format_string.format(**{
 
250
            key: valuetostring(client[key], key)
 
251
            for key in keywords }))
 
252
 
256
253
 
257
254
def has_actions(options):
258
255
    return any((options.enable,
274
271
                options.approve,
275
272
                options.deny))
276
273
 
 
274
 
277
275
def main():
278
276
    parser = argparse.ArgumentParser()
279
277
    parser.add_argument("--version", action="version",
280
 
                        version = "%(prog)s {0}".format(version),
 
278
                        version = "%(prog)s {}".format(version),
281
279
                        help="show version number and exit")
282
280
    parser.add_argument("-a", "--all", action="store_true",
283
281
                        help="Select all clients")
284
282
    parser.add_argument("-v", "--verbose", action="store_true",
285
283
                        help="Print all fields")
 
284
    parser.add_argument("-j", "--dump-json", action="store_true",
 
285
                        help="Dump client data in JSON format")
286
286
    parser.add_argument("-e", "--enable", action="store_true",
287
287
                        help="Enable client")
288
288
    parser.add_argument("-d", "--disable", action="store_true",
331
331
    if has_actions(options) and not (options.client or options.all):
332
332
        parser.error("Options require clients names or --all.")
333
333
    if options.verbose and has_actions(options):
334
 
        parser.error("--verbose can only be used alone or with"
335
 
                     " --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.")
336
337
    if options.all and not has_actions(options):
337
338
        parser.error("--all requires an action.")
338
 
 
 
339
    
339
340
    if options.check:
340
341
        fail_count, test_count = doctest.testmod()
341
342
        sys.exit(os.EX_OK if fail_count == 0 else 1)
344
345
        bus = dbus.SystemBus()
345
346
        mandos_dbus_objc = bus.get_object(busname, server_path)
346
347
    except dbus.exceptions.DBusException:
347
 
        print("Could not connect to Mandos server",
348
 
              file=sys.stderr)
 
348
        print("Could not connect to Mandos server", file=sys.stderr)
349
349
        sys.exit(1)
350
350
    
351
351
    mandos_serv = dbus.Interface(mandos_dbus_objc,
352
352
                                 dbus_interface = server_interface)
 
353
    mandos_serv_object_manager = dbus.Interface(
 
354
        mandos_dbus_objc, dbus_interface = dbus.OBJECT_MANAGER_IFACE)
353
355
    
354
356
    #block stderr since dbus library prints to stderr
355
357
    null = os.open(os.path.devnull, os.O_RDWR)
358
360
    os.close(null)
359
361
    try:
360
362
        try:
361
 
            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 }
362
368
        finally:
363
369
            #restore stderr
364
370
            os.dup2(stderrcopy, sys.stderr.fileno())
365
371
            os.close(stderrcopy)
366
 
    except dbus.exceptions.DBusException:
367
 
        print("Access denied: Accessing mandos server through dbus.",
368
 
              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)
369
375
        sys.exit(1)
370
376
    
371
377
    # Compile dict of (clients: properties) to process
372
378
    clients={}
373
379
    
374
380
    if options.all or not options.client:
375
 
        clients = dict((bus.get_object(busname, path), properties)
376
 
                       for path, properties in
377
 
                       mandos_clients.items())
 
381
        clients = { bus.get_object(busname, path): properties
 
382
                    for path, properties in mandos_clients.items() }
378
383
    else:
379
384
        for name in options.client:
380
 
            for path, client in mandos_clients.iteritems():
 
385
            for path, client in mandos_clients.items():
381
386
                if client["Name"] == name:
382
387
                    client_objc = bus.get_object(busname, path)
383
388
                    clients[client_objc] = client
384
389
                    break
385
390
            else:
386
 
                print("Client not found on server: {0!r}"
 
391
                print("Client not found on server: {!r}"
387
392
                      .format(name), file=sys.stderr)
388
393
                sys.exit(1)
389
394
    
390
395
    if not has_actions(options) and clients:
391
 
        if options.verbose:
392
 
            keywords = ("Name", "Enabled", "Timeout",
393
 
                        "LastCheckedOK", "Created", "Interval",
394
 
                        "Host", "Fingerprint", "CheckerRunning",
395
 
                        "LastEnabled", "ApprovalPending",
396
 
                        "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",
397
401
                        "LastApprovalRequest", "ApprovalDelay",
398
402
                        "ApprovalDuration", "Checker",
399
403
                        "ExtendedTimeout")
400
404
        else:
401
405
            keywords = defaultkeywords
402
406
        
403
 
        print_clients(clients.values(), keywords)
 
407
        if options.dump_json:
 
408
            json.dump({client["Name"]: {key:
 
409
                                        bool(client[key])
 
410
                                        if isinstance(client[key],
 
411
                                                      dbus.Boolean)
 
412
                                        else client[key]
 
413
                                        for key in keywords }
 
414
                       for client in clients.values() },
 
415
                      fp = sys.stdout, indent = 4,
 
416
                      separators = (',', ': '))
 
417
            print()
 
418
        else:
 
419
            print_clients(clients.values(), keywords)
404
420
    else:
405
421
        # Process each client in the list by all selected options
406
422
        for client in clients:
 
423
            
407
424
            def set_client_prop(prop, value):
408
425
                """Set a Client D-Bus property"""
409
426
                client.Set(client_interface, prop, value,
410
427
                           dbus_interface=dbus.PROPERTIES_IFACE)
 
428
            
411
429
            def set_client_prop_ms(prop, value):
412
430
                """Set a Client D-Bus property, converted
413
431
                from a string to milliseconds."""
414
432
                set_client_prop(prop,
415
 
                                timedelta_to_milliseconds
416
 
                                (string_to_delta(value)))
 
433
                                string_to_delta(value).total_seconds()
 
434
                                * 1000)
 
435
            
417
436
            if options.remove:
418
437
                mandos_serv.RemoveClient(client.__dbus_object_path__)
419
438
            if options.enable:
463
482
                client.Approve(dbus.Boolean(False),
464
483
                               dbus_interface=client_interface)
465
484
 
 
485
 
466
486
if __name__ == "__main__":
467
487
    main()