/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release
24.1.116 by Björn Påhlsson
added a mandos list client program
1
#!/usr/bin/python
237.2.3 by Teddy Hogeborn
Merge "mandos-list" from belorn.
2
# -*- mode: python; coding: utf-8 -*-
24.1.116 by Björn Påhlsson
added a mandos list client program
3
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
4
from __future__ import division
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
5
import sys
24.1.116 by Björn Påhlsson
added a mandos list client program
6
import dbus
7
from optparse import OptionParser
237.2.3 by Teddy Hogeborn
Merge "mandos-list" from belorn.
8
import locale
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
9
import datetime
10
import re
237.2.3 by Teddy Hogeborn
Merge "mandos-list" from belorn.
11
12
locale.setlocale(locale.LC_ALL, u'')
24.1.116 by Björn Påhlsson
added a mandos list client program
13
14
tablewords = {
237.2.3 by Teddy Hogeborn
Merge "mandos-list" from belorn.
15
    'name': u'Name',
16
    'enabled': u'Enabled',
17
    'timeout': u'Timeout',
18
    'last_checked_ok': u'Last Successful Check',
19
    'created': u'Created',
20
    'interval': u'Interval',
21
    'host': u'Host',
22
    'fingerprint': u'Fingerprint',
23
    'checker_running': u'Check Is Running',
24
    'last_enabled': u'Last Enabled',
25
    'checker': u'Checker',
24.1.116 by Björn Påhlsson
added a mandos list client program
26
    }
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
27
defaultkeywords = ('name', 'enabled', 'timeout', 'last_checked_ok',
28
                   'checker')
24.1.130 by Björn Påhlsson
new domain name for d-bus
29
domain = 'se.bsnet.fukt'
30
busname = domain + '.Mandos'
31
server_path = '/'
32
server_interface = domain + '.Mandos'
33
client_interface = domain + '.Mandos.Client'
267 by Teddy Hogeborn
* Makefile (version): Changed to "1.0.13".
34
version = "1.0.13"
24.1.118 by Björn Påhlsson
Added enable/disable
35
bus = dbus.SystemBus()
36
mandos_dbus_objc = bus.get_object(busname, server_path)
37
mandos_serv = dbus.Interface(mandos_dbus_objc,
38
                             dbus_interface = server_interface)
39
mandos_clients = mandos_serv.GetAllClientsWithProperties()
40
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
41
def datetime_to_milliseconds(dt):
42
    "Return the 'timeout' attribute in milliseconds"
43
    return ((dt.days * 24 * 60 * 60 * 1000)
44
            + (dt.seconds * 1000)
45
            + (dt.microseconds // 1000))
46
47
def milliseconds_to_string(ms):
48
    td = datetime.timedelta(0, 0, 0, ms)
49
    return "%s%02d:%02d:%02d" % (("%dT" % td.days) if td.days else "", # days
50
                           td.seconds // 3600,        # hours
51
                           (td.seconds % 3600) // 60, # minutes
52
                           (td.seconds % 60))         # seconds
53
54
55
def string_to_delta(interval):
56
    """Parse a string and return a datetime.timedelta
57
58
    >>> string_to_delta('7d')
59
    datetime.timedelta(7)
60
    >>> string_to_delta('60s')
61
    datetime.timedelta(0, 60)
62
    >>> string_to_delta('60m')
63
    datetime.timedelta(0, 3600)
64
    >>> string_to_delta('24h')
65
    datetime.timedelta(1)
66
    >>> string_to_delta(u'1w')
67
    datetime.timedelta(7)
68
    >>> string_to_delta('5m 30s')
69
    datetime.timedelta(0, 330)
70
    """
71
    timevalue = datetime.timedelta(0)
72
    regexp = re.compile("\d+[dsmhw]")
73
    
74
    for s in regexp.findall(interval):
75
        try:
76
            suffix = unicode(s[-1])
77
            value = int(s[:-1])
78
            if suffix == u"d":
79
                delta = datetime.timedelta(value)
80
            elif suffix == u"s":
81
                delta = datetime.timedelta(0, value)
82
            elif suffix == u"m":
83
                delta = datetime.timedelta(0, 0, 0, 0, value)
84
            elif suffix == u"h":
85
                delta = datetime.timedelta(0, 0, 0, 0, 0, value)
86
            elif suffix == u"w":
87
                delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value)
88
            else:
89
                raise ValueError
90
        except (ValueError, IndexError):
91
            raise ValueError
92
        timevalue += delta
93
    return timevalue
94
95
def print_clients(clients):
96
    def valuetostring(value, keyword):
97
        if type(value) is dbus.Boolean:
98
            return u"Yes" if value else u"No"
99
        if keyword in ("timeout", "interval"):
100
            return milliseconds_to_string(value)
101
        return unicode(value)
102
    
24.1.118 by Björn Påhlsson
Added enable/disable
103
    format_string = u' '.join(u'%%-%ds' %
104
                              max(len(tablewords[key]),
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
105
                                  max(len(valuetostring(client[key], key))
24.1.118 by Björn Påhlsson
Added enable/disable
106
                                      for client in
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
107
                                      clients))
24.1.118 by Björn Påhlsson
Added enable/disable
108
                              for key in keywords)
237.2.118 by Teddy Hogeborn
* mandos: White-space fixes only.
109
    print format_string % tuple(tablewords[key] for key in keywords)
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
110
    for client in clients:
111
        print format_string % tuple(valuetostring(client[key], key)
24.1.118 by Björn Påhlsson
Added enable/disable
112
                                    for key in keywords)
113
24.1.116 by Björn Påhlsson
added a mandos list client program
114
parser = OptionParser(version = "%%prog %s" % version)
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
115
parser.add_option("-a", "--all", action="store_true",
237.2.3 by Teddy Hogeborn
Merge "mandos-list" from belorn.
116
                  help="Print all fields")
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
117
parser.add_option("-e", "--enable", action="store_true",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
118
                  help="Enable client")
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
119
parser.add_option("-d", "--disable", action="store_true",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
120
                  help="disable client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
121
parser.add_option("-b", "--bump-timeout", action="store_true",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
122
                  help="Bump timeout for client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
123
parser.add_option("--start-checker", action="store_true",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
124
                  help="Start checker for client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
125
parser.add_option("--stop-checker", action="store_true",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
126
                  help="Stop checker for client")
24.1.126 by Björn Påhlsson
small stuff
127
parser.add_option("-V", "--is-valid", action="store_true",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
128
                  help="Check if client is still valid")
129
parser.add_option("-r", "--remove", action="store_true",
130
                  help="Remove client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
131
parser.add_option("-c", "--checker", type="string",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
132
                  help="Set checker command for client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
133
parser.add_option("-t", "--timeout", type="string",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
134
                  help="Set timeout for client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
135
parser.add_option("-i", "--interval", type="string",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
136
                  help="Set checker interval for client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
137
parser.add_option("-H", "--host", type="string",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
138
                  help="Set host for client")
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
139
parser.add_option("-s", "--secret", type="string",
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
140
                  help="Set password blob (file) for client")
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
141
options, client_names = parser.parse_args()
142
237.2.54 by Teddy Hogeborn
Merge from Björn:
143
# Compile list of clients to process
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
144
clients=[]
145
for name in client_names:
146
    for path, client in mandos_clients.iteritems():
147
        if client['name'] == name:
148
            client_objc = bus.get_object(busname, path)
149
            clients.append(dbus.Interface(client_objc,
150
                                          dbus_interface
151
                                          = client_interface))
152
            break
153
    else:
154
        print >> sys.stderr, "Client not found on server: %r" % name
155
        sys.exit(1)
156
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
157
if not clients and mandos_clients.values():
24.1.116 by Björn Påhlsson
added a mandos list client program
158
    keywords = defaultkeywords
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
159
    if options.all:
160
        keywords = ('name', 'enabled', 'timeout', 'last_checked_ok',
161
                    'created', 'interval', 'host', 'fingerprint',
162
                    'checker_running', 'last_enabled', 'checker')
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
163
    print_clients(mandos_clients.values())
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
164
165
# Process each client in the list by all selected options
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
166
for client in clients:
24.1.128 by Björn Påhlsson
fixed a bugg in mandos-ctl + added remove client option
167
    if options.remove:
168
        mandos_serv.RemoveClient(client.__dbus_object_path__)
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
169
    if options.enable:
170
        client.Enable()
171
    if options.disable:
172
        client.Disable()
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
173
    if options.bump_timeout:
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
174
        client.BumpTimeout()
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
175
    if options.start_checker:
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
176
        client.StartChecker()
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
177
    if options.stop_checker:
24.1.119 by Björn Påhlsson
Added more method support for mandos clients through mandos-ctl
178
        client.StopChecker()
24.1.121 by Björn Påhlsson
mandos-ctl: Added support for all client calls
179
    if options.is_valid:
180
        sys.exit(0 if client.IsStillValid() else 1)
181
    if options.checker:
182
        client.SetChecker(options.checker)
183
    if options.host:
184
        client.SetHost(options.host)
185
    if options.interval:
186
        client.SetInterval(datetime_to_milliseconds
187
                           (string_to_delta(options.interval)))
188
    if options.timeout:
189
        client.SetTimeout(datetime_to_milliseconds
190
                          (string_to_delta(options.timeout)))
191
    if options.secret:
192
        client.SetSecret(dbus.ByteArray(open(options.secret, 'rb').read()))
193