65
58
"ApprovalDelay": "Approval Delay",
66
59
"ApprovalDuration": "Approval Duration",
67
60
"Checker": "Checker",
68
"ExtendedTimeout": "Extended Timeout"
61
"ExtendedTimeout" : "Extended Timeout"
70
63
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
71
64
domain = "se.recompile"
72
65
busname = domain + ".Mandos"
74
67
server_interface = domain + ".Mandos"
75
68
client_interface = domain + ".Mandos.Client"
80
dbus.OBJECT_MANAGER_IFACE
81
except AttributeError:
82
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))
84
77
def milliseconds_to_string(ms):
85
78
td = datetime.timedelta(0, 0, 0, ms)
86
return ("{days}{hours:02}:{minutes:02}:{seconds:02}".format(
87
days = "{}T".format(td.days) if td.days else "",
88
hours = td.seconds // 3600,
89
minutes = (td.seconds % 3600) // 60,
90
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,
93
87
def rfc3339_duration_to_delta(duration):
94
"""Parse an RFC 3339 "duration" and return a datetime.timedelta
88
"""Parse a RFC 3339 "duration" and return a datetime.timedelta
96
90
>>> rfc3339_duration_to_delta("P7D")
97
91
datetime.timedelta(7)
109
103
datetime.timedelta(1, 200)
112
# Parsing an RFC 3339 duration with regular expressions is not
106
# Parsing a RFC 3339 duration with regular expressions is not
113
107
# possible - there would have to be multiple places for the same
114
# values, like seconds. The current code, while more esoteric, is
115
# cleaner without depending on a parsing library. If Python had a
108
# values, like seconds. This, while more esoteric, is cleaner
109
# without depending on a parsing library. If Python had a
116
110
# built-in library for parsing we would use it, but we'd like to
117
111
# avoid excessive use of external libraries.
119
113
# New type for defining tokens, syntax, and semantics all-in-one
120
Token = collections.namedtuple("Token", (
121
"regexp", # To match token; if "value" is not None, must have
122
# a "group" containing digits
123
"value", # datetime.timedelta or None
124
"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
125
123
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
126
124
# the "duration" ABNF definition in RFC 3339, Appendix A.
127
125
token_end = Token(re.compile(r"$"), None, frozenset())
128
126
token_second = Token(re.compile(r"(\d+)S"),
129
127
datetime.timedelta(seconds=1),
130
frozenset((token_end, )))
128
frozenset((token_end,)))
131
129
token_minute = Token(re.compile(r"(\d+)M"),
132
130
datetime.timedelta(minutes=1),
133
131
frozenset((token_second, token_end)))
149
147
frozenset((token_month, token_end)))
150
148
token_week = Token(re.compile(r"(\d+)W"),
151
149
datetime.timedelta(weeks=1),
152
frozenset((token_end, )))
150
frozenset((token_end,)))
153
151
token_duration = Token(re.compile(r"P"), None,
154
152
frozenset((token_year, token_month,
155
153
token_day, token_time,
157
155
# Define starting values
158
156
value = datetime.timedelta() # Value so far
159
157
found_token = None
160
followers = frozenset((token_duration, )) # Following valid tokens
158
followers = frozenset(token_duration,) # Following valid tokens
161
159
s = duration # String left to parse
162
160
# Loop until end token is found
163
161
while found_token is not token_end:
189
186
def string_to_delta(interval):
190
187
"""Parse a string and return a datetime.timedelta
192
>>> string_to_delta('7d')
189
>>> string_to_delta("7d")
193
190
datetime.timedelta(7)
194
>>> string_to_delta('60s')
191
>>> string_to_delta("60s")
195
192
datetime.timedelta(0, 60)
196
>>> string_to_delta('60m')
193
>>> string_to_delta("60m")
197
194
datetime.timedelta(0, 3600)
198
>>> string_to_delta('24h')
195
>>> string_to_delta("24h")
199
196
datetime.timedelta(1)
200
>>> string_to_delta('1w')
197
>>> string_to_delta("1w")
201
198
datetime.timedelta(7)
202
>>> string_to_delta('5m 30s')
199
>>> string_to_delta("5m 30s")
203
200
datetime.timedelta(0, 330)
202
value = datetime.timedelta(0)
203
regexp = re.compile(r"(\d+)([dsmhw]?)")
207
206
return rfc3339_duration_to_delta(interval)
208
207
except ValueError:
211
value = datetime.timedelta(0)
212
regexp = re.compile(r"(\d+)([dsmhw]?)")
214
210
for num, suffix in regexp.findall(interval):
215
211
if suffix == "d":
216
212
value += datetime.timedelta(int(num))
234
229
if keyword in ("Timeout", "Interval", "ApprovalDelay",
235
230
"ApprovalDuration", "ExtendedTimeout"):
236
231
return milliseconds_to_string(value)
232
return unicode(value)
239
234
# Create format string to print table rows
240
235
format_string = " ".join("{{{key}:{width}}}".format(
241
width = max(len(tablewords[key]),
242
max(len(valuetostring(client[key], key))
243
for client in clients)),
236
width = max(len(tablewords[key]),
237
max(len(valuetostring(client[key],
241
key = key) for key in keywords)
246
242
# Print header line
247
243
print(format_string.format(**tablewords))
248
244
for client in clients:
249
print(format_string.format(**{
250
key: valuetostring(client[key], key)
251
for key in keywords }))
245
print(format_string.format(**dict((key,
246
valuetostring(client[key],
248
for key in keywords)))
254
250
def has_actions(options):
255
251
return any((options.enable,
276
271
parser = argparse.ArgumentParser()
277
272
parser.add_argument("--version", action="version",
278
version = "%(prog)s {}".format(version),
273
version = "%(prog)s {0}".format(version),
279
274
help="show version number and exit")
280
275
parser.add_argument("-a", "--all", action="store_true",
281
276
help="Select all clients")
282
277
parser.add_argument("-v", "--verbose", action="store_true",
283
278
help="Print all fields")
284
parser.add_argument("-j", "--dump-json", action="store_true",
285
help="Dump client data in JSON format")
286
279
parser.add_argument("-e", "--enable", action="store_true",
287
280
help="Enable client")
288
281
parser.add_argument("-d", "--disable", action="store_true",
316
309
parser.add_argument("--approval-duration",
317
310
help="Set duration of one client approval")
318
311
parser.add_argument("-H", "--host", help="Set host for client")
319
parser.add_argument("-s", "--secret",
320
type=argparse.FileType(mode="rb"),
312
parser.add_argument("-s", "--secret", type=file,
321
313
help="Set password blob (file) for client")
322
314
parser.add_argument("-A", "--approve", action="store_true",
323
315
help="Approve any current client request")
331
323
if has_actions(options) and not (options.client or options.all):
332
324
parser.error("Options require clients names or --all.")
333
325
if options.verbose and has_actions(options):
334
parser.error("--verbose can only be used alone.")
335
if options.dump_json and (options.verbose or has_actions(options)):
336
parser.error("--dump-json can only be used alone.")
326
parser.error("--verbose can only be used alone or with"
337
328
if options.all and not has_actions(options):
338
329
parser.error("--all requires an action.")
340
331
if options.check:
341
332
fail_count, test_count = doctest.testmod()
342
sys.exit(os.EX_OK if fail_count == 0 else 1)
333
sys.exit(0 if fail_count == 0 else 1)
345
336
bus = dbus.SystemBus()
346
337
mandos_dbus_objc = bus.get_object(busname, server_path)
347
338
except dbus.exceptions.DBusException:
348
print("Could not connect to Mandos server", file=sys.stderr)
339
print("Could not connect to Mandos server",
351
343
mandos_serv = dbus.Interface(mandos_dbus_objc,
352
344
dbus_interface = server_interface)
353
mandos_serv_object_manager = dbus.Interface(
354
mandos_dbus_objc, dbus_interface = dbus.OBJECT_MANAGER_IFACE)
356
346
#block stderr since dbus library prints to stderr
357
347
null = os.open(os.path.devnull, os.O_RDWR)
363
mandos_clients = { path: ifs_and_props[client_interface]
364
for path, ifs_and_props in
365
mandos_serv_object_manager
366
.GetManagedObjects().items()
367
if client_interface in ifs_and_props }
353
mandos_clients = mandos_serv.GetAllClientsWithProperties()
370
356
os.dup2(stderrcopy, sys.stderr.fileno())
371
357
os.close(stderrcopy)
372
except dbus.exceptions.DBusException as e:
373
print("Access denied: Accessing mandos server through D-Bus: {}"
374
.format(e), file=sys.stderr)
358
except dbus.exceptions.DBusException:
359
print("Access denied: Accessing mandos server through dbus.",
377
363
# Compile dict of (clients: properties) to process
380
366
if options.all or not options.client:
381
clients = { bus.get_object(busname, path): properties
382
for path, properties in mandos_clients.items() }
367
clients = dict((bus.get_object(busname, path), properties)
368
for path, properties in
369
mandos_clients.iteritems())
384
371
for name in options.client:
385
for path, client in mandos_clients.items():
372
for path, client in mandos_clients.iteritems():
386
373
if client["Name"] == name:
387
374
client_objc = bus.get_object(busname, path)
388
375
clients[client_objc] = client
391
print("Client not found on server: {!r}"
378
print("Client not found on server: {0!r}"
392
379
.format(name), file=sys.stderr)
395
382
if not has_actions(options) and clients:
396
if options.verbose or options.dump_json:
397
keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK",
398
"Created", "Interval", "Host", "Fingerprint",
399
"CheckerRunning", "LastEnabled",
400
"ApprovalPending", "ApprovedByDefault",
384
keywords = ("Name", "Enabled", "Timeout",
385
"LastCheckedOK", "Created", "Interval",
386
"Host", "Fingerprint", "CheckerRunning",
387
"LastEnabled", "ApprovalPending",
401
389
"LastApprovalRequest", "ApprovalDelay",
402
390
"ApprovalDuration", "Checker",
403
391
"ExtendedTimeout")
405
393
keywords = defaultkeywords
407
if options.dump_json:
408
json.dump({client["Name"]: {key:
410
if isinstance(client[key],
413
for key in keywords }
414
for client in clients.values() },
415
fp = sys.stdout, indent = 4,
416
separators = (',', ': '))
419
print_clients(clients.values(), keywords)
395
print_clients(clients.values(), keywords)
421
397
# Process each client in the list by all selected options
422
398
for client in clients:
424
399
def set_client_prop(prop, value):
425
400
"""Set a Client D-Bus property"""
426
401
client.Set(client_interface, prop, value,
427
402
dbus_interface=dbus.PROPERTIES_IFACE)
429
403
def set_client_prop_ms(prop, value):
430
404
"""Set a Client D-Bus property, converted
431
405
from a string to milliseconds."""
432
406
set_client_prop(prop,
433
string_to_delta(value).total_seconds()
407
timedelta_to_milliseconds
408
(string_to_delta(value)))
436
409
if options.remove:
437
410
mandos_serv.RemoveClient(client.__dbus_object_path__)
438
411
if options.enable: