/
mod_auth_openidc.c
2229 lines (1811 loc) · 74.4 KB
/
mod_auth_openidc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/***************************************************************************
* Copyright (C) 2017-2024 ZmartZone Holding BV
* Copyright (C) 2013-2017 Ping Identity Corporation
* All rights reserved.
*
* DISCLAIMER OF WARRANTIES:
*
* THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
* ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NOR ARE THERE ANY
* WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
* USAGE. FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
* YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
* WILL BE UNINTERRUPTED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Initially based on mod_auth_cas.c:
* https://github.com/Jasig/mod_auth_cas
*
* Other code copied/borrowed/adapted:
* shared memory caching: mod_auth_mellon
*
* @Author: Hans Zandbelt - hans.zandbelt@openidc.com
*
**************************************************************************/
#include "mod_auth_openidc.h"
#include "cfg/cache.h"
#include "cfg/dir.h"
#include "cfg/oauth.h"
#include "handle/handle.h"
#include "metadata.h"
#include "metrics.h"
#include "oauth.h"
#include "proto.h"
#include "util.h"
#define OPENSSL_THREAD_DEFINES
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/opensslconf.h>
#include <openssl/opensslv.h>
#if (OPENSSL_VERSION_NUMBER < 0x01000000)
#define OPENSSL_NO_THREADID
#endif
#include <apr_portable.h>
#include <apr_sha1.h>
/*
* clean any suspicious headers in the HTTP request sent by the user agent
*/
static void oidc_scrub_request_headers(request_rec *r, const char *claim_prefix, apr_hash_t *scrub) {
const int prefix_len = claim_prefix ? _oidc_strlen(claim_prefix) : 0;
/* get an array representation of the incoming HTTP headers */
const apr_array_header_t *const h = apr_table_elts(r->headers_in);
/* table to keep the non-suspicious headers */
apr_table_t *clean_headers = apr_table_make(r->pool, h->nelts);
/* loop over the incoming HTTP headers */
const apr_table_entry_t *const e = (const apr_table_entry_t *)h->elts;
int i;
for (i = 0; i < h->nelts; i++) {
const char *const k = e[i].key;
/* is this header's name equivalent to a header that needs scrubbing? */
const char *hdr = (k != NULL) && (scrub != NULL) ? apr_hash_get(scrub, k, APR_HASH_KEY_STRING) : NULL;
const int header_matches = (hdr != NULL) && (oidc_util_strnenvcmp(k, hdr, -1) == 0);
/*
* would this header be interpreted as a mod_auth_openidc attribute? Note
* that prefix_len will be zero if no attr_prefix is defined,
* so this will always be false. Also note that we do not
* scrub headers if the prefix is empty because every header
* would match.
*/
const int prefix_matches =
(k != NULL) && prefix_len && (oidc_util_strnenvcmp(k, claim_prefix, prefix_len) == 0);
/* add to the clean_headers if non-suspicious, skip and report otherwise */
if (!prefix_matches && !header_matches) {
apr_table_addn(clean_headers, k, e[i].val);
} else {
oidc_warn(r, "scrubbed suspicious request header (%s: %.32s)", k, e[i].val);
}
}
/* overwrite the incoming headers with the cleaned result */
r->headers_in = clean_headers;
}
/*
* scrub all mod_auth_openidc related headers
*/
void oidc_scrub_headers(request_rec *r) {
oidc_cfg_t *cfg = ap_get_module_config(r->server->module_config, &auth_openidc_module);
const char *prefix = oidc_cfg_claim_prefix_get(cfg);
apr_hash_t *hdrs = apr_hash_make(r->pool);
if (_oidc_strcmp(prefix, "") == 0) {
if ((oidc_cfg_white_listed_claims_get(cfg) != NULL) &&
(apr_hash_count(oidc_cfg_white_listed_claims_get(cfg)) > 0))
hdrs = apr_hash_overlay(r->pool, oidc_cfg_white_listed_claims_get(cfg), hdrs);
else
oidc_warn(r, "both " OIDCClaimPrefix " and " OIDCWhiteListedClaims
" are empty: this renders an insecure setup!");
}
const char *authn_hdr = oidc_cfg_dir_authn_header_get(r);
if (authn_hdr != NULL)
apr_hash_set(hdrs, authn_hdr, APR_HASH_KEY_STRING, authn_hdr);
/*
* scrub all headers starting with OIDC_ first
*/
oidc_scrub_request_headers(r, OIDC_DEFAULT_HEADER_PREFIX, hdrs);
/*
* then see if the claim headers need to be removed on top of that
* (i.e. the prefix does not start with the default OIDC_)
*/
if ((_oidc_strstr(prefix, OIDC_DEFAULT_HEADER_PREFIX) != prefix)) {
oidc_scrub_request_headers(r, prefix, NULL);
}
}
/*
* strip the session cookie from the headers sent to the application/backend
*/
void oidc_strip_cookies(request_rec *r) {
char *cookie, *ctx, *result = NULL;
const char *name = NULL;
int i;
const apr_array_header_t *strip = oidc_cfg_dir_strip_cookies_get(r);
char *cookies = apr_pstrdup(r->pool, oidc_http_hdr_in_cookie_get(r));
if ((cookies != NULL) && (strip != NULL)) {
oidc_debug(r, "looking for the following cookies to strip from cookie header: %s",
apr_array_pstrcat(r->pool, strip, OIDC_CHAR_COMMA));
cookie = apr_strtok(cookies, OIDC_STR_SEMI_COLON, &ctx);
do {
while (cookie != NULL && *cookie == OIDC_CHAR_SPACE)
cookie++;
if (cookie == NULL)
break;
for (i = 0; i < strip->nelts; i++) {
name = APR_ARRAY_IDX(strip, i, const char *);
if ((_oidc_strncmp(cookie, name, _oidc_strlen(name)) == 0) &&
(cookie[_oidc_strlen(name)] == OIDC_CHAR_EQUAL)) {
oidc_debug(r, "stripping: %s", name);
break;
}
}
if (i == strip->nelts) {
result = result ? apr_psprintf(r->pool, "%s%s %s", result, OIDC_STR_SEMI_COLON, cookie)
: cookie;
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &ctx);
} while (cookie != NULL);
oidc_http_hdr_in_cookie_set(r, result);
}
}
#define OIDC_SHA1_LEN 20
/*
* calculates a hash value based on request fingerprint plus a provided nonce string.
*/
char *oidc_get_browser_state_hash(request_rec *r, oidc_cfg_t *c, const char *nonce) {
oidc_debug(r, "enter");
/* helper to hold to header values */
const char *value = NULL;
/* the hash context */
apr_sha1_ctx_t sha1;
/* Initialize the hash context */
apr_sha1_init(&sha1);
if (oidc_cfg_state_input_headers_get(c) & OIDC_STATE_INPUT_HEADERS_X_FORWARDED_FOR) {
/* get the X-FORWARDED-FOR header value */
value = oidc_http_hdr_in_x_forwarded_for_get(r);
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, _oidc_strlen(value));
}
if (oidc_cfg_state_input_headers_get(c) & OIDC_STATE_INPUT_HEADERS_USER_AGENT) {
/* get the USER-AGENT header value */
value = oidc_http_hdr_in_user_agent_get(r);
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, _oidc_strlen(value));
}
/* get the remote client IP address or host name */
/*
int remotehost_is_ip;
value = ap_get_remote_host(r->connection, r->per_dir_config,
REMOTE_NOLOOKUP, &remotehost_is_ip);
apr_sha1_update(&sha1, value, _oidc_strlen(value));
*/
/* concat the nonce parameter to the hash input */
apr_sha1_update(&sha1, nonce, _oidc_strlen(nonce));
/* finalize the hash input and calculate the resulting hash output */
unsigned char hash[OIDC_SHA1_LEN];
apr_sha1_final(hash, &sha1);
/* base64url-encode the resulting hash and return it */
char *result = NULL;
oidc_util_base64url_encode(r, &result, (const char *)hash, OIDC_SHA1_LEN, TRUE);
return result;
}
/*
* return the name for the state cookie
*/
char *oidc_get_state_cookie_name(request_rec *r, const char *state) {
return apr_psprintf(r->pool, "%s%s", oidc_cfg_dir_state_cookie_prefix_get(r), state);
}
/*
* check if s_json is valid provider metadata
*/
static apr_byte_t oidc_provider_validate_metadata_str(request_rec *r, oidc_cfg_t *c, const char *s_json,
json_t **j_provider, apr_byte_t decode_only) {
if (oidc_util_decode_json_object(r, s_json, j_provider) == FALSE)
return FALSE;
if (decode_only == TRUE)
return TRUE;
/* check to see if it is valid metadata */
if (oidc_metadata_provider_is_valid(r, c, *j_provider, NULL) == FALSE) {
oidc_warn(r, "cache corruption detected: invalid metadata from url: %s",
oidc_cfg_provider_metadata_url_get(oidc_cfg_provider_get(c)));
json_decref(*j_provider);
return FALSE;
}
return TRUE;
}
/*
* return the static provider configuration, i.e. from a metadata URL or configuration primitives
*/
apr_byte_t oidc_provider_static_config(request_rec *r, oidc_cfg_t *c, oidc_provider_t **provider) {
json_t *j_provider = NULL;
char *s_json = NULL;
/* see if we should configure a static provider based on external (cached) metadata */
if ((oidc_cfg_metadata_dir_get(c) != NULL) ||
(oidc_cfg_provider_metadata_url_get(oidc_cfg_provider_get(c)) == NULL)) {
*provider = oidc_cfg_provider_get(c);
return TRUE;
}
oidc_cache_get_provider(r, oidc_cfg_provider_metadata_url_get(oidc_cfg_provider_get(c)), &s_json);
if (s_json != NULL)
oidc_provider_validate_metadata_str(r, c, s_json, &j_provider, TRUE);
if (j_provider == NULL) {
if (oidc_metadata_provider_retrieve(r, c, NULL,
oidc_cfg_provider_metadata_url_get(oidc_cfg_provider_get(c)),
&j_provider, &s_json) == FALSE) {
oidc_error(r, "could not retrieve metadata from url: %s",
oidc_cfg_provider_metadata_url_get(oidc_cfg_provider_get(c)));
return FALSE;
}
json_decref(j_provider);
if (oidc_provider_validate_metadata_str(r, c, s_json, &j_provider, FALSE) == FALSE)
return FALSE;
oidc_cache_set_provider(
r, oidc_cfg_provider_metadata_url_get(oidc_cfg_provider_get(c)), s_json,
apr_time_now() + apr_time_from_sec(oidc_cfg_provider_metadata_refresh_interval_get(c) <= 0
? OIDC_CACHE_PROVIDER_METADATA_EXPIRY_DEFAULT
: oidc_cfg_provider_metadata_refresh_interval_get(c)));
}
*provider = oidc_cfg_provider_copy(r->pool, oidc_cfg_provider_get(c));
if (oidc_metadata_provider_parse(r, c, j_provider, *provider) == FALSE) {
oidc_error(r, "could not parse metadata from url: %s",
oidc_cfg_provider_metadata_url_get(oidc_cfg_provider_get(c)));
json_decref(j_provider);
return FALSE;
}
json_decref(j_provider);
return TRUE;
}
/*
* return the oidc_provider_t struct for the specified issuer
*/
oidc_provider_t *oidc_get_provider_for_issuer(request_rec *r, oidc_cfg_t *c, const char *issuer,
apr_byte_t allow_discovery) {
/* by default we'll assume that we're dealing with a single statically configured OP */
oidc_provider_t *provider = NULL;
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return NULL;
/* unless a metadata directory was configured, so we'll try and get the provider settings from there */
if (oidc_cfg_metadata_dir_get(c) != NULL) {
/* try and get metadata from the metadata directory for the OP that sent this response */
if ((oidc_metadata_get(r, c, issuer, &provider, allow_discovery) == FALSE) || (provider == NULL)) {
/* don't know nothing about this OP/issuer */
oidc_error(r, "no provider metadata found for issuer \"%s\"", issuer);
return NULL;
}
}
return provider;
}
/*
* return the HTTP method being called: only for POST data persistence purposes
*/
const char *oidc_original_request_method(request_rec *r, oidc_cfg_t *cfg, apr_byte_t handle_discovery_response) {
const char *method = OIDC_METHOD_GET;
char *m = NULL;
if ((handle_discovery_response == TRUE) && (oidc_util_request_matches_url(r, oidc_util_redirect_uri(r, cfg))) &&
(oidc_is_discovery_response(r, cfg))) {
oidc_util_request_parameter_get(r, OIDC_DISC_RM_PARAM, &m);
if (m != NULL)
method = apr_pstrdup(r->pool, m);
} else {
/*
* if POST preserve is not enabled for this location, there's no point in preserving
* the method either which would result in POSTing empty data on return;
* so we revert to legacy behavior
*/
if (oidc_cfg_dir_preserve_post_get(r) == 0)
return OIDC_METHOD_GET;
const char *content_type = oidc_http_hdr_in_content_type_get(r);
if ((r->method_number == M_POST) &&
(_oidc_strcmp(content_type, OIDC_HTTP_CONTENT_TYPE_FORM_ENCODED) == 0))
method = OIDC_METHOD_FORM_POST;
}
oidc_debug(r, "return: %s", method);
return method;
}
// element in a list of state cookies
typedef struct oidc_state_cookies_t {
char *name;
apr_time_t timestamp;
struct oidc_state_cookies_t *next;
} oidc_state_cookies_t;
/*
* delete superfluous state cookies i.e. exceeding the maximum, starting with the oldest ones
*/
static int oidc_delete_oldest_state_cookies(request_rec *r, oidc_cfg_t *c, int number_of_valid_state_cookies,
int max_number_of_state_cookies, oidc_state_cookies_t *first) {
oidc_state_cookies_t *cur = NULL, *prev = NULL, *prev_oldest = NULL, *oldest = NULL;
// loop over the list of state cookies, deleting the oldest one until we reach an acceptable number
while (number_of_valid_state_cookies >= max_number_of_state_cookies) {
oldest = first;
prev_oldest = NULL;
prev = first;
cur = first ? first->next : NULL;
// find the oldest state cookie in the list (stored in "oldest")
while (cur) {
if ((cur->timestamp < oldest->timestamp)) {
oldest = cur;
prev_oldest = prev;
}
prev = cur;
cur = cur->next;
}
oidc_warn(r, "deleting oldest state cookie: %s (time until expiry %" APR_TIME_T_FMT " seconds)",
oldest->name, apr_time_sec(oldest->timestamp - apr_time_now()));
oidc_http_set_cookie(r, oldest->name, "", 0, OIDC_COOKIE_EXT_SAME_SITE_NONE(c, r));
if (prev_oldest)
prev_oldest->next = oldest->next;
else
first = first ? first->next : NULL;
number_of_valid_state_cookies--;
}
return number_of_valid_state_cookies;
}
/*
* clean state cookies that have expired i.e. for outstanding requests that will never return
* successfully and return the number of remaining valid cookies/outstanding-requests while
* doing so
*/
int oidc_clean_expired_state_cookies(request_rec *r, oidc_cfg_t *c, const char *currentCookieName, int delete_oldest) {
int number_of_valid_state_cookies = 0;
oidc_state_cookies_t *first = NULL, *last = NULL;
char *cookie, *tokenizerCtx = NULL;
char *cookies = apr_pstrdup(r->pool, oidc_http_hdr_in_cookie_get(r));
if (cookies != NULL) {
cookie = apr_strtok(cookies, OIDC_STR_SEMI_COLON, &tokenizerCtx);
while (cookie != NULL) {
while (*cookie == OIDC_CHAR_SPACE)
cookie++;
if (_oidc_strstr(cookie, oidc_cfg_dir_state_cookie_prefix_get(r)) == cookie) {
char *cookieName = cookie;
while (cookie != NULL && *cookie != OIDC_CHAR_EQUAL)
cookie++;
if (*cookie == OIDC_CHAR_EQUAL) {
*cookie = '\0';
cookie++;
if ((currentCookieName == NULL) ||
(_oidc_strcmp(cookieName, currentCookieName) != 0)) {
oidc_proto_state_t *proto_state =
oidc_proto_state_from_cookie(r, c, cookie);
if (proto_state != NULL) {
json_int_t ts = oidc_proto_state_get_timestamp(proto_state);
if (apr_time_now() >
ts + apr_time_from_sec(oidc_cfg_state_timeout_get(c))) {
oidc_warn(
r, "state (%s) has expired (original_url=%s)",
cookieName,
oidc_proto_state_get_original_url(proto_state));
oidc_http_set_cookie(
r, cookieName, "", 0,
OIDC_COOKIE_EXT_SAME_SITE_NONE(c, r));
} else {
if (first == NULL) {
first = apr_pcalloc(
r->pool, sizeof(oidc_state_cookies_t));
last = first;
} else {
last->next = apr_pcalloc(
r->pool, sizeof(oidc_state_cookies_t));
last = last->next;
}
last->name = cookieName;
last->timestamp = ts;
last->next = NULL;
number_of_valid_state_cookies++;
}
oidc_proto_state_destroy(proto_state);
} else {
oidc_warn(
r,
"state cookie could not be retrieved/decoded, deleting: %s",
cookieName);
oidc_http_set_cookie(r, cookieName, "", 0,
OIDC_COOKIE_EXT_SAME_SITE_NONE(c, r));
}
}
}
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &tokenizerCtx);
}
}
if (delete_oldest > 0)
number_of_valid_state_cookies = oidc_delete_oldest_state_cookies(
r, c, number_of_valid_state_cookies, oidc_cfg_max_number_of_state_cookies_get(c), first);
return number_of_valid_state_cookies;
}
/*
* get the mod_auth_openidc related context from the (userdata in the) request
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
static apr_table_t *oidc_request_state(request_rec *rr) {
/* our state is always stored in the main request */
request_rec *r = (rr->main != NULL) ? rr->main : rr;
/* our state is a table, get it */
apr_table_t *state = NULL;
apr_pool_userdata_get((void **)&state, OIDC_USERDATA_KEY, r->pool);
/* if it does not exist, we'll create a new table */
if (state == NULL) {
state = apr_table_make(r->pool, 5);
apr_pool_userdata_set(state, OIDC_USERDATA_KEY, NULL, r->pool);
}
/* return the resulting table, always non-null now */
return state;
}
/*
* set a name/value pair in the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
void oidc_request_state_set(request_rec *r, const char *key, const char *value) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* put the name/value pair in that table */
apr_table_set(state, key, value);
}
/*
* get a name/value pair from the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
const char *oidc_request_state_get(request_rec *r, const char *key) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* return the value from the table */
return apr_table_get(state, key);
}
/*
* set the claims from a JSON object (c.q. id_token or user_info response) stored
* in the session in to HTTP headers passed on to the application
*/
static apr_byte_t oidc_set_app_claims(request_rec *r, oidc_cfg_t *cfg, const char *s_claims) {
json_t *j_claims = NULL;
oidc_appinfo_pass_in_t pass_in = oidc_cfg_dir_pass_info_in_get(r);
// optimize performance when `OIDCPassClaimsAs none` is set
if (pass_in == OIDC_APPINFO_PASS_NONE)
return TRUE;
/* decode the string-encoded attributes in to a JSON structure */
if (s_claims != NULL) {
if (oidc_util_decode_json_object(r, s_claims, &j_claims) == FALSE)
return FALSE;
}
/* set the resolved claims a HTTP headers for the application */
if (j_claims != NULL) {
oidc_util_set_app_infos(r, j_claims, oidc_cfg_claim_prefix_get(cfg), oidc_cfg_claim_delimiter_get(cfg),
pass_in, oidc_cfg_dir_pass_info_encoding_get(r));
/* release resources */
json_decref(j_claims);
}
return TRUE;
}
/*
* log message about max session duration
*/
void oidc_log_session_expires(request_rec *r, const char *msg, apr_time_t session_expires) {
char buf[APR_RFC822_DATE_LEN + 1];
apr_rfc822_date(buf, session_expires);
oidc_debug(r, "%s: %s (in %" APR_TIME_T_FMT " secs from now)", msg, buf,
apr_time_sec(session_expires - apr_time_now()));
}
/*
* see if this is a request that is capable of completing an authentication round trip to the Provider
*/
apr_byte_t oidc_is_auth_capable_request(request_rec *r) {
if ((oidc_http_hdr_in_x_requested_with_get(r) != NULL) &&
(_oidc_strnatcasecmp(oidc_http_hdr_in_x_requested_with_get(r), OIDC_HTTP_HDR_VAL_XML_HTTP_REQUEST) == 0))
return FALSE;
if ((oidc_http_hdr_in_sec_fetch_mode_get(r) != NULL) &&
(_oidc_strnatcasecmp(oidc_http_hdr_in_sec_fetch_mode_get(r), OIDC_HTTP_HDR_VAL_NAVIGATE) != 0))
return FALSE;
if ((oidc_http_hdr_in_sec_fetch_dest_get(r) != NULL) &&
(_oidc_strnatcasecmp(oidc_http_hdr_in_sec_fetch_dest_get(r), OIDC_HTTP_HDR_VAL_DOCUMENT) != 0))
return FALSE;
if ((oidc_http_hdr_in_accept_contains(r, OIDC_HTTP_CONTENT_TYPE_TEXT_HTML) == FALSE) &&
(oidc_http_hdr_in_accept_contains(r, OIDC_HTTP_CONTENT_TYPE_APP_XHTML_XML) == FALSE) &&
(oidc_http_hdr_in_accept_contains(r, OIDC_HTTP_CONTENT_TYPE_ANY) == FALSE))
return FALSE;
return TRUE;
}
/*
* find out which action we need to take when encountering an unauthenticated request
*/
static int oidc_handle_unauthenticated_user(request_rec *r, oidc_cfg_t *c) {
/* see if we've configured OIDCUnAuthAction for this path */
switch (oidc_cfg_dir_unauth_action_get(r)) {
case OIDC_UNAUTH_RETURN410:
return HTTP_GONE;
case OIDC_UNAUTH_RETURN407:
return HTTP_PROXY_AUTHENTICATION_REQUIRED;
case OIDC_UNAUTH_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTH_PASS:
r->user = "";
/*
* we're not going to pass information about an authenticated user to the application,
* but we do need to scrub the headers that mod_auth_openidc would set for security reasons
*/
oidc_scrub_headers(r);
return OK;
case OIDC_UNAUTH_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if ((oidc_cfg_dir_unauth_expr_is_set(r) == FALSE) && (oidc_is_auth_capable_request(r) == FALSE))
return HTTP_UNAUTHORIZED;
}
/*
* else: no session (regardless of whether it is main or sub-request),
* and we need to authenticate the user
*/
return oidc_request_authenticate_user(r, c, NULL, oidc_util_current_url(r, oidc_cfg_x_forwarded_headers_get(c)),
NULL, NULL, NULL, oidc_cfg_dir_path_auth_request_params_get(r),
oidc_cfg_dir_path_scope_get(r));
}
/*
* check if maximum session duration was exceeded
*/
static apr_byte_t oidc_check_max_session_duration(request_rec *r, oidc_cfg_t *cfg, oidc_session_t *session, int *rc) {
/* get the session expiry from the session data */
apr_time_t session_expires = oidc_session_get_session_expires(r, session);
/* check the expire timestamp against the current time */
if (apr_time_now() > session_expires) {
oidc_warn(r, "maximum session duration exceeded for user: %s", session->remote_user);
oidc_session_kill(r, session);
*rc = oidc_handle_unauthenticated_user(r, cfg);
return FALSE;
}
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
*rc = OK;
return TRUE;
}
/*
* validate received session cookie against the domain it was issued for:
*
* this handles the case where the cache configured is a the same single memcache, Redis, or file
* backend for different (virtual) hosts, or a client-side cookie protected with the same secret
*
* it also handles the case that a cookie is unexpectedly shared across multiple hosts in
* name-based virtual hosting even though the OP(s) would be the same
*/
static apr_byte_t oidc_check_cookie_domain(request_rec *r, oidc_cfg_t *cfg, oidc_session_t *session) {
const char *c_cookie_domain = oidc_cfg_cookie_domain_get(cfg)
? oidc_cfg_cookie_domain_get(cfg)
: oidc_util_current_url_host(r, oidc_cfg_x_forwarded_headers_get(cfg));
const char *s_cookie_domain = oidc_session_get_cookie_domain(r, session);
if ((s_cookie_domain == NULL) || (_oidc_strcmp(c_cookie_domain, s_cookie_domain) != 0)) {
oidc_warn(r,
"aborting: detected attempt to play cookie against a different domain/host than issued for! "
"(issued=%s, current=%s)",
s_cookie_domain, c_cookie_domain);
return FALSE;
}
return TRUE;
}
/*
* get a handle to the provider configuration via the "issuer" stored in the session
*/
apr_byte_t oidc_get_provider_from_session(request_rec *r, oidc_cfg_t *c, oidc_session_t *session,
oidc_provider_t **provider) {
oidc_debug(r, "enter");
/* get the issuer value from the session state */
const char *issuer = oidc_session_get_issuer(r, session);
if (issuer == NULL) {
oidc_warn(r, "empty or invalid session: no issuer found");
return FALSE;
}
/* get the provider info associated with the issuer value */
oidc_provider_t *p = oidc_get_provider_for_issuer(r, c, issuer, FALSE);
if (p == NULL) {
oidc_error(r, "session corrupted: no provider found for issuer: %s", issuer);
return FALSE;
}
*provider = p;
return TRUE;
}
/*
* copy the claims and id_token from the session to the request state and optionally return them
*/
static void oidc_copy_tokens_to_request_state(request_rec *r, oidc_session_t *session, const char **s_id_token,
const char **s_claims) {
const char *id_token = oidc_session_get_idtoken_claims(r, session);
const char *claims = oidc_session_get_userinfo_claims(r, session);
oidc_debug(r, "id_token=%s claims=%s", id_token, claims);
if (id_token != NULL) {
oidc_request_state_set(r, OIDC_REQUEST_STATE_KEY_IDTOKEN, id_token);
if (s_id_token != NULL)
*s_id_token = id_token;
}
if (claims != NULL) {
oidc_request_state_set(r, OIDC_REQUEST_STATE_KEY_CLAIMS, claims);
if (s_claims != NULL)
*s_claims = claims;
}
}
/*
* pass refresh_token, access_token and access_token_expires as headers/environment variables to the application
*/
apr_byte_t oidc_session_pass_tokens(request_rec *r, oidc_cfg_t *cfg, oidc_session_t *session, apr_byte_t *needs_save) {
oidc_appinfo_pass_in_t pass_in = oidc_cfg_dir_pass_info_in_get(r);
oidc_appinfo_encoding_t encoding = oidc_cfg_dir_pass_info_encoding_get(r);
/* set the refresh_token in the app headers/variables, if enabled for this location/directory */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if ((oidc_cfg_dir_pass_refresh_token_get(r) != 0) && (refresh_token != NULL)) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_REFRESH_TOKEN, refresh_token, OIDC_DEFAULT_HEADER_PREFIX,
pass_in, encoding);
}
/* set the access_token in the app headers/variables */
const char *access_token = oidc_session_get_access_token(r, session);
if ((oidc_cfg_dir_pass_access_token_get(r) != 0) && access_token != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ACCESS_TOKEN, access_token, OIDC_DEFAULT_HEADER_PREFIX, pass_in,
encoding);
}
/* set the expiry timestamp in the app headers/variables */
const char *access_token_expires = oidc_session_get_access_token_expires2str(r, session);
if ((oidc_cfg_dir_pass_access_token_get(r) != 0) && access_token_expires != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ACCESS_TOKEN_EXP, access_token_expires,
OIDC_DEFAULT_HEADER_PREFIX, pass_in, encoding);
}
/*
* reset the session inactivity timer
* but only do this once per 10% of the inactivity timeout interval (with a max to 60 seconds)
* for performance reasons
*
* now there's a small chance that the session ends 10% (or a minute) earlier than configured/expected
* cq. when there's a request after a recent save (so no update) and then no activity happens until
* a request comes in just before the session should expire
* ("recent" and "just before" refer to 10%-with-a-max-of-60-seconds of the inactivity interval after
* the start/last-update and before the expiry of the session respectively)
*
* this is be deemed acceptable here because of performance gain
*/
apr_time_t interval = apr_time_from_sec(oidc_cfg_session_inactivity_timeout_get(cfg));
apr_time_t now = apr_time_now();
apr_time_t slack = interval / 10;
if (slack > apr_time_from_sec(60))
slack = apr_time_from_sec(60);
if (session->expiry - now < interval - slack) {
session->expiry = now + interval;
*needs_save = TRUE;
}
/* log message about session expiry */
oidc_log_session_expires(r, "session inactivity timeout", session->expiry);
return TRUE;
}
#define OIDC_USERINFO_SIGNED_JWT_EXP_DEFAULT 60
#define OIDC_USERINFO_SIGNED_JWT_CACHE_TTL_DEFAULT -1
#define OIDC_USERINFO_SIGNED_JWT_CACHE_TTL_ENVVAR "OIDC_USERINFO_SIGNED_JWT_CACHE_TTL"
/*
* obtain the signed JWT cache TTL from the environment variables
*/
static int oidc_userinfo_signed_jwt_cache_ttl(request_rec *r) {
const char *s_ttl = apr_table_get(r->subprocess_env, OIDC_USERINFO_SIGNED_JWT_CACHE_TTL_ENVVAR);
return _oidc_str_to_int(s_ttl, OIDC_USERINFO_SIGNED_JWT_CACHE_TTL_DEFAULT);
}
/*
* create a signed JWT with s_claims payload and return the serialized form in cser
*/
static apr_byte_t oidc_userinfo_create_signed_jwt(request_rec *r, oidc_cfg_t *cfg, oidc_session_t *session,
const char *s_claims, char **cser) {
apr_byte_t rv = FALSE;
oidc_jwt_t *jwt = NULL;
oidc_jwk_t *jwk = NULL;
oidc_jose_error_t err;
apr_time_t access_token_expires = -1;
char *jti = NULL;
char *key = NULL;
json_t *json = NULL;
int ttl = 0;
int exp = 0;
apr_time_t expiry = 0;
oidc_debug(r, "enter: %s", s_claims);
jwk = oidc_util_key_list_first(oidc_cfg_private_keys_get(cfg), -1, OIDC_JOSE_JWK_SIG_STR);
// TODO: detect at config time
if (jwk == NULL) {
oidc_error(r, "no RSA/EC private signing keys have been configured (in " OIDCPrivateKeyFiles ")");
goto end;
}
jwt = oidc_jwt_new(r->pool, TRUE, TRUE);
if (jwt == NULL)
goto end;
jwt->header.kid = apr_pstrdup(r->pool, jwk->kid);
if (jwk->kty == CJOSE_JWK_KTY_RSA)
jwt->header.alg = apr_pstrdup(r->pool, CJOSE_HDR_ALG_RS256);
else if (jwk->kty == CJOSE_JWK_KTY_EC)
jwt->header.alg = apr_pstrdup(r->pool, CJOSE_HDR_ALG_ES256);
else {
oidc_error(r, "no usable RSA/EC signing keys has been configured (in " OIDCPrivateKeyFiles ")");
goto end;
}
json_object_set_new(jwt->payload.value.json, OIDC_CLAIM_AUD,
json_string(oidc_util_current_url(r, oidc_cfg_x_forwarded_headers_get(cfg))));
json_object_set_new(jwt->payload.value.json, OIDC_CLAIM_ISS,
json_string(oidc_cfg_provider_issuer_get(oidc_cfg_provider_get(cfg))));
oidc_util_decode_json_object(r, s_claims, &json);
if (json == NULL)
goto end;
if (oidc_util_json_merge(r, json, jwt->payload.value.json) == FALSE)
goto end;
s_claims = oidc_util_encode_json_object(r, jwt->payload.value.json, JSON_PRESERVE_ORDER | JSON_COMPACT);
if (oidc_jose_hash_and_base64url_encode(r->pool, OIDC_JOSE_ALG_SHA256, s_claims, _oidc_strlen(s_claims) + 1,
&key, &err) == FALSE) {
oidc_error(r, "oidc_jose_hash_and_base64url_encode failed: %s", oidc_jose_e2s(r->pool, err));
goto end;
}
ttl = oidc_userinfo_signed_jwt_cache_ttl(r);
if (ttl > -1)
oidc_cache_get_signed_jwt(r, key, cser);
if (*cser != NULL) {
oidc_debug(r, "signed JWT found in cache");
rv = TRUE;
goto end;
}
if (json_object_get(jwt->payload.value.json, OIDC_CLAIM_JTI) == NULL) {
oidc_util_generate_random_string(r, &jti, 16);
json_object_set_new(jwt->payload.value.json, OIDC_CLAIM_JTI, json_string(jti));
}
if (json_object_get(jwt->payload.value.json, OIDC_CLAIM_IAT) == NULL) {
json_object_set_new(jwt->payload.value.json, OIDC_CLAIM_IAT,
json_integer(apr_time_sec(apr_time_now())));
}
if (json_object_get(jwt->payload.value.json, OIDC_CLAIM_EXP) == NULL) {
access_token_expires = oidc_session_get_access_token_expires(r, session);
json_object_set_new(jwt->payload.value.json, OIDC_CLAIM_EXP,
json_integer(access_token_expires > 0 ? apr_time_sec(access_token_expires)
: apr_time_sec(apr_time_now()) +
OIDC_USERINFO_SIGNED_JWT_EXP_DEFAULT));
}
if (oidc_jwt_sign(r->pool, jwt, jwk, FALSE, &err) == FALSE) {
oidc_error(r, "oidc_jwt_sign failed: %s", oidc_jose_e2s(r->pool, err));
goto end;
}
*cser = oidc_jwt_serialize(r->pool, jwt, &err);
if (*cser == NULL) {
oidc_error(r, "oidc_jwt_serialize failed: %s", oidc_jose_e2s(r->pool, err));
goto end;
}
rv = TRUE;
if (ttl < 0)
goto end;
if (ttl == 0) {
// need to get the cache ttl from the exp claim
oidc_util_json_object_get_int(jwt->payload.value.json, OIDC_CLAIM_EXP, &exp, 0);
// actually the exp claim always exists by now
expiry = (exp > 0) ? apr_time_from_sec(exp)
: apr_time_now() + apr_time_from_sec(OIDC_USERINFO_SIGNED_JWT_EXP_DEFAULT);
} else {
// ttl > 0
expiry = apr_time_now() + apr_time_from_sec(ttl);
}
oidc_debug(r, "caching signed JWT with ~ttl(%ld)", apr_time_sec(expiry - apr_time_now()));
oidc_cache_set_signed_jwt(r, key, *cser, expiry);
end:
if (json)
json_decref(json);
if (jwt)
oidc_jwt_destroy(jwt);
return rv;
}
/*
* pass the userinfo claims to headers and/or environment variables, encoded as configured
*/
static void oidc_pass_userinfo_as(request_rec *r, oidc_cfg_t *cfg, oidc_session_t *session, const char *s_claims,
oidc_appinfo_pass_in_t pass_in, oidc_appinfo_encoding_t encoding) {
const apr_array_header_t *pass_userinfo_as = NULL;
oidc_pass_user_info_as_t *p = NULL;
int i = 0;
char *cser = NULL;
pass_userinfo_as = oidc_cfg_dir_pass_userinfo_as_get(r);
#ifdef USE_LIBJQ
s_claims = oidc_util_jq_filter(r, s_claims, oidc_cfg_dir_userinfo_claims_expr_get(r));
#endif
for (i = 0; (pass_userinfo_as != NULL) && (i < pass_userinfo_as->nelts); i++) {
p = APR_ARRAY_IDX(pass_userinfo_as, i, oidc_pass_user_info_as_t *);
switch (p->type) {
case OIDC_PASS_USERINFO_AS_CLAIMS:
/* set the userinfo claims in the app headers */
oidc_set_app_claims(r, cfg, s_claims);
break;