/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to mandos-ctl

  • Committer: teddy at bsnet
  • Date: 2010-09-14 18:22:03 UTC
  • Revision ID: teddy@fukt.bsnet.se-20100914182203-w26c64tdthto4jg2
* mandos-monitor.xml: New.
* Makefile (PROGS): Add "mandos-monitor".
  (DOCS): Add "mandos-monitor.xml".
  (mandos-monitor.8, mandos-monitor.8.xhtml, mandos-monitor): New.
  (install-server): Install "mandos-ctl" and "mandos-monitor" too.
  (uninstall-server): Remove "mandos-ctl" and "mandos-monitor" too.
* mandos-monitor: Don't log uninteresting messages.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/python
2
2
# -*- mode: python; coding: utf-8 -*-
3
 
4
 
# Mandos Monitor - Control and monitor the Mandos server
5
 
6
 
# Copyright © 2008-2010 Teddy Hogeborn
7
 
# Copyright © 2008-2010 Björn Påhlsson
8
 
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.
13
 
#
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.
18
 
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/>.
21
 
22
 
# Contact the authors at <mandos@fukt.bsnet.se>.
23
 
24
 
 
25
 
from __future__ import division, absolute_import, unicode_literals
26
 
 
 
3
 
 
4
from __future__ import division
27
5
import sys
28
6
import dbus
29
7
from optparse import OptionParser
32
10
import re
33
11
import os
34
12
 
35
 
locale.setlocale(locale.LC_ALL, "")
 
13
locale.setlocale(locale.LC_ALL, u'')
36
14
 
37
15
tablewords = {
38
 
    "Name": "Name",
39
 
    "Enabled": "Enabled",
40
 
    "Timeout": "Timeout",
41
 
    "LastCheckedOK": "Last Successful Check",
42
 
    "LastApprovalRequest": "Last Approval Request",
43
 
    "Created": "Created",
44
 
    "Interval": "Interval",
45
 
    "Host": "Host",
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",
53
 
    "Checker": "Checker",
 
16
    'Name': u'Name',
 
17
    'Enabled': u'Enabled',
 
18
    'Timeout': u'Timeout',
 
19
    'LastCheckedOK': u'Last Successful Check',
 
20
    'Created': u'Created',
 
21
    'Interval': u'Interval',
 
22
    'Host': u'Host',
 
23
    'Fingerprint': u'Fingerprint',
 
24
    'CheckerRunning': u'Check Is Running',
 
25
    'LastEnabled': u'Last Enabled',
 
26
    'Checker': u'Checker',
54
27
    }
55
 
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
56
 
domain = "se.bsnet.fukt"
57
 
busname = domain + ".Mandos"
58
 
server_path = "/"
59
 
server_interface = domain + ".Mandos"
60
 
client_interface = domain + ".Mandos.Client"
61
 
version = "1.2.3"
 
28
defaultkeywords = ('Name', 'Enabled', 'Timeout', 'LastCheckedOK')
 
29
domain = 'se.bsnet.fukt'
 
30
busname = domain + '.Mandos'
 
31
server_path = '/'
 
32
server_interface = domain + '.Mandos'
 
33
client_interface = domain + '.Mandos.Client'
 
34
version = "1.0.14"
62
35
 
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))
68
41
 
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
81
54
 
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)
94
67
    """
95
68
    timevalue = datetime.timedelta(0)
99
72
        try:
100
73
            suffix = unicode(s[-1])
101
74
            value = int(s[:-1])
102
 
            if suffix == "d":
 
75
            if suffix == u"d":
103
76
                delta = datetime.timedelta(value)
104
 
            elif suffix == "s":
 
77
            elif suffix == u"s":
105
78
                delta = datetime.timedelta(0, value)
106
 
            elif suffix == "m":
 
79
            elif suffix == u"m":
107
80
                delta = datetime.timedelta(0, 0, 0, 0, value)
108
 
            elif suffix == "h":
 
81
            elif suffix == u"h":
109
82
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
110
 
            elif suffix == "w":
 
83
            elif suffix == u"w":
111
84
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
112
85
            else:
113
86
                raise ValueError
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",
124
 
                       "ApprovalDuration"):
 
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)
127
99
    
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],
132
 
                                                       key))
133
 
                                     for client in
134
 
                                     clients))
135
 
                             for key in keywords)
 
101
    format_string = u' '.join(u'%%-%ds' %
 
102
                              max(len(tablewords[key]),
 
103
                                  max(len(valuetostring(client[key],
 
104
                                                        key))
 
105
                                      for client in
 
106
                                      clients))
 
107
                              for key in keywords)
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)
141
 
 
142
113
def has_actions(options):
143
114
    return any((options.enable,
144
115
                options.disable,
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,
158
126
                options.approve,
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()
206
 
        
 
164
 
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"
211
 
                         " --all.")
 
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.")
214
 
        
 
170
            parser.error('--all requires an action')
 
171
            
215
172
        try:
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."
239
196
            sys.exit(1)
240
197
            
241
 
        # Compile dict of (clients: properties) to process
242
 
        clients={}
243
 
        
 
198
        # Compile list of clients to process
 
199
        clients=[]
 
200
 
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())
248
203
        else:
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)
254
209
                        break
255
210
                else:
256
211
                    print >> sys.stderr, "Client not found on server: %r" % name
258
213
            
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",
265
 
                            "ApprovedByDefault",
266
 
                            "LastApprovalRequest", "ApprovalDelay",
267
 
                            "ApprovalDuration", "Checker")
 
216
                keywords = ('Name', 'Enabled', 'Timeout', 'LastCheckedOK',
 
217
                            'Created', 'Interval', 'Host', 'Fingerprint',
 
218
                            'CheckerRunning', 'LastEnabled', 'Checker')
268
219
            else:
269
220
                keywords = defaultkeywords
270
 
            
271
 
            print_clients(clients.values(), keywords)
 
221
                
 
222
            print_clients(mandos_clients.values(), keywords)
272
223
        else:
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,
289
 
                                             "Enabled",
 
240
                                             u"Enabled",
290
241
                                             dbus_interface=dbus.PROPERTIES_IFACE)
291
242
                             else 1)
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)
295
246
                if options.host:
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.
307
 
                                                approval_delay)),
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.
313
 
                                                approval_duration)),
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
 
257
                                                         (options.timeout)),
319
258
                               dbus_interface=dbus.PROPERTIES_IFACE)
320
259
                if options.secret:
321
 
                    client.Set(client_interface, "Secret",
322
 
                               dbus.ByteArray(open(options.secret,
323
 
                                                   "rb").read()),
324
 
                               dbus_interface=dbus.PROPERTIES_IFACE)
325
 
                if options.approved_by_default is not None:
326
 
                    client.Set(client_interface, "ApprovedByDefault",
327
 
                               dbus.Boolean(options
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)
333
 
                elif options.deny:
334
 
                    client.Approve(dbus.Boolean(False),
335
 
                                   dbus_interface=client_interface)
 
264
                    client.Approve(dbus.Boolean(True), dbus_interface=client_interface)
 
265
                if options.deny:
 
266
                    client.Approve(dbus.Boolean(False), dbus_interface=client_interface)
336
267
 
337
 
if __name__ == "__main__":
 
268
if __name__ == '__main__':
338
269
    main()