/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: 2016-03-19 22:27:06 UTC
  • mfrom: (342 release)
  • mto: (237.7.594 trunk)
  • mto: This revision was merged to the branch mainline in revision 343.
  • Revision ID: teddy@recompile.se-20160319222706-n61m90vqve42k1vc
Merge from release branch

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