/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-05-30 16:47:00 UTC
  • Revision ID: teddy@recompile.se-20150530164700-77zrd7964gdhbk1f
mandos: Disable D-Bus if any DBusException is raised when connecting.

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-2016 Teddy Hogeborn
7
 
# Copyright © 2008-2016 Björn Påhlsson
 
6
# Copyright © 2008-2015 Teddy Hogeborn
 
7
# Copyright © 2008-2015 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
43
42
 
44
43
import dbus
45
44
 
73
72
server_path = "/"
74
73
server_interface = domain + ".Mandos"
75
74
client_interface = domain + ".Mandos.Client"
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"
 
75
version = "1.6.9"
 
76
 
83
77
 
84
78
def milliseconds_to_string(ms):
85
79
    td = datetime.timedelta(0, 0, 0, ms)
117
111
    # avoid excessive use of external libraries.
118
112
    
119
113
    # New type for defining tokens, syntax, and semantics all-in-one
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
 
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
125
123
    # RFC 3339 "duration" tokens, syntax, and semantics; taken from
126
124
    # the "duration" ABNF definition in RFC 3339, Appendix A.
127
125
    token_end = Token(re.compile(r"$"), None, frozenset())
180
178
                break
181
179
        else:
182
180
            # No currently valid tokens were found
183
 
            raise ValueError("Invalid RFC 3339 duration: {!r}"
184
 
                             .format(duration))
 
181
            raise ValueError("Invalid RFC 3339 duration")
185
182
    # End token found
186
183
    return value
187
184
 
189
186
def string_to_delta(interval):
190
187
    """Parse a string and return a datetime.timedelta
191
188
    
192
 
    >>> string_to_delta('7d')
 
189
    >>> string_to_delta("7d")
193
190
    datetime.timedelta(7)
194
 
    >>> string_to_delta('60s')
 
191
    >>> string_to_delta("60s")
195
192
    datetime.timedelta(0, 60)
196
 
    >>> string_to_delta('60m')
 
193
    >>> string_to_delta("60m")
197
194
    datetime.timedelta(0, 3600)
198
 
    >>> string_to_delta('24h')
 
195
    >>> string_to_delta("24h")
199
196
    datetime.timedelta(1)
200
 
    >>> string_to_delta('1w')
 
197
    >>> string_to_delta("1w")
201
198
    datetime.timedelta(7)
202
 
    >>> string_to_delta('5m 30s')
 
199
    >>> string_to_delta("5m 30s")
203
200
    datetime.timedelta(0, 330)
204
201
    """
205
202
    
281
278
                        help="Select all clients")
282
279
    parser.add_argument("-v", "--verbose", action="store_true",
283
280
                        help="Print all fields")
284
 
    parser.add_argument("-j", "--dump-json", action="store_true",
285
 
                        help="Dump client data in JSON format")
286
281
    parser.add_argument("-e", "--enable", action="store_true",
287
282
                        help="Enable client")
288
283
    parser.add_argument("-d", "--disable", action="store_true",
331
326
    if has_actions(options) and not (options.client or options.all):
332
327
        parser.error("Options require clients names or --all.")
333
328
    if options.verbose and has_actions(options):
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
        parser.error("--verbose can only be used alone or with"
 
330
                     " --all.")
337
331
    if options.all and not has_actions(options):
338
332
        parser.error("--all requires an action.")
339
 
    
 
333
 
340
334
    if options.check:
341
335
        fail_count, test_count = doctest.testmod()
342
336
        sys.exit(os.EX_OK if fail_count == 0 else 1)
350
344
    
351
345
    mandos_serv = dbus.Interface(mandos_dbus_objc,
352
346
                                 dbus_interface = server_interface)
353
 
    mandos_serv_object_manager = dbus.Interface(
354
 
        mandos_dbus_objc, dbus_interface = dbus.OBJECT_MANAGER_IFACE)
355
347
    
356
348
    #block stderr since dbus library prints to stderr
357
349
    null = os.open(os.path.devnull, os.O_RDWR)
360
352
    os.close(null)
361
353
    try:
362
354
        try:
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
            mandos_clients = mandos_serv.GetAllClientsWithProperties()
368
356
        finally:
369
357
            #restore stderr
370
358
            os.dup2(stderrcopy, sys.stderr.fileno())
371
359
            os.close(stderrcopy)
372
 
    except dbus.exceptions.DBusException as e:
373
 
        print("Access denied: Accessing mandos server through D-Bus: {}"
374
 
              .format(e), file=sys.stderr)
 
360
    except dbus.exceptions.DBusException:
 
361
        print("Access denied: Accessing mandos server through dbus.",
 
362
              file=sys.stderr)
375
363
        sys.exit(1)
376
364
    
377
365
    # Compile dict of (clients: properties) to process
393
381
                sys.exit(1)
394
382
    
395
383
    if not has_actions(options) and clients:
396
 
        if options.verbose or options.dump_json:
 
384
        if options.verbose:
397
385
            keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
398
386
                        "Created", "Interval", "Host", "Fingerprint",
399
387
                        "CheckerRunning", "LastEnabled",
404
392
        else:
405
393
            keywords = defaultkeywords
406
394
        
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)
 
395
        print_clients(clients.values(), keywords)
416
396
    else:
417
397
        # Process each client in the list by all selected options
418
398
        for client in clients: