/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: 2014-03-28 22:32:21 UTC
  • Revision ID: teddy@recompile.se-20140328223221-w579qlvlex5if3dn
Fix location and format of signing key file.

* debian/upstream/signing-key.asc: Added.
* debian/upstream-signing-key.pgp: Removed.

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-2014 Teddy Hogeborn
 
7
# Copyright © 2008-2014 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
 
try:
30
 
    from future_builtins import *
31
 
except ImportError:
32
 
    pass
 
29
from future_builtins import *
33
30
 
34
31
import sys
35
32
import argparse
39
36
import os
40
37
import collections
41
38
import doctest
42
 
import json
43
39
 
44
40
import dbus
45
41
 
46
 
if sys.version_info.major == 2:
47
 
    str = unicode
48
 
 
49
42
locale.setlocale(locale.LC_ALL, "")
50
43
 
51
44
tablewords = {
65
58
    "ApprovalDelay": "Approval Delay",
66
59
    "ApprovalDuration": "Approval Duration",
67
60
    "Checker": "Checker",
68
 
    "ExtendedTimeout": "Extended Timeout"
69
 
}
 
61
    "ExtendedTimeout" : "Extended Timeout"
 
62
    }
70
63
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
71
64
domain = "se.recompile"
72
65
busname = domain + ".Mandos"
73
66
server_path = "/"
74
67
server_interface = domain + ".Mandos"
75
68
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"
 
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))
83
76
 
84
77
def milliseconds_to_string(ms):
85
78
    td = datetime.timedelta(0, 0, 0, ms)
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))
 
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
                    ))
91
85
 
92
86
 
93
87
def rfc3339_duration_to_delta(duration):
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())
128
126
    token_second = Token(re.compile(r"(\d+)S"),
129
127
                         datetime.timedelta(seconds=1),
130
 
                         frozenset((token_end, )))
 
128
                         frozenset((token_end,)))
131
129
    token_minute = Token(re.compile(r"(\d+)M"),
132
130
                         datetime.timedelta(minutes=1),
133
131
                         frozenset((token_second, token_end)))
149
147
                       frozenset((token_month, token_end)))
150
148
    token_week = Token(re.compile(r"(\d+)W"),
151
149
                       datetime.timedelta(weeks=1),
152
 
                       frozenset((token_end, )))
 
150
                       frozenset((token_end,)))
153
151
    token_duration = Token(re.compile(r"P"), None,
154
152
                           frozenset((token_year, token_month,
155
153
                                      token_day, token_time,
156
 
                                      token_week)))
 
154
                                      token_week))),
157
155
    # Define starting values
158
156
    value = datetime.timedelta() # Value so far
159
157
    found_token = None
160
 
    followers = frozenset((token_duration, )) # Following valid tokens
 
158
    followers = frozenset(token_duration,) # Following valid tokens
161
159
    s = duration                # String left to parse
162
160
    # Loop until end token is found
163
161
    while found_token is not token_end:
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
    
226
223
            value += datetime.timedelta(0, 0, 0, int(num))
227
224
    return value
228
225
 
229
 
 
230
226
def print_clients(clients, keywords):
231
227
    def valuetostring(value, keyword):
232
228
        if type(value) is dbus.Boolean:
234
230
        if keyword in ("Timeout", "Interval", "ApprovalDelay",
235
231
                       "ApprovalDuration", "ExtendedTimeout"):
236
232
            return milliseconds_to_string(value)
237
 
        return str(value)
 
233
        return unicode(value)
238
234
    
239
235
    # Create format string to print table rows
240
236
    format_string = " ".join("{{{key}:{width}}}".format(
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)
 
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)
246
243
    # Print header line
247
244
    print(format_string.format(**tablewords))
248
245
    for client in clients:
249
 
        print(format_string.format(**{
250
 
            key: valuetostring(client[key], key)
251
 
            for key in keywords }))
252
 
 
 
246
        print(format_string.format(**dict((key,
 
247
                                           valuetostring(client[key],
 
248
                                                         key))
 
249
                                          for key in keywords)))
253
250
 
254
251
def has_actions(options):
255
252
    return any((options.enable,
271
268
                options.approve,
272
269
                options.deny))
273
270
 
274
 
 
275
271
def main():
276
272
    parser = argparse.ArgumentParser()
277
273
    parser.add_argument("--version", action="version",
278
 
                        version = "%(prog)s {}".format(version),
 
274
                        version = "%(prog)s {0}".format(version),
279
275
                        help="show version number and exit")
280
276
    parser.add_argument("-a", "--all", action="store_true",
281
277
                        help="Select all clients")
282
278
    parser.add_argument("-v", "--verbose", action="store_true",
283
279
                        help="Print all fields")
284
 
    parser.add_argument("-j", "--dump-json", action="store_true",
285
 
                        help="Dump client data in JSON format")
286
280
    parser.add_argument("-e", "--enable", action="store_true",
287
281
                        help="Enable client")
288
282
    parser.add_argument("-d", "--disable", action="store_true",
316
310
    parser.add_argument("--approval-duration",
317
311
                        help="Set duration of one client approval")
318
312
    parser.add_argument("-H", "--host", help="Set host for client")
319
 
    parser.add_argument("-s", "--secret",
320
 
                        type=argparse.FileType(mode="rb"),
 
313
    parser.add_argument("-s", "--secret", type=file,
321
314
                        help="Set password blob (file) for client")
322
315
    parser.add_argument("-A", "--approve", action="store_true",
323
316
                        help="Approve any current client request")
331
324
    if has_actions(options) and not (options.client or options.all):
332
325
        parser.error("Options require clients names or --all.")
333
326
    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.")
 
327
        parser.error("--verbose can only be used alone or with"
 
328
                     " --all.")
337
329
    if options.all and not has_actions(options):
338
330
        parser.error("--all requires an action.")
339
 
    
 
331
 
340
332
    if options.check:
341
333
        fail_count, test_count = doctest.testmod()
342
334
        sys.exit(os.EX_OK if fail_count == 0 else 1)
345
337
        bus = dbus.SystemBus()
346
338
        mandos_dbus_objc = bus.get_object(busname, server_path)
347
339
    except dbus.exceptions.DBusException:
348
 
        print("Could not connect to Mandos server", file=sys.stderr)
 
340
        print("Could not connect to Mandos server",
 
341
              file=sys.stderr)
349
342
        sys.exit(1)
350
343
    
351
344
    mandos_serv = dbus.Interface(mandos_dbus_objc,
352
345
                                 dbus_interface = server_interface)
353
 
    mandos_serv_object_manager = dbus.Interface(
354
 
        mandos_dbus_objc, dbus_interface = dbus.OBJECT_MANAGER_IFACE)
355
346
    
356
347
    #block stderr since dbus library prints to stderr
357
348
    null = os.open(os.path.devnull, os.O_RDWR)
360
351
    os.close(null)
361
352
    try:
362
353
        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 }
 
354
            mandos_clients = mandos_serv.GetAllClientsWithProperties()
368
355
        finally:
369
356
            #restore stderr
370
357
            os.dup2(stderrcopy, sys.stderr.fileno())
371
358
            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)
 
359
    except dbus.exceptions.DBusException:
 
360
        print("Access denied: Accessing mandos server through dbus.",
 
361
              file=sys.stderr)
375
362
        sys.exit(1)
376
363
    
377
364
    # Compile dict of (clients: properties) to process
378
365
    clients={}
379
366
    
380
367
    if options.all or not options.client:
381
 
        clients = { bus.get_object(busname, path): properties
382
 
                    for path, properties in mandos_clients.items() }
 
368
        clients = dict((bus.get_object(busname, path), properties)
 
369
                       for path, properties in
 
370
                       mandos_clients.iteritems())
383
371
    else:
384
372
        for name in options.client:
385
 
            for path, client in mandos_clients.items():
 
373
            for path, client in mandos_clients.iteritems():
386
374
                if client["Name"] == name:
387
375
                    client_objc = bus.get_object(busname, path)
388
376
                    clients[client_objc] = client
389
377
                    break
390
378
            else:
391
 
                print("Client not found on server: {!r}"
 
379
                print("Client not found on server: {0!r}"
392
380
                      .format(name), file=sys.stderr)
393
381
                sys.exit(1)
394
382
    
395
383
    if not has_actions(options) and clients:
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",
 
384
        if options.verbose:
 
385
            keywords = ("Name", "Enabled", "Timeout",
 
386
                        "LastCheckedOK", "Created", "Interval",
 
387
                        "Host", "Fingerprint", "CheckerRunning",
 
388
                        "LastEnabled", "ApprovalPending",
 
389
                        "ApprovedByDefault",
401
390
                        "LastApprovalRequest", "ApprovalDelay",
402
391
                        "ApprovalDuration", "Checker",
403
392
                        "ExtendedTimeout")
404
393
        else:
405
394
            keywords = defaultkeywords
406
395
        
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)
 
396
        print_clients(clients.values(), keywords)
416
397
    else:
417
398
        # Process each client in the list by all selected options
418
399
        for client in clients:
419
 
            
420
400
            def set_client_prop(prop, value):
421
401
                """Set a Client D-Bus property"""
422
402
                client.Set(client_interface, prop, value,
423
403
                           dbus_interface=dbus.PROPERTIES_IFACE)
424
 
            
425
404
            def set_client_prop_ms(prop, value):
426
405
                """Set a Client D-Bus property, converted
427
406
                from a string to milliseconds."""
428
407
                set_client_prop(prop,
429
 
                                string_to_delta(value).total_seconds()
430
 
                                * 1000)
431
 
            
 
408
                                timedelta_to_milliseconds
 
409
                                (string_to_delta(value)))
432
410
            if options.remove:
433
411
                mandos_serv.RemoveClient(client.__dbus_object_path__)
434
412
            if options.enable:
478
456
                client.Approve(dbus.Boolean(False),
479
457
                               dbus_interface=client_interface)
480
458
 
481
 
 
482
459
if __name__ == "__main__":
483
460
    main()