Coverage Report

Created: 2026-12-01 06:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mod_auth_openidc/src/oauth.c
Line
Count
Source
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one
3
 * or more contributor license agreements.  See the NOTICE file
4
 * distributed with this work for additional information
5
 * regarding copyright ownership.  The ASF licenses this file
6
 * to you under the Apache License, Version 2.0 (the
7
 * "License"); you may not use this file except in compliance
8
 * with the License.  You may obtain a copy of the License at
9
 *
10
 *   http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing,
13
 * software distributed under the License is distributed on an
14
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
 * KIND, either express or implied.  See the License for the
16
 * specific language governing permissions and limitations
17
 * under the License.
18
 */
19
20
/***************************************************************************
21
 * Copyright (C) 2017-2026 ZmartZone Holding BV
22
 * Copyright (C) 2013-2017 Ping Identity Corporation
23
 * All rights reserved.
24
 *
25
 * DISCLAIMER OF WARRANTIES:
26
 *
27
 * THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
28
 * ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
29
 * WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
30
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  NOR ARE THERE ANY
31
 * WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
32
 * USAGE.  FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
33
 * YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
34
 * WILL BE UNINTERRUPTED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
35
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
36
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES HOWEVER CAUSED AND ON ANY THEORY OF
37
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
38
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
39
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40
 *
41
 * @Author: Hans Zandbelt - hans.zandbelt@openidc.com
42
 */
43
44
#include "cfg/oauth.h"
45
#include "cfg/dir.h"
46
#include "cfg/parse.h"
47
#include "handle/handle.h"
48
#include "metadata.h"
49
#include "metrics.h"
50
#include "mod_auth_openidc.h"
51
#include "proto/proto.h"
52
#include "util/request_state.h"
53
#include "util/util.h"
54
#include "util/util_cfg.h"
55
56
#include <apr_lib.h>
57
58
/*
59
 * retrieve the OAuth 2.0 metadata discovery document from the specified URL
60
 */
61
apr_byte_t oidc_oauth_metadata_provider_retrieve(request_rec *r, oidc_cfg_t *cfg, const char *issuer, const char *url,
62
0
             oidc_json_t **j_metadata, char **response) {
63
64
  /* get provider metadata from the specified URL with the specified parameters */
65
0
  if (oidc_http_get(r, url, NULL, NULL, NULL, NULL, oidc_cfg_oauth_ssl_validate_server_get(cfg), response, NULL,
66
0
        NULL, oidc_cfg_http_timeout_short_get(cfg), oidc_cfg_outgoing_proxy_get(cfg),
67
0
        oidc_cfg_dir_pass_cookies_get(r), NULL, NULL, NULL) == FALSE)
68
0
    return FALSE;
69
70
  /* decode and see if it is not an error response somehow */
71
0
  if (oidc_json_decode_and_check_error(r, *response, j_metadata) == FALSE) {
72
0
    oidc_error(r, "JSON parsing of retrieved Discovery document failed");
73
0
    return FALSE;
74
0
  }
75
76
  /* check to see if it is valid metadata */
77
78
  /* all OK */
79
0
  return TRUE;
80
0
}
81
82
/*
83
 * Return the shared configuration or a request-scoped copy containing metadata endpoints.
84
 * Request-pool strings must never be stored in the shared server configuration.
85
 */
86
0
static oidc_cfg_t *oidc_oauth_provider_config(request_rec *r, oidc_cfg_t *c) {
87
88
0
  oidc_json_t *j_provider = NULL;
89
0
  char *s_json = NULL;
90
0
  oidc_cfg_t *rc = NULL;
91
92
  /* see if we should configure a static provider based on external (cached) metadata */
93
0
  if (oidc_cfg_oauth_metadata_url_get(c) == NULL)
94
0
    return c;
95
96
0
  oidc_cache_get_oauth_provider(r, oidc_cfg_oauth_metadata_url_get(c), &s_json);
97
98
0
  if (s_json == NULL) {
99
100
0
    if (oidc_oauth_metadata_provider_retrieve(r, c, NULL, oidc_cfg_oauth_metadata_url_get(c), &j_provider,
101
0
                &s_json) == FALSE) {
102
0
      oidc_error(r, "could not retrieve metadata from url: %s", oidc_cfg_oauth_metadata_url_get(c));
103
0
      return c;
104
0
    }
105
106
0
    oidc_cache_set_oauth_provider(
107
0
        r, oidc_cfg_oauth_metadata_url_get(c), s_json,
108
0
        apr_time_now() + apr_time_from_sec(oidc_cfg_provider_metadata_refresh_interval_get(c) <= 0
109
0
                 ? OIDC_CACHE_PROVIDER_METADATA_EXPIRY_DEFAULT
110
0
                 : oidc_cfg_provider_metadata_refresh_interval_get(c)));
111
112
0
  } else {
113
114
0
    oidc_json_decode_object(r, s_json, &j_provider);
115
116
    /* check to see if it is valid metadata */
117
0
  }
118
119
  /* parse into a private per-request view; on failure fall back to the (unmutated) shared config */
120
0
  rc = oidc_cfg_request_view(r->pool, c);
121
0
  if (oidc_oauth_metadata_provider_parse(r, rc, j_provider) == FALSE) {
122
0
    oidc_error(r, "could not parse metadata from url: %s", oidc_cfg_oauth_metadata_url_get(c));
123
0
    rc = c;
124
0
  }
125
126
0
  if (j_provider)
127
0
    oidc_json_decref(j_provider);
128
129
0
  return rc;
130
0
}
131
132
/*
133
 * validate an access token against the validation endpoint of the Authorization server and gets a response back
134
 */
135
0
static apr_byte_t oidc_oauth_validate_access_token(request_rec *r, oidc_cfg_t *c, const char *token, char **response) {
136
137
0
  oidc_debug(r, "enter");
138
139
0
  char *basic_auth = NULL;
140
0
  char *bearer_auth = NULL;
141
142
  /* assemble parameters to call the token endpoint for validation */
143
0
  apr_table_t *params = apr_table_make(r->pool, 4);
144
145
  /* add any configured extra static parameters to the introspection endpoint */
146
0
  oidc_util_table_add_query_encoded_params(r->pool, params, oidc_cfg_oauth_introspection_endpoint_params_get(c));
147
148
  /* add the access_token itself */
149
0
  apr_table_addn(params, oidc_cfg_oauth_introspection_token_param_name_get(c), token);
150
151
0
  const char *bearer_access_token_auth =
152
0
      ((oidc_cfg_oauth_introspection_client_auth_bearer_token_get(c) != NULL) &&
153
0
       _oidc_strcmp(oidc_cfg_oauth_introspection_client_auth_bearer_token_get(c), "") == 0)
154
0
    ? token
155
0
    : oidc_cfg_oauth_introspection_client_auth_bearer_token_get(c);
156
157
  /* a JWT client assertion is addressed to the configured issuer identifier of the AS (RFC 10070), or else
158
   * to the introspection endpoint URL as before */
159
0
  oidc_proto_endpoint_auth_aud_t aud = {oidc_cfg_oauth_introspection_endpoint_auth_aud_get(c), TRUE};
160
0
  if (aud.value == NULL) {
161
0
    aud.value = oidc_cfg_oauth_introspection_endpoint_url_get(c);
162
0
    aud.is_issuer = FALSE;
163
0
  }
164
165
  /* add the token endpoint authentication credentials */
166
0
  if (oidc_proto_token_endpoint_auth(r, c, oidc_cfg_oauth_introspection_endpoint_auth_get(c),
167
0
             oidc_cfg_oauth_introspection_endpoint_auth_alg_get(c),
168
0
             oidc_cfg_oauth_client_id_get(c), oidc_cfg_oauth_client_secret_get(c), NULL,
169
0
             aud, params, bearer_access_token_auth, &basic_auth, &bearer_auth) == FALSE)
170
0
    return FALSE;
171
172
  /* call the endpoint with the constructed parameter set and return the resulting response */
173
0
  return oidc_cfg_oauth_introspection_endpoint_method_get(c) == OIDC_INTROSPECTION_METHOD_GET
174
0
       ? oidc_http_get(r, oidc_cfg_oauth_introspection_endpoint_url_get(c), params, basic_auth, bearer_auth,
175
0
           NULL, oidc_cfg_oauth_ssl_validate_server_get(c), response, NULL, NULL,
176
0
           oidc_cfg_http_timeout_long_get(c), oidc_cfg_outgoing_proxy_get(c),
177
0
           oidc_cfg_dir_pass_cookies_get(r),
178
0
           oidc_cfg_oauth_introspection_endpoint_tls_client_cert_get(c),
179
0
           oidc_cfg_oauth_introspection_endpoint_tls_client_key_get(c),
180
0
           oidc_cfg_oauth_introspection_endpoint_tls_client_key_pwd_get(c))
181
0
       : oidc_http_post_form(r, oidc_cfg_oauth_introspection_endpoint_url_get(c), params, basic_auth,
182
0
           bearer_auth, NULL, oidc_cfg_oauth_ssl_validate_server_get(c), response, NULL,
183
0
           NULL, oidc_cfg_http_timeout_long_get(c), oidc_cfg_outgoing_proxy_get(c),
184
0
           oidc_cfg_dir_pass_cookies_get(r),
185
0
           oidc_cfg_oauth_introspection_endpoint_tls_client_cert_get(c),
186
0
           oidc_cfg_oauth_introspection_endpoint_tls_client_key_get(c),
187
0
           oidc_cfg_oauth_introspection_endpoint_tls_client_key_pwd_get(c));
188
0
}
189
190
/*
191
 * extract the password portion of a base64-encoded Basic auth value (treated as token)
192
 */
193
0
static const char *oidc_oauth_token_from_basic(request_rec *r, const char *auth_line) {
194
0
  char *decoded_line = NULL;
195
0
  int decoded_len = 0;
196
197
0
  if (oidc_util_base64_decode(r->pool, auth_line, &decoded_line, &decoded_len) != NULL)
198
0
    return NULL;
199
0
  decoded_line[decoded_len] = '\0';
200
0
  if (strchr(decoded_line, ':') == NULL)
201
0
    return NULL;
202
203
  /* Strip the username and colon and take just the password */
204
0
  ap_getword_nulls(r->pool, (const char **)&decoded_line, ':');
205
0
  return decoded_line;
206
0
}
207
208
/*
209
 * extract the bearer token from the Authorization header (Bearer or Basic scheme)
210
 */
211
0
static const char *oidc_oauth_token_from_auth_header(request_rec *r, oidc_oauth_accept_token_in_t accept_token_in) {
212
0
  const char *auth_line = oidc_http_hdr_in_authorization_get(r);
213
0
  const char *token = NULL;
214
0
  char *scheme = NULL;
215
216
0
  if (auth_line == NULL)
217
0
    return NULL;
218
219
0
  oidc_debug(r, "authorization header found");
220
0
  scheme = ap_getword(r->pool, &auth_line, OIDC_CHAR_SPACE);
221
222
0
  if ((_oidc_strnatcasecmp(scheme, OIDC_PROTO_BEARER) == 0) &&
223
0
      (accept_token_in & OIDC_OAUTH_ACCEPT_TOKEN_IN_HEADER)) {
224
0
    while (apr_isspace(*auth_line))
225
0
      auth_line++;
226
0
    return apr_pstrdup(r->pool, auth_line);
227
0
  }
228
229
0
  if ((_oidc_strnatcasecmp(scheme, OIDC_PROTO_BASIC) == 0) &&
230
0
      (accept_token_in & OIDC_OAUTH_ACCEPT_TOKEN_IN_BASIC)) {
231
0
    token = oidc_oauth_token_from_basic(r, auth_line);
232
0
    if (token != NULL)
233
0
      return token;
234
0
  }
235
236
0
  oidc_warn(r, "client used unsupported authentication scheme: %s", scheme);
237
0
  return NULL;
238
0
}
239
240
/* RFC 6750 permits the access token in exactly one location, so reject a repeated one */
241
static const char *const OIDC_OAUTH_NO_REPEAT[] = {OIDC_PROTO_ACCESS_TOKEN, NULL};
242
243
/*
244
 * extract the bearer token from a POST body parameter
245
 */
246
0
static const char *oidc_oauth_token_from_post(request_rec *r) {
247
0
  apr_table_t *params = apr_table_make(r->pool, 8);
248
0
  if (oidc_util_read_post_params_reject_dup(r, params, TRUE, OIDC_PROTO_ACCESS_TOKEN, OIDC_OAUTH_NO_REPEAT) ==
249
0
      FALSE)
250
0
    return NULL;
251
0
  return apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN);
252
0
}
253
254
/*
255
 * extract the bearer token from a query string parameter
256
 */
257
0
static const char *oidc_oauth_token_from_query(request_rec *r) {
258
0
  apr_table_t *params = apr_table_make(r->pool, 8);
259
0
  if (oidc_util_read_form_encoded_params_reject_dup(r, params, r->args, OIDC_OAUTH_NO_REPEAT) == FALSE)
260
0
    return NULL;
261
0
  return apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN);
262
0
}
263
264
/*
265
 * extract the bearer token from a cookie
266
 */
267
0
static const char *oidc_oauth_token_from_cookie(request_rec *r, const char *cookie_name) {
268
0
  const char *auth_line = oidc_http_get_cookie(r, cookie_name);
269
0
  if (auth_line == NULL) {
270
0
    oidc_warn(r, "no cookie found with name: %s", cookie_name);
271
0
    return NULL;
272
0
  }
273
0
  return apr_pstrdup(r->pool, auth_line);
274
0
}
275
276
/*
277
 * get the authorization header that should contain a bearer token
278
 */
279
0
apr_byte_t oidc_oauth_get_bearer_token(request_rec *r, const char **access_token) {
280
281
  /* get the directory specific setting on how the token can be passed in */
282
0
  oidc_oauth_accept_token_in_t accept_token_in = oidc_cfg_dir_oauth_accept_token_in_get(r);
283
0
  const char *cookie_name =
284
0
      oidc_cfg_dir_accept_token_in_option_get(r, OIDC_OAUTH_ACCEPT_TOKEN_IN_OPTION_COOKIE_NAME);
285
286
0
  oidc_debug(r, "accept_token_in=%d", accept_token_in);
287
288
0
  *access_token = NULL;
289
290
0
  if (accept_token_in & (OIDC_OAUTH_ACCEPT_TOKEN_IN_HEADER | OIDC_OAUTH_ACCEPT_TOKEN_IN_BASIC))
291
0
    *access_token = oidc_oauth_token_from_auth_header(r, accept_token_in);
292
293
0
  if ((*access_token == NULL) && (r->method_number == M_POST) &&
294
0
      (accept_token_in & OIDC_OAUTH_ACCEPT_TOKEN_IN_POST))
295
0
    *access_token = oidc_oauth_token_from_post(r);
296
297
0
  if ((*access_token == NULL) && (accept_token_in & OIDC_OAUTH_ACCEPT_TOKEN_IN_QUERY))
298
0
    *access_token = oidc_oauth_token_from_query(r);
299
300
0
  if ((*access_token == NULL) && (accept_token_in & OIDC_OAUTH_ACCEPT_TOKEN_IN_COOKIE))
301
0
    *access_token = oidc_oauth_token_from_cookie(r, cookie_name);
302
303
0
  if (*access_token == NULL) {
304
0
    oidc_debug(r, "no bearer token found in the allowed methods: %s",
305
0
         oidc_cfg_dir_accept_oauth_token_in2str(r->pool, accept_token_in));
306
0
    return FALSE;
307
0
  }
308
309
  /* log some stuff */
310
0
  oidc_debug(r, "bearer token: %s", oidc_util_mask_value(r, *access_token));
311
0
  return TRUE;
312
0
}
313
314
/* number of seconds a validated token is cached for when its expiry claim cannot bound the entry */
315
#define OIDC_OAUTH_CACHE_DEFAULT_EXPIRY_SECONDS 60
316
317
/*
318
 * Bound the cache entry by the configured expiry claim. Missing or nonnumeric mandatory claims
319
 * fail; optional unusable claims and nonpositive numeric claims leave the default unchanged.
320
 */
321
static apr_byte_t oidc_oauth_parse_and_cache_token_expiry(request_rec *r, oidc_cfg_t *c,
322
                const oidc_json_t *introspection_response,
323
                const char *expiry_claim_name, int expiry_format_absolute,
324
0
                int expiry_claim_is_mandatory, apr_time_t *cache_until) {
325
326
0
  oidc_debug(r, "expiry_claim_name=%s, expiry_format_absolute=%d, expiry_claim_is_mandatory=%d",
327
0
       expiry_claim_name, expiry_format_absolute, expiry_claim_is_mandatory);
328
329
0
  const oidc_json_t *expiry = oidc_json_object_get(introspection_response, expiry_claim_name);
330
331
0
  if (expiry == NULL) {
332
0
    if (expiry_claim_is_mandatory) {
333
0
      oidc_error(r, "the token claims did not contain the mandatory \"%s\" expiry claim",
334
0
           expiry_claim_name);
335
0
      return FALSE;
336
0
    }
337
0
    return TRUE;
338
0
  }
339
340
  /*
341
   * a NumericDate is a JSON number and may hold a non-integer value (RFC 7519 section 2), so accept any
342
   * number here: this matches what oidc_proto_jwt_validate accepted when it verified the same claim
343
   */
344
0
  if (!oidc_json_is_number(expiry)) {
345
0
    if (expiry_claim_is_mandatory) {
346
0
      oidc_error(r,
347
0
           "the token claims contain a \"%s\" expiry claim but it is not a JSON number (RFC "
348
0
           "7519 section 2)",
349
0
           expiry_claim_name);
350
0
      return FALSE;
351
0
    }
352
0
    oidc_warn(r,
353
0
        "the token claims contain an (optional) \"%s\" expiry claim that is not a JSON number (RFC "
354
0
        "7519 section 2); caching the result for the default %d seconds instead",
355
0
        expiry_claim_name, OIDC_OAUTH_CACHE_DEFAULT_EXPIRY_SECONDS);
356
0
    return TRUE;
357
0
  }
358
359
  /* Truncate to expire no later than the claim; clamp the double before converting it. */
360
0
  double value = oidc_json_number_value(expiry);
361
0
  if (!(value > 0)) {
362
    /* NB: the value itself is not logged: it comes from the token or the introspection response and
363
     * formatting an arbitrary double takes hundreds of digits */
364
0
    oidc_warn(r,
365
0
        "the \"%s\" expiry claim has a value that is not greater than 0; caching the result for the "
366
0
        "default %d seconds instead",
367
0
        expiry_claim_name, OIDC_OAUTH_CACHE_DEFAULT_EXPIRY_SECONDS);
368
0
    return TRUE;
369
0
  }
370
371
0
  *cache_until = oidc_util_apr_time_from_sec(value);
372
0
  if (expiry_format_absolute == FALSE)
373
0
    *cache_until = oidc_util_apr_time_add(*cache_until, apr_time_now());
374
375
0
  return TRUE;
376
0
}
377
378
0
#define OIDC_OAUTH_CACHE_KEY_RESPONSE "r"
379
0
#define OIDC_OAUTH_CACHE_KEY_TIMESTAMP "t"
380
381
0
static const char *oidc_oauth_cache_key_str(const char *s) {
382
0
  return (s != NULL) ? s : "";
383
0
}
384
385
0
static int oidc_oauth_cache_key_cmp(const void *a, const void *b) {
386
0
  return _oidc_strcmp(*(const char *const *)a, *(const char *const *)b);
387
0
}
388
389
/*
390
 * add the JSON serialization of each local verification key, sorted so that the result does not
391
 * depend on configuration order or on the iteration order of the shared key hash table
392
 */
393
0
static apr_byte_t oidc_oauth_cache_key_add_jwks(request_rec *r, const oidc_cfg_t *c, apr_array_header_t *parts) {
394
0
  const apr_array_header_t *public_keys = oidc_cfg_oauth_verify_public_keys_get(c);
395
0
  apr_hash_t *shared_keys = oidc_cfg_oauth_verify_shared_keys_get(c);
396
0
  apr_array_header_t *keys = apr_array_make(r->pool, 4, sizeof(const char *));
397
0
  oidc_jose_error_t err;
398
0
  char *s_json = NULL;
399
400
0
  for (int i = 0; (public_keys != NULL) && (i < public_keys->nelts); i++) {
401
0
    if (oidc_jwk_to_json(r->pool, APR_ARRAY_IDX(public_keys, i, const oidc_jwk_t *), &s_json, &err) ==
402
0
        FALSE)
403
0
      goto error;
404
0
    APR_ARRAY_PUSH(keys, const char *) = s_json;
405
0
  }
406
407
0
  for (apr_hash_index_t *hi = (shared_keys != NULL) ? apr_hash_first(r->pool, shared_keys) : NULL; hi != NULL;
408
0
       hi = apr_hash_next(hi)) {
409
0
    void *jwk = NULL;
410
0
    apr_hash_this(hi, NULL, NULL, &jwk);
411
0
    if (oidc_jwk_to_json(r->pool, (const oidc_jwk_t *)jwk, &s_json, &err) == FALSE)
412
0
      goto error;
413
0
    APR_ARRAY_PUSH(keys, const char *) = s_json;
414
0
  }
415
416
0
  qsort(keys->elts, keys->nelts, keys->elt_size, oidc_oauth_cache_key_cmp);
417
0
  apr_array_cat(parts, keys);
418
0
  return TRUE;
419
420
0
error:
421
0
  oidc_error(r, "oidc_jwk_to_json failed: %s", oidc_jose_e2s(r->pool, err));
422
0
  return FALSE;
423
0
}
424
425
/*
426
 * return the cache key for the validation result of an access token: the result is only valid for
427
 * the verifier that produced it, so bind it to the introspection endpoint and client, or to the
428
 * JWKs URI and the local verification keys; returns NULL when the key cannot be constructed
429
 */
430
0
const char *oidc_oauth_cache_key(request_rec *r, const oidc_cfg_t *c, const char *access_token) {
431
0
  apr_array_header_t *parts = apr_array_make(r->pool, 8, sizeof(const char *));
432
0
  const char *url = oidc_cfg_oauth_introspection_endpoint_url_get(c);
433
0
  char *binding = NULL;
434
435
0
  if (url != NULL) {
436
0
    APR_ARRAY_PUSH(parts, const char *) = "introspect";
437
0
    APR_ARRAY_PUSH(parts, const char *) = url;
438
0
    APR_ARRAY_PUSH(parts, const char *) = oidc_oauth_cache_key_str(oidc_cfg_oauth_client_id_get(c));
439
0
  } else {
440
0
    APR_ARRAY_PUSH(parts, const char *) = "jwt";
441
0
    APR_ARRAY_PUSH(parts, const char *) = oidc_oauth_cache_key_str(oidc_cfg_oauth_verify_jwks_uri_get(c));
442
0
    if (oidc_oauth_cache_key_add_jwks(r, c, parts) == FALSE)
443
0
      return NULL;
444
0
  }
445
446
0
  if (oidc_util_hash_string_and_base64url_encode(r, OIDC_JOSE_ALG_SHA256, apr_array_pstrcat(r->pool, parts, '\n'),
447
0
                   &binding) == FALSE)
448
0
    return NULL;
449
450
0
  return apr_pstrcat(r->pool, binding, ".", access_token, NULL);
451
0
}
452
453
/*
454
 * the cache key of an access token's validation result as oidc_oauth_check_userid() stores it, i.e. with the
455
 * endpoints obtained from OIDCOAuthServerMetadataURL when configured
456
 */
457
0
const char *oidc_oauth_cache_key_resolved(request_rec *r, oidc_cfg_t *c, const char *access_token) {
458
0
  return oidc_oauth_cache_key(r, oidc_oauth_provider_config(r, c), access_token);
459
0
}
460
461
/*
462
 * cache the OAuth 2.0 introspection results for the specified access token
463
 */
464
static apr_byte_t oidc_oauth_cache_access_token(request_rec *r, const oidc_cfg_t *c, apr_time_t cache_until,
465
0
            const char *access_token, oidc_json_t *json) {
466
467
  /* no cache mode */
468
0
  int token_introspection_interval = oidc_cfg_dir_token_introspection_interval_get(r);
469
0
  if (token_introspection_interval == -1) {
470
0
    oidc_debug(r, "not caching introspection result");
471
0
    return TRUE;
472
0
  }
473
474
0
  const char *key = oidc_oauth_cache_key(r, c, access_token);
475
0
  if (key == NULL)
476
0
    return FALSE;
477
478
0
  oidc_debug(r, "caching introspection result");
479
480
0
  oidc_json_t *cache_entry = oidc_json_object();
481
0
  oidc_json_object_set(cache_entry, OIDC_OAUTH_CACHE_KEY_RESPONSE, json);
482
0
  oidc_json_object_set_new(cache_entry, OIDC_OAUTH_CACHE_KEY_TIMESTAMP,
483
0
         oidc_json_integer(apr_time_sec(apr_time_now())));
484
0
  const char *cache_value = oidc_json_encode(r->pool, cache_entry, OIDC_JSON_PRESERVE_ORDER | OIDC_JSON_COMPACT);
485
486
  /* set it in the cache so subsequent request don't need to validate the access_token and get the claims anymore
487
   */
488
0
  oidc_cache_set_access_token(r, key, cache_value, cache_until);
489
490
0
  oidc_json_decref(cache_entry);
491
492
0
  return TRUE;
493
0
}
494
495
/*
496
 * retrieve the OAuth 2.0 introspection results from the cache, for a previously introspected access token
497
 */
498
static apr_byte_t oidc_oauth_get_cached_access_token(request_rec *r, const oidc_cfg_t *c, const char *access_token,
499
0
                 oidc_json_t **json) {
500
0
  oidc_json_t *cache_entry = NULL;
501
0
  char *s_cache_entry = NULL;
502
503
  /* no cache mode */
504
0
  int token_introspection_interval = oidc_cfg_dir_token_introspection_interval_get(r);
505
0
  if (token_introspection_interval == -1) {
506
0
    return FALSE;
507
0
  }
508
509
0
  const char *key = oidc_oauth_cache_key(r, c, access_token);
510
0
  if (key == NULL)
511
0
    return FALSE;
512
513
  /* see if we've got the claims for this access_token cached already */
514
0
  oidc_cache_get_access_token(r, key, &s_cache_entry);
515
516
0
  if (s_cache_entry == NULL)
517
0
    return FALSE;
518
519
  /* json decode the cache entry */
520
0
  if (oidc_json_decode_object(r, s_cache_entry, &cache_entry) == FALSE) {
521
0
    *json = NULL;
522
0
    return FALSE;
523
0
  }
524
525
  /* compare the timestamp against the freshness requirement */
526
0
  const oidc_json_t *v = oidc_json_object_get(cache_entry, OIDC_OAUTH_CACHE_KEY_TIMESTAMP);
527
0
  apr_time_t now = apr_time_sec(apr_time_now());
528
0
  if ((token_introspection_interval > 0) && (now > oidc_json_integer_value(v) + token_introspection_interval)) {
529
530
    /* printout info about the event */
531
0
    char buf[APR_RFC822_DATE_LEN + 1];
532
0
    apr_rfc822_date(buf, apr_time_from_sec(oidc_json_integer_value(v)));
533
0
    oidc_debug(r,
534
0
         "token that was validated/cached at: [%s], does not meet token freshness requirement: %d)",
535
0
         buf, token_introspection_interval);
536
537
    /* invalidate the cache entry */
538
0
    *json = NULL;
539
0
    oidc_json_decref(cache_entry);
540
0
    return FALSE;
541
0
  }
542
543
0
  oidc_debug(r, "returning cached introspection result that meets freshness requirements: %s", s_cache_entry);
544
545
  /* we've got a cached introspection result that is still valid for this path's requirements */
546
0
  *json = oidc_json_copy(oidc_json_object_get(cache_entry, OIDC_OAUTH_CACHE_KEY_RESPONSE));
547
548
0
  oidc_json_decref(cache_entry);
549
0
  return TRUE;
550
0
}
551
552
/*
553
 * check the value of the "active" claim in an introspection response
554
 */
555
0
static apr_byte_t oidc_oauth_introspection_active_is_valid(request_rec *r, const oidc_json_t *active) {
556
0
  if (oidc_json_is_boolean(active)) {
557
0
    if (oidc_json_is_true(active))
558
0
      return TRUE;
559
0
    oidc_debug(r, "\"%s\" boolean object with value \"false\" found in response JSON object",
560
0
         OIDC_PROTO_ACTIVE);
561
0
    return FALSE;
562
0
  }
563
0
  if (oidc_json_is_string(active)) {
564
0
    if (_oidc_strnatcasecmp(oidc_json_string_value(active), "true") == 0)
565
0
      return TRUE;
566
0
    oidc_debug(r,
567
0
         "\"%s\" string object with value that is not equal to \"true\" found in response JSON "
568
0
         "object: %s",
569
0
         OIDC_PROTO_ACTIVE, oidc_json_string_value(active));
570
0
    return FALSE;
571
0
  }
572
0
  oidc_debug(r, "no \"%s\" boolean or string object found in response JSON object", OIDC_PROTO_ACTIVE);
573
0
  return FALSE;
574
0
}
575
576
/*
577
 * validate the introspection response (active claim + expiry) and cache it on success
578
 */
579
static apr_byte_t oidc_oauth_introspection_validate_and_cache(request_rec *r, oidc_cfg_t *c, const char *access_token,
580
0
                    oidc_json_t *result) {
581
0
  const oidc_json_t *active = oidc_json_object_get(result, OIDC_PROTO_ACTIVE);
582
0
  apr_time_t cache_until = apr_time_now() + apr_time_from_sec(OIDC_OAUTH_CACHE_DEFAULT_EXPIRY_SECONDS);
583
584
0
  if (active != NULL) {
585
0
    if (oidc_oauth_introspection_active_is_valid(r, active) == FALSE) {
586
0
      OIDC_METRICS_ERROR_REASON(r, "inactive");
587
0
      return FALSE;
588
0
    }
589
0
    if (oidc_oauth_parse_and_cache_token_expiry(r, c, result, OIDC_CLAIM_EXP, TRUE, FALSE, &cache_until) ==
590
0
        FALSE) {
591
0
      OIDC_METRICS_ERROR_REASON(r, "exp");
592
0
      return FALSE;
593
0
    }
594
0
  } else {
595
    /* the "active" member is REQUIRED by RFC 7662; warn when it is absent since validity is then
596
     * derived solely from the (possibly optional) configured expiry claim */
597
0
    oidc_warn(r,
598
0
        "introspection response did not contain the RFC 7662 \"%s\" member; token validity is "
599
0
        "determined solely from the \"%s\" expiry claim",
600
0
        OIDC_PROTO_ACTIVE, oidc_cfg_oauth_introspection_token_expiry_claim_name_get(c));
601
0
    if (oidc_oauth_parse_and_cache_token_expiry(
602
0
      r, c, result, oidc_cfg_oauth_introspection_token_expiry_claim_name_get(c),
603
0
      oidc_cfg_oauth_introspection_token_expiry_claim_format_get(c) ==
604
0
          OIDC_TOKEN_EXPIRY_CLAIM_FORMAT_ABSOLUTE,
605
0
      oidc_cfg_oauth_introspection_token_expiry_claim_required_get(c) ==
606
0
          OIDC_TOKEN_EXPIRY_CLAIM_REQUIRED_MANDATORY,
607
0
      &cache_until) == FALSE) {
608
0
      OIDC_METRICS_ERROR_REASON(r, "exp");
609
0
      return FALSE;
610
0
    }
611
0
  }
612
613
  /* set it in the cache so subsequent request don't need to validate the access_token and get the claims anymore
614
   */
615
0
  oidc_oauth_cache_access_token(r, c, cache_until, access_token, result);
616
0
  return TRUE;
617
0
}
618
619
/*
620
 * fetch and validate an introspection result for the given access_token from the AS
621
 */
622
0
static apr_byte_t oidc_oauth_introspect(request_rec *r, oidc_cfg_t *c, const char *access_token, oidc_json_t **result) {
623
0
  char *s_json = NULL;
624
625
  /* not cached, go out and validate the access_token against the Authorization server and get the JSON
626
   * claims back */
627
0
  if (oidc_oauth_validate_access_token(r, c, access_token, &s_json) == FALSE) {
628
0
    oidc_error(r, "could not get a validation response from the Authorization server");
629
0
    OIDC_METRICS_ERROR_REASON(r, "introspection");
630
0
    return FALSE;
631
0
  }
632
633
  /* decode and see if it is not an error response somehow */
634
0
  if (oidc_json_decode_and_check_error(r, s_json, result) == FALSE) {
635
0
    OIDC_METRICS_ERROR_REASON(r, "introspection");
636
0
    return FALSE;
637
0
  }
638
639
0
  if (oidc_oauth_introspection_validate_and_cache(r, c, access_token, *result) == FALSE) {
640
0
    oidc_json_decref(*result);
641
0
    *result = NULL;
642
0
    return FALSE;
643
0
  }
644
645
0
  return TRUE;
646
0
}
647
648
/*
649
 * shape the introspection result into the form returned to the caller: a PingFederate-style
650
 * nested access_token (enriched with client_id/scope) or the spec-compliant result as-is
651
 */
652
0
static void oidc_oauth_shape_introspection_token(oidc_json_t *result, oidc_json_t **token) {
653
0
  oidc_json_t *tkn = oidc_json_object_get(result, OIDC_PROTO_ACCESS_TOKEN);
654
0
  if ((tkn != NULL) && (oidc_json_is_object(tkn))) {
655
    /*
656
     * assume PingFederate validation: copy over those claims from the access_token
657
     * that are relevant for authorization purposes
658
     */
659
0
    oidc_json_object_set(tkn, OIDC_PROTO_CLIENT_ID, oidc_json_object_get(result, OIDC_PROTO_CLIENT_ID));
660
0
    oidc_json_object_set(tkn, OIDC_PROTO_SCOPE, oidc_json_object_get(result, OIDC_PROTO_SCOPE));
661
    /* return only the pimped access_token results */
662
0
    *token = oidc_json_copy(tkn);
663
0
    oidc_json_decref(result);
664
0
  } else {
665
    /* assume spec compliant introspection */
666
0
    *token = result;
667
0
  }
668
0
}
669
670
/*
671
 * resolve and validate an access_token against the configured Authorization Server
672
 */
673
static apr_byte_t oidc_oauth_resolve_access_token(request_rec *r, oidc_cfg_t *c, const char *access_token,
674
0
              oidc_json_t **token, char **response) {
675
0
  oidc_json_t *result = NULL;
676
677
  /* see if we've got the claims for this access_token cached already */
678
0
  oidc_oauth_get_cached_access_token(r, c, access_token, &result);
679
680
0
  if ((result == NULL) && (oidc_oauth_introspect(r, c, access_token, &result) == FALSE))
681
0
    return FALSE;
682
683
  /* return the access_token JSON object */
684
0
  oidc_oauth_shape_introspection_token(result, token);
685
686
  /* stringify the response */
687
0
  *response = oidc_json_encode(r->pool, *token, OIDC_JSON_PRESERVE_ORDER | OIDC_JSON_COMPACT);
688
689
0
  return TRUE;
690
0
}
691
692
/*
693
 * validate the "aud" claim of a locally validated JWT access token against the configured
694
 * audience value(s): this resource server must be among the intended recipients of the token,
695
 * but - unlike an id_token - other audiences may legitimately be present as well
696
 */
697
0
static apr_byte_t oidc_oauth_validate_jwt_aud(request_rec *r, const oidc_cfg_t *c, const oidc_json_t *claims) {
698
0
  const apr_array_header_t *arr = oidc_cfg_oauth_verify_aud_values_get(c);
699
0
  const oidc_json_t *aud = NULL;
700
701
  /* no audience configured: nothing to match against */
702
0
  if ((arr == NULL) || (arr->nelts == 0))
703
0
    return TRUE;
704
705
0
  aud = oidc_json_object_get(claims, OIDC_CLAIM_AUD);
706
0
  if (aud == NULL) {
707
0
    oidc_error(r,
708
0
         "JWT access token does not contain an \"%s\" claim, so it cannot be matched against the "
709
0
         "configured " OIDCOAuthVerifyAudience " value(s)",
710
0
         OIDC_CLAIM_AUD);
711
0
    return FALSE;
712
0
  }
713
714
0
  if (oidc_json_is_string(aud)) {
715
0
    for (int i = 0; i < arr->nelts; i++)
716
0
      if (_oidc_strcmp(oidc_json_string_value(aud), APR_ARRAY_IDX(arr, i, const char *)) == 0)
717
0
        return TRUE;
718
0
  } else if (oidc_json_is_array(aud)) {
719
    /* "aud" may be a single string or an array of strings (RFC 7519 section 4.1.3) */
720
0
    for (int i = 0; i < arr->nelts; i++)
721
0
      if (oidc_json_array_has_value(r, aud, APR_ARRAY_IDX(arr, i, const char *)) == TRUE)
722
0
        return TRUE;
723
0
  } else {
724
0
    oidc_error(r, "\"%s\" claim in the JWT access token is neither a string nor an array", OIDC_CLAIM_AUD);
725
0
    return FALSE;
726
0
  }
727
728
0
  oidc_error(r,
729
0
       "none of the configured " OIDCOAuthVerifyAudience " values matches the \"%s\" claim in the JWT "
730
0
       "access token",
731
0
       OIDC_CLAIM_AUD);
732
0
  return FALSE;
733
0
}
734
735
/*
736
 * validate the "iss" claim of a locally validated JWT access token against the configured issuer
737
 */
738
0
static apr_byte_t oidc_oauth_validate_jwt_iss(request_rec *r, const oidc_cfg_t *c, const oidc_json_t *claims) {
739
0
  const char *iss = oidc_cfg_oauth_verify_issuer_get(c);
740
0
  char *s_iss = NULL;
741
742
  /* no issuer configured: nothing to match against */
743
0
  if (iss == NULL)
744
0
    return TRUE;
745
746
0
  if (oidc_json_object_get_string(r->pool, claims, OIDC_CLAIM_ISS, &s_iss, NULL) == FALSE)
747
0
    return FALSE;
748
749
0
  if (s_iss == NULL) {
750
0
    oidc_error(r,
751
0
         "JWT access token does not contain an \"%s\" claim, so it cannot be matched against the "
752
0
         "configured " OIDCOAuthVerifyIssuer " value (%s)",
753
0
         OIDC_CLAIM_ISS, iss);
754
0
    return FALSE;
755
0
  }
756
757
0
  if (oidc_util_issuer_match(iss, s_iss) == FALSE) {
758
0
    oidc_error(r,
759
0
         "configured " OIDCOAuthVerifyIssuer " (%s) does not match the \"%s\" claim (%s) in the "
760
0
         "JWT access token",
761
0
         iss, OIDC_CLAIM_ISS, s_iss);
762
0
    return FALSE;
763
0
  }
764
765
0
  return TRUE;
766
0
}
767
768
/*
769
 * Validate RFC 9068 resource-server claims even on cache hits, which may be shared by vhosts
770
 * with different audience or issuer settings.
771
 */
772
0
static apr_byte_t oidc_oauth_validate_jwt_claims(request_rec *r, const oidc_cfg_t *c, const oidc_json_t *claims) {
773
0
  if (oidc_oauth_validate_jwt_iss(r, c, claims) == FALSE) {
774
0
    OIDC_METRICS_ERROR_REASON(r, "iss");
775
0
    return FALSE;
776
0
  }
777
0
  if (oidc_oauth_validate_jwt_aud(r, c, claims) == FALSE) {
778
0
    OIDC_METRICS_ERROR_REASON(r, "aud");
779
0
    return FALSE;
780
0
  }
781
0
  return TRUE;
782
0
}
783
784
/*
785
 * validate a JWT access token (locally)
786
 *
787
 * NB: reuses the following settings from the OIDC (RP) configuration section, as documented
788
 *     in auth_openidc.conf:
789
 *     - the JWKs cache refresh interval (OIDCJWKSRefreshInterval)
790
 *     - decryption key material (OIDCPrivateKeyFiles)
791
 *
792
 * OIDCOAuthRemoteUserClaim client_id
793
 * # 32x 61 hex
794
 * OIDCOAuthVerifySharedKeys aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
795
 */
796
static apr_byte_t oidc_oauth_validate_jwt_access_token(request_rec *r, oidc_cfg_t *c, const char *access_token,
797
0
                   oidc_json_t **token, char **response) {
798
799
0
  oidc_debug(r, "enter: JWT access_token header=%s",
800
0
       oidc_proto_jwt_header_peek(r, access_token, NULL, NULL, NULL));
801
802
0
  oidc_jose_error_t err;
803
0
  oidc_jwk_t *jwk = NULL;
804
0
  apr_hash_t *decrypt_keys = NULL;
805
0
  oidc_json_t *cached = NULL;
806
807
  /* Reuse cached validation until token expiry or the configured introspection interval. */
808
0
  oidc_oauth_get_cached_access_token(r, c, access_token, &cached);
809
0
  if (cached != NULL) {
810
0
    if (oidc_oauth_validate_jwt_claims(r, c, cached) == FALSE) {
811
0
      oidc_json_decref(cached);
812
0
      return FALSE;
813
0
    }
814
0
    *token = cached;
815
0
    *response = oidc_json_encode(r->pool, cached, OIDC_JSON_PRESERVE_ORDER | OIDC_JSON_COMPACT);
816
0
    return TRUE;
817
0
  }
818
819
0
  if (oidc_cfg_oauth_decrypt_shared_keys_get(c) != NULL) {
820
    /* symmetric decryption keys configured with OIDCOAuthDecryptSharedKeys */
821
0
    decrypt_keys = oidc_util_key_sets_merge(r->pool, oidc_cfg_oauth_decrypt_shared_keys_get(c),
822
0
              oidc_cfg_private_keys_get(c));
823
0
  } else {
824
    /* fall back to a symmetric key derived from the client secret configured for the
825
     * OpenID Connect provider, alongside the OIDCPrivateKeyFiles key material */
826
0
    if (oidc_util_key_symmetric_create(r, oidc_cfg_provider_client_secret_get(oidc_cfg_provider_get(c)), 0,
827
0
               NULL, TRUE, &jwk) == FALSE)
828
0
      return FALSE;
829
0
    decrypt_keys = oidc_util_key_symmetric_merge(r->pool, oidc_cfg_private_keys_get(c), jwk);
830
0
  }
831
832
0
  oidc_jwt_t *jwt = NULL;
833
0
  if (oidc_jwt_parse(r->pool, access_token, &jwt, decrypt_keys, FALSE, &err) == FALSE) {
834
0
    oidc_error(r, "could not parse JWT from access_token: %s", oidc_jose_e2s(r->pool, err));
835
0
    OIDC_METRICS_ERROR_REASON(r, "parse");
836
0
    oidc_jwk_destroy(jwk);
837
0
    return FALSE;
838
0
  }
839
840
0
  oidc_jwk_destroy(jwk);
841
0
  oidc_debug(r, "successfully parsed JWT with header: %s", jwt->header.value.str);
842
843
  /*
844
   * RFC 9068 requires exp. Validate iss and aud after signature verification, including on
845
   * cache hits; iat is not enforced for access tokens.
846
   */
847
0
  if (oidc_proto_jwt_validate(r, jwt, NULL, TRUE, FALSE, -1) == FALSE) {
848
    /* NB: oidc_proto_jwt_validate recorded the specific exp/iat error reason */
849
0
    oidc_jwt_destroy(jwt);
850
0
    return FALSE;
851
0
  }
852
853
0
  oidc_debug(
854
0
      r, "verify JWT against %d statically configured public keys and %d shared keys, with JWKs URI set to %s",
855
0
      oidc_cfg_oauth_verify_public_keys_get(c) ? oidc_cfg_oauth_verify_public_keys_get(c)->nelts : 0,
856
0
      oidc_cfg_oauth_verify_shared_keys_get(c) ? apr_hash_count(oidc_cfg_oauth_verify_shared_keys_get(c)) : 0,
857
0
      oidc_cfg_oauth_verify_jwks_uri_get(c));
858
859
  /* the JWKs cache refresh interval is shared with the OIDC provider one (OIDCJWKSRefreshInterval),
860
   * as documented in auth_openidc.conf */
861
0
  oidc_jwks_uri_t jwks_uri = {oidc_cfg_oauth_verify_jwks_uri_get(c),
862
0
            oidc_cfg_provider_jwks_uri_refresh_interval_get(oidc_cfg_provider_get(c)), NULL,
863
0
            NULL};
864
0
  if (oidc_proto_jwt_verify(r, c, jwt, &jwks_uri, oidc_cfg_oauth_ssl_validate_server_get(c),
865
0
          oidc_util_key_sets_merge(r->pool, oidc_cfg_oauth_verify_shared_keys_get(c),
866
0
                 oidc_cfg_oauth_verify_public_keys_get(c)),
867
0
          NULL) == FALSE) {
868
0
    oidc_error(r, "JWT access token signature could not be validated, aborting");
869
0
    OIDC_METRICS_ERROR_REASON(r, "signature");
870
0
    oidc_jwt_destroy(jwt);
871
0
    return FALSE;
872
0
  }
873
874
0
  oidc_debug(r, "successfully verified JWT access token: %s", jwt->payload.value.str);
875
876
  /* the signature is authentic: now check that the token was actually meant for us */
877
0
  if (oidc_oauth_validate_jwt_claims(r, c, jwt->payload.value.json) == FALSE) {
878
0
    oidc_jwt_destroy(jwt);
879
0
    return FALSE;
880
0
  }
881
882
  /* cache the validated claims bounded by the token's expiry so subsequent requests carrying the same
883
   * bearer token skip re-verification; "exp" is mandatory and was verified above, so it always bounds
884
   * the entry here and the default below is not reached */
885
0
  apr_time_t cache_until = apr_time_now() + apr_time_from_sec(OIDC_OAUTH_CACHE_DEFAULT_EXPIRY_SECONDS);
886
0
  if (oidc_oauth_parse_and_cache_token_expiry(r, c, jwt->payload.value.json, OIDC_CLAIM_EXP, TRUE, FALSE,
887
0
                &cache_until) == TRUE)
888
0
    oidc_oauth_cache_access_token(r, c, cache_until, access_token, jwt->payload.value.json);
889
890
0
  *token = oidc_json_copy(jwt->payload.value.json);
891
0
  *response = jwt->payload.value.str;
892
893
0
  oidc_jwt_destroy(jwt);
894
895
0
  return TRUE;
896
0
}
897
898
/*
899
 * set the unique user identifier that will be propagated in the Apache r->user and REMOTE_USER variables
900
 */
901
0
static apr_byte_t oidc_oauth_set_request_user(request_rec *r, const oidc_cfg_t *c, const oidc_json_t *token) {
902
0
  char *remote_user = NULL;
903
904
0
  if (oidc_get_remote_user(r, oidc_cfg_oauth_remote_user_claim_name_get(c),
905
0
         oidc_cfg_oauth_remote_user_claim_get(c)->reg_exp,
906
0
         oidc_cfg_oauth_remote_user_claim_get(c)->replace, token, &remote_user) == FALSE) {
907
0
    oidc_error(
908
0
        r,
909
0
        "" OIDCOAuthRemoteUserClaim
910
0
        " is set to \"%s\", but could not set the remote user based the available claims for the user",
911
0
        oidc_cfg_oauth_remote_user_claim_name_get(c));
912
0
    OIDC_METRICS_ERROR_REASON(r, "remote_user");
913
0
    return FALSE;
914
0
  }
915
916
0
  r->user = apr_pstrdup(r->pool, remote_user);
917
0
  oidc_debug(r, "set user to \"%s\" based on claim: \"%s\"%s", r->user,
918
0
       oidc_cfg_oauth_remote_user_claim_name_get(c),
919
0
       oidc_cfg_oauth_remote_user_claim_get(c)->reg_exp
920
0
           ? apr_psprintf(r->pool, " and expression: \"%s\" and replace string: \"%s\"",
921
0
              oidc_cfg_oauth_remote_user_claim_get(c)->reg_exp,
922
0
              oidc_cfg_oauth_remote_user_claim_get(c)->replace)
923
0
           : "");
924
0
  return TRUE;
925
0
}
926
927
/*
928
 * handle "special" requests directed at the Redirect URI (JWKS, remove-access-token-cache);
929
 * returns the status to send back, or DECLINED if not a special request
930
 */
931
0
static int oidc_oauth_check_userid_redirect_uri(request_rec *r, oidc_cfg_t *c) {
932
0
  if (oidc_util_url_has_parameter(r, OIDC_REDIRECT_URI_REQUEST_JWKS)) {
933
0
    OIDC_METRICS_COUNTER_INC(r, c, OM_REDIRECT_URI_REQUEST_JWKS);
934
    /*
935
     * Will be handled in the content handler; avoid:
936
     * No authentication done but request not allowed without authentication
937
     * by setting r->user. No authentication happened, so any OIDC_* headers
938
     * on this request came from the client and must not survive it.
939
     */
940
0
    oidc_scrub_headers(r);
941
0
    r->user = "";
942
0
    return OK;
943
0
  }
944
0
  if (oidc_util_url_has_parameter(r, OIDC_REDIRECT_URI_REQUEST_REMOVE_AT_CACHE))
945
0
    return oidc_revoke_at_cache_remove(r, c);
946
0
  return DECLINED;
947
0
}
948
949
/*
950
 * validate the access token via the configured introspection endpoint or as a local JWT
951
 */
952
static apr_byte_t oidc_oauth_validate_token(request_rec *r, oidc_cfg_t *c, const char *access_token,
953
0
              oidc_json_t **claims, char **s_token) {
954
0
  if (oidc_cfg_oauth_introspection_endpoint_url_get(c) != NULL)
955
0
    return oidc_oauth_resolve_access_token(r, c, access_token, claims, s_token);
956
0
  return oidc_oauth_validate_jwt_access_token(r, c, access_token, claims, s_token);
957
0
}
958
959
/*
960
 * propagate claims and access_token into the application HTTP headers
961
 */
962
static void oidc_oauth_pass_info_to_app(request_rec *r, const oidc_cfg_t *c, oidc_json_t *claims,
963
0
          const char *access_token) {
964
0
  const char *authn_header = oidc_cfg_dir_authn_header_get(r);
965
0
  oidc_appinfo_pass_in_t pass_in = oidc_cfg_dir_pass_info_in_get(r);
966
0
  oidc_appinfo_encoding_t encoding = oidc_cfg_dir_pass_info_encoding_get(r);
967
968
0
  if ((r->user != NULL) && (authn_header != NULL))
969
0
    oidc_http_hdr_in_set(r, authn_header, r->user);
970
971
0
  oidc_util_appinfo_set_all(r, claims, oidc_cfg_claim_prefix_get(c), oidc_cfg_claim_delimiter_get(c), pass_in,
972
0
          encoding);
973
974
0
  if (access_token != NULL)
975
0
    oidc_util_appinfo_set(r, OIDC_APP_INFO_ACCESS_TOKEN, access_token, OIDC_DEFAULT_HEADER_PREFIX, pass_in,
976
0
              encoding);
977
0
}
978
979
/* the value that a rejected access token is counted with when no check recorded why it was rejected */
980
#define OIDC_OAUTH_ERROR_REASON_OTHER "other"
981
982
/*
983
 * reject an access token: count it, with the check that it failed, and return the 401 for it
984
 *
985
 * NB: the caller returns this from the authentication hook, which ends the request, so the authorization
986
 *     hook never runs for it: that is where a request that does not meet a Require is counted in this same
987
 *     counter (oidc_authz_24_unauthorized_user), without a value, which is why a rejected token always has one
988
 */
989
0
static int oidc_oauth_return_invalid_token(request_rec *r, const oidc_cfg_t *c, const char *error_description) {
990
0
  const char *reason = oidc_metrics_error_reason_consume(r);
991
0
  OIDC_METRICS_COUNTER_INC_VALUE(r, c, OM_AUTHZ_ERROR_OAUTH20,
992
0
               reason != NULL ? reason : OIDC_OAUTH_ERROR_REASON_OTHER);
993
0
  return oidc_proto_return_www_authenticate(r, OIDC_PROTO_ERR_INVALID_TOKEN, error_description);
994
0
}
995
996
/*
997
 * main routine: handle OAuth 2.0 authentication/authorization
998
 */
999
0
int oidc_oauth_check_userid(request_rec *r, oidc_cfg_t *c, const char *access_token) {
1000
0
  oidc_json_t *claims = NULL;
1001
0
  char *s_token = NULL;
1002
0
  int rv = DECLINED;
1003
1004
  /*
1005
   * NB: do not recycle r->user from r->main/r->prev on sub-requests or internal redirects:
1006
   * Apache core already does that when the per-directory configuration is identical and only
1007
   * runs this hook when it differs, in which case the bearer token must be validated here
1008
   */
1009
0
  if (ap_is_initial_req(r) && (oidc_util_url_matches_redirect_uri(r, c) == TRUE))
1010
0
    rv = oidc_oauth_check_userid_redirect_uri(r, c);
1011
0
  if (rv != DECLINED)
1012
0
    return rv;
1013
1014
  /* we don't have a session yet */
1015
1016
  /* obtain/refresh metadata from OAuth metadata document URL if configured; from here on use the
1017
   * returned per-request view so metadata-derived endpoints never mutate the shared server config */
1018
0
  c = oidc_oauth_provider_config(r, c);
1019
1020
  /* get the bearer access token from the Authorization header */
1021
0
  if ((access_token == NULL) && (oidc_oauth_get_bearer_token(r, &access_token) == FALSE)) {
1022
0
    if (r->method_number == M_OPTIONS) {
1023
      /* a CORS preflight is let through unauthenticated, so the OIDC_* headers
1024
       * it carries are the client's own and must be scrubbed like on any other
1025
       * path that returns OK without authenticating */
1026
0
      oidc_scrub_headers(r);
1027
0
      r->user = "";
1028
0
      return OK;
1029
0
    }
1030
0
    return oidc_proto_return_www_authenticate(r, OIDC_PROTO_ERR_INVALID_REQUEST,
1031
0
                "No bearer token found in the request");
1032
0
  }
1033
1034
0
  oidc_util_set_trace_parent(r, c, access_token);
1035
1036
  /* validate the obtained access token against the OAuth AS validation endpoint */
1037
0
  if (oidc_oauth_validate_token(r, c, access_token, &claims, &s_token) == FALSE)
1038
0
    return oidc_oauth_return_invalid_token(r, c,
1039
0
                   oidc_cfg_oauth_introspection_endpoint_url_get(c) != NULL
1040
0
                 ? "Reference token could not be introspected"
1041
0
                 : "JWT token could not be validated");
1042
1043
  /* check that we've got something back */
1044
0
  if (claims == NULL) {
1045
0
    oidc_error(r, "could not resolve claims (token == NULL)");
1046
0
    return oidc_oauth_return_invalid_token(r, c, "No claims could be parsed from the token");
1047
0
  }
1048
1049
  /* store the parsed token (cq. the claims from the response) in the request state so it can be accessed by the
1050
   * authz routines */
1051
0
  oidc_request_state_json_set(r, OIDC_REQUEST_STATE_KEY_CLAIMS, claims);
1052
1053
  /* set the request user */
1054
0
  if (oidc_oauth_set_request_user(r, c, claims) == FALSE) {
1055
0
    oidc_json_decref(claims);
1056
0
    oidc_error(r, "remote user could not be set, aborting with HTTP_UNAUTHORIZED");
1057
0
    return oidc_oauth_return_invalid_token(r, c, "Could not set remote user");
1058
0
  }
1059
1060
  /*
1061
   * we're going to pass the information that we have to the application,
1062
   * but first we need to scrub the headers that we're going to use for security reasons
1063
   */
1064
0
  oidc_scrub_headers(r);
1065
1066
0
  oidc_oauth_pass_info_to_app(r, c, claims, access_token);
1067
1068
  /* free JSON resources */
1069
0
  oidc_json_decref(claims);
1070
1071
  /* strip any cookies that we need to */
1072
0
  oidc_strip_cookies(r);
1073
1074
0
  return OK;
1075
0
}