/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: 2014-08-09 13:12:55 UTC
  • mto: (237.7.304 trunk)
  • mto: This revision was merged to the branch mainline in revision 323.
  • Revision ID: teddy@recompile.se-20140809131255-lp31j98u2pl0xpe6
mandos: Stop using str() and remove unnecessary unicode() calls.

* mandos (if_nametoindex): Use "bytes" literal instead of str().
  (initlogger): Use a unicode string for log device.
  (AvahiError.__unicode__): Removed.
  (DBusPropertyException.__unicode__): - '' -
  (ClientDBus.Secret_dbus_property): Use bytes() instead of str().
  (IPv6_TCPServer.server_bind): Use .encode() instead of str().
  (string_to_delta): Removed unnecessary unicode() call.
  (main): Use "isinstance(x, bytes)" instead of "type(x) is str", use
          .decode() instead of unicode(), and use .encode() instead of
          str().

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