2
2
# -*- mode: python; coding: utf-8 -*-
4
# Mandos Monitor - Control and monitor the Mandos server
6
# Copyright © 2008-2010 Teddy Hogeborn
7
# Copyright © 2008-2010 Björn Påhlsson
9
# This program is free software: you can redistribute it and/or modify
10
# it under the terms of the GNU General Public License as published by
11
# the Free Software Foundation, either version 3 of the License, or
12
# (at your option) any later version.
14
# This program is distributed in the hope that it will be useful,
15
# but WITHOUT ANY WARRANTY; without even the implied warranty of
16
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
# GNU General Public License for more details.
19
# You should have received a copy of the GNU General Public License
20
# along with this program. If not, see <http://www.gnu.org/licenses/>.
22
# Contact the authors at <mandos@fukt.bsnet.se>.
25
from __future__ import division, absolute_import, unicode_literals
4
from __future__ import division
29
7
from optparse import OptionParser
35
locale.setlocale(locale.LC_ALL, "")
13
locale.setlocale(locale.LC_ALL, u'')
41
"LastCheckedOK": "Last Successful Check",
42
"LastApprovalRequest": "Last Approval Request",
44
"Interval": "Interval",
46
"Fingerprint": "Fingerprint",
47
"CheckerRunning": "Check Is Running",
48
"LastEnabled": "Last Enabled",
49
"ApprovalPending": "Approval Is Pending",
50
"ApprovedByDefault": "Approved By Default",
51
"ApprovalDelay": "Approval Delay",
52
"ApprovalDuration": "Approval Duration",
17
'Enabled': u'Enabled',
18
'Timeout': u'Timeout',
19
'LastCheckedOK': u'Last Successful Check',
20
'Created': u'Created',
21
'Interval': u'Interval',
23
'Fingerprint': u'Fingerprint',
24
'CheckerRunning': u'Check Is Running',
25
'LastEnabled': u'Last Enabled',
26
'Checker': u'Checker',
55
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
56
domain = "se.bsnet.fukt"
57
busname = domain + ".Mandos"
59
server_interface = domain + ".Mandos"
60
client_interface = domain + ".Mandos.Client"
28
defaultkeywords = ('Name', 'Enabled', 'Timeout', 'LastCheckedOK')
29
domain = 'se.bsnet.fukt'
30
busname = domain + '.Mandos'
32
server_interface = domain + '.Mandos'
33
client_interface = domain + '.Mandos.Client'
63
36
def timedelta_to_milliseconds(td):
64
"""Convert a datetime.timedelta object to milliseconds"""
37
"Convert a datetime.timedelta object to milliseconds"
65
38
return ((td.days * 24 * 60 * 60 * 1000)
66
39
+ (td.seconds * 1000)
67
40
+ (td.microseconds // 1000))
69
42
def milliseconds_to_string(ms):
70
43
td = datetime.timedelta(0, 0, 0, ms)
71
return ("%(days)s%(hours)02d:%(minutes)02d:%(seconds)02d"
44
return (u"%(days)s%(hours)02d:%(minutes)02d:%(seconds)02d"
72
45
% { "days": "%dT" % td.days if td.days else "",
73
46
"hours": td.seconds // 3600,
74
47
"minutes": (td.seconds % 3600) // 60,
79
52
def string_to_delta(interval):
80
53
"""Parse a string and return a datetime.timedelta
82
>>> string_to_delta("7d")
55
>>> string_to_delta('7d')
83
56
datetime.timedelta(7)
84
>>> string_to_delta("60s")
57
>>> string_to_delta('60s')
85
58
datetime.timedelta(0, 60)
86
>>> string_to_delta("60m")
59
>>> string_to_delta('60m')
87
60
datetime.timedelta(0, 3600)
88
>>> string_to_delta("24h")
61
>>> string_to_delta('24h')
89
62
datetime.timedelta(1)
90
>>> string_to_delta("1w")
63
>>> string_to_delta(u'1w')
91
64
datetime.timedelta(7)
92
>>> string_to_delta("5m 30s")
65
>>> string_to_delta('5m 30s')
93
66
datetime.timedelta(0, 330)
95
68
timevalue = datetime.timedelta(0)
100
73
suffix = unicode(s[-1])
101
74
value = int(s[:-1])
103
76
delta = datetime.timedelta(value)
105
78
delta = datetime.timedelta(0, value)
107
80
delta = datetime.timedelta(0, 0, 0, 0, value)
109
82
delta = datetime.timedelta(0, 0, 0, 0, 0, value)
111
84
delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
119
92
def print_clients(clients, keywords):
120
93
def valuetostring(value, keyword):
121
94
if type(value) is dbus.Boolean:
122
return "Yes" if value else "No"
123
if keyword in ("Timeout", "Interval", "ApprovalDelay",
95
return u"Yes" if value else u"No"
96
if keyword in (u"timeout", u"interval"):
125
97
return milliseconds_to_string(value)
126
98
return unicode(value)
128
100
# Create format string to print table rows
129
format_string = " ".join("%%-%ds" %
130
max(len(tablewords[key]),
131
max(len(valuetostring(client[key],
101
format_string = u' '.join(u'%%-%ds' %
102
max(len(tablewords[key]),
103
max(len(valuetostring(client[key],
136
108
# Print header line
137
109
print format_string % tuple(tablewords[key] for key in keywords)
138
110
for client in clients:
139
111
print format_string % tuple(valuetostring(client[key], key)
140
112
for key in keywords)
142
113
def has_actions(options):
143
114
return any((options.enable,
150
121
options.checker is not None,
151
122
options.timeout is not None,
152
123
options.interval is not None,
153
options.approved_by_default is not None,
154
options.approval_delay is not None,
155
options.approval_duration is not None,
156
124
options.host is not None,
157
125
options.secret is not None,
184
152
help="Set timeout for client")
185
153
parser.add_option("-i", "--interval", type="string",
186
154
help="Set checker interval for client")
187
parser.add_option("--approve-by-default", action="store_true",
188
dest="approved_by_default",
189
help="Set client to be approved by default")
190
parser.add_option("--deny-by-default", action="store_false",
191
dest="approved_by_default",
192
help="Set client to be denied by default")
193
parser.add_option("--approval-delay", type="string",
194
help="Set delay before client approve/deny")
195
parser.add_option("--approval-duration", type="string",
196
help="Set duration of one client approval")
197
155
parser.add_option("-H", "--host", type="string",
198
156
help="Set host for client")
199
157
parser.add_option("-s", "--secret", type="string",
203
161
parser.add_option("-D", "--deny", action="store_true",
204
162
help="Deny any current client request")
205
163
options, client_names = parser.parse_args()
207
165
if has_actions(options) and not client_names and not options.all:
208
parser.error("Options require clients names or --all.")
166
parser.error('Options requires clients names or --all.')
209
167
if options.verbose and has_actions(options):
210
parser.error("--verbose can only be used alone or with"
168
parser.error('Verbose option can only be used alone or with --all.')
212
169
if options.all and not has_actions(options):
213
parser.error("--all requires an action.")
170
parser.error('--all requires an action')
216
173
bus = dbus.SystemBus()
217
174
mandos_dbus_objc = bus.get_object(busname, server_path)
238
195
print >> sys.stderr, "Access denied: Accessing mandos server through dbus."
241
# Compile dict of (clients: properties) to process
198
# Compile list of clients to process
244
201
if options.all or not client_names:
245
clients = dict((bus.get_object(busname, path), properties)
246
for path, properties in
247
mandos_clients.iteritems())
202
clients = (bus.get_object(busname, path) for path in mandos_clients.iterkeys())
249
204
for name in client_names:
250
205
for path, client in mandos_clients.iteritems():
251
if client["Name"] == name:
206
if client['Name'] == name:
252
207
client_objc = bus.get_object(busname, path)
253
clients[client_objc] = client
208
clients.append(client_objc)
256
211
print >> sys.stderr, "Client not found on server: %r" % name
259
214
if not has_actions(options) and clients:
260
215
if options.verbose:
261
keywords = ("Name", "Enabled", "Timeout",
262
"LastCheckedOK", "Created", "Interval",
263
"Host", "Fingerprint", "CheckerRunning",
264
"LastEnabled", "ApprovalPending",
266
"LastApprovalRequest", "ApprovalDelay",
267
"ApprovalDuration", "Checker")
216
keywords = ('Name', 'Enabled', 'Timeout', 'LastCheckedOK',
217
'Created', 'Interval', 'Host', 'Fingerprint',
218
'CheckerRunning', 'LastEnabled', 'Checker')
269
220
keywords = defaultkeywords
271
print_clients(clients.values(), keywords)
222
print_clients(mandos_clients.values(), keywords)
273
224
# Process each client in the list by all selected options
274
225
for client in clients:
286
237
client.StopChecker(dbus_interface=client_interface)
287
238
if options.is_enabled:
288
239
sys.exit(0 if client.Get(client_interface,
290
241
dbus_interface=dbus.PROPERTIES_IFACE)
292
243
if options.checker:
293
client.Set(client_interface, "Checker", options.checker,
244
client.Set(client_interface, u"Checker", options.checker,
294
245
dbus_interface=dbus.PROPERTIES_IFACE)
296
client.Set(client_interface, "Host", options.host,
247
client.Set(client_interface, u"Host", options.host,
297
248
dbus_interface=dbus.PROPERTIES_IFACE)
298
249
if options.interval:
299
client.Set(client_interface, "Interval",
250
client.Set(client_interface, u"Interval",
300
251
timedelta_to_milliseconds
301
252
(string_to_delta(options.interval)),
302
253
dbus_interface=dbus.PROPERTIES_IFACE)
303
if options.approval_delay:
304
client.Set(client_interface, "ApprovalDelay",
305
timedelta_to_milliseconds
306
(string_to_delta(options.
308
dbus_interface=dbus.PROPERTIES_IFACE)
309
if options.approval_duration:
310
client.Set(client_interface, "ApprovalDuration",
311
timedelta_to_milliseconds
312
(string_to_delta(options.
314
dbus_interface=dbus.PROPERTIES_IFACE)
315
254
if options.timeout:
316
client.Set(client_interface, "Timeout",
317
timedelta_to_milliseconds
318
(string_to_delta(options.timeout)),
255
client.Set(client_interface, u"Timeout",
256
timedelta_to_milliseconds(string_to_delta
319
258
dbus_interface=dbus.PROPERTIES_IFACE)
320
259
if options.secret:
321
client.Set(client_interface, "Secret",
322
dbus.ByteArray(open(options.secret,
324
dbus_interface=dbus.PROPERTIES_IFACE)
325
if options.approved_by_default is not None:
326
client.Set(client_interface, "ApprovedByDefault",
328
.approved_by_default),
260
client.Set(client_interface, u"Secret",
261
dbus.ByteArray(open(options.secret, u'rb').read()),
329
262
dbus_interface=dbus.PROPERTIES_IFACE)
330
263
if options.approve:
331
client.Approve(dbus.Boolean(True),
332
dbus_interface=client_interface)
334
client.Approve(dbus.Boolean(False),
335
dbus_interface=client_interface)
264
client.Approve(dbus.Boolean(True), dbus_interface=client_interface)
266
client.Approve(dbus.Boolean(False), dbus_interface=client_interface)
337
if __name__ == "__main__":
268
if __name__ == '__main__':