Coverage Report

Created: 2026-11-12 07:05

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
0
    oidc_warn(r,
363
0
        "the \"%s\" expiry claim has a value <= 0 (%.0f); caching the result for the default %d "
364
0
        "seconds instead",
365
0
        expiry_claim_name, value, OIDC_OAUTH_CACHE_DEFAULT_EXPIRY_SECONDS);
366
0
    return TRUE;
367
0
  }
368
369
0
  *cache_until = oidc_util_apr_time_from_sec(value);
370
0
  if (expiry_format_absolute == FALSE)
371
0
    *cache_until = oidc_util_apr_time_add(*cache_until, apr_time_now());
372
373
0
  return TRUE;
374
0
}
375
376
0
#define OIDC_OAUTH_CACHE_KEY_RESPONSE "r"
377
0
#define OIDC_OAUTH_CACHE_KEY_TIMESTAMP "t"
378
379
0
static const char *oidc_oauth_cache_key_str(const char *s) {
380
0
  return (s != NULL) ? s : "";
381
0
}
382
383
0
static int oidc_oauth_cache_key_cmp(const void *a, const void *b) {
384
0
  return _oidc_strcmp(*(const char *const *)a, *(const char *const *)b);
385
0
}
386
387
/*
388
 * add the JSON serialization of each local verification key, sorted so that the result does not
389
 * depend on configuration order or on the iteration order of the shared key hash table
390
 */
391
0
static apr_byte_t oidc_oauth_cache_key_add_jwks(request_rec *r, const oidc_cfg_t *c, apr_array_header_t *parts) {
392
0
  const apr_array_header_t *public_keys = oidc_cfg_oauth_verify_public_keys_get(c);
393
0
  apr_hash_t *shared_keys = oidc_cfg_oauth_verify_shared_keys_get(c);
394
0
  apr_array_header_t *keys = apr_array_make(r->pool, 4, sizeof(const char *));
395
0
  oidc_jose_error_t err;
396
0
  char *s_json = NULL;
397
398
0
  for (int i = 0; (public_keys != NULL) && (i < public_keys->nelts); i++) {
399
0
    if (oidc_jwk_to_json(r->pool, APR_ARRAY_IDX(public_keys, i, const oidc_jwk_t *), &s_json, &err) ==
400
0
        FALSE)
401
0
      goto error;
402
0
    APR_ARRAY_PUSH(keys, const char *) = s_json;
403
0
  }
404
405
0
  for (apr_hash_index_t *hi = (shared_keys != NULL) ? apr_hash_first(r->pool, shared_keys) : NULL; hi != NULL;
406
0
       hi = apr_hash_next(hi)) {
407
0
    void *jwk = NULL;
408
0
    apr_hash_this(hi, NULL, NULL, &jwk);
409
0
    if (oidc_jwk_to_json(r->pool, (const oidc_jwk_t *)jwk, &s_json, &err) == FALSE)
410
0
      goto error;
411
0
    APR_ARRAY_PUSH(keys, const char *) = s_json;
412
0
  }
413
414
0
  qsort(keys->elts, keys->nelts, keys->elt_size, oidc_oauth_cache_key_cmp);
415
0
  apr_array_cat(parts, keys);
416
0
  return TRUE;
417
418
0
error:
419
0
  oidc_error(r, "oidc_jwk_to_json failed: %s", oidc_jose_e2s(r->pool, err));
420
0
  return FALSE;
421
0
}
422
423
/*
424
 * return the cache key for the validation result of an access token: the result is only valid for
425
 * the verifier that produced it, so bind it to the introspection endpoint and client, or to the
426
 * JWKs URI and the local verification keys; returns NULL when the key cannot be constructed
427
 */
428
0
const char *oidc_oauth_cache_key(request_rec *r, const oidc_cfg_t *c, const char *access_token) {
429
0
  apr_array_header_t *parts = apr_array_make(r->pool, 8, sizeof(const char *));
430
0
  const char *url = oidc_cfg_oauth_introspection_endpoint_url_get(c);
431
0
  char *binding = NULL;
432
433
0
  if (url != NULL) {
434
0
    APR_ARRAY_PUSH(parts, const char *) = "introspect";
435
0
    APR_ARRAY_PUSH(parts, const char *) = url;
436
0
    APR_ARRAY_PUSH(parts, const char *) = oidc_oauth_cache_key_str(oidc_cfg_oauth_client_id_get(c));
437
0
  } else {
438
0
    APR_ARRAY_PUSH(parts, const char *) = "jwt";
439
0
    APR_ARRAY_PUSH(parts, const char *) = oidc_oauth_cache_key_str(oidc_cfg_oauth_verify_jwks_uri_get(c));
440
0
    if (oidc_oauth_cache_key_add_jwks(r, c, parts) == FALSE)
441
0
      return NULL;
442
0
  }
443
444
0
  if (oidc_util_hash_string_and_base64url_encode(r, OIDC_JOSE_ALG_SHA256, apr_array_pstrcat(r->pool, parts, '\n'),
445
0
                   &binding) == FALSE)
446
0
    return NULL;
447
448
0
  return apr_pstrcat(r->pool, binding, ".", access_token, NULL);
449
0
}
450
451
/*
452
 * cache the OAuth 2.0 introspection results for the specified access token
453
 */
454
static apr_byte_t oidc_oauth_cache_access_token(request_rec *r, const oidc_cfg_t *c, apr_time_t cache_until,
455
0
            const char *access_token, oidc_json_t *json) {
456
457
  /* no cache mode */
458
0
  int token_introspection_interval = oidc_cfg_dir_token_introspection_interval_get(r);
459
0
  if (token_introspection_interval == -1) {
460
0
    oidc_debug(r, "not caching introspection result");
461
0
    return TRUE;
462
0
  }
463
464
0
  const char *key = oidc_oauth_cache_key(r, c, access_token);
465
0
  if (key == NULL)
466
0
    return FALSE;
467
468
0
  oidc_debug(r, "caching introspection result");
469
470
0
  oidc_json_t *cache_entry = oidc_json_object();
471
0
  oidc_json_object_set(cache_entry, OIDC_OAUTH_CACHE_KEY_RESPONSE, json);
472
0
  oidc_json_object_set_new(cache_entry, OIDC_OAUTH_CACHE_KEY_TIMESTAMP,
473
0
         oidc_json_integer(apr_time_sec(apr_time_now())));
474
0
  const char *cache_value = oidc_json_encode(r->pool, cache_entry, OIDC_JSON_PRESERVE_ORDER | OIDC_JSON_COMPACT);
475
476
  /* set it in the cache so subsequent request don't need to validate the access_token and get the claims anymore
477
   */
478
0
  oidc_cache_set_access_token(r, key, cache_value, cache_until);
479
480
0
  oidc_json_decref(cache_entry);
481
482
0
  return TRUE;
483
0
}
484
485
/*
486
 * retrieve the OAuth 2.0 introspection results from the cache, for a previously introspected access token
487
 */
488
static apr_byte_t oidc_oauth_get_cached_access_token(request_rec *r, const oidc_cfg_t *c, const char *access_token,
489
0
                 oidc_json_t **json) {
490
0
  oidc_json_t *cache_entry = NULL;
491
0
  char *s_cache_entry = NULL;
492
493
  /* no cache mode */
494
0
  int token_introspection_interval = oidc_cfg_dir_token_introspection_interval_get(r);
495
0
  if (token_introspection_interval == -1) {
496
0
    return FALSE;
497
0
  }
498
499
0
  const char *key = oidc_oauth_cache_key(r, c, access_token);
500
0
  if (key == NULL)
501
0
    return FALSE;
502
503
  /* see if we've got the claims for this access_token cached already */
504
0
  oidc_cache_get_access_token(r, key, &s_cache_entry);
505
506
0
  if (s_cache_entry == NULL)
507
0
    return FALSE;
508
509
  /* json decode the cache entry */
510
0
  if (oidc_json_decode_object(r, s_cache_entry, &cache_entry) == FALSE) {
511
0
    *json = NULL;
512
0
    return FALSE;
513
0
  }
514
515
  /* compare the timestamp against the freshness requirement */
516
0
  const oidc_json_t *v = oidc_json_object_get(cache_entry, OIDC_OAUTH_CACHE_KEY_TIMESTAMP);
517
0
  apr_time_t now = apr_time_sec(apr_time_now());
518
0
  if ((token_introspection_interval > 0) && (now > oidc_json_integer_value(v) + token_introspection_interval)) {
519
520
    /* printout info about the event */
521
0
    char buf[APR_RFC822_DATE_LEN + 1];
522
0
    apr_rfc822_date(buf, apr_time_from_sec(oidc_json_integer_value(v)));
523
0
    oidc_debug(r,
524
0
         "token that was validated/cached at: [%s], does not meet token freshness requirement: %d)",
525
0
         buf, token_introspection_interval);
526
527
    /* invalidate the cache entry */
528
0
    *json = NULL;
529
0
    oidc_json_decref(cache_entry);
530
0
    return FALSE;
531
0
  }
532
533
0
  oidc_debug(r, "returning cached introspection result that meets freshness requirements: %s", s_cache_entry);
534
535
  /* we've got a cached introspection result that is still valid for this path's requirements */
536
0
  *json = oidc_json_copy(oidc_json_object_get(cache_entry, OIDC_OAUTH_CACHE_KEY_RESPONSE));
537
538
0
  oidc_json_decref(cache_entry);
539
0
  return TRUE;
540
0
}
541
542
/*
543
 * check the value of the "active" claim in an introspection response
544
 */
545
0
static apr_byte_t oidc_oauth_introspection_active_is_valid(request_rec *r, const oidc_json_t *active) {
546
0
  if (oidc_json_is_boolean(active)) {
547
0
    if (oidc_json_is_true(active))
548
0
      return TRUE;
549
0
    oidc_debug(r, "\"%s\" boolean object with value \"false\" found in response JSON object",
550
0
         OIDC_PROTO_ACTIVE);
551
0
    return FALSE;
552
0
  }
553
0
  if (oidc_json_is_string(active)) {
554
0
    if (_oidc_strnatcasecmp(oidc_json_string_value(active), "true") == 0)
555
0
      return TRUE;
556
0
    oidc_debug(r,
557
0
         "\"%s\" string object with value that is not equal to \"true\" found in response JSON "
558
0
         "object: %s",
559
0
         OIDC_PROTO_ACTIVE, oidc_json_string_value(active));
560
0
    return FALSE;
561
0
  }
562
0
  oidc_debug(r, "no \"%s\" boolean or string object found in response JSON object", OIDC_PROTO_ACTIVE);
563
0
  return FALSE;
564
0
}
565
566
/*
567
 * validate the introspection response (active claim + expiry) and cache it on success
568
 */
569
static apr_byte_t oidc_oauth_introspection_validate_and_cache(request_rec *r, oidc_cfg_t *c, const char *access_token,
570
0
                    oidc_json_t *result) {
571
0
  const oidc_json_t *active = oidc_json_object_get(result, OIDC_PROTO_ACTIVE);
572
0
  apr_time_t cache_until = apr_time_now() + apr_time_from_sec(OIDC_OAUTH_CACHE_DEFAULT_EXPIRY_SECONDS);
573
574
0
  if (active != NULL) {
575
0
    if (oidc_oauth_introspection_active_is_valid(r, active) == FALSE) {
576
0
      OIDC_METRICS_ERROR_REASON(r, "inactive");
577
0
      return FALSE;
578
0
    }
579
0
    if (oidc_oauth_parse_and_cache_token_expiry(r, c, result, OIDC_CLAIM_EXP, TRUE, FALSE, &cache_until) ==
580
0
        FALSE) {
581
0
      OIDC_METRICS_ERROR_REASON(r, "exp");
582
0
      return FALSE;
583
0
    }
584
0
  } else {
585
    /* the "active" member is REQUIRED by RFC 7662; warn when it is absent since validity is then
586
     * derived solely from the (possibly optional) configured expiry claim */
587
0
    oidc_warn(r,
588
0
        "introspection response did not contain the RFC 7662 \"%s\" member; token validity is "
589
0
        "determined solely from the \"%s\" expiry claim",
590
0
        OIDC_PROTO_ACTIVE, oidc_cfg_oauth_introspection_token_expiry_claim_name_get(c));
591
0
    if (oidc_oauth_parse_and_cache_token_expiry(
592
0
      r, c, result, oidc_cfg_oauth_introspection_token_expiry_claim_name_get(c),
593
0
      oidc_cfg_oauth_introspection_token_expiry_claim_format_get(c) ==
594
0
          OIDC_TOKEN_EXPIRY_CLAIM_FORMAT_ABSOLUTE,
595
0
      oidc_cfg_oauth_introspection_token_expiry_claim_required_get(c) ==
596
0
          OIDC_TOKEN_EXPIRY_CLAIM_REQUIRED_MANDATORY,
597
0
      &cache_until) == FALSE) {
598
0
      OIDC_METRICS_ERROR_REASON(r, "exp");
599
0
      return FALSE;
600
0
    }
601
0
  }
602
603
  /* set it in the cache so subsequent request don't need to validate the access_token and get the claims anymore
604
   */
605
0
  oidc_oauth_cache_access_token(r, c, cache_until, access_token, result);
606
0
  return TRUE;
607
0
}
608
609
/*
610
 * fetch and validate an introspection result for the given access_token from the AS
611
 */
612
0
static apr_byte_t oidc_oauth_introspect(request_rec *r, oidc_cfg_t *c, const char *access_token, oidc_json_t **result) {
613
0
  char *s_json = NULL;
614
615
  /* not cached, go out and validate the access_token against the Authorization server and get the JSON
616
   * claims back */
617
0
  if (oidc_oauth_validate_access_token(r, c, access_token, &s_json) == FALSE) {
618
0
    oidc_error(r, "could not get a validation response from the Authorization server");
619
0
    return FALSE;
620
0
  }
621
622
  /* decode and see if it is not an error response somehow */
623
0
  if (oidc_json_decode_and_check_error(r, s_json, result) == FALSE)
624
0
    return FALSE;
625
626
0
  if (oidc_oauth_introspection_validate_and_cache(r, c, access_token, *result) == FALSE) {
627
0
    oidc_json_decref(*result);
628
0
    *result = NULL;
629
0
    return FALSE;
630
0
  }
631
632
0
  return TRUE;
633
0
}
634
635
/*
636
 * shape the introspection result into the form returned to the caller: a PingFederate-style
637
 * nested access_token (enriched with client_id/scope) or the spec-compliant result as-is
638
 */
639
0
static void oidc_oauth_shape_introspection_token(oidc_json_t *result, oidc_json_t **token) {
640
0
  oidc_json_t *tkn = oidc_json_object_get(result, OIDC_PROTO_ACCESS_TOKEN);
641
0
  if ((tkn != NULL) && (oidc_json_is_object(tkn))) {
642
    /*
643
     * assume PingFederate validation: copy over those claims from the access_token
644
     * that are relevant for authorization purposes
645
     */
646
0
    oidc_json_object_set(tkn, OIDC_PROTO_CLIENT_ID, oidc_json_object_get(result, OIDC_PROTO_CLIENT_ID));
647
0
    oidc_json_object_set(tkn, OIDC_PROTO_SCOPE, oidc_json_object_get(result, OIDC_PROTO_SCOPE));
648
    /* return only the pimped access_token results */
649
0
    *token = oidc_json_copy(tkn);
650
0
    oidc_json_decref(result);
651
0
  } else {
652
    /* assume spec compliant introspection */
653
0
    *token = result;
654
0
  }
655
0
}
656
657
/*
658
 * resolve and validate an access_token against the configured Authorization Server
659
 */
660
static apr_byte_t oidc_oauth_resolve_access_token(request_rec *r, oidc_cfg_t *c, const char *access_token,
661
0
              oidc_json_t **token, char **response) {
662
0
  oidc_json_t *result = NULL;
663
664
  /* see if we've got the claims for this access_token cached already */
665
0
  oidc_oauth_get_cached_access_token(r, c, access_token, &result);
666
667
0
  if ((result == NULL) && (oidc_oauth_introspect(r, c, access_token, &result) == FALSE))
668
0
    return FALSE;
669
670
  /* return the access_token JSON object */
671
0
  oidc_oauth_shape_introspection_token(result, token);
672
673
  /* stringify the response */
674
0
  *response = oidc_json_encode(r->pool, *token, OIDC_JSON_PRESERVE_ORDER | OIDC_JSON_COMPACT);
675
676
0
  return TRUE;
677
0
}
678
679
/*
680
 * validate the "aud" claim of a locally validated JWT access token against the configured
681
 * audience value(s): this resource server must be among the intended recipients of the token,
682
 * but - unlike an id_token - other audiences may legitimately be present as well
683
 */
684
0
static apr_byte_t oidc_oauth_validate_jwt_aud(request_rec *r, const oidc_cfg_t *c, const oidc_json_t *claims) {
685
0
  const apr_array_header_t *arr = oidc_cfg_oauth_verify_aud_values_get(c);
686
0
  const oidc_json_t *aud = NULL;
687
688
  /* no audience configured: nothing to match against */
689
0
  if ((arr == NULL) || (arr->nelts == 0))
690
0
    return TRUE;
691
692
0
  aud = oidc_json_object_get(claims, OIDC_CLAIM_AUD);
693
0
  if (aud == NULL) {
694
0
    oidc_error(r,
695
0
         "JWT access token does not contain an \"%s\" claim, so it cannot be matched against the "
696
0
         "configured " OIDCOAuthVerifyAudience " value(s)",
697
0
         OIDC_CLAIM_AUD);
698
0
    return FALSE;
699
0
  }
700
701
0
  if (oidc_json_is_string(aud)) {
702
0
    for (int i = 0; i < arr->nelts; i++)
703
0
      if (_oidc_strcmp(oidc_json_string_value(aud), APR_ARRAY_IDX(arr, i, const char *)) == 0)
704
0
        return TRUE;
705
0
  } else if (oidc_json_is_array(aud)) {
706
    /* "aud" may be a single string or an array of strings (RFC 7519 section 4.1.3) */
707
0
    for (int i = 0; i < arr->nelts; i++)
708
0
      if (oidc_json_array_has_value(r, aud, APR_ARRAY_IDX(arr, i, const char *)) == TRUE)
709
0
        return TRUE;
710
0
  } else {
711
0
    oidc_error(r, "\"%s\" claim in the JWT access token is neither a string nor an array", OIDC_CLAIM_AUD);
712
0
    return FALSE;
713
0
  }
714
715
0
  oidc_error(r,
716
0
       "none of the configured " OIDCOAuthVerifyAudience " values matches the \"%s\" claim in the JWT "
717
0
       "access token",
718
0
       OIDC_CLAIM_AUD);
719
0
  return FALSE;
720
0
}
721
722
/*
723
 * validate the "iss" claim of a locally validated JWT access token against the configured issuer
724
 */
725
0
static apr_byte_t oidc_oauth_validate_jwt_iss(request_rec *r, const oidc_cfg_t *c, const oidc_json_t *claims) {
726
0
  const char *iss = oidc_cfg_oauth_verify_issuer_get(c);
727
0
  char *s_iss = NULL;
728
729
  /* no issuer configured: nothing to match against */
730
0
  if (iss == NULL)
731
0
    return TRUE;
732
733
0
  if (oidc_json_object_get_string(r->pool, claims, OIDC_CLAIM_ISS, &s_iss, NULL) == FALSE)
734
0
    return FALSE;
735
736
0
  if (s_iss == NULL) {
737
0
    oidc_error(r,
738
0
         "JWT access token does not contain an \"%s\" claim, so it cannot be matched against the "
739
0
         "configured " OIDCOAuthVerifyIssuer " value (%s)",
740
0
         OIDC_CLAIM_ISS, iss);
741
0
    return FALSE;
742
0
  }
743
744
0
  if (oidc_util_issuer_match(iss, s_iss) == FALSE) {
745
0
    oidc_error(r,
746
0
         "configured " OIDCOAuthVerifyIssuer " (%s) does not match the \"%s\" claim (%s) in the "
747
0
         "JWT access token",
748
0
         iss, OIDC_CLAIM_ISS, s_iss);
749
0
    return FALSE;
750
0
  }
751
752
0
  return TRUE;
753
0
}
754
755
/*
756
 * Validate RFC 9068 resource-server claims even on cache hits, which may be shared by vhosts
757
 * with different audience or issuer settings.
758
 */
759
0
static apr_byte_t oidc_oauth_validate_jwt_claims(request_rec *r, const oidc_cfg_t *c, const oidc_json_t *claims) {
760
0
  if (oidc_oauth_validate_jwt_iss(r, c, claims) == FALSE)
761
0
    return FALSE;
762
0
  return oidc_oauth_validate_jwt_aud(r, c, claims);
763
0
}
764
765
/*
766
 * validate a JWT access token (locally)
767
 *
768
 * NB: reuses the following settings from the OIDC (RP) configuration section, as documented
769
 *     in auth_openidc.conf:
770
 *     - the JWKs cache refresh interval (OIDCJWKSRefreshInterval)
771
 *     - decryption key material (OIDCPrivateKeyFiles)
772
 *
773
 * OIDCOAuthRemoteUserClaim client_id
774
 * # 32x 61 hex
775
 * OIDCOAuthVerifySharedKeys aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
776
 */
777
static apr_byte_t oidc_oauth_validate_jwt_access_token(request_rec *r, oidc_cfg_t *c, const char *access_token,
778
0
                   oidc_json_t **token, char **response) {
779
780
0
  oidc_debug(r, "enter: JWT access_token header=%s",
781
0
       oidc_proto_jwt_header_peek(r, access_token, NULL, NULL, NULL));
782
783
0
  oidc_jose_error_t err;
784
0
  oidc_jwk_t *jwk = NULL;
785
0
  apr_hash_t *decrypt_keys = NULL;
786
0
  oidc_json_t *cached = NULL;
787
788
  /* Reuse cached validation until token expiry or the configured introspection interval. */
789
0
  oidc_oauth_get_cached_access_token(r, c, access_token, &cached);
790
0
  if (cached != NULL) {
791
0
    if (oidc_oauth_validate_jwt_claims(r, c, cached) == FALSE) {
792
0
      oidc_json_decref(cached);
793
0
      return FALSE;
794
0
    }
795
0
    *token = cached;
796
0
    *response = oidc_json_encode(r->pool, cached, OIDC_JSON_PRESERVE_ORDER | OIDC_JSON_COMPACT);
797
0
    return TRUE;
798
0
  }
799
800
0
  if (oidc_cfg_oauth_decrypt_shared_keys_get(c) != NULL) {
801
    /* symmetric decryption keys configured with OIDCOAuthDecryptSharedKeys */
802
0
    decrypt_keys = oidc_util_key_sets_merge(r->pool, oidc_cfg_oauth_decrypt_shared_keys_get(c),
803
0
              oidc_cfg_private_keys_get(c));
804
0
  } else {
805
    /* fall back to a symmetric key derived from the client secret configured for the
806
     * OpenID Connect provider, alongside the OIDCPrivateKeyFiles key material */
807
0
    if (oidc_util_key_symmetric_create(r, oidc_cfg_provider_client_secret_get(oidc_cfg_provider_get(c)), 0,
808
0
               NULL, TRUE, &jwk) == FALSE)
809
0
      return FALSE;
810
0
    decrypt_keys = oidc_util_key_symmetric_merge(r->pool, oidc_cfg_private_keys_get(c), jwk);
811
0
  }
812
813
0
  oidc_jwt_t *jwt = NULL;
814
0
  if (oidc_jwt_parse(r->pool, access_token, &jwt, decrypt_keys, FALSE, &err) == FALSE) {
815
0
    oidc_error(r, "could not parse JWT from access_token: %s", oidc_jose_e2s(r->pool, err));
816
0
    oidc_jwk_destroy(jwk);
817
0
    return FALSE;
818
0
  }
819
820
0
  oidc_jwk_destroy(jwk);
821
0
  oidc_debug(r, "successfully parsed JWT with header: %s", jwt->header.value.str);
822
823
  /*
824
   * RFC 9068 requires exp. Validate iss and aud after signature verification, including on
825
   * cache hits; iat is not enforced for access tokens.
826
   */
827
0
  if (oidc_proto_jwt_validate(r, jwt, NULL, TRUE, FALSE, -1) == FALSE) {
828
0
    oidc_jwt_destroy(jwt);
829
0
    return FALSE;
830
0
  }
831
832
0
  oidc_debug(
833
0
      r, "verify JWT against %d statically configured public keys and %d shared keys, with JWKs URI set to %s",
834
0
      oidc_cfg_oauth_verify_public_keys_get(c) ? oidc_cfg_oauth_verify_public_keys_get(c)->nelts : 0,
835
0
      oidc_cfg_oauth_verify_shared_keys_get(c) ? apr_hash_count(oidc_cfg_oauth_verify_shared_keys_get(c)) : 0,
836
0
      oidc_cfg_oauth_verify_jwks_uri_get(c));
837
838
  /* the JWKs cache refresh interval is shared with the OIDC provider one (OIDCJWKSRefreshInterval),
839
   * as documented in auth_openidc.conf */
840
0
  oidc_jwks_uri_t jwks_uri = {oidc_cfg_oauth_verify_jwks_uri_get(c),
841
0
            oidc_cfg_provider_jwks_uri_refresh_interval_get(oidc_cfg_provider_get(c)), NULL,
842
0
            NULL};
843
0
  if (oidc_proto_jwt_verify(r, c, jwt, &jwks_uri, oidc_cfg_oauth_ssl_validate_server_get(c),
844
0
          oidc_util_key_sets_merge(r->pool, oidc_cfg_oauth_verify_shared_keys_get(c),
845
0
                 oidc_cfg_oauth_verify_public_keys_get(c)),
846
0
          NULL) == FALSE) {
847
0
    oidc_error(r, "JWT access token signature could not be validated, aborting");
848
0
    oidc_jwt_destroy(jwt);
849
0
    return FALSE;
850
0
  }
851
852
0
  oidc_debug(r, "successfully verified JWT access token: %s", jwt->payload.value.str);
853
854
  /* the signature is authentic: now check that the token was actually meant for us */
855
0
  if (oidc_oauth_validate_jwt_claims(r, c, jwt->payload.value.json) == FALSE) {
856
0
    oidc_jwt_destroy(jwt);
857
0
    return FALSE;
858
0
  }
859
860
  /* cache the validated claims bounded by the token's expiry so subsequent requests carrying the same
861
   * bearer token skip re-verification; "exp" is mandatory and was verified above, so it always bounds
862
   * the entry here and the default below is not reached */
863
0
  apr_time_t cache_until = apr_time_now() + apr_time_from_sec(OIDC_OAUTH_CACHE_DEFAULT_EXPIRY_SECONDS);
864
0
  if (oidc_oauth_parse_and_cache_token_expiry(r, c, jwt->payload.value.json, OIDC_CLAIM_EXP, TRUE, FALSE,
865
0
                &cache_until) == TRUE)
866
0
    oidc_oauth_cache_access_token(r, c, cache_until, access_token, jwt->payload.value.json);
867
868
0
  *token = oidc_json_copy(jwt->payload.value.json);
869
0
  *response = jwt->payload.value.str;
870
871
0
  oidc_jwt_destroy(jwt);
872
873
0
  return TRUE;
874
0
}
875
876
/*
877
 * set the unique user identifier that will be propagated in the Apache r->user and REMOTE_USER variables
878
 */
879
0
static apr_byte_t oidc_oauth_set_request_user(request_rec *r, const oidc_cfg_t *c, const oidc_json_t *token) {
880
0
  char *remote_user = NULL;
881
882
0
  if (oidc_get_remote_user(r, oidc_cfg_oauth_remote_user_claim_name_get(c),
883
0
         oidc_cfg_oauth_remote_user_claim_get(c)->reg_exp,
884
0
         oidc_cfg_oauth_remote_user_claim_get(c)->replace, token, &remote_user) == FALSE) {
885
0
    oidc_error(
886
0
        r,
887
0
        "" OIDCOAuthRemoteUserClaim
888
0
        " is set to \"%s\", but could not set the remote user based the available claims for the user",
889
0
        oidc_cfg_oauth_remote_user_claim_name_get(c));
890
0
    return FALSE;
891
0
  }
892
893
0
  r->user = apr_pstrdup(r->pool, remote_user);
894
0
  oidc_debug(r, "set user to \"%s\" based on claim: \"%s\"%s", r->user,
895
0
       oidc_cfg_oauth_remote_user_claim_name_get(c),
896
0
       oidc_cfg_oauth_remote_user_claim_get(c)->reg_exp
897
0
           ? apr_psprintf(r->pool, " and expression: \"%s\" and replace string: \"%s\"",
898
0
              oidc_cfg_oauth_remote_user_claim_get(c)->reg_exp,
899
0
              oidc_cfg_oauth_remote_user_claim_get(c)->replace)
900
0
           : "");
901
0
  return TRUE;
902
0
}
903
904
/*
905
 * handle "special" requests directed at the Redirect URI (JWKS, remove-access-token-cache);
906
 * returns the status to send back, or DECLINED if not a special request
907
 */
908
0
static int oidc_oauth_check_userid_redirect_uri(request_rec *r, const oidc_cfg_t *c) {
909
0
  if (oidc_util_url_has_parameter(r, OIDC_REDIRECT_URI_REQUEST_JWKS)) {
910
0
    OIDC_METRICS_COUNTER_INC(r, c, OM_REDIRECT_URI_REQUEST_JWKS);
911
    /*
912
     * Will be handled in the content handler; avoid:
913
     * No authentication done but request not allowed without authentication
914
     * by setting r->user. No authentication happened, so any OIDC_* headers
915
     * on this request came from the client and must not survive it.
916
     */
917
0
    oidc_scrub_headers(r);
918
0
    r->user = "";
919
0
    return OK;
920
0
  }
921
0
  if (oidc_util_url_has_parameter(r, OIDC_REDIRECT_URI_REQUEST_REMOVE_AT_CACHE))
922
0
    return oidc_revoke_at_cache_remove(r, c);
923
0
  return DECLINED;
924
0
}
925
926
/*
927
 * validate the access token via the configured introspection endpoint or as a local JWT
928
 */
929
static apr_byte_t oidc_oauth_validate_token(request_rec *r, oidc_cfg_t *c, const char *access_token,
930
0
              oidc_json_t **claims, char **s_token) {
931
0
  if (oidc_cfg_oauth_introspection_endpoint_url_get(c) != NULL)
932
0
    return oidc_oauth_resolve_access_token(r, c, access_token, claims, s_token);
933
0
  return oidc_oauth_validate_jwt_access_token(r, c, access_token, claims, s_token);
934
0
}
935
936
/*
937
 * propagate claims and access_token into the application HTTP headers
938
 */
939
static void oidc_oauth_pass_info_to_app(request_rec *r, const oidc_cfg_t *c, oidc_json_t *claims,
940
0
          const char *access_token) {
941
0
  const char *authn_header = oidc_cfg_dir_authn_header_get(r);
942
0
  oidc_appinfo_pass_in_t pass_in = oidc_cfg_dir_pass_info_in_get(r);
943
0
  oidc_appinfo_encoding_t encoding = oidc_cfg_dir_pass_info_encoding_get(r);
944
945
0
  if ((r->user != NULL) && (authn_header != NULL))
946
0
    oidc_http_hdr_in_set(r, authn_header, r->user);
947
948
0
  oidc_util_appinfo_set_all(r, claims, oidc_cfg_claim_prefix_get(c), oidc_cfg_claim_delimiter_get(c), pass_in,
949
0
          encoding);
950
951
0
  if (access_token != NULL)
952
0
    oidc_util_appinfo_set(r, OIDC_APP_INFO_ACCESS_TOKEN, access_token, OIDC_DEFAULT_HEADER_PREFIX, pass_in,
953
0
              encoding);
954
0
}
955
956
/*
957
 * main routine: handle OAuth 2.0 authentication/authorization
958
 */
959
0
int oidc_oauth_check_userid(request_rec *r, oidc_cfg_t *c, const char *access_token) {
960
0
  oidc_json_t *claims = NULL;
961
0
  char *s_token = NULL;
962
0
  int rv = DECLINED;
963
964
  /*
965
   * NB: do not recycle r->user from r->main/r->prev on sub-requests or internal redirects:
966
   * Apache core already does that when the per-directory configuration is identical and only
967
   * runs this hook when it differs, in which case the bearer token must be validated here
968
   */
969
0
  if (ap_is_initial_req(r) && (oidc_util_url_matches_redirect_uri(r, c) == TRUE))
970
0
    rv = oidc_oauth_check_userid_redirect_uri(r, c);
971
0
  if (rv != DECLINED)
972
0
    return rv;
973
974
  /* we don't have a session yet */
975
976
  /* obtain/refresh metadata from OAuth metadata document URL if configured; from here on use the
977
   * returned per-request view so metadata-derived endpoints never mutate the shared server config */
978
0
  c = oidc_oauth_provider_config(r, c);
979
980
  /* get the bearer access token from the Authorization header */
981
0
  if ((access_token == NULL) && (oidc_oauth_get_bearer_token(r, &access_token) == FALSE)) {
982
0
    if (r->method_number == M_OPTIONS) {
983
      /* a CORS preflight is let through unauthenticated, so the OIDC_* headers
984
       * it carries are the client's own and must be scrubbed like on any other
985
       * path that returns OK without authenticating */
986
0
      oidc_scrub_headers(r);
987
0
      r->user = "";
988
0
      return OK;
989
0
    }
990
0
    return oidc_proto_return_www_authenticate(r, OIDC_PROTO_ERR_INVALID_REQUEST,
991
0
                "No bearer token found in the request");
992
0
  }
993
994
0
  oidc_util_set_trace_parent(r, c, access_token);
995
996
  /* validate the obtained access token against the OAuth AS validation endpoint */
997
0
  if (oidc_oauth_validate_token(r, c, access_token, &claims, &s_token) == FALSE)
998
0
    return oidc_proto_return_www_authenticate(r, OIDC_PROTO_ERR_INVALID_TOKEN,
999
0
                oidc_cfg_oauth_introspection_endpoint_url_get(c) != NULL
1000
0
                    ? "Reference token could not be introspected"
1001
0
                    : "JWT token could not be validated");
1002
1003
  /* check that we've got something back */
1004
0
  if (claims == NULL) {
1005
0
    oidc_error(r, "could not resolve claims (token == NULL)");
1006
0
    return oidc_proto_return_www_authenticate(r, OIDC_PROTO_ERR_INVALID_TOKEN,
1007
0
                "No claims could be parsed from the token");
1008
0
  }
1009
1010
  /* store the parsed token (cq. the claims from the response) in the request state so it can be accessed by the
1011
   * authz routines */
1012
0
  oidc_request_state_json_set(r, OIDC_REQUEST_STATE_KEY_CLAIMS, claims);
1013
1014
  /* set the request user */
1015
0
  if (oidc_oauth_set_request_user(r, c, claims) == FALSE) {
1016
0
    oidc_json_decref(claims);
1017
0
    oidc_error(r, "remote user could not be set, aborting with HTTP_UNAUTHORIZED");
1018
0
    return oidc_proto_return_www_authenticate(r, OIDC_PROTO_ERR_INVALID_TOKEN, "Could not set remote user");
1019
0
  }
1020
1021
  /*
1022
   * we're going to pass the information that we have to the application,
1023
   * but first we need to scrub the headers that we're going to use for security reasons
1024
   */
1025
0
  oidc_scrub_headers(r);
1026
1027
0
  oidc_oauth_pass_info_to_app(r, c, claims, access_token);
1028
1029
  /* free JSON resources */
1030
0
  oidc_json_decref(claims);
1031
1032
  /* strip any cookies that we need to */
1033
0
  oidc_strip_cookies(r);
1034
1035
0
  return OK;
1036
0
}