/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 Hogeborn
  • Date: 2011-03-08 19:41:59 UTC
  • mto: (237.4.29 release)
  • mto: This revision was merged to the branch mainline in revision 473.
  • Revision ID: teddy@fukt.bsnet.se-20110308194159-h0p66a3rabn8cjkb
Tags: version-1.3.0-1
* Makefile (version): Changed to "1.3.0".
* NEWS (Version 1.3.0): New entry.
* debian/changelog (1.3.0-1): - '' -

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
 
from __future__ import division
 
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, print_function,
 
26
                        unicode_literals)
 
27
 
5
28
import sys
6
29
import dbus
7
30
from optparse import OptionParser
10
33
import re
11
34
import os
12
35
 
13
 
locale.setlocale(locale.LC_ALL, u'')
 
36
locale.setlocale(locale.LC_ALL, "")
14
37
 
15
38
tablewords = {
16
 
    'Name': u'Name',
17
 
    'Enabled': u'Enabled',
18
 
    'Timeout': u'Timeout',
19
 
    'LastCheckedOK': u'Last Successful Check',
20
 
    'LastApprovalRequest': u'Last Approval Request',
21
 
    'Created': u'Created',
22
 
    'Interval': u'Interval',
23
 
    'Host': u'Host',
24
 
    'Fingerprint': u'Fingerprint',
25
 
    'CheckerRunning': u'Check Is Running',
26
 
    'LastEnabled': u'Last Enabled',
27
 
    'ApprovalPending': u'Approval Is Pending',
28
 
    'ApprovedByDefault': u'Approved By Default',
29
 
    'ApprovalDelay': u"Approval Delay",
30
 
    'ApprovalDuration': u"Approval Duration",
31
 
    'Checker': u'Checker',
 
39
    "Name": "Name",
 
40
    "Enabled": "Enabled",
 
41
    "Timeout": "Timeout",
 
42
    "LastCheckedOK": "Last Successful Check",
 
43
    "LastApprovalRequest": "Last Approval Request",
 
44
    "Created": "Created",
 
45
    "Interval": "Interval",
 
46
    "Host": "Host",
 
47
    "Fingerprint": "Fingerprint",
 
48
    "CheckerRunning": "Check Is Running",
 
49
    "LastEnabled": "Last Enabled",
 
50
    "ApprovalPending": "Approval Is Pending",
 
51
    "ApprovedByDefault": "Approved By Default",
 
52
    "ApprovalDelay": "Approval Delay",
 
53
    "ApprovalDuration": "Approval Duration",
 
54
    "Checker": "Checker",
32
55
    }
33
 
defaultkeywords = ('Name', 'Enabled', 'Timeout', 'LastCheckedOK')
34
 
domain = 'se.bsnet.fukt'
35
 
busname = domain + '.Mandos'
36
 
server_path = '/'
37
 
server_interface = domain + '.Mandos'
38
 
client_interface = domain + '.Mandos.Client'
39
 
version = "1.0.14"
 
56
defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK")
 
57
domain = "se.bsnet.fukt"
 
58
busname = domain + ".Mandos"
 
59
server_path = "/"
 
60
server_interface = domain + ".Mandos"
 
61
client_interface = domain + ".Mandos.Client"
 
62
version = "1.3.0"
40
63
 
41
64
def timedelta_to_milliseconds(td):
42
 
    "Convert a datetime.timedelta object to milliseconds"
 
65
    """Convert a datetime.timedelta object to milliseconds"""
43
66
    return ((td.days * 24 * 60 * 60 * 1000)
44
67
            + (td.seconds * 1000)
45
68
            + (td.microseconds // 1000))
46
69
 
47
70
def milliseconds_to_string(ms):
48
71
    td = datetime.timedelta(0, 0, 0, ms)
49
 
    return (u"%(days)s%(hours)02d:%(minutes)02d:%(seconds)02d"
 
72
    return ("%(days)s%(hours)02d:%(minutes)02d:%(seconds)02d"
50
73
            % { "days": "%dT" % td.days if td.days else "",
51
74
                "hours": td.seconds // 3600,
52
75
                "minutes": (td.seconds % 3600) // 60,
57
80
def string_to_delta(interval):
58
81
    """Parse a string and return a datetime.timedelta
59
82
 
60
 
    >>> string_to_delta('7d')
 
83
    >>> string_to_delta("7d")
61
84
    datetime.timedelta(7)
62
 
    >>> string_to_delta('60s')
 
85
    >>> string_to_delta("60s")
63
86
    datetime.timedelta(0, 60)
64
 
    >>> string_to_delta('60m')
 
87
    >>> string_to_delta("60m")
65
88
    datetime.timedelta(0, 3600)
66
 
    >>> string_to_delta('24h')
 
89
    >>> string_to_delta("24h")
67
90
    datetime.timedelta(1)
68
 
    >>> string_to_delta(u'1w')
 
91
    >>> string_to_delta("1w")
69
92
    datetime.timedelta(7)
70
 
    >>> string_to_delta('5m 30s')
 
93
    >>> string_to_delta("5m 30s")
71
94
    datetime.timedelta(0, 330)
72
95
    """
73
96
    timevalue = datetime.timedelta(0)
77
100
        try:
78
101
            suffix = unicode(s[-1])
79
102
            value = int(s[:-1])
80
 
            if suffix == u"d":
 
103
            if suffix == "d":
81
104
                delta = datetime.timedelta(value)
82
 
            elif suffix == u"s":
 
105
            elif suffix == "s":
83
106
                delta = datetime.timedelta(0, value)
84
 
            elif suffix == u"m":
 
107
            elif suffix == "m":
85
108
                delta = datetime.timedelta(0, 0, 0, 0, value)
86
 
            elif suffix == u"h":
 
109
            elif suffix == "h":
87
110
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
88
 
            elif suffix == u"w":
 
111
            elif suffix == "w":
89
112
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
90
113
            else:
91
114
                raise ValueError
97
120
def print_clients(clients, keywords):
98
121
    def valuetostring(value, keyword):
99
122
        if type(value) is dbus.Boolean:
100
 
            return u"Yes" if value else u"No"
101
 
        if keyword in (u"Timeout", u"Interval", u"ApprovalDelay",
102
 
                       u"ApprovalDuration"):
 
123
            return "Yes" if value else "No"
 
124
        if keyword in ("Timeout", "Interval", "ApprovalDelay",
 
125
                       "ApprovalDuration"):
103
126
            return milliseconds_to_string(value)
104
127
        return unicode(value)
105
128
    
106
129
    # Create format string to print table rows
107
 
    format_string = u' '.join(u'%%-%ds' %
108
 
                              max(len(tablewords[key]),
109
 
                                  max(len(valuetostring(client[key],
110
 
                                                        key))
111
 
                                      for client in
112
 
                                      clients))
113
 
                              for key in keywords)
 
130
    format_string = " ".join("%%-%ds" %
 
131
                             max(len(tablewords[key]),
 
132
                                 max(len(valuetostring(client[key],
 
133
                                                       key))
 
134
                                     for client in
 
135
                                     clients))
 
136
                             for key in keywords)
114
137
    # Print header line
115
 
    print format_string % tuple(tablewords[key] for key in keywords)
 
138
    print(format_string % tuple(tablewords[key] for key in keywords))
116
139
    for client in clients:
117
 
        print format_string % tuple(valuetostring(client[key], key)
118
 
                                    for key in keywords)
 
140
        print(format_string % tuple(valuetostring(client[key], key)
 
141
                                    for key in keywords))
119
142
 
120
143
def has_actions(options):
121
144
    return any((options.enable,
163
186
        parser.add_option("-i", "--interval", type="string",
164
187
                          help="Set checker interval for client")
165
188
        parser.add_option("--approve-by-default", action="store_true",
166
 
                          dest=u"approved_by_default",
 
189
                          dest="approved_by_default",
167
190
                          help="Set client to be approved by default")
168
191
        parser.add_option("--deny-by-default", action="store_false",
169
 
                          dest=u"approved_by_default",
 
192
                          dest="approved_by_default",
170
193
                          help="Set client to be denied by default")
171
194
        parser.add_option("--approval-delay", type="string",
172
195
                          help="Set delay before client approve/deny")
183
206
        options, client_names = parser.parse_args()
184
207
        
185
208
        if has_actions(options) and not client_names and not options.all:
186
 
            parser.error('Options require clients names or --all.')
 
209
            parser.error("Options require clients names or --all.")
187
210
        if options.verbose and has_actions(options):
188
 
            parser.error('--verbose can only be used alone or with'
189
 
                         ' --all.')
 
211
            parser.error("--verbose can only be used alone or with"
 
212
                         " --all.")
190
213
        if options.all and not has_actions(options):
191
 
            parser.error('--all requires an action.')
 
214
            parser.error("--all requires an action.")
192
215
        
193
216
        try:
194
217
            bus = dbus.SystemBus()
195
218
            mandos_dbus_objc = bus.get_object(busname, server_path)
196
219
        except dbus.exceptions.DBusException:
197
 
            print >> sys.stderr, "Could not connect to Mandos server"
 
220
            print("Could not connect to Mandos server",
 
221
                  file=sys.stderr)
198
222
            sys.exit(1)
199
223
    
200
224
        mandos_serv = dbus.Interface(mandos_dbus_objc,
213
237
                os.dup2(stderrcopy, sys.stderr.fileno())
214
238
                os.close(stderrcopy)
215
239
        except dbus.exceptions.DBusException, e:
216
 
            print >> sys.stderr, "Access denied: Accessing mandos server through dbus."
 
240
            print("Access denied: Accessing mandos server through dbus.",
 
241
                  file=sys.stderr)
217
242
            sys.exit(1)
218
243
            
219
244
        # Compile dict of (clients: properties) to process
226
251
        else:
227
252
            for name in client_names:
228
253
                for path, client in mandos_clients.iteritems():
229
 
                    if client['Name'] == name:
 
254
                    if client["Name"] == name:
230
255
                        client_objc = bus.get_object(busname, path)
231
256
                        clients[client_objc] = client
232
257
                        break
233
258
                else:
234
 
                    print >> sys.stderr, "Client not found on server: %r" % name
 
259
                    print("Client not found on server: %r" % name,
 
260
                          file=sys.stderr)
235
261
                    sys.exit(1)
236
262
            
237
263
        if not has_actions(options) and clients:
238
264
            if options.verbose:
239
 
                keywords = ('Name', 'Enabled', 'Timeout',
240
 
                            'LastCheckedOK', 'Created', 'Interval',
241
 
                            'Host', 'Fingerprint', 'CheckerRunning',
242
 
                            'LastEnabled', 'ApprovalPending',
243
 
                            'ApprovedByDefault',
244
 
                            'LastApprovalRequest', 'ApprovalDelay',
245
 
                            'ApprovalDuration', 'Checker')
 
265
                keywords = ("Name", "Enabled", "Timeout",
 
266
                            "LastCheckedOK", "Created", "Interval",
 
267
                            "Host", "Fingerprint", "CheckerRunning",
 
268
                            "LastEnabled", "ApprovalPending",
 
269
                            "ApprovedByDefault",
 
270
                            "LastApprovalRequest", "ApprovalDelay",
 
271
                            "ApprovalDuration", "Checker")
246
272
            else:
247
273
                keywords = defaultkeywords
248
274
            
264
290
                    client.StopChecker(dbus_interface=client_interface)
265
291
                if options.is_enabled:
266
292
                    sys.exit(0 if client.Get(client_interface,
267
 
                                             u"Enabled",
 
293
                                             "Enabled",
268
294
                                             dbus_interface=dbus.PROPERTIES_IFACE)
269
295
                             else 1)
270
296
                if options.checker:
271
 
                    client.Set(client_interface, u"Checker", options.checker,
 
297
                    client.Set(client_interface, "Checker", options.checker,
272
298
                               dbus_interface=dbus.PROPERTIES_IFACE)
273
299
                if options.host:
274
 
                    client.Set(client_interface, u"Host", options.host,
 
300
                    client.Set(client_interface, "Host", options.host,
275
301
                               dbus_interface=dbus.PROPERTIES_IFACE)
276
302
                if options.interval:
277
 
                    client.Set(client_interface, u"Interval",
 
303
                    client.Set(client_interface, "Interval",
278
304
                               timedelta_to_milliseconds
279
305
                               (string_to_delta(options.interval)),
280
306
                               dbus_interface=dbus.PROPERTIES_IFACE)
281
307
                if options.approval_delay:
282
 
                    client.Set(client_interface, u"ApprovalDelay",
 
308
                    client.Set(client_interface, "ApprovalDelay",
283
309
                               timedelta_to_milliseconds
284
310
                               (string_to_delta(options.
285
311
                                                approval_delay)),
286
312
                               dbus_interface=dbus.PROPERTIES_IFACE)
287
313
                if options.approval_duration:
288
 
                    client.Set(client_interface, u"ApprovalDuration",
 
314
                    client.Set(client_interface, "ApprovalDuration",
289
315
                               timedelta_to_milliseconds
290
316
                               (string_to_delta(options.
291
317
                                                approval_duration)),
292
318
                               dbus_interface=dbus.PROPERTIES_IFACE)
293
319
                if options.timeout:
294
 
                    client.Set(client_interface, u"Timeout",
 
320
                    client.Set(client_interface, "Timeout",
295
321
                               timedelta_to_milliseconds
296
322
                               (string_to_delta(options.timeout)),
297
323
                               dbus_interface=dbus.PROPERTIES_IFACE)
298
324
                if options.secret:
299
 
                    client.Set(client_interface, u"Secret",
 
325
                    client.Set(client_interface, "Secret",
300
326
                               dbus.ByteArray(open(options.secret,
301
 
                                                   u'rb').read()),
 
327
                                                   "rb").read()),
302
328
                               dbus_interface=dbus.PROPERTIES_IFACE)
303
329
                if options.approved_by_default is not None:
304
 
                    client.Set(client_interface, u"ApprovedByDefault",
 
330
                    client.Set(client_interface, "ApprovedByDefault",
305
331
                               dbus.Boolean(options
306
332
                                            .approved_by_default),
307
333
                               dbus_interface=dbus.PROPERTIES_IFACE)
312
338
                    client.Approve(dbus.Boolean(False),
313
339
                                   dbus_interface=client_interface)
314
340
 
315
 
if __name__ == '__main__':
 
341
if __name__ == "__main__":
316
342
    main()