65
64
"ApprovalDelay": "Approval Delay",
66
65
"ApprovalDuration": "Approval Duration",
67
66
"Checker": "Checker",
68
"ExtendedTimeout": "Extended Timeout",
70
"LastCheckerStatus": "Last Checker Status",
67
"ExtendedTimeout" : "Extended Timeout"
72
69
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
73
70
domain = "se.recompile"
74
71
busname = domain + ".Mandos"
76
73
server_interface = domain + ".Mandos"
77
74
client_interface = domain + ".Mandos.Client"
82
dbus.OBJECT_MANAGER_IFACE
83
except AttributeError:
84
dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
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))
86
83
def milliseconds_to_string(ms):
87
84
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))
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,
95
93
def rfc3339_duration_to_delta(duration):
119
117
# avoid excessive use of external libraries.
121
119
# 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
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
127
129
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
128
130
# the "duration" ABNF definition in RFC 3339, Appendix A.
129
131
token_end = Token(re.compile(r"$"), None, frozenset())
130
132
token_second = Token(re.compile(r"(\d+)S"),
131
133
datetime.timedelta(seconds=1),
132
frozenset((token_end, )))
134
frozenset((token_end,)))
133
135
token_minute = Token(re.compile(r"(\d+)M"),
134
136
datetime.timedelta(minutes=1),
135
137
frozenset((token_second, token_end)))
191
192
def string_to_delta(interval):
192
193
"""Parse a string and return a datetime.timedelta
194
>>> string_to_delta('7d')
195
>>> string_to_delta("7d")
195
196
datetime.timedelta(7)
196
>>> string_to_delta('60s')
197
>>> string_to_delta("60s")
197
198
datetime.timedelta(0, 60)
198
>>> string_to_delta('60m')
199
>>> string_to_delta("60m")
199
200
datetime.timedelta(0, 3600)
200
>>> string_to_delta('24h')
201
>>> string_to_delta("24h")
201
202
datetime.timedelta(1)
202
>>> string_to_delta('1w')
203
>>> string_to_delta("1w")
203
204
datetime.timedelta(7)
204
>>> string_to_delta('5m 30s')
205
>>> string_to_delta("5m 30s")
205
206
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], key))
245
for client in clients)),
243
width = max(len(tablewords[key]),
244
max(len(valuetostring(client[key],
248
key = key) for key in keywords)
248
249
# Print header line
249
250
print(format_string.format(**tablewords))
250
251
for client in clients:
251
print(format_string.format(**{
252
key: valuetostring(client[key], key)
253
for key in keywords }))
252
print(format_string.format(**dict((key,
253
valuetostring(client[key],
255
for key in keywords)))
256
257
def has_actions(options):
257
258
return any((options.enable,
278
278
parser = argparse.ArgumentParser()
279
279
parser.add_argument("--version", action="version",
280
version = "%(prog)s {}".format(version),
280
version = "%(prog)s {0}".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")
288
286
parser.add_argument("-e", "--enable", action="store_true",
289
287
help="Enable client")
290
288
parser.add_argument("-d", "--disable", action="store_true",
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 }
361
mandos_clients = mandos_serv.GetAllClientsWithProperties()
372
364
os.dup2(stderrcopy, sys.stderr.fileno())
373
365
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)
366
except dbus.exceptions.DBusException:
367
print("Access denied: Accessing mandos server through dbus.",
379
371
# Compile dict of (clients: properties) to process
382
374
if options.all or not options.client:
383
clients = { bus.get_object(busname, path): properties
384
for path, properties in mandos_clients.items() }
375
clients = dict((bus.get_object(busname, path), properties)
376
for path, properties in
377
mandos_clients.items())
386
379
for name in options.client:
387
for path, client in mandos_clients.items():
380
for path, client in mandos_clients.iteritems():
388
381
if client["Name"] == name:
389
382
client_objc = bus.get_object(busname, path)
390
383
clients[client_objc] = client
393
print("Client not found on server: {!r}"
386
print("Client not found on server: {0!r}"
394
387
.format(name), file=sys.stderr)
397
390
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",
392
keywords = ("Name", "Enabled", "Timeout",
393
"LastCheckedOK", "Created", "Interval",
394
"Host", "Fingerprint", "CheckerRunning",
395
"LastEnabled", "ApprovalPending",
403
397
"LastApprovalRequest", "ApprovalDelay",
404
398
"ApprovalDuration", "Checker",
405
"ExtendedTimeout", "Expires",
408
401
keywords = defaultkeywords
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)
403
print_clients(clients.values(), keywords)
424
405
# Process each client in the list by all selected options
425
406
for client in clients:
427
407
def set_client_prop(prop, value):
428
408
"""Set a Client D-Bus property"""
429
409
client.Set(client_interface, prop, value,
430
410
dbus_interface=dbus.PROPERTIES_IFACE)
432
411
def set_client_prop_ms(prop, value):
433
412
"""Set a Client D-Bus property, converted
434
413
from a string to milliseconds."""
435
414
set_client_prop(prop,
436
string_to_delta(value).total_seconds()
415
timedelta_to_milliseconds
416
(string_to_delta(value)))
439
417
if options.remove:
440
418
mandos_serv.RemoveClient(client.__dbus_object_path__)
441
419
if options.enable: