1/* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements.  See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License.  You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "ap_provider.h"
18#include "httpd.h"
19#include "http_config.h"
20#include "http_log.h"
21#include "apr_lib.h"
22#include "apr_dbd.h"
23#include "mod_dbd.h"
24#include "apr_strings.h"
25#include "mod_auth.h"
26#include "apr_md5.h"
27#include "apu_version.h"
28
29module AP_MODULE_DECLARE_DATA authn_dbd_module;
30
31typedef struct {
32    const char *user;
33    const char *realm;
34} authn_dbd_conf;
35typedef struct {
36    const char *label;
37    const char *query;
38} authn_dbd_rec;
39
40/* optional function - look it up once in post_config */
41static ap_dbd_t *(*authn_dbd_acquire_fn)(request_rec*) = NULL;
42static void (*authn_dbd_prepare_fn)(server_rec*, const char*, const char*) = NULL;
43
44static void *authn_dbd_cr_conf(apr_pool_t *pool, char *dummy)
45{
46    authn_dbd_conf *ret = apr_pcalloc(pool, sizeof(authn_dbd_conf));
47    return ret;
48}
49static void *authn_dbd_merge_conf(apr_pool_t *pool, void *BASE, void *ADD)
50{
51    authn_dbd_conf *add = ADD;
52    authn_dbd_conf *base = BASE;
53    authn_dbd_conf *ret = apr_palloc(pool, sizeof(authn_dbd_conf));
54    ret->user = (add->user == NULL) ? base->user : add->user;
55    ret->realm = (add->realm == NULL) ? base->realm : add->realm;
56    return ret;
57}
58static const char *authn_dbd_prepare(cmd_parms *cmd, void *cfg, const char *query)
59{
60    static unsigned int label_num = 0;
61    char *label;
62
63    if (authn_dbd_prepare_fn == NULL) {
64        authn_dbd_prepare_fn = APR_RETRIEVE_OPTIONAL_FN(ap_dbd_prepare);
65        if (authn_dbd_prepare_fn == NULL) {
66            return "You must load mod_dbd to enable AuthDBD functions";
67        }
68        authn_dbd_acquire_fn = APR_RETRIEVE_OPTIONAL_FN(ap_dbd_acquire);
69    }
70    label = apr_psprintf(cmd->pool, "authn_dbd_%d", ++label_num);
71
72    authn_dbd_prepare_fn(cmd->server, query, label);
73
74    /* save the label here for our own use */
75    return ap_set_string_slot(cmd, cfg, label);
76}
77static const command_rec authn_dbd_cmds[] =
78{
79    AP_INIT_TAKE1("AuthDBDUserPWQuery", authn_dbd_prepare,
80                  (void *)APR_OFFSETOF(authn_dbd_conf, user), ACCESS_CONF,
81                  "Query used to fetch password for user"),
82    AP_INIT_TAKE1("AuthDBDUserRealmQuery", authn_dbd_prepare,
83                  (void *)APR_OFFSETOF(authn_dbd_conf, realm), ACCESS_CONF,
84                  "Query used to fetch password for user+realm"),
85    {NULL}
86};
87static authn_status authn_dbd_password(request_rec *r, const char *user,
88                                       const char *password)
89{
90    apr_status_t rv;
91    const char *dbd_password = NULL;
92    apr_dbd_prepared_t *statement;
93    apr_dbd_results_t *res = NULL;
94    apr_dbd_row_t *row = NULL;
95
96    authn_dbd_conf *conf = ap_get_module_config(r->per_dir_config,
97                                                &authn_dbd_module);
98    ap_dbd_t *dbd = authn_dbd_acquire_fn(r);
99    if (dbd == NULL) {
100        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
101                      "Failed to acquire database connection to look up "
102                      "user '%s'", user);
103        return AUTH_GENERAL_ERROR;
104    }
105
106    if (conf->user == NULL) {
107        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
108                      "No AuthDBDUserPWQuery has been specified");
109        return AUTH_GENERAL_ERROR;
110    }
111
112    statement = apr_hash_get(dbd->prepared, conf->user, APR_HASH_KEY_STRING);
113    if (statement == NULL) {
114        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
115                      "A prepared statement could not be found for "
116                      "AuthDBDUserPWQuery with the key '%s'", conf->user);
117        return AUTH_GENERAL_ERROR;
118    }
119    if (apr_dbd_pvselect(dbd->driver, r->pool, dbd->handle, &res, statement,
120                              0, user, NULL) != 0) {
121        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
122                      "Query execution error looking up '%s' "
123                      "in database", user);
124        return AUTH_GENERAL_ERROR;
125    }
126    for (rv = apr_dbd_get_row(dbd->driver, r->pool, res, &row, -1);
127         rv != -1;
128         rv = apr_dbd_get_row(dbd->driver, r->pool, res, &row, -1)) {
129        if (rv != 0) {
130            ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
131                          "Error retrieving results while looking up '%s' "
132                          "in database", user);
133            return AUTH_GENERAL_ERROR;
134        }
135        if (dbd_password == NULL) {
136#if APU_MAJOR_VERSION > 1 || (APU_MAJOR_VERSION == 1 && APU_MINOR_VERSION >= 3)
137            /* add the rest of the columns to the environment */
138            int i = 1;
139            const char *name;
140            for (name = apr_dbd_get_name(dbd->driver, res, i);
141                 name != NULL;
142                 name = apr_dbd_get_name(dbd->driver, res, i)) {
143
144                char *str = apr_pstrcat(r->pool, AUTHN_PREFIX,
145                                        name,
146                                        NULL);
147                int j = sizeof(AUTHN_PREFIX)-1; /* string length of "AUTHENTICATE_", excluding the trailing NIL */
148                while (str[j]) {
149                    if (!apr_isalnum(str[j])) {
150                        str[j] = '_';
151                    }
152                    else {
153                        str[j] = apr_toupper(str[j]);
154                    }
155                    j++;
156                }
157                apr_table_set(r->subprocess_env, str,
158                              apr_dbd_get_entry(dbd->driver, row, i));
159                i++;
160            }
161#endif
162            dbd_password = apr_dbd_get_entry(dbd->driver, row, 0);
163        }
164        /* we can't break out here or row won't get cleaned up */
165    }
166
167    if (!dbd_password) {
168        return AUTH_USER_NOT_FOUND;
169    }
170
171    rv = apr_password_validate(password, dbd_password);
172
173    if (rv != APR_SUCCESS) {
174        return AUTH_DENIED;
175    }
176
177    return AUTH_GRANTED;
178}
179static authn_status authn_dbd_realm(request_rec *r, const char *user,
180                                    const char *realm, char **rethash)
181{
182    apr_status_t rv;
183    const char *dbd_hash = NULL;
184    apr_dbd_prepared_t *statement;
185    apr_dbd_results_t *res = NULL;
186    apr_dbd_row_t *row = NULL;
187
188    authn_dbd_conf *conf = ap_get_module_config(r->per_dir_config,
189                                                &authn_dbd_module);
190    ap_dbd_t *dbd = authn_dbd_acquire_fn(r);
191    if (dbd == NULL) {
192        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
193                      "Failed to acquire database connection to look up "
194                      "user '%s:%s'", user, realm);
195        return AUTH_GENERAL_ERROR;
196    }
197    if (conf->realm == NULL) {
198        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
199                      "No AuthDBDUserRealmQuery has been specified");
200        return AUTH_GENERAL_ERROR;
201    }
202    statement = apr_hash_get(dbd->prepared, conf->realm, APR_HASH_KEY_STRING);
203    if (statement == NULL) {
204        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
205                      "A prepared statement could not be found for "
206                      "AuthDBDUserRealmQuery with the key '%s'", conf->realm);
207        return AUTH_GENERAL_ERROR;
208    }
209    if (apr_dbd_pvselect(dbd->driver, r->pool, dbd->handle, &res, statement,
210                              0, user, realm, NULL) != 0) {
211        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
212                      "Query execution error looking up '%s:%s' "
213                      "in database", user, realm);
214        return AUTH_GENERAL_ERROR;
215    }
216    for (rv = apr_dbd_get_row(dbd->driver, r->pool, res, &row, -1);
217         rv != -1;
218         rv = apr_dbd_get_row(dbd->driver, r->pool, res, &row, -1)) {
219        if (rv != 0) {
220            ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
221                          "Error retrieving results while looking up '%s:%s' "
222                          "in database", user, realm);
223            return AUTH_GENERAL_ERROR;
224        }
225        if (dbd_hash == NULL) {
226#if APU_MAJOR_VERSION > 1 || (APU_MAJOR_VERSION == 1 && APU_MINOR_VERSION >= 3)
227            /* add the rest of the columns to the environment */
228            int i = 1;
229            const char *name;
230            for (name = apr_dbd_get_name(dbd->driver, res, i);
231                 name != NULL;
232                 name = apr_dbd_get_name(dbd->driver, res, i)) {
233
234                char *str = apr_pstrcat(r->pool, AUTHN_PREFIX,
235                                        name,
236                                        NULL);
237                int j = sizeof(AUTHN_PREFIX)-1; /* string length of "AUTHENTICATE_", excluding the trailing NIL */
238                while (str[j]) {
239                    if (!apr_isalnum(str[j])) {
240                        str[j] = '_';
241                    }
242                    else {
243                        str[j] = apr_toupper(str[j]);
244                    }
245                    j++;
246                }
247                apr_table_set(r->subprocess_env, str,
248                              apr_dbd_get_entry(dbd->driver, row, i));
249                i++;
250            }
251#endif
252            dbd_hash = apr_dbd_get_entry(dbd->driver, row, 0);
253        }
254        /* we can't break out here or row won't get cleaned up */
255    }
256
257    if (!dbd_hash) {
258        return AUTH_USER_NOT_FOUND;
259    }
260
261    *rethash = apr_pstrdup(r->pool, dbd_hash);
262    return AUTH_USER_FOUND;
263}
264static void authn_dbd_hooks(apr_pool_t *p)
265{
266    static const authn_provider authn_dbd_provider = {
267        &authn_dbd_password,
268        &authn_dbd_realm
269    };
270
271    ap_register_provider(p, AUTHN_PROVIDER_GROUP, "dbd", "0", &authn_dbd_provider);
272}
273module AP_MODULE_DECLARE_DATA authn_dbd_module =
274{
275    STANDARD20_MODULE_STUFF,
276    authn_dbd_cr_conf,
277    authn_dbd_merge_conf,
278    NULL,
279    NULL,
280    authn_dbd_cmds,
281    authn_dbd_hooks
282};
283