/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#!/usr/bin/python
# -*- mode: python; coding: utf-8 -*-
# 
# Mandos Monitor - Control and monitor the Mandos server
# 
# Copyright © 2008-2010 Teddy Hogeborn
# Copyright © 2008-2010 Björn Påhlsson
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 
# Contact the authors at <mandos@fukt.bsnet.se>.
# 

from __future__ import division
import sys
import dbus
from optparse import OptionParser
import locale
import datetime
import re
import os

locale.setlocale(locale.LC_ALL, u"")

tablewords = {
    u"Name": u"Name",
    u"Enabled": u"Enabled",
    u"Timeout": u"Timeout",
    u"LastCheckedOK": u"Last Successful Check",
    u"LastApprovalRequest": u"Last Approval Request",
    u"Created": u"Created",
    u"Interval": u"Interval",
    u"Host": u"Host",
    u"Fingerprint": u"Fingerprint",
    u"CheckerRunning": u"Check Is Running",
    u"LastEnabled": u"Last Enabled",
    u"ApprovalPending": u"Approval Is Pending",
    u"ApprovedByDefault": u"Approved By Default",
    u"ApprovalDelay": u"Approval Delay",
    u"ApprovalDuration": u"Approval Duration",
    u"Checker": u"Checker",
    }
defaultkeywords = (u"Name", u"Enabled", u"Timeout", u"LastCheckedOK")
domain = u"se.bsnet.fukt"
busname = domain + u".Mandos"
server_path = u"/"
server_interface = domain + u".Mandos"
client_interface = domain + u".Mandos.Client"
version = u"1.2.3"

def timedelta_to_milliseconds(td):
    """Convert a datetime.timedelta object to milliseconds"""
    return ((td.days * 24 * 60 * 60 * 1000)
            + (td.seconds * 1000)
            + (td.microseconds // 1000))

def milliseconds_to_string(ms):
    td = datetime.timedelta(0, 0, 0, ms)
    return (u"%(days)s%(hours)02d:%(minutes)02d:%(seconds)02d"
            % { u"days": u"%dT" % td.days if td.days else u"",
                u"hours": td.seconds // 3600,
                u"minutes": (td.seconds % 3600) // 60,
                u"seconds": td.seconds % 60,
                })


def string_to_delta(interval):
    """Parse a string and return a datetime.timedelta

    >>> string_to_delta("7d")
    datetime.timedelta(7)
    >>> string_to_delta("60s")
    datetime.timedelta(0, 60)
    >>> string_to_delta("60m")
    datetime.timedelta(0, 3600)
    >>> string_to_delta("24h")
    datetime.timedelta(1)
    >>> string_to_delta(u"1w")
    datetime.timedelta(7)
    >>> string_to_delta("5m 30s")
    datetime.timedelta(0, 330)
    """
    timevalue = datetime.timedelta(0)
    regexp = re.compile(u"\d+[dsmhw]")
    
    for s in regexp.findall(interval):
        try:
            suffix = unicode(s[-1])
            value = int(s[:-1])
            if suffix == u"d":
                delta = datetime.timedelta(value)
            elif suffix == u"s":
                delta = datetime.timedelta(0, value)
            elif suffix == u"m":
                delta = datetime.timedelta(0, 0, 0, 0, value)
            elif suffix == u"h":
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
            elif suffix == u"w":
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
            else:
                raise ValueError
        except (ValueError, IndexError):
            raise ValueError
        timevalue += delta
    return timevalue

def print_clients(clients, keywords):
    def valuetostring(value, keyword):
        if type(value) is dbus.Boolean:
            return u"Yes" if value else u"No"
        if keyword in (u"Timeout", u"Interval", u"ApprovalDelay",
                       u"ApprovalDuration"):
            return milliseconds_to_string(value)
        return unicode(value)
    
    # Create format string to print table rows
    format_string = u" ".join(u"%%-%ds" %
                              max(len(tablewords[key]),
                                  max(len(valuetostring(client[key],
                                                        key))
                                      for client in
                                      clients))
                              for key in keywords)
    # Print header line
    print format_string % tuple(tablewords[key] for key in keywords)
    for client in clients:
        print format_string % tuple(valuetostring(client[key], key)
                                    for key in keywords)

def has_actions(options):
    return any((options.enable,
                options.disable,
                options.bump_timeout,
                options.start_checker,
                options.stop_checker,
                options.is_enabled,
                options.remove,
                options.checker is not None,
                options.timeout is not None,
                options.interval is not None,
                options.approved_by_default is not None,
                options.approval_delay is not None,
                options.approval_duration is not None,
                options.host is not None,
                options.secret is not None,
                options.approve,
                options.deny))
        
def main():
	parser = OptionParser(version = u"%%prog %s" % version)
	parser.add_option(u"-a", u"--all", action=u"store_true",
	                  help=u"Select all clients")
	parser.add_option(u"-v", u"--verbose", action=u"store_true",
	                  help=u"Print all fields")
	parser.add_option(u"-e", u"--enable", action=u"store_true",
	                  help=u"Enable client")
	parser.add_option(u"-d", u"--disable", action=u"store_true",
	                  help=u"disable client")
	parser.add_option(u"-b", u"--bump-timeout", action=u"store_true",
	                  help=u"Bump timeout for client")
	parser.add_option(u"--start-checker", action=u"store_true",
	                  help=u"Start checker for client")
	parser.add_option(u"--stop-checker", action=u"store_true",
	                  help=u"Stop checker for client")
	parser.add_option(u"-V", u"--is-enabled", action=u"store_true",
	                  help=u"Check if client is enabled")
	parser.add_option(u"-r", u"--remove", action=u"store_true",
	                  help=u"Remove client")
	parser.add_option(u"-c", u"--checker", type=u"string",
	                  help=u"Set checker command for client")
	parser.add_option(u"-t", u"--timeout", type=u"string",
	                  help=u"Set timeout for client")
	parser.add_option(u"-i", u"--interval", type=u"string",
	                  help=u"Set checker interval for client")
        parser.add_option(u"--approve-by-default", action=u"store_true",
                          dest=u"approved_by_default",
                          help=u"Set client to be approved by default")
        parser.add_option(u"--deny-by-default", action=u"store_false",
                          dest=u"approved_by_default",
                          help=u"Set client to be denied by default")
        parser.add_option(u"--approval-delay", type=u"string",
                          help=u"Set delay before client approve/deny")
        parser.add_option(u"--approval-duration", type=u"string",
                          help=u"Set duration of one client approval")
	parser.add_option(u"-H", u"--host", type=u"string",
	                  help=u"Set host for client")
	parser.add_option(u"-s", u"--secret", type=u"string",
	                  help=u"Set password blob (file) for client")
	parser.add_option(u"-A", u"--approve", action=u"store_true",
	                  help=u"Approve any current client request")
	parser.add_option(u"-D", u"--deny", action=u"store_true",
	                  help=u"Deny any current client request")
	options, client_names = parser.parse_args()
        
        if has_actions(options) and not client_names and not options.all:
            parser.error(u"Options require clients names or --all.")
        if options.verbose and has_actions(options):
            parser.error(u"--verbose can only be used alone or with"
                         u" --all.")
        if options.all and not has_actions(options):
            parser.error(u"--all requires an action.")
        
        try:
            bus = dbus.SystemBus()
            mandos_dbus_objc = bus.get_object(busname, server_path)
        except dbus.exceptions.DBusException:
            print >> sys.stderr, u"Could not connect to Mandos server"
            sys.exit(1)
    
        mandos_serv = dbus.Interface(mandos_dbus_objc,
                                     dbus_interface = server_interface)

        #block stderr since dbus library prints to stderr
        null = os.open(os.path.devnull, os.O_RDWR)
        stderrcopy = os.dup(sys.stderr.fileno())
        os.dup2(null, sys.stderr.fileno())
        os.close(null)
        try:
            try:
                mandos_clients = mandos_serv.GetAllClientsWithProperties()
            finally:
                #restore stderr
                os.dup2(stderrcopy, sys.stderr.fileno())
                os.close(stderrcopy)
        except dbus.exceptions.DBusException, e:
            print >> sys.stderr, u"Access denied: Accessing mandos server through dbus."
            sys.exit(1)
            
	# Compile dict of (clients: properties) to process
	clients={}
        
        if options.all or not client_names:
            clients = dict((bus.get_object(busname, path), properties)
                           for path, properties in
                           mandos_clients.iteritems())
        else:
            for name in client_names:
                for path, client in mandos_clients.iteritems():
                    if client[u"Name"] == name:
                        client_objc = bus.get_object(busname, path)
                        clients[client_objc] = client
                        break
                else:
                    print >> sys.stderr, u"Client not found on server: %r" % name
                    sys.exit(1)
            
	if not has_actions(options) and clients:
	    if options.verbose:
	        keywords = (u"Name", u"Enabled", u"Timeout",
                            u"LastCheckedOK", u"Created", u"Interval",
                            u"Host", u"Fingerprint", u"CheckerRunning",
                            u"LastEnabled", u"ApprovalPending",
                            u"ApprovedByDefault",
                            u"LastApprovalRequest", u"ApprovalDelay",
                            u"ApprovalDuration", u"Checker")
            else:
                keywords = defaultkeywords
            
	    print_clients(clients.values(), keywords)
        else:
            # Process each client in the list by all selected options
            for client in clients:
                if options.remove:
                    mandos_serv.RemoveClient(client.__dbus_object_path__)
                if options.enable:
                    client.Enable(dbus_interface=client_interface)
                if options.disable:
                    client.Disable(dbus_interface=client_interface)
                if options.bump_timeout:
                    client.CheckedOK(dbus_interface=client_interface)
                if options.start_checker:
                    client.StartChecker(dbus_interface=client_interface)
                if options.stop_checker:
                    client.StopChecker(dbus_interface=client_interface)
                if options.is_enabled:
                    sys.exit(0 if client.Get(client_interface,
                                             u"Enabled",
                                             dbus_interface=dbus.PROPERTIES_IFACE)
                             else 1)
                if options.checker:
                    client.Set(client_interface, u"Checker", options.checker,
                               dbus_interface=dbus.PROPERTIES_IFACE)
                if options.host:
                    client.Set(client_interface, u"Host", options.host,
                               dbus_interface=dbus.PROPERTIES_IFACE)
                if options.interval:
                    client.Set(client_interface, u"Interval",
                               timedelta_to_milliseconds
                               (string_to_delta(options.interval)),
                               dbus_interface=dbus.PROPERTIES_IFACE)
                if options.approval_delay:
                    client.Set(client_interface, u"ApprovalDelay",
                               timedelta_to_milliseconds
                               (string_to_delta(options.
                                                approval_delay)),
                               dbus_interface=dbus.PROPERTIES_IFACE)
                if options.approval_duration:
                    client.Set(client_interface, u"ApprovalDuration",
                               timedelta_to_milliseconds
                               (string_to_delta(options.
                                                approval_duration)),
                               dbus_interface=dbus.PROPERTIES_IFACE)
                if options.timeout:
                    client.Set(client_interface, u"Timeout",
                               timedelta_to_milliseconds
                               (string_to_delta(options.timeout)),
                               dbus_interface=dbus.PROPERTIES_IFACE)
                if options.secret:
                    client.Set(client_interface, u"Secret",
                               dbus.ByteArray(open(options.secret,
                                                   u"rb").read()),
                               dbus_interface=dbus.PROPERTIES_IFACE)
                if options.approved_by_default is not None:
                    client.Set(client_interface, u"ApprovedByDefault",
                               dbus.Boolean(options
                                            .approved_by_default),
                               dbus_interface=dbus.PROPERTIES_IFACE)
                if options.approve:
                    client.Approve(dbus.Boolean(True),
                                   dbus_interface=client_interface)
                elif options.deny:
                    client.Approve(dbus.Boolean(False),
                                   dbus_interface=client_interface)

if __name__ == u"__main__":
    main()