/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-07-03 03:32:28 UTC
  • Revision ID: teddy@recompile.se-20160703033228-cafpnnfs53kdg52g
Change all http:// URLs to https:// wherever possible.

* INSTALL (Prerequisites/Libraries/Mandos Server): Change "http://" to
  "https://" wherever possible.
* Makefile (FORTIFY): - '' -
* mandos.xml (SEE ALSO): - '' -
* plugin-runner.c (main): - '' -
* plugins.d/mandos-client.c (start_mandos_communication): - '' -
* plugins.d/mandos-client.xml (SEE ALSO): - '' -

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