summaryrefslogtreecommitdiffstats
path: root/custodia/httpd/server.py
blob: 8f02a782c44ae9a7f4851cdf58833444b6db72fb (plain)
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# Copyright (C) 2015  Custodia Project Contributors - see LICENSE file

import errno
import os
import shutil
import socket
import struct

import six

try:
    # pylint: disable=import-error
    from BaseHTTPServer import BaseHTTPRequestHandler
    from SocketServer import ForkingMixIn, UnixStreamServer
    from urlparse import urlparse, parse_qs
    from urllib import unquote
except ImportError:
    # pylint: disable=import-error,no-name-in-module
    from http.server import BaseHTTPRequestHandler
    from socketserver import ForkingMixIn, UnixStreamServer
    from urllib.parse import urlparse, parse_qs, unquote

from custodia import log


SO_PEERCRED = getattr(socket, 'SO_PEERCRED', 17)
SO_PEERSEC = getattr(socket, 'SO_PEERSEC', 31)
SELINUX_CONTEXT_LEN = 256
MAX_REQUEST_SIZE = 10 * 1024 * 1024  # For now limit body to 10MiB


class HTTPError(Exception):

    def __init__(self, code=None, message=None):
        self.code = code if code is not None else 500
        self.mesg = message
        errstring = '%d: %s' % (self.code, self.mesg)
        log.debug(errstring)
        super(HTTPError, self).__init__(errstring)


class ForkingLocalHTTPServer(ForkingMixIn, UnixStreamServer):

    """
    A forking HTTP Server.
    Each request runs into a forked server so that the whole environment
    is clean and isolated, and parallel requests cannot unintentionally
    influence one another.

    When a request is received it is parsed by the handler_class provided
    at server initialization.
    """

    server_string = "Custodia/0.1"
    allow_reuse_address = True
    socket_file = None

    def __init__(self, server_address, handler_class, config):
        UnixStreamServer.__init__(self, server_address, handler_class)
        if 'consumers' not in config:
            raise ValueError('Configuration does not provide any consumer')
        self.config = config
        if 'server_string' in self.config:
            self.server_string = self.config['server_string']
        self._auditlog = log.AuditLog(self.config)

    def server_bind(self):
        oldmask = os.umask(000)
        UnixStreamServer.server_bind(self)
        os.umask(oldmask)
        self.socket_file = self.socket.getsockname()


class LocalHTTPRequestHandler(BaseHTTPRequestHandler):

    """
    This request handler is a slight modification of BaseHTTPRequestHandler
    where the per-request handler is replaced.

    When a request comes in it is parsed and the 'request' dictionary is
    populated accordingly. Additionally a 'creds' structure is added to the
    request.

    The 'creds' structure contains the data retrieved via a call to
    getsockopt with the SO_PEERCRED option. This retrieves via kernel assist
    the uid,gid and pid of the process on the other side of the unix socket
    on which the request has been made. This can be used for authentication
    and/or authorization purposes.
    The 'creds' structure is further augmented with a 'context' option
    containing the Selinux Context string for the calling process, if
    available.

    after the request is parsed the server's pipeline() function is invoked
    in order to handle it. The pipeline() should return a response object,
    where te return 'code', the 'output' and 'headers' may be found.

    If no 'code' is present the request is assumed to be successful and a
    '200 OK' status code will be sent back to the client.

    The 'output' parameter can be a string or a file like object.

    The 'headers' objct must be a dictionary where keys are headers names.

    By default we assume HTTP1.0
    """

    protocol_version = "HTTP/1.0"

    def __init__(self, *args, **kwargs):
        BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
        self.requestline = ''
        self.request_version = ''
        self.command = ''
        self.raw_requestline = None
        self.close_connection = 0
        self.path = None
        self.query = None
        self.url = None
        self.body = None
        self.loginuid = None

    def version_string(self):
        return self.server.server_string

    def _get_loginuid(self, pid):
        loginuid = None
        try:
            with open("/proc/" + str(pid) + "/loginuid", "r") as f:
                loginuid = int(f.read(), 10)
        except IOError as e:
            if e.errno != errno.ENOENT:
                raise
        if loginuid == -1:
            loginuid = None
        return loginuid

    @property
    def peer_creds(self):
        creds = self.request.getsockopt(socket.SOL_SOCKET, SO_PEERCRED,
                                        struct.calcsize('3i'))
        pid, uid, gid = struct.unpack('3i', creds)
        try:
            creds = self.request.getsockopt(socket.SOL_SOCKET, SO_PEERSEC,
                                            SELINUX_CONTEXT_LEN)
            context = creds.decode('utf-8')
        except Exception as e:
            log.debug("Couldn't retrieve SELinux Context: (%s)" % str(e))
            context = None

        return {'pid': pid, 'uid': uid, 'gid': gid, 'context': context}

    def parse_request(self, *args, **kwargs):
        if not BaseHTTPRequestHandler.parse_request(self, *args, **kwargs):
            return False

        # grab the loginuid from `/proc` as soon as possible
        creds = self.peer_creds
        self.loginuid = self._get_loginuid(creds['pid'])

        # after basic parsing also use urlparse to retrieve individual
        # elements of a request.
        url = urlparse(self.path)

        # Yes, override path with the path part only
        self.path = unquote(url.path)

        # Create dict out of query
        self.query = parse_qs(url.query)

        # keep the rest into the 'url' element in case someone needs it
        self.url = url

        return True

    def parse_body(self):
        length = int(self.headers.get('content-length', 0))
        if length > MAX_REQUEST_SIZE:
            raise HTTPError(413)
        if length == 0:
            self.body = None
        else:
            self.body = self.rfile.read(length)

    def handle_one_request(self):
        # Set a fake client address to make log functions happy
        self.client_address = ['127.0.0.1', 0]
        try:
            if not self.server.config:
                self.close_connection = 1
                return
            self.raw_requestline = self.rfile.readline(65537)
            if not self.raw_requestline:
                self.close_connection = 1
                return
            if len(self.raw_requestline) > 65536:
                self.requestline = ''
                self.request_version = ''
                self.command = ''
                self.send_error(414)
                self.wfile.flush()
                return
            if not self.parse_request():
                self.close_connection = 1
                return
            try:
                self.parse_body()
            except HTTPError as e:
                self.send_error(e.code, e.mesg)
                self.wfile.flush()
                return
            request = {'creds': self.peer_creds,
                       'command': self.command,
                       'path': self.path,
                       'query': self.query,
                       'url': self.url,
                       'version': self.request_version,
                       'headers': self.headers,
                       'body': self.body}
            try:
                response = self.pipeline(self.server.config, request)
                if response is None:
                    raise HTTPError(500)
            except HTTPError as e:
                self.send_error(e.code, e.mesg)
                self.wfile.flush()
                return
            except socket.timeout as e:
                self.log_error("Request timed out: %r", e)
                self.close_connection = 1
                return
            except Exception as e:  # pylint: disable=broad-except
                self.log_error("Handler failed: %r", e)
                self.log_traceback()
                self.send_error(500)
                self.wfile.flush()
                return
            self.send_response(response.get('code', 200))
            for header, value in six.iteritems(response.get('headers', {})):
                self.send_header(header, value)
            self.end_headers()
            output = response.get('output', None)
            if hasattr(output, 'read'):
                shutil.copyfileobj(output, self.wfile)
                output.close()
            elif output is not None:
                self.wfile.write(str(output).encode('utf-8'))
            else:
                self.close_connection = 1
            self.wfile.flush()
            return
        except socket.timeout as e:
            self.log_error("Request timed out: %r", e)
            self.close_connection = 1
            return

    def log_traceback(self):
        self.log_error('Traceback:\n%s' % log.stacktrace())

    def pipeline(self, config, request):
        """
        The pipeline() function handles authentication and invocation of
        the correct consumer based on the server configuration, that is
        provided at initialization time.

        When authentication is performed all the authenticators are
        executed. If any returns False, authentication fails and a 403
        error is raised. If none of them positively succeeds and they all
        return None then also authentication fails and a 403 error is
        raised. Authentication plugins can add attributes to the request
        object for use of authorization or other plugins.

        When authorization is performed and positive result will cause the
        operation to be accepted and any negative result will cause it to
        fail. If no authorization plugin returns a positive result a 403
        error is returned.

        Once authentication and authorization are successful the pipeline
        will parse the path component and find the consumer plugin that
        handles the provided path walking up the path component by
        component until a consumer is found.

        Paths are walked up from the leaf to the root, so if two consumers
        hang on the same tree, the one closer to the leaf will be used. If
        there is a trailing path when the conumer is selected then it will
        be stored in the request dicstionary named 'trail'. The 'trail' is
        an ordered list of the path components below the consumer entry
        point.
        """

        # auth framework here
        authers = config.get('authenticators')
        if authers is None:
            raise HTTPError(403)
        valid_once = False
        for auth in authers:
            valid = authers[auth].handle(request)
            if valid is False:
                raise HTTPError(403)
            elif valid is True:
                valid_once = True
        if valid_once is not True:
            self.server._auditlog.svc_access(log.AUDIT_SVC_AUTH_FAIL,
                                             request['creds']['pid'], "MAIN",
                                             'No auth')
            raise HTTPError(403)

        # auhz framework here
        authzers = config.get('authorizers')
        if authzers is None:
            raise HTTPError(403)
        for authz in authzers:
            valid = authzers[authz].handle(request)
            if valid is not None:
                break
        if valid is not True:
            self.server._auditlog.svc_access(log.AUDIT_SVC_AUTHZ_FAIL,
                                             request['creds']['pid'], "MAIN",
                                             request.get('path', '/'))
            raise HTTPError(403)

        # Select consumer
        path = request.get('path', '')
        if not os.path.isabs(path):
            raise HTTPError(400)

        trail = []
        while path != '':
            if path in config['consumers']:
                con = config['consumers'][path]
                if len(trail) != 0:
                    request['trail'] = trail
                return con.handle(request)
            if path == '/':
                path = ''
            else:
                head, tail = os.path.split(path)
                trail.insert(0, tail)
                path = head

        raise HTTPError(404)


class LocalHTTPServer(object):

    def __init__(self, address, config):
        if address[0] != '/':
            raise ValueError('Must use absolute unix socket name')
        if os.path.exists(address):
            os.remove(address)
        self.httpd = ForkingLocalHTTPServer(address, LocalHTTPRequestHandler,
                                            config)

    def get_socket(self):
        return (self.httpd.socket, self.httpd.socket_file)

    def serve(self):
        return self.httpd.serve_forever()