64
65
"ApprovalDelay": "Approval Delay",
65
66
"ApprovalDuration": "Approval Duration",
66
67
"Checker": "Checker",
67
"ExtendedTimeout" : "Extended Timeout"
68
"ExtendedTimeout": "Extended Timeout",
70
"LastCheckerStatus": "Last Checker Status",
69
72
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
70
73
domain = "se.recompile"
71
74
busname = domain + ".Mandos"
73
76
server_interface = domain + ".Mandos"
74
77
client_interface = domain + ".Mandos.Client"
77
def timedelta_to_milliseconds(td):
78
"""Convert a datetime.timedelta object to milliseconds"""
79
return ((td.days * 24 * 60 * 60 * 1000)
81
+ (td.microseconds // 1000))
82
dbus.OBJECT_MANAGER_IFACE
83
except AttributeError:
84
dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
83
86
def milliseconds_to_string(ms):
84
87
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,
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))
93
95
def rfc3339_duration_to_delta(duration):
117
119
# avoid excessive use of external libraries.
119
121
# 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"
125
"value", # datetime.timedelta or
127
"followers")) # Tokens valid after
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
129
127
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
130
128
# the "duration" ABNF definition in RFC 3339, Appendix A.
131
129
token_end = Token(re.compile(r"$"), None, frozenset())
132
130
token_second = Token(re.compile(r"(\d+)S"),
133
131
datetime.timedelta(seconds=1),
134
frozenset((token_end,)))
132
frozenset((token_end, )))
135
133
token_minute = Token(re.compile(r"(\d+)M"),
136
134
datetime.timedelta(minutes=1),
137
135
frozenset((token_second, token_end)))
153
151
frozenset((token_month, token_end)))
154
152
token_week = Token(re.compile(r"(\d+)W"),
155
153
datetime.timedelta(weeks=1),
156
frozenset((token_end,)))
154
frozenset((token_end, )))
157
155
token_duration = Token(re.compile(r"P"), None,
158
156
frozenset((token_year, token_month,
159
157
token_day, token_time,
161
159
# Define starting values
162
160
value = datetime.timedelta() # Value so far
163
161
found_token = None
164
followers = frozenset(token_duration,) # Following valid tokens
162
followers = frozenset((token_duration, )) # Following valid tokens
165
163
s = duration # String left to parse
166
164
# Loop until end token is found
167
165
while found_token is not token_end:
192
191
def string_to_delta(interval):
193
192
"""Parse a string and return a datetime.timedelta
195
>>> string_to_delta("7d")
194
>>> string_to_delta('7d')
196
195
datetime.timedelta(7)
197
>>> string_to_delta("60s")
196
>>> string_to_delta('60s')
198
197
datetime.timedelta(0, 60)
199
>>> string_to_delta("60m")
198
>>> string_to_delta('60m')
200
199
datetime.timedelta(0, 3600)
201
>>> string_to_delta("24h")
200
>>> string_to_delta('24h')
202
201
datetime.timedelta(1)
203
>>> string_to_delta("1w")
202
>>> string_to_delta('1w')
204
203
datetime.timedelta(7)
205
>>> string_to_delta("5m 30s")
204
>>> string_to_delta('5m 30s')
206
205
datetime.timedelta(0, 330)
241
241
# Create format string to print table rows
242
242
format_string = " ".join("{{{key}:{width}}}".format(
243
width = max(len(tablewords[key]),
244
max(len(valuetostring(client[key],
248
key = key) for key in keywords)
243
width = max(len(tablewords[key]),
244
max(len(valuetostring(client[key], key))
245
for client in clients)),
249
248
# Print header line
250
249
print(format_string.format(**tablewords))
251
250
for client in clients:
252
print(format_string.format(**dict((key,
253
valuetostring(client[key],
255
for key in keywords)))
251
print(format_string.format(**{
252
key: valuetostring(client[key], key)
253
for key in keywords }))
257
256
def has_actions(options):
258
257
return any((options.enable,
278
278
parser = argparse.ArgumentParser()
279
279
parser.add_argument("--version", action="version",
280
version = "%(prog)s {0}".format(version),
280
version = "%(prog)s {}".format(version),
281
281
help="show version number and exit")
282
282
parser.add_argument("-a", "--all", action="store_true",
283
283
help="Select all clients")
284
284
parser.add_argument("-v", "--verbose", action="store_true",
285
285
help="Print all fields")
286
parser.add_argument("-j", "--dump-json", action="store_true",
287
help="Dump client data in JSON format")
286
288
parser.add_argument("-e", "--enable", action="store_true",
287
289
help="Enable client")
288
290
parser.add_argument("-d", "--disable", action="store_true",
361
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 }
364
372
os.dup2(stderrcopy, sys.stderr.fileno())
365
373
os.close(stderrcopy)
366
except dbus.exceptions.DBusException:
367
print("Access denied: Accessing mandos server through dbus.",
374
except dbus.exceptions.DBusException as e:
375
print("Access denied: Accessing mandos server through D-Bus: {}"
376
.format(e), file=sys.stderr)
371
379
# Compile dict of (clients: properties) to process
374
382
if options.all or not options.client:
375
clients = dict((bus.get_object(busname, path), properties)
376
for path, properties in
377
mandos_clients.items())
383
clients = { bus.get_object(busname, path): properties
384
for path, properties in mandos_clients.items() }
379
386
for name in options.client:
380
for path, client in mandos_clients.iteritems():
387
for path, client in mandos_clients.items():
381
388
if client["Name"] == name:
382
389
client_objc = bus.get_object(busname, path)
383
390
clients[client_objc] = client
386
print("Client not found on server: {0!r}"
393
print("Client not found on server: {!r}"
387
394
.format(name), file=sys.stderr)
390
397
if not has_actions(options) and clients:
392
keywords = ("Name", "Enabled", "Timeout",
393
"LastCheckedOK", "Created", "Interval",
394
"Host", "Fingerprint", "CheckerRunning",
395
"LastEnabled", "ApprovalPending",
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",
397
403
"LastApprovalRequest", "ApprovalDelay",
398
404
"ApprovalDuration", "Checker",
405
"ExtendedTimeout", "Expires",
401
408
keywords = defaultkeywords
403
print_clients(clients.values(), keywords)
410
if options.dump_json:
411
json.dump({client["Name"]: {key:
413
if isinstance(client[key],
416
for key in keywords }
417
for client in clients.values() },
418
fp = sys.stdout, indent = 4,
419
separators = (',', ': '))
422
print_clients(clients.values(), keywords)
405
424
# Process each client in the list by all selected options
406
425
for client in clients:
407
427
def set_client_prop(prop, value):
408
428
"""Set a Client D-Bus property"""
409
429
client.Set(client_interface, prop, value,
410
430
dbus_interface=dbus.PROPERTIES_IFACE)
411
432
def set_client_prop_ms(prop, value):
412
433
"""Set a Client D-Bus property, converted
413
434
from a string to milliseconds."""
414
435
set_client_prop(prop,
415
timedelta_to_milliseconds
416
(string_to_delta(value)))
436
string_to_delta(value).total_seconds()
417
439
if options.remove:
418
440
mandos_serv.RemoveClient(client.__dbus_object_path__)
419
441
if options.enable: