65
58
"ApprovalDelay": "Approval Delay",
66
59
"ApprovalDuration": "Approval Duration",
67
60
"Checker": "Checker",
68
"ExtendedTimeout": "Extended Timeout",
70
"LastCheckerStatus": "Last Checker Status",
61
"ExtendedTimeout" : "Extended Timeout"
72
63
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
73
64
domain = "se.recompile"
74
65
busname = domain + ".Mandos"
76
67
server_interface = domain + ".Mandos"
77
68
client_interface = domain + ".Mandos.Client"
82
dbus.OBJECT_MANAGER_IFACE
83
except AttributeError:
84
dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
71
def timedelta_to_milliseconds(td):
72
"""Convert a datetime.timedelta object to milliseconds"""
73
return ((td.days * 24 * 60 * 60 * 1000)
75
+ (td.microseconds // 1000))
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 = "{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,
95
87
def rfc3339_duration_to_delta(duration):
119
111
# avoid excessive use of external libraries.
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"
119
"value", # datetime.timedelta or
121
"followers")) # Tokens valid after
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:
191
186
def string_to_delta(interval):
192
187
"""Parse a string and return a datetime.timedelta
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)
236
230
if keyword in ("Timeout", "Interval", "ApprovalDelay",
237
231
"ApprovalDuration", "ExtendedTimeout"):
238
232
return milliseconds_to_string(value)
233
return unicode(value)
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)),
237
width = max(len(tablewords[key]),
238
max(len(valuetostring(client[key],
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 }))
246
print(format_string.format(**dict((key,
247
valuetostring(client[key],
249
for key in keywords)))
256
251
def has_actions(options):
257
252
return any((options.enable,
278
272
parser = argparse.ArgumentParser()
279
273
parser.add_argument("--version", action="version",
280
version = "%(prog)s {}".format(version),
274
version = "%(prog)s {0}".format(version),
281
275
help="show version number and exit")
282
276
parser.add_argument("-a", "--all", action="store_true",
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",
318
310
parser.add_argument("--approval-duration",
319
311
help="Set duration of one client approval")
320
312
parser.add_argument("-H", "--host", help="Set host for client")
321
parser.add_argument("-s", "--secret",
322
type=argparse.FileType(mode="rb"),
313
parser.add_argument("-s", "--secret", type=file,
323
314
help="Set password blob (file) for client")
324
315
parser.add_argument("-A", "--approve", action="store_true",
325
316
help="Approve any current client request")
333
324
if has_actions(options) and not (options.client or options.all):
334
325
parser.error("Options require clients names or --all.")
335
326
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.")
327
parser.error("--verbose can only be used alone or with"
339
329
if options.all and not has_actions(options):
340
330
parser.error("--all requires an action.")
342
332
if options.check:
343
333
fail_count, test_count = doctest.testmod()
344
sys.exit(os.EX_OK if fail_count == 0 else 1)
334
sys.exit(0 if fail_count == 0 else 1)
347
337
bus = dbus.SystemBus()
348
338
mandos_dbus_objc = bus.get_object(busname, server_path)
349
339
except dbus.exceptions.DBusException:
350
print("Could not connect to Mandos server", file=sys.stderr)
340
print("Could not connect to Mandos server",
353
344
mandos_serv = dbus.Interface(mandos_dbus_objc,
354
345
dbus_interface = server_interface)
355
mandos_serv_object_manager = dbus.Interface(
356
mandos_dbus_objc, dbus_interface = dbus.OBJECT_MANAGER_IFACE)
358
347
#block stderr since dbus library prints to stderr
359
348
null = os.open(os.path.devnull, os.O_RDWR)
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
mandos_clients = mandos_serv.GetAllClientsWithProperties()
372
357
os.dup2(stderrcopy, sys.stderr.fileno())
373
358
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)
359
except dbus.exceptions.DBusException:
360
print("Access denied: Accessing mandos server through dbus.",
379
364
# Compile dict of (clients: properties) to process
382
367
if options.all or not options.client:
383
clients = { bus.get_object(busname, path): properties
384
for path, properties in mandos_clients.items() }
368
clients = dict((bus.get_object(busname, path), properties)
369
for path, properties in
370
mandos_clients.iteritems())
386
372
for name in options.client:
387
for path, client in mandos_clients.items():
373
for path, client in mandos_clients.iteritems():
388
374
if client["Name"] == name:
389
375
client_objc = bus.get_object(busname, path)
390
376
clients[client_objc] = client
393
print("Client not found on server: {!r}"
379
print("Client not found on server: {0!r}"
394
380
.format(name), file=sys.stderr)
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",
385
keywords = ("Name", "Enabled", "Timeout",
386
"LastCheckedOK", "Created", "Interval",
387
"Host", "Fingerprint", "CheckerRunning",
388
"LastEnabled", "ApprovalPending",
403
390
"LastApprovalRequest", "ApprovalDelay",
404
391
"ApprovalDuration", "Checker",
405
"ExtendedTimeout", "Expires",
408
394
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)
396
print_clients(clients.values(), keywords)
424
398
# Process each client in the list by all selected options
425
399
for client in clients:
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)
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
string_to_delta(value).total_seconds()
408
timedelta_to_milliseconds
409
(string_to_delta(value)))
439
410
if options.remove:
440
411
mandos_serv.RemoveClient(client.__dbus_object_path__)
441
412
if options.enable: