source: mod_gnutls/src/gnutls_cache.c @ de1ceab

asynciodebian/mastermainproxy-ticket
Last change on this file since de1ceab was de1ceab, checked in by Fiona Klute <fiona.klute@…>, 5 years ago

Replace internal cache implementation with mod_socache

Massively simplifies mod_gnutls code, and using mod_socache_shmcb will
allow for extremely simple cache setup (no configuration needed as
long as the module is available, not implemented yet).

  • Property mode set to 100644
File size: 13.9 KB
Line 
1/*
2 *  Copyright 2004-2005 Paul Querna
3 *  Copyright 2008 Nikos Mavrogiannopoulos
4 *  Copyright 2011 Dash Shendy
5 *  Copyright 2015-2018 Fiona Klute
6 *
7 *  Licensed under the Apache License, Version 2.0 (the "License");
8 *  you may not use this file except in compliance with the License.
9 *  You may obtain a copy of the License at
10 *
11 *      http://www.apache.org/licenses/LICENSE-2.0
12 *
13 *  Unless required by applicable law or agreed to in writing, software
14 *  distributed under the License is distributed on an "AS IS" BASIS,
15 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 *  See the License for the specific language governing permissions and
17 *  limitations under the License.
18 */
19
20/**
21 * @file gnutls_cache.c
22 *
23 * The signatures of the `(dbm|mc)_cache_...()` functions may be a bit
24 * confusing: "store" and "expire" take a server_rec, "fetch" an
25 * mgs_handle_t, and "delete" the `void*` required for a
26 * `gnutls_db_remove_func`. The first two have matching `..._session`
27 * functions to fit their respective GnuTLS session cache signatures.
28 *
29 * This is because "store", "expire" (dbm only), and "fetch" are also
30 * needed for the OCSP cache. Their `..._session` variants have been
31 * created to take care of the session cache specific parts, mainly
32 * calculating the DB key from the session ID. They have to match the
33 * appropriate GnuTLS DB function signatures.
34 *
35 * Additionally, there are the `mc_cache_(store|fetch)_generic()`
36 * functions. They exist because memcached requires string keys while
37 * DBM accepts binary keys, and provide wrappers to turn binary keys
38 * into hex strings with a `mod_gnutls:` prefix.
39 *
40 * To update cached OCSP responses independent of client connections,
41 * "store" and "expire" have to work without a connection context. On
42 * the other hand "fetch" does not need to do that, because cached
43 * OCSP responses will be retrieved for use in client connections.
44 */
45
46#include "gnutls_cache.h"
47#include "mod_gnutls.h"
48#include "gnutls_config.h"
49
50#include <ap_socache.h>
51
52#if HAVE_APR_MEMCACHE
53#include "apr_memcache.h"
54#endif
55
56#include "apr_dbm.h"
57#include <apr_escape.h>
58
59#include "ap_mpm.h"
60#include <util_mutex.h>
61
62#include <unistd.h>
63#include <sys/types.h>
64
65#if !defined(OS2) && !defined(WIN32) && !defined(BEOS) && !defined(NETWARE)
66#include "unixd.h"
67#endif
68
69/** Default session cache timeout */
70#define MGS_DEFAULT_CACHE_TIMEOUT 300
71
72/** Prefix for keys used with a memcached cache */
73#define MC_TAG "mod_gnutls:"
74/** Maximum length of the hex string representation of a GnuTLS
75 * session ID: two characters per byte, plus one more for `\0` */
76#if GNUTLS_VERSION_NUMBER >= 0x030400
77#define GNUTLS_SESSION_ID_STRING_LEN ((GNUTLS_MAX_SESSION_ID_SIZE * 2) + 1)
78#else
79#define GNUTLS_SESSION_ID_STRING_LEN ((GNUTLS_MAX_SESSION_ID * 2) + 1)
80#endif
81
82#if MODULE_MAGIC_NUMBER_MAJOR < 20081201
83#define ap_unixd_config unixd_config
84#endif
85
86#ifdef APLOG_USE_MODULE
87APLOG_USE_MODULE(gnutls);
88#endif
89
90/**
91 * Turn a GnuTLS session ID into the key format we use with DBM
92 * caches. Name the Session ID as `server:port.SessionID` to disallow
93 * resuming sessions on different servers.
94 *
95 * @return `0` on success, `-1` on failure
96 */
97static int mgs_session_id2dbm(conn_rec *c, unsigned char *id, int idlen,
98                              gnutls_datum_t *dbmkey)
99{
100    char sz[GNUTLS_SESSION_ID_STRING_LEN];
101    apr_status_t rv = apr_escape_hex(sz, id, idlen, 0, NULL);
102    if (rv != APR_SUCCESS)
103        return -1;
104
105    char *newkey = apr_psprintf(c->pool, "%s:%d.%s",
106                                c->base_server->server_hostname,
107                                c->base_server->port, sz);
108    dbmkey->size = strlen(newkey);
109    /* signedness does not matter for arbitrary bits */
110    dbmkey->data = (unsigned char*) newkey;
111    return 0;
112}
113
114/** The OPENSSL_TIME_FORMAT macro and mgs_time2sz() serve to print
115 * time in a format compatible with OpenSSL's `ASN1_TIME_print()`
116 * function. */
117#define OPENSSL_TIME_FORMAT "%b %d %k:%M:%S %Y %Z"
118
119char *mgs_time2sz(time_t in_time, char *str, int strsize)
120{
121    apr_time_exp_t vtm;
122    apr_size_t ret_size;
123    apr_time_t t;
124
125
126    apr_time_ansi_put(&t, in_time);
127    apr_time_exp_gmt(&vtm, t);
128    apr_strftime(str, &ret_size, strsize - 1, OPENSSL_TIME_FORMAT, &vtm);
129
130    return str;
131}
132
133
134
135static int socache_store(server_rec *server, gnutls_datum_t key,
136                         gnutls_datum_t data, apr_time_t expiry)
137{
138    mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
139        ap_get_module_config(server->module_config, &gnutls_module);
140
141    apr_pool_t *spool;
142    apr_pool_create(&spool, NULL);
143
144    apr_global_mutex_lock(sc->cache->mutex);
145    apr_status_t rv = sc->cache->prov->store(sc->cache->socache, server,
146                                             key.data, key.size,
147                                             expiry,
148                                             data.data, data.size,
149                                             spool);
150    apr_global_mutex_unlock(sc->cache->mutex);
151
152    if (rv != APR_SUCCESS)
153    {
154        ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, server,
155                     "error storing in cache '%s:%s'",
156                     sc->cache->prov->name, sc->cache_config);
157        apr_pool_destroy(spool);
158        return -1;
159    }
160
161    ap_log_error(APLOG_MARK, APLOG_TRACE1, rv, server,
162                 "stored %u bytes of data (%u byte key) in cache '%s:%s'",
163                 data.size, key.size,
164                 sc->cache->prov->name, sc->cache_config);
165    apr_pool_destroy(spool);
166    return 0;
167}
168
169
170
171static int socache_store_session(void *baton, gnutls_datum_t key,
172                                 gnutls_datum_t data)
173{
174    mgs_handle_t *ctxt = baton;
175    gnutls_datum_t dbmkey;
176
177    if (mgs_session_id2dbm(ctxt->c, key.data, key.size, &dbmkey) < 0)
178        return -1;
179
180    apr_time_t expiry = apr_time_now() + ctxt->sc->cache_timeout;
181
182    return socache_store(ctxt->c->base_server, dbmkey, data, expiry);
183}
184
185
186
187// 4K should be enough for OCSP responses and sessions alike
188#define SOCACHE_FETCH_BUF_SIZE 4096
189static gnutls_datum_t socache_fetch(server_rec *server, gnutls_datum_t key,
190                                    apr_pool_t *pool)
191{
192    mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
193        ap_get_module_config(server->module_config, &gnutls_module);
194
195    gnutls_datum_t data = {NULL, 0};
196    data.data = gnutls_malloc(SOCACHE_FETCH_BUF_SIZE);
197    if (data.data == NULL)
198        return data;
199    data.size = SOCACHE_FETCH_BUF_SIZE;
200
201    apr_pool_t *spool;
202    apr_pool_create(&spool, pool);
203
204    apr_global_mutex_lock(sc->cache->mutex);
205    apr_status_t rv = sc->cache->prov->retrieve(sc->cache->socache, server,
206                                                key.data, key.size,
207                                                data.data, &data.size,
208                                                spool);
209    apr_global_mutex_unlock(sc->cache->mutex);
210
211    if (rv != APR_SUCCESS)
212    {
213        /* APR_NOTFOUND means there's no such object. */
214        if (rv == APR_NOTFOUND)
215            ap_log_error(APLOG_MARK, APLOG_TRACE1, rv, server,
216                         "requested entry not found in cache '%s:%s'.",
217                         sc->cache->prov->name, sc->cache_config);
218        else
219            ap_log_error(APLOG_MARK, APLOG_WARNING, rv, server,
220                         "error fetching from cache '%s:%s'",
221                         sc->cache->prov->name, sc->cache_config);
222        /* free unused buffer */
223        gnutls_free(data.data);
224        data.data = NULL;
225        data.size = 0;
226    }
227    else
228    {
229        ap_log_error(APLOG_MARK, APLOG_TRACE1, rv, server,
230                     "fetched %u bytes from cache '%s:%s'",
231                     data.size, sc->cache->prov->name, sc->cache_config);
232    }
233    apr_pool_destroy(spool);
234
235    return data;
236}
237
238static gnutls_datum_t socache_fetch_session(void *baton, gnutls_datum_t key)
239{
240    gnutls_datum_t data = {NULL, 0};
241    gnutls_datum_t dbmkey;
242    mgs_handle_t *ctxt = baton;
243
244    if (mgs_session_id2dbm(ctxt->c, key.data, key.size, &dbmkey) < 0)
245        return data;
246
247    return socache_fetch(ctxt->c->base_server, dbmkey, ctxt->c->pool);
248}
249
250
251
252static int socache_delete(void *baton, gnutls_datum_t key)
253{
254    gnutls_datum_t tmpkey;
255    mgs_handle_t *ctxt = baton;
256
257    if (mgs_session_id2dbm(ctxt->c, key.data, key.size, &tmpkey) < 0)
258        return -1;
259
260    apr_global_mutex_lock(ctxt->sc->cache->mutex);
261    apr_status_t rv = ctxt->sc->cache->prov->remove(ctxt->sc->cache->socache,
262                                                    ctxt->c->base_server,
263                                                    key.data, key.size,
264                                                    ctxt->c->pool);
265    apr_global_mutex_unlock(ctxt->sc->cache->mutex);
266
267    if (rv != APR_SUCCESS) {
268        ap_log_error(APLOG_MARK, APLOG_NOTICE, rv,
269                     ctxt->c->base_server,
270                     "error deleting from cache '%s:%s'",
271                     ctxt->sc->cache->prov->name, ctxt->sc->cache_config);
272        return -1;
273    }
274    return 0;
275}
276
277
278
279static apr_status_t cleanup_socache(void *data)
280{
281    server_rec *s = data;
282    mgs_srvconf_rec *sc = (mgs_srvconf_rec *)
283        ap_get_module_config(s->module_config, &gnutls_module);
284    ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, s,
285                 "Cleaning up socache '%s:%s'",
286                 sc->cache->prov->name, sc->cache_config);
287    sc->cache->prov->destroy(sc->cache->socache, s);
288    return APR_SUCCESS;
289}
290
291
292
293int mgs_cache_post_config(apr_pool_t *pconf, apr_pool_t *ptemp,
294                          server_rec *s, mgs_srvconf_rec *sc)
295{
296    apr_status_t rv = APR_SUCCESS;
297    /* if GnuTLSCache was never explicitly set: */
298    if (sc->cache_type == mgs_cache_unset || sc->cache_type == mgs_cache_none)
299    {
300        sc->cache_type = mgs_cache_none;
301        /* Cache disabled, done. */
302        return APR_SUCCESS;
303    }
304    /* if GnuTLSCacheTimeout was never explicitly set: */
305    if (sc->cache_timeout == MGS_TIMEOUT_UNSET)
306        sc->cache_timeout = apr_time_from_sec(MGS_DEFAULT_CACHE_TIMEOUT);
307
308    /* initialize mutex only once */
309    if (sc->cache == NULL)
310    {
311        sc->cache = apr_palloc(pconf, sizeof(struct mgs_cache));
312        rv = ap_global_mutex_create(&sc->cache->mutex, NULL,
313                                    MGS_CACHE_MUTEX_NAME,
314                                    NULL, s, pconf, 0);
315        if (rv != APR_SUCCESS)
316            return rv;
317    }
318
319    char *pname = NULL;
320
321    if (sc->cache_type == mgs_cache_dbm || sc->cache_type == mgs_cache_gdbm)
322    {
323        pname = "dbm";
324        sc->cache->store = socache_store;
325        sc->cache->fetch = socache_fetch;
326        //return dbm_cache_post_config(pconf, s, sc);
327    }
328#if HAVE_APR_MEMCACHE
329    else if (sc->cache_type == mgs_cache_memcache)
330    {
331        pname = "memcache";
332        sc->cache->store = socache_store;
333        sc->cache->fetch = socache_fetch;
334    }
335#endif
336    else if (sc->cache_type == mgs_cache_shmcb)
337    {
338        pname = "shmcb";
339        sc->cache->store = socache_store;
340        sc->cache->fetch = socache_fetch;
341    }
342
343    /* Find the right socache provider */
344    sc->cache->prov = ap_lookup_provider(AP_SOCACHE_PROVIDER_GROUP,
345                                         pname,
346                                         AP_SOCACHE_PROVIDER_VERSION);
347    if (sc->cache->prov)
348    {
349        /* Cache found; create it, passing anything beyond the colon. */
350        const char *err = sc->cache->prov->create(&sc->cache->socache,
351                                                  sc->cache_config,
352                                                  ptemp, pconf);
353        if (err != NULL)
354        {
355            ap_log_error(APLOG_MARK, APLOG_EMERG, APR_EGENERAL, s,
356                         "Creating cache '%s:%s' failed: %s",
357                         pname, sc->cache_config, err);
358            return HTTP_INSUFFICIENT_STORAGE;
359        }
360        ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, s,
361                     "%s: Socache '%s' created.", __func__, pname);
362
363        // TODO: provide hints
364        rv = sc->cache->prov->init(sc->cache->socache,
365                                   "mod_gnutls-session", NULL, s, pconf);
366        if (rv != APR_SUCCESS)
367        {
368            ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
369                         "Initializing cache '%s:%s' failed!",
370                         pname, sc->cache_config);
371            return HTTP_INSUFFICIENT_STORAGE;
372        }
373        ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, s,
374                     "%s: socache '%s:%s' created.", __func__,
375                     pname, sc->cache_config);
376    }
377    else
378    {
379        ap_log_error(APLOG_MARK, APLOG_EMERG, APR_EGENERAL, s,
380                     "Could not find socache provider '%s', please make sure "
381                     "that the provider name is valid and the "
382                     "appropriate mod_socache submodule is loaded.", pname);
383        return HTTP_NOT_FOUND;
384    }
385
386    apr_pool_pre_cleanup_register(pconf, s, cleanup_socache);
387
388    return APR_SUCCESS;
389}
390
391int mgs_cache_child_init(apr_pool_t * p,
392                         server_rec * s,
393                         mgs_srvconf_rec * sc)
394{
395    /* reinit cache mutex */
396    const char *lockfile = apr_global_mutex_lockfile(sc->cache->mutex);
397    apr_status_t rv = apr_global_mutex_child_init(&sc->cache->mutex,
398                                                  lockfile, p);
399    if (rv != APR_SUCCESS)
400        ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
401                     "Failed to reinit mutex '%s'", MGS_CACHE_MUTEX_NAME);
402
403    return 0;
404}
405
406#include <assert.h>
407
408int mgs_cache_session_init(mgs_handle_t * ctxt)
409{
410    if (ctxt->sc->cache_type != mgs_cache_none)
411    {
412        gnutls_db_set_retrieve_function(ctxt->session,
413                                        socache_fetch_session);
414        gnutls_db_set_remove_function(ctxt->session,
415                                      socache_delete);
416        gnutls_db_set_store_function(ctxt->session,
417                                     socache_store_session);
418        gnutls_db_set_ptr(ctxt->session, ctxt);
419    }
420    return 0;
421}
Note: See TracBrowser for help on using the repository browser.