summaryrefslogtreecommitdiffstats
path: root/ipapython/ccache_storage.py
blob: f2de30152ca912516dd1930699f5e8946c937637 (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
#
# Copyright (C) 2017  FreeIPA Contributors see COPYING for license
#

import ctypes
import os
import sys

import six


class KRB5Error(Exception):
    pass


PY3 = sys.version_info[0] == 3


try:
    LIBKRB5 = ctypes.CDLL('libkrb5.so.3')
except OSError as e:  # pragma: no cover
    LIBKRB5 = e
else:
    class c_text_p(ctypes.c_char_p):  # noqa
        """A c_char_p variant that can handle UTF-8 text"""
        @classmethod
        def from_param(cls, value):
            if value is None:
                return None
            if PY3 and isinstance(value, str):
                return value.encode('utf-8')
            elif not PY3 and isinstance(value, unicode):  # noqa
                return value.encode('utf-8')
            elif not isinstance(value, bytes):
                raise TypeError(value)
            else:
                return value

        @property
        def text(self):
            value = self.value
            if value is None:
                return None
            elif not isinstance(value, str):
                return value.decode('utf-8')
            return value

    class _krb5_context(ctypes.Structure):  # noqa
        """krb5/krb5.h struct _krb5_context"""
        __slots__ = ()
        _fields_ = []

    class _krb5_ccache(ctypes.Structure):  # noqa
        """krb5/krb5.h struct _krb5_ccache"""
        __slots__ = ()
        _fields_ = []

    class _krb5_data(ctypes.Structure):  # noqa
        """krb5/krb5.h struct _krb5_data"""
        __slots__ = ()
        _fields_ = [
            ("magic", ctypes.c_int32),
            ("length", ctypes.c_uint),
            ("data", ctypes.c_char_p),
        ]

    class krb5_principal_data(ctypes.Structure):  # noqa
        """krb5/krb5.h struct krb5_principal_data"""
        __slots__ = ()
        _fields_ = []

    def krb5_errcheck(result, func, arguments):
        """Error checker for krb5_error return value"""
        if result != 0:
            raise KRB5Error(result, func.__name__, arguments)

    krb5_principal = ctypes.POINTER(krb5_principal_data)
    krb5_context = ctypes.POINTER(_krb5_context)
    krb5_ccache = ctypes.POINTER(_krb5_ccache)
    krb5_data_p = ctypes.POINTER(_krb5_data)
    krb5_error = ctypes.c_int32

    krb5_init_context = LIBKRB5.krb5_init_context
    krb5_init_context.argtypes = (ctypes.POINTER(krb5_context), )
    krb5_init_context.restype = krb5_error
    krb5_init_context.errcheck = krb5_errcheck

    krb5_free_context = LIBKRB5.krb5_free_context
    krb5_free_context.argtypes = (krb5_context, )
    krb5_free_context.retval = None

    krb5_free_principal = LIBKRB5.krb5_free_principal
    krb5_free_principal.argtypes = (krb5_context, krb5_principal)
    krb5_free_principal.retval = None

    krb5_free_data_contents = LIBKRB5.krb5_free_data_contents
    krb5_free_data_contents.argtypes = (krb5_context, krb5_data_p)
    krb5_free_data_contents.retval = None

    krb5_cc_default = LIBKRB5.krb5_cc_default
    krb5_cc_default.argtypes = (krb5_context, ctypes.POINTER(krb5_ccache), )
    krb5_cc_default.restype = krb5_error
    krb5_cc_default.errcheck = krb5_errcheck

    krb5_cc_close = LIBKRB5.krb5_cc_close
    krb5_cc_close.argtypes = (krb5_context, krb5_ccache, )
    krb5_cc_close.retval = krb5_error
    krb5_cc_close.errcheck = krb5_errcheck

    krb5_parse_name = LIBKRB5.krb5_parse_name
    krb5_parse_name.argtypes = (krb5_context, ctypes.c_char_p,
                                ctypes.POINTER(krb5_principal), )
    krb5_parse_name.retval = krb5_error
    krb5_parse_name.errcheck = krb5_errcheck

    krb5_cc_set_config = LIBKRB5.krb5_cc_set_config
    krb5_cc_set_config.argtypes = (krb5_context, krb5_ccache, krb5_principal,
                                   ctypes.c_char_p, krb5_data_p, )
    krb5_cc_set_config.retval = krb5_error
    krb5_cc_set_config.errcheck = krb5_errcheck

    krb5_cc_get_config = LIBKRB5.krb5_cc_get_config
    krb5_cc_get_config.argtypes = (krb5_context, krb5_ccache, krb5_principal,
                                   ctypes.c_char_p, krb5_data_p, )
    krb5_cc_get_config.retval = krb5_error
    krb5_cc_get_config.errcheck = krb5_errcheck

class session_store:
    def __init__(self, name='X-IPA-Session-Cookie'):
        self.__context = None
        if isinstance(LIBKRB5, Exception):  # pragma: no cover
            raise LIBKRB5
        context = krb5_context()
        krb5_init_context(ctypes.byref(context))
        self.__context = context

        self._hidden_cred_name = name

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        if self.__context:
            krb5_free_context(self.__context)
            self.__context = None

    def __del__(self):
        self.__exit__(None, None, None)

    def store_cookie(self, client, value):
        """
        Stores the session cookie in a hidden ccache entry.
        """
        assert isinstance(client, six.string_types)
        assert isinstance(value, bytes)

        principal = ccache = None

        try:
            principal = krb5_principal()
            krb5_parse_name(self.__context, ctypes.c_char_p(client),
                            ctypes.byref(principal))

            ccache = krb5_ccache()
            krb5_cc_default(self.__context, ctypes.byref(ccache))

            buf = ctypes.create_string_buffer(value)
            data = _krb5_data()
            data.data = buf.value
            data.length = len(buf)
            krb5_cc_set_config(self.__context, ccache, principal,
                               self._hidden_cred_name, ctypes.byref(data))

        finally:
            if principal:
                krb5_free_principal(self.__context, principal)
            if ccache:
                krb5_cc_close(self.__context, ccache)

    def get_cookie(self, client):
        """
        Gets the session cookie in a hidden ccache entry.
        """
        assert isinstance(client, six.string_types)

        principal = ccache = data = None

        try:
            principal = krb5_principal()
            krb5_parse_name(self.__context, ctypes.c_char_p(client),
                            ctypes.byref(principal))

            ccache = krb5_ccache()
            krb5_cc_default(self.__context, ctypes.byref(ccache))

            data = _krb5_data()
            krb5_cc_get_config(self.__context, ccache, principal,
                               self._hidden_cred_name, ctypes.byref(data))

            return str(data.data)

        finally:
            if principal:
                krb5_free_principal(self.__context, principal)
            if ccache:
                krb5_cc_close(self.__context, ccache)
            if data:
                krb5_free_data_contents(self.__context, data)

    def remove_cookie(self, client):
        """
        Stores the session cookie in a hidden ccache entry.
        """
        assert isinstance(client, six.string_types)

        principal = ccache = None

        try:
            principal = krb5_principal()
            krb5_parse_name(self.__context, ctypes.c_char_p(client),
                            ctypes.byref(principal))

            ccache = krb5_ccache()
            krb5_cc_default(self.__context, ctypes.byref(ccache))

            krb5_cc_set_config(self.__context, ccache, principal,
                               self._hidden_cred_name, None)

        finally:
            if principal:
                krb5_free_principal(self.__context, principal)
            if ccache:
                krb5_cc_close(self.__context, ccache)