/
mod_auth_openidc.c
4191 lines (3458 loc) · 140 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-2019 ZmartZone IAM
* Copyright (C) 2013-2017 Ping Identity Corporation
* All rights reserved.
*
* For further information please contact:
*
* Ping Identity Corporation
* 1099 18th St Suite 2950
* Denver, CO 80202
* 303.468.2900
* http://www.pingidentity.com
*
* 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@zmartzone.eu
*
**************************************************************************/
#include "apr_hash.h"
#include "apr_strings.h"
#include "ap_config.h"
#include "ap_provider.h"
#include "apr_lib.h"
#include "apr_file_io.h"
#include "apr_sha1.h"
#include "apr_base64.h"
#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_request.h"
#include "mod_auth_openidc.h"
#define ERROR 2
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url);
// TODO:
// - sort out oidc_cfg vs. oidc_dir_cfg stuff
// - rigid input checking on discovery responses
// - check self-issued support
// - README.quickstart
// - refresh metadata once-per too? (for non-signing key changes)
extern module AP_MODULE_DECLARE_DATA auth_openidc_module;
/*
* 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 ? 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_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_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 *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *prefix = oidc_cfg_claim_prefix(r);
apr_hash_t *hdrs = apr_hash_make(r->pool);
if (apr_strnatcmp(prefix, "") == 0) {
if ((cfg->white_listed_claims != NULL)
&& (apr_hash_count(cfg->white_listed_claims) > 0))
hdrs = apr_hash_overlay(r->pool, cfg->white_listed_claims, hdrs);
else
oidc_warn(r,
"both " OIDCClaimPrefix " and " OIDCWhiteListedClaims " are empty: this renders an insecure setup!");
}
char *authn_hdr = oidc_cfg_dir_authn_header(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 ((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;
apr_array_header_t *strip = oidc_dir_cfg_strip_cookies(r);
char *cookies = apr_pstrdup(r->pool, oidc_util_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++;
for (i = 0; i < strip->nelts; i++) {
name = ((const char**) strip->elts)[i];
if ((strncmp(cookie, name, strlen(name)) == 0)
&& (cookie[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_util_hdr_in_cookie_set(r, result);
}
}
#define OIDC_SHA1_LEN 20
/*
* calculates a hash value based on request fingerprint plus a provided nonce string.
*/
static char *oidc_get_browser_state_hash(request_rec *r, 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);
/* get the X-FORWARDED-FOR header value */
value = oidc_util_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, strlen(value));
/* get the USER-AGENT header value */
value = oidc_util_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, 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, strlen(value));
*/
/* concat the nonce parameter to the hash input */
apr_sha1_update(&sha1, nonce, strlen(nonce));
/* concat the token binding ID if present */
value = oidc_util_get_provided_token_binding_id(r);
if (value != NULL) {
oidc_debug(r,
"Provided Token Binding ID environment variable found; adding its value to the state");
apr_sha1_update(&sha1, value, strlen(value));
}
/* 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_base64url_encode(r, &result, (const char *) hash, OIDC_SHA1_LEN, TRUE);
return result;
}
/*
* return the name for the state cookie
*/
static char *oidc_get_state_cookie_name(request_rec *r, const char *state) {
return apr_psprintf(r->pool, "%s%s", OIDC_STATE_COOKIE_PREFIX, state);
}
/*
* return the static provider configuration, i.e. from a metadata URL or configuration primitives
*/
static apr_byte_t oidc_provider_static_config(request_rec *r, oidc_cfg *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 ((c->metadata_dir != NULL) || (c->provider.metadata_url == NULL)) {
*provider = &c->provider;
return TRUE;
}
oidc_cache_get_provider(r, c->provider.metadata_url, &s_json);
if (s_json == NULL) {
if (oidc_metadata_provider_retrieve(r, c, NULL,
c->provider.metadata_url, &j_provider, &s_json) == FALSE) {
oidc_error(r, "could not retrieve metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
oidc_cache_set_provider(r, c->provider.metadata_url, s_json,
apr_time_now() + (c->provider_metadata_refresh_interval <= 0 ? apr_time_from_sec( OIDC_CACHE_PROVIDER_METADATA_EXPIRY_DEFAULT) : c->provider_metadata_refresh_interval));
} else {
oidc_util_decode_json_object(r, s_json, &j_provider);
/* check to see if it is valid metadata */
if (oidc_metadata_provider_is_valid(r, c, j_provider, NULL) == FALSE) {
oidc_error(r,
"cache corruption detected: invalid metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
}
*provider = apr_pcalloc(r->pool, sizeof(oidc_provider_t));
memcpy(*provider, &c->provider, sizeof(oidc_provider_t));
if (oidc_metadata_provider_parse(r, c, j_provider, *provider) == FALSE) {
oidc_error(r, "could not parse metadata from url: %s",
c->provider.metadata_url);
if (j_provider)
json_decref(j_provider);
return FALSE;
}
json_decref(j_provider);
return TRUE;
}
/*
* return the oidc_provider_t struct for the specified issuer
*/
static oidc_provider_t *oidc_get_provider_for_issuer(request_rec *r,
oidc_cfg *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 (c->metadata_dir != 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;
}
/*
* find out whether the request is a response from an IDP discovery page
*/
static apr_byte_t oidc_is_discovery_response(request_rec *r, oidc_cfg *cfg) {
/*
* prereq: this is a call to the configured redirect_uri, now see if:
* the OIDC_DISC_OP_PARAM is present
*/
return oidc_util_request_has_parameter(r, OIDC_DISC_OP_PARAM)
|| oidc_util_request_has_parameter(r, OIDC_DISC_USER_PARAM);
}
/*
* return the HTTP method being called: only for POST data persistence purposes
*/
static const char *oidc_original_request_method(request_rec *r, oidc_cfg *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_get_redirect_uri(r, cfg)))
&& (oidc_is_discovery_response(r, cfg))) {
oidc_util_get_request_parameter(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(r) == 0)
return OIDC_METHOD_GET;
const char *content_type = oidc_util_hdr_in_content_type_get(r);
if ((r->method_number == M_POST) && (apr_strnatcmp(content_type,
OIDC_CONTENT_TYPE_FORM_ENCODED) == 0))
method = OIDC_METHOD_FORM_POST;
}
oidc_debug(r, "return: %s", method);
return method;
}
/*
* send an OpenID Connect authorization request to the specified provider preserving POST parameters using HTML5 storage
*/
apr_byte_t oidc_post_preserve_javascript(request_rec *r, const char *location,
char **javascript, char **javascript_method) {
if (oidc_cfg_dir_preserve_post(r) == 0)
return FALSE;
oidc_debug(r, "enter");
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *method = oidc_original_request_method(r, cfg, FALSE);
if (apr_strnatcmp(method, OIDC_METHOD_FORM_POST) != 0)
return FALSE;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return FALSE;
}
const apr_array_header_t *arr = apr_table_elts(params);
const apr_table_entry_t *elts = (const apr_table_entry_t*) arr->elts;
int i;
char *json = "";
for (i = 0; i < arr->nelts; i++) {
json = apr_psprintf(r->pool, "%s'%s': '%s'%s", json,
oidc_util_escape_string(r, elts[i].key),
oidc_util_escape_string(r, elts[i].val),
i < arr->nelts - 1 ? "," : "");
}
json = apr_psprintf(r->pool, "{ %s }", json);
const char *jmethod = "preserveOnLoad";
const char *jscript =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function %s() {\n"
" sessionStorage.setItem('mod_auth_openidc_preserve_post_params', JSON.stringify(%s));\n"
" %s"
" }\n"
" </script>\n", jmethod, json,
location ?
apr_psprintf(r->pool, "window.location='%s';\n",
location) :
"");
if (location == NULL) {
if (javascript_method)
*javascript_method = apr_pstrdup(r->pool, jmethod);
if (javascript)
*javascript = apr_pstrdup(r->pool, jscript);
} else {
oidc_util_html_send(r, "Preserving...", jscript, jmethod,
"<p>Preserving...</p>", OK);
}
return TRUE;
}
/*
* restore POST parameters on original_url from HTML5 local storage
*/
static int oidc_request_post_preserved_restore(request_rec *r,
const char *original_url) {
oidc_debug(r, "enter: original_url=%s", original_url);
const char *method = "postOnLoad";
const char *script =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function str_decode(string) {\n"
" try {\n"
" result = decodeURIComponent(string);\n"
" } catch (e) {\n"
" result = unescape(string);\n"
" }\n"
" return result;\n"
" }\n"
" function %s() {\n"
" var mod_auth_openidc_preserve_post_params = JSON.parse(sessionStorage.getItem('mod_auth_openidc_preserve_post_params'));\n"
" sessionStorage.removeItem('mod_auth_openidc_preserve_post_params');\n"
" for (var key in mod_auth_openidc_preserve_post_params) {\n"
" var input = document.createElement(\"input\");\n"
" input.name = str_decode(key);\n"
" input.value = str_decode(mod_auth_openidc_preserve_post_params[key]);\n"
" input.type = \"hidden\";\n"
" document.forms[0].appendChild(input);\n"
" }\n"
" document.forms[0].action = '%s';\n"
" document.forms[0].submit();\n"
" }\n"
" </script>\n", method, original_url);
const char *body = " <p>Restoring...</p>\n"
" <form method=\"post\"></form>\n";
return oidc_util_html_send(r, "Restoring...", script, method, body,
OK);
}
/*
* parse state that was sent to us by the issuer
*/
static apr_byte_t oidc_unsolicited_proto_state(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t **proto_state) {
char *alg = NULL;
oidc_debug(r, "enter: state header=%s",
oidc_proto_peek_jwt_header(r, state, &alg));
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret,
oidc_alg2keysize(alg), OIDC_JOSE_ALG_SHA256,
TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwt_t *jwt = NULL;
if (oidc_jwt_parse(r->pool, state, &jwt,
oidc_util_merge_symmetric_key(r->pool, c->private_keys, jwk),
&err) == FALSE) {
oidc_error(r,
"could not parse JWT from state: invalid unsolicited response: %s",
oidc_jose_e2s(r->pool, err));
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully parsed JWT from state");
if (jwt->payload.iss == NULL) {
oidc_error(r, "no \"%s\" could be retrieved from JWT state, aborting",
OIDC_CLAIM_ISS);
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_provider_t *provider = oidc_get_provider_for_issuer(r, c,
jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_jwt_destroy(jwt);
return FALSE;
}
/* validate the state JWT, validating optional exp + iat */
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack,
OIDC_TOKEN_BINDING_POLICY_DISABLED) == FALSE) {
oidc_jwt_destroy(jwt);
return FALSE;
}
char *rfp = NULL;
if (oidc_jose_get_string(r->pool, jwt->payload.value.json, OIDC_CLAIM_RFP,
TRUE, &rfp, &err) == FALSE) {
oidc_error(r,
"no \"%s\" claim could be retrieved from JWT state, aborting: %s",
OIDC_CLAIM_RFP, oidc_jose_e2s(r->pool, err));
oidc_jwt_destroy(jwt);
return FALSE;
}
if (apr_strnatcmp(rfp, OIDC_PROTO_ISS) != 0) {
oidc_error(r, "\"%s\" (%s) does not match \"%s\", aborting",
OIDC_CLAIM_RFP, rfp, OIDC_PROTO_ISS);
oidc_jwt_destroy(jwt);
return FALSE;
}
char *target_link_uri = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_TARGET_LINK_URI,
FALSE, &target_link_uri, NULL);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
oidc_error(r,
"no \"%s\" claim could be retrieved from JWT state and no " OIDCDefaultURL " is set, aborting",
OIDC_CLAIM_TARGET_LINK_URI);
oidc_jwt_destroy(jwt);
return FALSE;
}
target_link_uri = c->default_sso_url;
}
if (c->metadata_dir != NULL) {
if ((oidc_metadata_get(r, c, jwt->payload.iss, &provider, FALSE)
== FALSE) || (provider == NULL)) {
oidc_error(r, "no provider metadata found for provider \"%s\"",
jwt->payload.iss);
oidc_jwt_destroy(jwt);
return FALSE;
}
}
char *jti = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json, OIDC_CLAIM_JTI,
FALSE, &jti,
NULL);
if (jti == NULL) {
char *cser = oidc_jwt_serialize(r->pool, jwt, &err);
if (cser == NULL)
return FALSE;
if (oidc_util_hash_string_and_base64url_encode(r, OIDC_JOSE_ALG_SHA256,
cser, &jti) == FALSE) {
oidc_error(r,
"oidc_util_hash_string_and_base64url_encode returned an error");
return FALSE;
}
}
char *replay = NULL;
oidc_cache_get_jti(r, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the \"%s\" value (%s) passed in the browser state was found in the cache already; possible replay attack!?",
OIDC_CLAIM_JTI, jti);
oidc_jwt_destroy(jwt);
return FALSE;
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
oidc_cache_set_jti(r, jti, jti, apr_time_now() + jti_cache_duration);
oidc_debug(r,
"jti \"%s\" validated successfully and is now cached for %" APR_TIME_T_FMT " seconds",
jti, apr_time_sec(jti_cache_duration));
jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, c, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk), NULL) == FALSE) {
oidc_error(r, "state JWT could not be validated, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully verified state JWT");
*proto_state = oidc_proto_state_new();
oidc_proto_state_set_issuer(*proto_state, jwt->payload.iss);
oidc_proto_state_set_original_url(*proto_state, target_link_uri);
oidc_proto_state_set_original_method(*proto_state, OIDC_METHOD_GET);
oidc_proto_state_set_response_mode(*proto_state, provider->response_mode);
oidc_proto_state_set_response_type(*proto_state, provider->response_type);
oidc_proto_state_set_timestamp_now(*proto_state);
oidc_jwt_destroy(jwt);
return TRUE;
}
typedef struct oidc_state_cookies_t {
char *name;
apr_time_t timestamp;
struct oidc_state_cookies_t *next;
} oidc_state_cookies_t;
static int oidc_delete_oldest_state_cookies(request_rec *r,
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;
while (number_of_valid_state_cookies >= max_number_of_state_cookies) {
oldest = first;
prev_oldest = NULL;
prev = first;
cur = first->next;
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_util_set_cookie(r, oldest->name, "", 0, NULL);
if (prev_oldest)
prev_oldest->next = oldest->next;
else
first = first->next;
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
*/
static int oidc_clean_expired_state_cookies(request_rec *r, oidc_cfg *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_util_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 (strstr(cookie, OIDC_STATE_COOKIE_PREFIX) == cookie) {
char *cookieName = cookie;
while (cookie != NULL && *cookie != OIDC_CHAR_EQUAL)
cookie++;
if (*cookie == OIDC_CHAR_EQUAL) {
*cookie = '\0';
cookie++;
if ((currentCookieName == NULL)
|| (apr_strnatcmp(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(c->state_timeout)) {
oidc_warn(r,
"state (%s) has expired (original_url=%s)",
cookieName,
oidc_proto_state_get_original_url(
proto_state));
oidc_util_set_cookie(r, cookieName, "", 0,
NULL);
} 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);
}
}
}
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &tokenizerCtx);
}
}
if (delete_oldest > 0)
number_of_valid_state_cookies = oidc_delete_oldest_state_cookies(r,
number_of_valid_state_cookies, c->max_number_of_state_cookies,
first);
return number_of_valid_state_cookies;
}
/*
* restore the state that was maintained between authorization request and response in an encrypted cookie
*/
static apr_byte_t oidc_restore_proto_state(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t **proto_state) {
oidc_debug(r, "enter");
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* clean expired state cookies to avoid pollution */
oidc_clean_expired_state_cookies(r, c, cookieName, FALSE);
/* get the state cookie value first */
char *cookieValue = oidc_util_get_cookie(r, cookieName);
if (cookieValue == NULL) {
oidc_error(r, "no \"%s\" state cookie found", cookieName);
return oidc_unsolicited_proto_state(r, c, state, proto_state);
}
/* clear state cookie because we don't need it anymore */
oidc_util_set_cookie(r, cookieName, "", 0, NULL);
*proto_state = oidc_proto_state_from_cookie(r, c, cookieValue);
if (*proto_state == NULL)
return FALSE;
const char *nonce = oidc_proto_state_get_nonce(*proto_state);
/* calculate the hash of the browser fingerprint concatenated with the nonce */
char *calc = oidc_get_browser_state_hash(r, nonce);
/* compare the calculated hash with the value provided in the authorization response */
if (apr_strnatcmp(calc, state) != 0) {
oidc_error(r,
"calculated state from cookie does not match state parameter passed back in URL: \"%s\" != \"%s\"",
state, calc);
oidc_proto_state_destroy(*proto_state);
return FALSE;
}
apr_time_t ts = oidc_proto_state_get_timestamp(*proto_state);
/* check that the timestamp is not beyond the valid interval */
if (apr_time_now() > ts + apr_time_from_sec(c->state_timeout)) {
oidc_error(r, "state has expired");
/*
* note that this overrides redirection to the OIDCDefaultURL as done later...
* see: https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/mod_auth_openidc/L4JFBw-XCNU/BWi2Fmk2AwAJ
*/
oidc_util_html_send_error(r, c->error_template,
"Invalid Authentication Response",
apr_psprintf(r->pool,
"This is due to a timeout; please restart your authentication session by re-entering the URL/bookmark you originally wanted to access: %s",
oidc_proto_state_get_original_url(*proto_state)),
OK);
oidc_proto_state_destroy(*proto_state);
return FALSE;
}
/* add the state */
oidc_proto_state_set_state(*proto_state, state);
/* log the restored state object */
oidc_debug(r, "restored state: %s",
oidc_proto_state_to_string(r, *proto_state));
/* we've made it */
return TRUE;
}
/*
* set the state that is maintained between an authorization request and an authorization response
* in a cookie in the browser that is cryptographically bound to that state
*/
static int oidc_authorization_request_set_cookie(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t *proto_state) {
/*
* create a cookie consisting of 8 elements:
* random value, original URL, original method, issuer, response_type, response_mod, prompt and timestamp
* encoded as JSON, encrypting the resulting JSON value
*/
char *cookieValue = oidc_proto_state_to_cookie(r, c, proto_state);
if (cookieValue == NULL)
return HTTP_INTERNAL_SERVER_ERROR;
/*
* clean expired state cookies to avoid pollution and optionally
* try to avoid the number of state cookies exceeding a max
*/
int number_of_cookies = oidc_clean_expired_state_cookies(r, c, NULL,
oidc_cfg_delete_oldest_state_cookies(c));
int max_number_of_cookies = oidc_cfg_max_number_of_state_cookies(c);
if ((max_number_of_cookies > 0)
&& (number_of_cookies >= max_number_of_cookies)) {
oidc_warn(r,
"the number of existing, valid state cookies (%d) has exceeded the limit (%d), no additional authorization request + state cookie can be generated, aborting the request",
number_of_cookies, max_number_of_cookies);
/*
* TODO: the html_send code below caters for the case that there's a user behind a
* browser generating this request, rather than a piece of XHR code; how would an
* XHR client handle this?
*/
/*
* it appears that sending content with a 503 turns the HTTP status code
* into a 200 so we'll avoid that for now: the user will see Apache specific
* readable text anyway
*
return oidc_util_html_send_error(r, c->error_template,
"Too Many Outstanding Requests",
apr_psprintf(r->pool,
"No authentication request could be generated since there are too many outstanding authentication requests already; you may have to wait up to %d seconds to be able to create a new request",
c->state_timeout),
HTTP_SERVICE_UNAVAILABLE);
*/
return HTTP_SERVICE_UNAVAILABLE;
}
/* assemble the cookie name for the state cookie */
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* set it as a cookie */
oidc_util_set_cookie(r, cookieName, cookieValue, -1,
c->cookie_same_site ? OIDC_COOKIE_EXT_SAME_SITE_LAX : NULL);
return HTTP_OK;
}
/*
* 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,
const oidc_cfg * const cfg, oidc_session_t *session,
const char *s_claims) {
json_t *j_claims = NULL;
/* 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(r),
cfg->claim_delimiter, oidc_cfg_dir_pass_info_in_headers(r),
oidc_cfg_dir_pass_info_in_envvars(r));
/* release resources */