/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk
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
#!/usr/bin/python

import SocketServer
import socket
import select
from optparse import OptionParser
import datetime
import errno
import gnutls.crypto
import gnutls.connection
import gnutls.errors
import ConfigParser
import sys
import re
import os
import signal

class Client(object):
    def __init__(self, name=None, options=None, dn=None,
                 password=None, passfile=None, fqdn=None,
                 timeout=None, interval=-1):
        self.name = name
        self.dn = dn
        if password:
            self.password = password
        elif passfile:
            self.password = open(passfile).readall()
        else:
            print "No Password or Passfile in client config file"
            # raise RuntimeError XXX
            self.password = "gazonk"
        self.fqdn = fqdn                # string
        self.created = datetime.datetime.now()
        self.last_seen = None           # datetime.datetime()
        if timeout is None:
            timeout = options.timeout
        self.timeout = timeout          # datetime.timedelta()
        if interval == -1:
            interval = options.interval
        self.interval = interval        # datetime.timedelta()
        self.next_check = datetime.datetime.now() # datetime.datetime()
        self.checker = None             # or a subprocess.Popen()
    def check_action(self, now=None):
        """The checker said something and might have completed.
        Check if is has, and take appropriate actions."""
        if self.checker.poll() is None:
            # False alarm, no result yet
            #self.checker.read()
            return
        if now is None:
            now = datetime.datetime.now()
        if self.checker.returncode == 0:
            self.last_seen = now
        while self.next_check <= now:
            self.next_check += self.interval
    handle_request = check_action
    def start_checker(self):
        self.stop_checker()
        try:
            self.checker = subprocess.Popen("sleep 1; fping -q -- %s"
                                            % re.escape(self.fqdn),
                                            stdout=subprocess.PIPE,
                                            close_fds=True,
                                            shell=True, cwd="/")
        except subprocess.OSError, e:
            print "Failed to start subprocess:", e
    def stop_checker(self):
        if self.checker is None:
            return
        os.kill(self.checker.pid, signal.SIGTERM)
        if self.checker.poll() is None:
            os.kill(self.checker.pid, signal.SIGKILL)
        self.checker = None
    __del__ = stop_checker
    def fileno(self):
        if self.checker is None:
            return None
        return self.checker.stdout.fileno()
    def next_stop(self):
        """The time when something must be done about this client"""
        return min(self.last_seen + self.timeout, self.next_check)
    def still_valid(self, now=None):
        """Has this client's timeout not passed?"""
        if now is None:
            now = datetime.datetime.now()
        return now < (self.last_seen + timeout)
    def it_is_time_to_check(self, now=None):
        if now is None:
            now = datetime.datetime.now()
        return self.next_check <= now


class server_metaclass(type):
    "Common behavior for the UDP and TCP server classes"
    def __new__(cls, name, bases, attrs):
        attrs["address_family"] = socket.AF_INET6
        attrs["allow_reuse_address"] = True
        def server_bind(self):
            if self.options.interface:
                if not hasattr(socket, "SO_BINDTODEVICE"):
                    # From /usr/include/asm-i486/socket.h
                    socket.SO_BINDTODEVICE = 25
                try:
                    self.socket.setsockopt(socket.SOL_SOCKET,
                                           socket.SO_BINDTODEVICE,
                                           self.options.interface)
                except socket.error, error:
                    if error[0] == errno.EPERM:
                        print "Warning: No permission to bind to interface", \
                              self.options.interface
                    else:
                        raise error
            return super(type(self), self).server_bind()
        attrs["server_bind"] = server_bind
        def init(self, *args, **kwargs):
            if "options" in kwargs:
                self.options = kwargs["options"]
                del kwargs["options"]
            if "clients" in kwargs:
                self.clients = kwargs["clients"]
                del kwargs["clients"]
            if "credentials" in kwargs:
                self.credentials = kwargs["credentials"]
                del kwargs["credentials"]
            return super(type(self), self).__init__(*args, **kwargs)
        attrs["__init__"] = init
        return type.__new__(cls, name, bases, attrs)


class udp_handler(SocketServer.DatagramRequestHandler, object):
    def handle(self):
        self.wfile.write("Polo")
        print "UDP request answered"


class IPv6_UDPServer(SocketServer.UDPServer, object):
    __metaclass__ = server_metaclass
    def verify_request(self, request, client_address):
        print "UDP request came"
        return request[0] == "Marco"


class tcp_handler(SocketServer.BaseRequestHandler, object):
    def handle(self):
        print "TCP request came"
        print "Request:", self.request
        print "Client Address:", self.client_address
        print "Server:", self.server
        session = gnutls.connection.ServerSession(self.request,
                                                  self.server.credentials)
        session.handshake()
        if session.peer_certificate:
            print "DN:", session.peer_certificate.subject
        try:
            session.verify_peer()
        except gnutls.errors.CertificateError, error:
            print "Verify failed", error
            session.bye()
            return
        try:
            session.send(dict((client.dn, client.password)
                              for client in self.server.clients)
                         [session.peer_certificate.subject])
        except KeyError:
            session.send("gazonk")
            # Log maybe? XXX
        session.bye()


class IPv6_TCPServer(SocketServer.ForkingTCPServer, object):
    __metaclass__ = server_metaclass
    request_queue_size = 1024


in6addr_any = "::"

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)
    """
    try:
        suffix=unicode(interval[-1])
        value=int(interval[:-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
    return delta


def main():
    parser = OptionParser()
    parser.add_option("-i", "--interface", type="string",
                      default="eth0", metavar="IF",
                      help="Interface to bind to")
    parser.add_option("--cert", type="string", default="cert.pem",
                      metavar="FILE",
                      help="Public key certificate to use")
    parser.add_option("--key", type="string", default="key.pem",
                      metavar="FILE",
                      help="Private key to use")
    parser.add_option("--ca", type="string", default="ca.pem",
                      metavar="FILE",
                      help="Certificate Authority certificate to use")
    parser.add_option("--crl", type="string", default="crl.pem",
                      metavar="FILE",
                      help="Certificate Revokation List to use")
    parser.add_option("-p", "--port", type="int", default=49001,
                      help="Port number to receive requests on")
    parser.add_option("--dh", type="int", metavar="BITS",
                      help="DH group to use")
    parser.add_option("-t", "--timeout", type="string", # Parsed later
                      default="15m",
                      help="Amount of downtime allowed for clients")
    parser.add_option("--interval", type="string", # Parsed later
                      default="5m",
                      help="How often to check that a client is up")
    parser.add_option("--check", action="store_true", default=False,
                      help="Run self-test")
    (options, args) = parser.parse_args()

    if options.check:
        import doctest
        doctest.testmod()
        sys.exit()
    
    # Parse the time arguments
    try:
        options.timeout = string_to_delta(options.timeout)
    except ValueError:
        parser.error("option --timeout: Unparseable time")
    
    try:
        options.interval = string_to_delta(options.interval)
    except ValueError:
        parser.error("option --interval: Unparseable time")
    
    cert = gnutls.crypto.X509Certificate(open(options.cert).read())
    key = gnutls.crypto.X509PrivateKey(open(options.key).read())
    ca = gnutls.crypto.X509Certificate(open(options.ca).read())
    crl = gnutls.crypto.X509CRL(open(options.crl).read())
    cred = gnutls.connection.X509Credentials(cert, key, [ca], [crl])
    
    # Parse config file
    defaults = {}
    client_config_object = ConfigParser.SafeConfigParser(defaults)
    client_config_object.read("mandos-clients.conf")
    clients = [Client(name=section, options=options,
                      **(dict(client_config_object.items(section))))
               for section in client_config_object.sections()]
    
    udp_server = IPv6_UDPServer((in6addr_any, options.port),
                                udp_handler,
                                options=options)
    
    tcp_server = IPv6_TCPServer((in6addr_any, options.port),
                                tcp_handler,
                                options=options,
                                clients=clients,
                                credentials=cred)
    
    while True:
        try:
            input, out, err = select.select((udp_server,
                                             tcp_server), (), ())
            if not input:
                pass
            else:
                for obj in input:
                    obj.handle_request()
        except KeyboardInterrupt:
            break
    
    # Cleanup here
    for client in clients:
        client.stop_checker()


if __name__ == "__main__":
    main()