4
4
# Mandos Monitor - Control and monitor the Mandos server
6
# Copyright © 2008-2014 Teddy Hogeborn
7
# Copyright © 2008-2014 Björn Påhlsson
6
# Copyright © 2008-2015 Teddy Hogeborn
7
# Copyright © 2008-2015 Björn Påhlsson
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
64
64
"ApprovalDelay": "Approval Delay",
65
65
"ApprovalDuration": "Approval Duration",
66
66
"Checker": "Checker",
67
"ExtendedTimeout" : "Extended Timeout"
67
"ExtendedTimeout": "Extended Timeout"
69
69
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
70
70
domain = "se.recompile"
71
71
busname = domain + ".Mandos"
73
73
server_interface = domain + ".Mandos"
74
74
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))
79
dbus.OBJECT_MANAGER_IFACE
80
except AttributeError:
81
dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
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,
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))
93
92
def rfc3339_duration_to_delta(duration):
117
116
# avoid excessive use of external libraries.
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"
125
"value", # datetime.timedelta or
127
"followers")) # Tokens valid after
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:
192
188
def string_to_delta(interval):
193
189
"""Parse a string and return a datetime.timedelta
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)
229
225
value += datetime.timedelta(0, 0, 0, int(num))
232
229
def print_clients(clients, keywords):
233
230
def valuetostring(value, keyword):
234
231
if type(value) is dbus.Boolean:
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],
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)),
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],
255
for key in keywords }))
248
print(format_string.format(**{
249
key: valuetostring(client[key], key)
250
for key in keywords }))
257
253
def has_actions(options):
258
254
return any((options.enable,
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",
344
print("Could not connect to Mandos server", file=sys.stderr)
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)
354
352
#block stderr since dbus library prints to stderr
355
353
null = os.open(os.path.devnull, os.O_RDWR)
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 }
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
except dbus.exceptions.DBusException as e:
369
print("Access denied: Accessing mandos server through D-Bus: {}"
370
.format(e), file=sys.stderr)
371
373
# Compile dict of (clients: properties) to process
382
384
clients[client_objc] = client
385
print("Client not found on server: {0!r}"
387
print("Client not found on server: {!r}"
386
388
.format(name), file=sys.stderr)
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",
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")
404
405
# Process each client in the list by all selected options
405
406
for client in clients:
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)
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()
416
420
if options.remove:
417
421
mandos_serv.RemoveClient(client.__dbus_object_path__)
418
422
if options.enable: