/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: 2011-02-15 19:27:23 UTC
  • mto: This revision was merged to the branch mainline in revision 465.
  • Revision ID: teddy@fukt.bsnet.se-20110215192723-qpftjhlvzadm5cjc
* mandos-ctl: Use unicode string literals.

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, unicode_literals
 
26
 
5
27
import sys
6
28
import dbus
7
29
from optparse import OptionParser
10
32
import re
11
33
import os
12
34
 
13
 
locale.setlocale(locale.LC_ALL, u'')
 
35
locale.setlocale(locale.LC_ALL, "")
14
36
 
15
37
tablewords = {
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',
 
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",
27
54
    }
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"
 
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"
35
62
 
36
63
def timedelta_to_milliseconds(td):
37
 
    "Convert a datetime.timedelta object to milliseconds"
 
64
    """Convert a datetime.timedelta object to milliseconds"""
38
65
    return ((td.days * 24 * 60 * 60 * 1000)
39
66
            + (td.seconds * 1000)
40
67
            + (td.microseconds // 1000))
41
68
 
42
69
def milliseconds_to_string(ms):
43
70
    td = datetime.timedelta(0, 0, 0, ms)
44
 
    return (u"%(days)s%(hours)02d:%(minutes)02d:%(seconds)02d"
 
71
    return ("%(days)s%(hours)02d:%(minutes)02d:%(seconds)02d"
45
72
            % { "days": "%dT" % td.days if td.days else "",
46
73
                "hours": td.seconds // 3600,
47
74
                "minutes": (td.seconds % 3600) // 60,
52
79
def string_to_delta(interval):
53
80
    """Parse a string and return a datetime.timedelta
54
81
 
55
 
    >>> string_to_delta('7d')
 
82
    >>> string_to_delta("7d")
56
83
    datetime.timedelta(7)
57
 
    >>> string_to_delta('60s')
 
84
    >>> string_to_delta("60s")
58
85
    datetime.timedelta(0, 60)
59
 
    >>> string_to_delta('60m')
 
86
    >>> string_to_delta("60m")
60
87
    datetime.timedelta(0, 3600)
61
 
    >>> string_to_delta('24h')
 
88
    >>> string_to_delta("24h")
62
89
    datetime.timedelta(1)
63
 
    >>> string_to_delta(u'1w')
 
90
    >>> string_to_delta("1w")
64
91
    datetime.timedelta(7)
65
 
    >>> string_to_delta('5m 30s')
 
92
    >>> string_to_delta("5m 30s")
66
93
    datetime.timedelta(0, 330)
67
94
    """
68
95
    timevalue = datetime.timedelta(0)
72
99
        try:
73
100
            suffix = unicode(s[-1])
74
101
            value = int(s[:-1])
75
 
            if suffix == u"d":
 
102
            if suffix == "d":
76
103
                delta = datetime.timedelta(value)
77
 
            elif suffix == u"s":
 
104
            elif suffix == "s":
78
105
                delta = datetime.timedelta(0, value)
79
 
            elif suffix == u"m":
 
106
            elif suffix == "m":
80
107
                delta = datetime.timedelta(0, 0, 0, 0, value)
81
 
            elif suffix == u"h":
 
108
            elif suffix == "h":
82
109
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
83
 
            elif suffix == u"w":
 
110
            elif suffix == "w":
84
111
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
85
112
            else:
86
113
                raise ValueError
92
119
def print_clients(clients, keywords):
93
120
    def valuetostring(value, keyword):
94
121
        if type(value) is dbus.Boolean:
95
 
            return u"Yes" if value else u"No"
96
 
        if keyword in (u"Timeout", u"Interval"):
 
122
            return "Yes" if value else "No"
 
123
        if keyword in ("Timeout", "Interval", "ApprovalDelay",
 
124
                       "ApprovalDuration"):
97
125
            return milliseconds_to_string(value)
98
126
        return unicode(value)
99
127
    
100
128
    # Create format string to print table rows
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)
 
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)
108
136
    # Print header line
109
137
    print format_string % tuple(tablewords[key] for key in keywords)
110
138
    for client in clients:
122
150
                options.checker is not None,
123
151
                options.timeout is not None,
124
152
                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,
125
156
                options.host is not None,
126
157
                options.secret is not None,
127
158
                options.approve,
153
184
                          help="Set timeout for client")
154
185
        parser.add_option("-i", "--interval", type="string",
155
186
                          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")
156
197
        parser.add_option("-H", "--host", type="string",
157
198
                          help="Set host for client")
158
199
        parser.add_option("-s", "--secret", type="string",
164
205
        options, client_names = parser.parse_args()
165
206
        
166
207
        if has_actions(options) and not client_names and not options.all:
167
 
            parser.error('Options requires clients names or --all.')
 
208
            parser.error("Options require clients names or --all.")
168
209
        if options.verbose and has_actions(options):
169
 
            parser.error('Verbose option can only be used alone or with --all.')
 
210
            parser.error("--verbose can only be used alone or with"
 
211
                         " --all.")
170
212
        if options.all and not has_actions(options):
171
 
            parser.error('--all requires an action')
172
 
            
 
213
            parser.error("--all requires an action.")
 
214
        
173
215
        try:
174
216
            bus = dbus.SystemBus()
175
217
            mandos_dbus_objc = bus.get_object(busname, server_path)
206
248
        else:
207
249
            for name in client_names:
208
250
                for path, client in mandos_clients.iteritems():
209
 
                    if client['Name'] == name:
 
251
                    if client["Name"] == name:
210
252
                        client_objc = bus.get_object(busname, path)
211
253
                        clients[client_objc] = client
212
254
                        break
216
258
            
217
259
        if not has_actions(options) and clients:
218
260
            if options.verbose:
219
 
                keywords = ('Name', 'Enabled', 'Timeout', 'LastCheckedOK',
220
 
                            'Created', 'Interval', 'Host', 'Fingerprint',
221
 
                            'CheckerRunning', 'LastEnabled', 'Checker')
 
261
                keywords = ("Name", "Enabled", "Timeout",
 
262
                            "LastCheckedOK", "Created", "Interval",
 
263
                            "Host", "Fingerprint", "CheckerRunning",
 
264
                            "LastEnabled", "ApprovalPending",
 
265
                            "ApprovedByDefault",
 
266
                            "LastApprovalRequest", "ApprovalDelay",
 
267
                            "ApprovalDuration", "Checker")
222
268
            else:
223
269
                keywords = defaultkeywords
224
 
                
 
270
            
225
271
            print_clients(clients.values(), keywords)
226
272
        else:
227
273
            # Process each client in the list by all selected options
240
286
                    client.StopChecker(dbus_interface=client_interface)
241
287
                if options.is_enabled:
242
288
                    sys.exit(0 if client.Get(client_interface,
243
 
                                             u"Enabled",
 
289
                                             "Enabled",
244
290
                                             dbus_interface=dbus.PROPERTIES_IFACE)
245
291
                             else 1)
246
292
                if options.checker:
247
 
                    client.Set(client_interface, u"Checker", options.checker,
 
293
                    client.Set(client_interface, "Checker", options.checker,
248
294
                               dbus_interface=dbus.PROPERTIES_IFACE)
249
295
                if options.host:
250
 
                    client.Set(client_interface, u"Host", options.host,
 
296
                    client.Set(client_interface, "Host", options.host,
251
297
                               dbus_interface=dbus.PROPERTIES_IFACE)
252
298
                if options.interval:
253
 
                    client.Set(client_interface, u"Interval",
 
299
                    client.Set(client_interface, "Interval",
254
300
                               timedelta_to_milliseconds
255
301
                               (string_to_delta(options.interval)),
256
302
                               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)
257
315
                if options.timeout:
258
 
                    client.Set(client_interface, u"Timeout",
259
 
                               timedelta_to_milliseconds(string_to_delta
260
 
                                                         (options.timeout)),
 
316
                    client.Set(client_interface, "Timeout",
 
317
                               timedelta_to_milliseconds
 
318
                               (string_to_delta(options.timeout)),
261
319
                               dbus_interface=dbus.PROPERTIES_IFACE)
262
320
                if options.secret:
263
 
                    client.Set(client_interface, u"Secret",
264
 
                               dbus.ByteArray(open(options.secret, u'rb').read()),
 
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),
265
329
                               dbus_interface=dbus.PROPERTIES_IFACE)
266
330
                if options.approve:
267
 
                    client.Approve(dbus.Boolean(True), dbus_interface=client_interface)
268
 
                if options.deny:
269
 
                    client.Approve(dbus.Boolean(False), dbus_interface=client_interface)
 
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)
270
336
 
271
 
if __name__ == '__main__':
 
337
if __name__ == "__main__":
272
338
    main()