-
Notifications
You must be signed in to change notification settings - Fork 327
/
util.c
2265 lines (1928 loc) · 63 KB
/
util.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.
*
* @Author: Hans Zandbelt - [email protected]
*/
#include "util.h"
#include "cfg/dir.h"
#include "mod_auth_openidc.h"
#include "proto/proto.h"
#include "metrics.h"
#include "pcre_subst.h"
#ifdef USE_LIBJQ
#include "jq.h"
#endif
#include <apr_base64.h>
#include <apr_lib.h>
#include <http_protocol.h>
#include <httpd.h>
#ifdef USE_URANDOM
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#define DEV_RANDOM "/dev/urandom"
#endif
/*
* generate a number of random bytes, either using libapr or urandom (no per-request logging)
*/
apr_byte_t oidc_util_random_bytes(unsigned char *buf, apr_size_t length) {
apr_byte_t rv = TRUE;
#ifndef USE_URANDOM
rv = (apr_generate_random_bytes(buf, length) == APR_SUCCESS);
#else
int fd = -1;
do {
apr_ssize_t rc;
if (fd == -1) {
fd = open(DEV_RANDOM, O_RDONLY);
if (fd == -1)
return errno;
}
do {
rc = read(fd, buf, length);
} while (rc == -1 && errno == EINTR);
if (rc < 0) {
int errnum = errno;
close(fd);
return errnum;
} else if (rc == 0) {
close(fd);
fd = -1; /* force open() again */
} else {
buf += rc;
length -= rc;
}
} while (length > 0);
close(fd);
rv = TRUE;
#endif
return rv;
}
/*
* generate a number of random bytes, either using libapr or urandom
*/
apr_byte_t oidc_util_generate_random_bytes(request_rec *r, unsigned char *buf, apr_size_t length) {
apr_byte_t rv = TRUE;
const char *gen = NULL;
#ifndef USE_URANDOM
gen = "apr";
#else
gen = DEV_RANDOM;
#endif
oidc_debug(r, "oidc_util_random_bytes [%s] call for %" APR_SIZE_T_FMT " bytes", gen, length);
rv = oidc_util_random_bytes(buf, length);
oidc_debug(r, "oidc_util_random_bytes returned: %d", rv);
return rv;
}
/*
* generate a random string of (lowercase) hexadecimal characters, representing byte_len bytes
*/
apr_byte_t oidc_util_generate_random_hex_string(request_rec *r, char **hex_str, int byte_len) {
unsigned char *bytes = apr_pcalloc(r->pool, byte_len);
int i = 0;
if (oidc_util_generate_random_bytes(r, bytes, byte_len) != TRUE) {
oidc_error(r, "oidc_util_generate_random_bytes returned an error");
return FALSE;
}
*hex_str = "";
for (i = 0; i < byte_len; i++)
*hex_str = apr_psprintf(r->pool, "%s%02x", *hex_str, bytes[i]);
return TRUE;
}
/*
* generate a random string value value of a specified byte length
*/
apr_byte_t oidc_util_generate_random_string(request_rec *r, char **output, int len) {
unsigned char *bytes = apr_pcalloc(r->pool, len);
if (oidc_util_generate_random_bytes(r, bytes, len) != TRUE) {
oidc_error(r, "oidc_util_generate_random_bytes returned an error");
return FALSE;
}
if (oidc_util_base64url_encode(r, output, (const char *)bytes, len, TRUE) <= 0) {
oidc_error(r, "oidc_base64url_encode returned an error");
return FALSE;
}
return TRUE;
}
/*
* base64url encode a string
*/
int oidc_util_base64url_encode(request_rec *r, char **dst, const char *src, int src_len, int remove_padding) {
if ((src == NULL) || (src_len <= 0)) {
oidc_error(r, "not encoding anything; src=NULL and/or src_len<1");
return -1;
}
unsigned int enc_len = apr_base64_encode_len(src_len);
char *enc = apr_palloc(r->pool, enc_len);
apr_base64_encode(enc, src, src_len);
unsigned int i = 0;
while (enc[i] != '\0') {
if (enc[i] == '+')
enc[i] = '-';
if (enc[i] == '/')
enc[i] = '_';
if (enc[i] == '=')
enc[i] = ',';
i++;
}
if (remove_padding) {
/* remove /0 and padding */
if (enc_len > 0)
enc_len--;
if ((enc_len > 0) && (enc[enc_len - 1] == ','))
enc_len--;
if ((enc_len > 0) && (enc[enc_len - 1] == ','))
enc_len--;
enc[enc_len] = '\0';
}
*dst = enc;
return enc_len;
}
/*
* parse a base64 encoded binary value from the provided string
*/
char *oidc_util_base64_decode(apr_pool_t *pool, const char *input, char **output, int *output_len) {
int len = apr_base64_decode_len(input);
*output = apr_pcalloc(pool, len);
*output_len = apr_base64_decode(*output, input);
if (*output_len <= 0)
return apr_psprintf(pool, "base64-decoding of \"%s\" failed", input);
return NULL;
}
/*
* base64url decode a string
*/
int oidc_util_base64url_decode(apr_pool_t *pool, char **dst, const char *src) {
if (src == NULL) {
return -1;
}
char *dec = apr_pstrdup(pool, src);
int i = 0;
while (dec[i] != '\0') {
if (dec[i] == '-')
dec[i] = '+';
if (dec[i] == '_')
dec[i] = '/';
if (dec[i] == ',')
dec[i] = '=';
i++;
}
switch (_oidc_strlen(dec) % 4) {
case 0:
break;
case 2:
dec = apr_pstrcat(pool, dec, "==", NULL);
break;
case 3:
dec = apr_pstrcat(pool, dec, "=", NULL);
break;
default:
return 0;
}
int dlen = -1;
oidc_util_base64_decode(pool, dec, dst, &dlen);
return dlen;
}
/*
* return the serialized header part of a A256GCM encrypted JWT (input)
*/
static const char *oidc_util_jwt_hdr_dir_a256gcm(request_rec *r, char *input) {
char *compact_encoded_jwt = NULL;
char *p = NULL;
static const char *_oidc_jwt_hdr_dir_a256gcm = NULL;
static oidc_crypto_passphrase_t passphrase;
if (_oidc_jwt_hdr_dir_a256gcm != NULL)
return _oidc_jwt_hdr_dir_a256gcm;
if (input == NULL) {
passphrase.secret1 = "needs_non_empty_string";
passphrase.secret2 = NULL;
oidc_util_jwt_create(r, &passphrase, "some_string", &compact_encoded_jwt);
} else {
compact_encoded_jwt = input;
}
p = _oidc_strstr(compact_encoded_jwt, "..");
if (p) {
_oidc_jwt_hdr_dir_a256gcm = apr_pstrndup(r->server->process->pconf, compact_encoded_jwt,
_oidc_strlen(compact_encoded_jwt) - _oidc_strlen(p) + 2);
oidc_debug(r, "saved _oidc_jwt_hdr_dir_a256gcm header: %s", _oidc_jwt_hdr_dir_a256gcm);
}
return _oidc_jwt_hdr_dir_a256gcm;
}
/*
* helper function to override a variable value with an optionally provided environment variable
*/
static apr_byte_t oidc_util_env_var_override(request_rec *r, const char *env_var_name, apr_byte_t return_when_set) {
const char *s = NULL;
if (r->subprocess_env == NULL)
return !return_when_set;
s = apr_table_get(r->subprocess_env, env_var_name);
return (s != NULL) && (_oidc_strcmp(s, "true") == 0) ? return_when_set : !return_when_set;
}
#define OIDC_JWT_INTERNAL_NO_COMPRESS_ENV_VAR "OIDC_JWT_INTERNAL_NO_COMPRESS"
/*
* check if we need to compress (internal) encrypted JWTs or not
*/
static apr_byte_t oidc_util_jwt_internal_compress(request_rec *r) {
// avoid compressing JWTs that need to be compatible with external producers/consumers
return oidc_util_env_var_override(r, OIDC_JWT_INTERNAL_NO_COMPRESS_ENV_VAR, FALSE);
}
#define OIDC_JWT_INTERNAL_STRIP_HDR_ENV_VAR "OIDC_JWT_INTERNAL_STRIP_HDR"
/*
* check if we need to strip the header from (internal) encrypted JWTs or not
*/
static apr_byte_t oidc_util_jwt_internal_strip_header(request_rec *r) {
// avoid stripping JWT headers that need to be compatible with external producers/consumers
return oidc_util_env_var_override(r, OIDC_JWT_INTERNAL_STRIP_HDR_ENV_VAR, TRUE);
}
/*
* create an encrypted JWT for internal purposes (i.e. state cookie, session cookie, or encrypted cache value)
*/
apr_byte_t oidc_util_jwt_create(request_rec *r, const oidc_crypto_passphrase_t *passphrase, const char *s_payload,
char **compact_encoded_jwt) {
apr_byte_t rv = FALSE;
oidc_jose_error_t err;
char *cser = NULL;
int cser_len = 0;
oidc_jwk_t *jwk = NULL;
oidc_jwt_t *jwe = NULL;
if (passphrase->secret1 == NULL) {
oidc_error(r, "secret is not set");
goto end;
}
if (oidc_util_create_symmetric_key(r, passphrase->secret1, 0, OIDC_JOSE_ALG_SHA256, FALSE, &jwk) == FALSE)
goto end;
if (oidc_util_jwt_internal_compress(r)) {
if (oidc_jose_compress(r->pool, s_payload, _oidc_strlen(s_payload), &cser, &cser_len, &err) == FALSE) {
oidc_error(r, "oidc_jose_compress failed: %s", oidc_jose_e2s(r->pool, err));
goto end;
}
} else {
cser = apr_pstrdup(r->pool, s_payload);
cser_len = _oidc_strlen(s_payload);
}
jwe = oidc_jwt_new(r->pool, TRUE, FALSE);
if (jwe == NULL) {
oidc_error(r, "creating JWE failed");
goto end;
}
jwe->header.alg = apr_pstrdup(r->pool, CJOSE_HDR_ALG_DIR);
jwe->header.enc = apr_pstrdup(r->pool, CJOSE_HDR_ENC_A256GCM);
if (passphrase->secret2 != NULL)
jwe->header.kid = apr_pstrdup(r->pool, "1");
if (oidc_jwt_encrypt(r->pool, jwe, jwk, cser, cser_len, compact_encoded_jwt, &err) == FALSE) {
oidc_error(r, "encrypting JWT failed: %s", oidc_jose_e2s(r->pool, err));
goto end;
}
if ((*compact_encoded_jwt != NULL) && (oidc_util_jwt_internal_strip_header(r)))
*compact_encoded_jwt += _oidc_strlen(oidc_util_jwt_hdr_dir_a256gcm(r, *compact_encoded_jwt));
rv = TRUE;
end:
if (jwe != NULL)
oidc_jwt_destroy(jwe);
if (jwk != NULL)
oidc_jwk_destroy(jwk);
return rv;
}
/*
* verify an encrypted JWT for internal purposes
*/
apr_byte_t oidc_util_jwt_verify(request_rec *r, const oidc_crypto_passphrase_t *passphrase,
const char *compact_encoded_jwt, char **s_payload) {
apr_byte_t rv = FALSE;
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
oidc_jwt_t *jwt = NULL;
char *payload = NULL;
int payload_len = 0;
char *plaintext = NULL;
int plaintext_len = 0;
apr_hash_t *keys = NULL;
char *alg = NULL;
char *enc = NULL;
char *kid = NULL;
if (oidc_util_jwt_internal_strip_header(r))
compact_encoded_jwt =
apr_pstrcat(r->pool, oidc_util_jwt_hdr_dir_a256gcm(r, NULL), compact_encoded_jwt, NULL);
oidc_proto_jwt_header_peek(r, compact_encoded_jwt, &alg, &enc, &kid);
if ((_oidc_strcmp(alg, CJOSE_HDR_ALG_DIR) != 0) || (_oidc_strcmp(enc, CJOSE_HDR_ENC_A256GCM) != 0)) {
oidc_error(r, "corrupted JWE header, alg=\"%s\" enc=\"%s\"", alg, enc);
goto end;
}
keys = apr_hash_make(r->pool);
if ((passphrase->secret2 != NULL) && (kid == NULL)) {
if (oidc_util_create_symmetric_key(r, passphrase->secret2, 0, OIDC_JOSE_ALG_SHA256, FALSE, &jwk) ==
FALSE)
goto end;
} else {
if (oidc_util_create_symmetric_key(r, passphrase->secret1, 0, OIDC_JOSE_ALG_SHA256, FALSE, &jwk) ==
FALSE)
goto end;
}
apr_hash_set(keys, "1", APR_HASH_KEY_STRING, jwk);
if (oidc_jwe_decrypt(r->pool, compact_encoded_jwt, keys, &plaintext, &plaintext_len, &err, FALSE) == FALSE) {
oidc_error(r, "decrypting JWE failed: %s", oidc_jose_e2s(r->pool, err));
goto end;
}
if (oidc_util_jwt_internal_compress(r)) {
if (oidc_jose_uncompress(r->pool, (char *)plaintext, plaintext_len, &payload, &payload_len, &err) ==
FALSE) {
oidc_error(r, "oidc_jose_uncompress failed: %s", oidc_jose_e2s(r->pool, err));
goto end;
}
} else {
payload = plaintext;
payload_len = plaintext_len;
}
*s_payload = apr_pstrndup(r->pool, payload, payload_len);
rv = TRUE;
end:
if (jwk != NULL)
oidc_jwk_destroy(jwk);
if (jwt != NULL)
oidc_jwt_destroy(jwt);
return rv;
}
/*
* convert a character to an ENVIRONMENT-variable-safe variant
*/
static int oidc_util_char_to_env(int c) {
return apr_isalnum(c) ? apr_toupper(c) : '_';
}
/*
* compare two strings based on how they would be converted to an
* environment variable, as per oidc_char_to_env. If len is specified
* as less than zero, then the full strings will be compared. Returns
* less than, equal to, or greater than zero based on whether the
* first argument's conversion to an environment variable is less
* than, equal to, or greater than the second.
*/
int oidc_util_strnenvcmp(const char *a, const char *b, int len) {
int d = 0;
int i = 0;
while (1) {
/* If len < 0 then we don't stop based on length */
if (len >= 0 && i >= len)
return 0;
/* If we're at the end of both strings, they're equal */
if (!*a && !*b)
return 0;
/* If the second string is shorter, pick it: */
if (*a && !*b)
return 1;
/* If the first string is shorter, pick it: */
if (!*a && *b)
return -1;
/* Normalize the characters as for conversion to an
* environment variable. */
d = oidc_util_char_to_env(*a) - oidc_util_char_to_env(*b);
if (d)
return d;
a++;
b++;
i++;
}
}
/*
* HTML escape a string
*/
char *oidc_util_html_escape(apr_pool_t *pool, const char *s) {
// TODO: this has performance/memory issues for large chunks of HTML
const char chars[6] = {'&', '\'', '\"', '>', '<', '\0'};
const char *const replace[] = {
"&", "'", """, ">", "<",
};
unsigned int i = 0;
unsigned int j = 0;
unsigned int k = 0;
unsigned int n = 0;
unsigned int m = 0;
const char *ptr = chars;
unsigned int len = _oidc_strlen(ptr);
char *r = apr_pcalloc(pool, _oidc_strlen(s) * 6);
for (i = 0; i < _oidc_strlen(s); i++) {
for (n = 0; n < len; n++) {
if (s[i] == chars[n]) {
m = (unsigned int)_oidc_strlen(replace[n]);
for (k = 0; k < m; k++)
r[j + k] = replace[n][k];
j += m;
break;
}
}
if (n == len) {
r[j] = s[i];
j++;
}
}
r[j] = '\0';
return apr_pstrdup(pool, r);
}
/*
* JavaScript escape a string
*/
char *oidc_util_javascript_escape(apr_pool_t *pool, const char *s) {
const char *cp = NULL;
char *output = NULL;
size_t outputlen = 0;
int i = 0;
if (s == NULL) {
return NULL;
}
outputlen = 0;
for (cp = s; *cp; cp++) {
switch (*cp) {
case '\'':
case '"':
case '\\':
case '/':
case 0x0D:
case 0x0A:
outputlen += 2;
break;
case '<':
case '>':
outputlen += 4;
break;
default:
outputlen += 1;
break;
}
}
i = 0;
output = apr_pcalloc(pool, outputlen + 1);
for (cp = s; *cp; cp++) {
switch (*cp) {
case '\'':
if (i <= outputlen - 2)
(void)_oidc_strcpy(&output[i], "\\'");
i += 2;
break;
case '"':
if (i <= outputlen - 2)
(void)_oidc_strcpy(&output[i], "\\\"");
i += 2;
break;
case '\\':
if (i <= outputlen - 2)
(void)_oidc_strcpy(&output[i], "\\\\");
i += 2;
break;
case '/':
if (i <= outputlen - 2)
(void)_oidc_strcpy(&output[i], "\\/");
i += 2;
break;
case 0x0D:
if (i <= outputlen - 2)
(void)_oidc_strcpy(&output[i], "\\r");
i += 2;
break;
case 0x0A:
if (i <= outputlen - 2)
(void)_oidc_strcpy(&output[i], "\\n");
i += 2;
break;
case '<':
if (i <= outputlen - 4)
(void)_oidc_strcpy(&output[i], "\\x3c");
i += 4;
break;
case '>':
if (i <= outputlen - 4)
(void)_oidc_strcpy(&output[i], "\\x3e");
i += 4;
break;
default:
if (i <= outputlen - 1)
output[i] = *cp;
i += 1;
break;
}
}
output[i] = '\0';
return output;
}
/*
* find a needle (s2) in a haystack (s1) using case-insensitive string compare
*/
const char *oidc_util_strcasestr(const char *s1, const char *s2) {
const char *s = s1;
const char *p = s2;
if ((s == NULL) || (p == NULL))
return NULL;
do {
if (!*p)
return s1;
if ((*p == *s) || (tolower(*p) == tolower(*s))) {
++p;
++s;
} else {
p = s2;
if (!*s)
return NULL;
s = ++s1;
}
} while (1);
}
/*
* get the URL scheme that is currently being accessed
*/
static const char *oidc_util_current_url_scheme(const request_rec *r, oidc_hdr_x_forwarded_t x_forwarded_headers) {
/* first see if there's a proxy/load-balancer in front of us */
const char *scheme_str = NULL;
if (x_forwarded_headers & OIDC_HDR_FORWARDED)
scheme_str = oidc_http_hdr_forwarded_get(r, "proto");
if ((scheme_str == NULL) && (x_forwarded_headers & OIDC_HDR_X_FORWARDED_PROTO))
scheme_str = oidc_http_hdr_in_x_forwarded_proto_get(r);
/* if not we'll determine the scheme used to connect to this server */
if (scheme_str == NULL) {
#ifdef APACHE2_0
scheme_str = (char *)ap_http_method(r);
#else
scheme_str = ap_http_scheme(r);
#endif
}
if ((scheme_str == NULL) ||
((_oidc_strcmp(scheme_str, "http") != 0) && (_oidc_strcmp(scheme_str, "https") != 0))) {
oidc_warn(r,
"detected HTTP scheme \"%s\" is not \"http\" nor \"https\"; perhaps your reverse proxy "
"passes a wrongly configured \"%s\" header: falling back to default \"https\"",
scheme_str, OIDC_HTTP_HDR_X_FORWARDED_PROTO);
scheme_str = "https";
}
return scheme_str;
}
/*
* get the port part from a Host header
*/
static const char *oidc_util_port_from_host(const char *host_hdr) {
char *p = NULL;
char *i = NULL;
if (host_hdr) {
if (host_hdr[0] == '[') {
i = strchr(host_hdr, ']');
p = strchr(i, OIDC_CHAR_COLON);
} else {
p = strchr(host_hdr, OIDC_CHAR_COLON);
}
}
if (p)
return p;
else
return NULL;
}
/*
* get the URL port that is currently being accessed
*/
static const char *oidc_get_current_url_port(const request_rec *r, const char *scheme_str, int x_forwarded_headers) {
const char *host_hdr = NULL;
const char *port_str = NULL;
/*
* first see if there's a proxy/load-balancer in front of us
* that sets X-Forwarded-Port
*/
if (x_forwarded_headers & OIDC_HDR_X_FORWARDED_PORT)
port_str = oidc_http_hdr_in_x_forwarded_port_get(r);
if (port_str)
return port_str;
/*
* see if we can get the port from the "X-Forwarded-Host" or "Forwarded" header
* and if that header was set we'll assume defaults
*/
if (x_forwarded_headers & OIDC_HDR_FORWARDED)
host_hdr = oidc_http_hdr_forwarded_get(r, "host");
if ((host_hdr == NULL) && (x_forwarded_headers & OIDC_HDR_X_FORWARDED_HOST))
host_hdr = oidc_http_hdr_in_x_forwarded_host_get(r);
if (host_hdr) {
port_str = oidc_util_port_from_host(host_hdr);
if (port_str)
port_str++;
return port_str;
}
/*
* see if we can get the port from the "Host" header; if not
* we'll determine the port locally
*/
host_hdr = oidc_http_hdr_in_host_get(r);
if (host_hdr) {
port_str = oidc_util_port_from_host(host_hdr);
if (port_str) {
port_str++;
return port_str;
}
}
/*
* if X-Forwarded-Proto assume the default port otherwise the
* port should have been set in the X-Forwarded-Port header
*/
if ((x_forwarded_headers & OIDC_HDR_X_FORWARDED_PROTO) && (oidc_http_hdr_in_x_forwarded_proto_get(r)))
return NULL;
/*
* do the same for the Forwarded: proto= header
*/
if ((x_forwarded_headers & OIDC_HDR_FORWARDED) && (oidc_http_hdr_forwarded_get(r, "proto")))
return NULL;
/*
* if no port was set in the Host header and no X-Forwarded-Proto was set, we'll
* determine the port locally and don't print it when it's the default for the protocol
*/
const apr_port_t port = r->connection->local_addr->port;
if ((_oidc_strcmp(scheme_str, "https") == 0) && port == 443)
return NULL;
else if ((_oidc_strcmp(scheme_str, "http") == 0) && port == 80)
return NULL;
port_str = apr_psprintf(r->pool, "%u", port);
return port_str;
}
/*
* get the hostname part of the URL that is currently being accessed
*/
const char *oidc_util_current_url_host(request_rec *r, oidc_hdr_x_forwarded_t x_forwarded_headers) {
const char *host_str = NULL;
char *p = NULL;
char *i = NULL;
if (x_forwarded_headers & OIDC_HDR_FORWARDED)
host_str = oidc_http_hdr_forwarded_get(r, "host");
if ((host_str == NULL) && (x_forwarded_headers & OIDC_HDR_X_FORWARDED_HOST))
host_str = oidc_http_hdr_in_x_forwarded_host_get(r);
if (host_str == NULL)
host_str = oidc_http_hdr_in_host_get(r);
if (host_str) {
host_str = apr_pstrdup(r->pool, host_str);
if (host_str[0] == '[') {
i = strchr(host_str, ']');
p = strchr(i, OIDC_CHAR_COLON);
} else {
p = strchr(host_str, OIDC_CHAR_COLON);
}
if (p != NULL)
*p = '\0';
} else {
/* no Host header, HTTP 1.0 */
host_str = ap_get_server_name(r);
}
return host_str;
}
/*
* get the base part of the current URL (scheme + host (+ port))
*/
static const char *oidc_get_current_url_base(request_rec *r, oidc_hdr_x_forwarded_t x_forwarded_headers) {
const char *scheme_str = NULL;
const char *host_str = NULL;
const char *port_str = NULL;
oidc_cfg_x_forwarded_headers_check(r, x_forwarded_headers);
scheme_str = oidc_util_current_url_scheme(r, x_forwarded_headers);
host_str = oidc_util_current_url_host(r, x_forwarded_headers);
port_str = oidc_get_current_url_port(r, scheme_str, x_forwarded_headers);
port_str = port_str ? apr_psprintf(r->pool, ":%s", port_str) : "";
char *url = apr_pstrcat(r->pool, scheme_str, "://", host_str, port_str, NULL);
return url;
}
/*
* get the URL that is currently being accessed
*/
char *oidc_util_current_url(request_rec *r, oidc_hdr_x_forwarded_t x_forwarded_headers) {
char *url = NULL;
char *path = NULL;
apr_uri_t uri;
path = r->uri;
/* check if we're dealing with a forward proxying secenario i.e. a non-relative URL */
if ((path) && (path[0] != '/')) {
_oidc_memset(&uri, 0, sizeof(apr_uri_t));
if (apr_uri_parse(r->pool, r->uri, &uri) == APR_SUCCESS)
path = apr_pstrcat(r->pool, uri.path, (r->args != NULL && *r->args != '\0' ? "?" : ""), r->args,
NULL);
else
oidc_warn(r, "apr_uri_parse failed on non-relative URL: %s", r->uri);
} else {
/* make sure we retain URL-encoded characters original URL that we send the user back to */
path = r->unparsed_uri;
}
url = apr_pstrcat(r->pool, oidc_get_current_url_base(r, x_forwarded_headers), path, NULL);
oidc_debug(r, "current URL '%s'", url);
return url;
}
/*
* infer a full absolute URL from the (optional) relative one
*/
const char *oidc_util_absolute_url(request_rec *r, oidc_cfg_t *cfg, const char *url) {
if ((url != NULL) && (url[0] == OIDC_CHAR_FORWARD_SLASH)) {
url = apr_pstrcat(r->pool, oidc_get_current_url_base(r, oidc_cfg_x_forwarded_headers_get(cfg)), url,
NULL);
oidc_debug(r, "determined absolute url: %s", url);
}
return url;
}
/*
* check if the request is on a secure HTTPs (TLS) connection
*/
apr_byte_t oidc_util_request_is_secure(request_rec *r, oidc_cfg_t *c) {
return (_oidc_strnatcasecmp("https", oidc_util_current_url_scheme(r, oidc_cfg_x_forwarded_headers_get(c))) ==
0);
}
/*
* return absolute Redirect URI
*/
const char *oidc_util_redirect_uri(request_rec *r, oidc_cfg_t *cfg) {
return oidc_util_absolute_url(r, cfg, oidc_cfg_redirect_uri_get(cfg));
}
/*
* see if the currently accessed path matches a path from a defined URL
*/
apr_byte_t oidc_util_request_matches_url(request_rec *r, const char *url) {
apr_uri_t uri;
_oidc_memset(&uri, 0, sizeof(apr_uri_t));
if ((url == NULL) || (apr_uri_parse(r->pool, url, &uri) != APR_SUCCESS))
return FALSE;
oidc_debug(r, "comparing \"%s\"==\"%s\"", r->parsed_uri.path, uri.path);
if ((r->parsed_uri.path == NULL) || (uri.path == NULL))
return (r->parsed_uri.path == uri.path);
return (_oidc_strcmp(r->parsed_uri.path, uri.path) == 0);
}
/*
* see if the currently accessed path has a certain query parameter
*/
apr_byte_t oidc_util_request_has_parameter(request_rec *r, const char *param) {
if (r->args == NULL)
return FALSE;
const char *option1 = apr_psprintf(r->pool, "%s=", param);
const char *option2 = apr_psprintf(r->pool, "&%s=", param);
return ((_oidc_strstr(r->args, option1) == r->args) || (_oidc_strstr(r->args, option2) != NULL)) ? TRUE : FALSE;
}
/*
* get a query parameter
*/
apr_byte_t oidc_util_request_parameter_get(request_rec *r, char *name, char **value) {
char *tokenizer_ctx = NULL;
char *p = NULL;
char *args = NULL;
const char *k_param = apr_psprintf(r->pool, "%s=", name);
const size_t k_param_sz = _oidc_strlen(k_param);
*value = NULL;
if (r->args == NULL || _oidc_strlen(r->args) == 0)
return FALSE;
/* not sure why we do this, but better be safe than sorry */
args = apr_pstrmemdup(r->pool, r->args, _oidc_strlen(r->args));
p = apr_strtok(args, OIDC_STR_AMP, &tokenizer_ctx);
do {
if (p && _oidc_strncmp(p, k_param, k_param_sz) == 0) {
*value = apr_pstrdup(r->pool, p + k_param_sz);
*value = oidc_http_url_decode(r, *value);
}
p = apr_strtok(NULL, OIDC_STR_AMP, &tokenizer_ctx);
} while (p);
return (*value != NULL ? TRUE : FALSE);
}
/*
* printout a JSON string value
*/
static apr_byte_t oidc_util_json_string_print(request_rec *r, json_t *result, const char *key, const char *log) {
json_t *value = json_object_get(result, key);
if (value != NULL && !json_is_null(value)) {
oidc_error(r, "%s: response contained an \"%s\" entry with value: \"%s\"", log, key,
oidc_util_encode_json_object(r, value, JSON_ENCODE_ANY));
return TRUE;
}
return FALSE;
}
/*
* check a JSON object for "error" results and printout
*/
apr_byte_t oidc_util_check_json_error(request_rec *r, json_t *json) {
if (oidc_util_json_string_print(r, json, OIDC_PROTO_ERROR, "oidc_util_check_json_error") == TRUE) {
oidc_util_json_string_print(r, json, OIDC_PROTO_ERROR_DESCRIPTION, "oidc_util_check_json_error");
return TRUE;
}
return FALSE;
}
#define OIDC_JSON_MAX_ERROR_STR 4096
/*
* parse a JSON object
*/
apr_byte_t oidc_util_decode_json_object_err(request_rec *r, const char *str, json_t **json, apr_byte_t log_err) {
if (str == NULL)
return FALSE;
json_error_t json_error;
*json = json_loads(str, 0, &json_error);
/* decode the JSON contents of the buffer */
if (*json == NULL) {
if (log_err) {
/* something went wrong */
#if JANSSON_VERSION_HEX >= 0x020B00
if (json_error_code(&json_error) == json_error_null_character) {
oidc_error(r, "JSON parsing returned an error: %s", json_error.text);
} else {
#endif
oidc_error(r, "JSON parsing returned an error: %s (%s)", json_error.text,
apr_pstrndup(r->pool, str, OIDC_JSON_MAX_ERROR_STR));
#if JANSSON_VERSION_HEX >= 0x020B00
}
#endif
}
return FALSE;
}
if (!json_is_object(*json)) {
/* oops, no JSON */
if (log_err) {
oidc_error(r, "parsed JSON did not contain a JSON object");
json_decref(*json);