forked from apereo/mod_auth_cas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod_auth_cas.c
2867 lines (2476 loc) · 101 KB
/
mod_auth_cas.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
/*
*
* Copyright 2011 the mod_auth_cas team.
*
* Licensed 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.
*
* mod_auth_cas.c
* Apache CAS Authentication Module
* Version 1.0.10
*
* Contact: cas-user@apereo.org
*
*/
#include <error.h>
#include <string.h>
#include <sys/file.h>
#include <sys/types.h>
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <curl/curl.h>
#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_protocol.h"
#include "http_request.h"
#include "http_log.h"
#include "util_md5.h"
#include "ap_config.h"
#include "ap_release.h"
#include "pcre.h"
#include "apr_buckets.h"
#include "apr_file_info.h"
#include "apr_lib.h"
#include "apr_md5.h"
#include "apr_thread_mutex.h"
#include "apr_strings.h"
#include "apr_xml.h"
#include "cas_saml_attr.h"
/* Apache is NOT a well-behaved citizen. It unconditionally
* pollutes global defines with its own autoheaders.
* Must undef any autoconf variables that need local definition. */
#undef PACKAGE_BUGREPORT
#undef PACKAGE_NAME
#undef PACKAGE_STRING
#undef PACKAGE_TARNAME
#undef PACKAGE_VERSION
/* Autoconf config.h */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "mod_auth_cas.h"
#if defined(OPENSSL_THREADS) && APR_HAS_THREADS
static apr_thread_mutex_t **ssl_locks;
static int ssl_num_locks;
#endif /* defined(OPENSSL_THREADS) && APR_HAS_THREADS */
#ifdef APLOG_USE_MODULE
APLOG_USE_MODULE(auth_cas);
#endif
int cas_flock(apr_file_t *fileHandle, int lockOperation, request_rec *r)
{
apr_os_file_t osFileHandle;
int flockErr;
apr_os_file_get(&osFileHandle, fileHandle);
do {
flockErr = flock(osFileHandle, lockOperation);
} while(flockErr == -1 && errno == EINTR);
if(r != NULL && flockErr) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: Failed to apply locking operation (%s)", strerror(errno));
}
return flockErr;
}
/* mod_auth_cas configuration specific functions */
void *cas_create_server_config(apr_pool_t *pool, server_rec *svr)
{
cas_cfg *c = apr_pcalloc(pool, sizeof(cas_cfg));
c->merged = FALSE;
c->CASVersion = CAS_DEFAULT_VERSION;
c->CASDebug = CAS_DEFAULT_DEBUG;
c->CASValidateDepth = CAS_DEFAULT_VALIDATE_DEPTH;
c->CASCertificatePath = CAS_DEFAULT_CA_PATH;
c->CASCookiePath = CAS_DEFAULT_COOKIE_PATH;
c->CASCookieEntropy = CAS_DEFAULT_COOKIE_ENTROPY;
c->CASTimeout = CAS_DEFAULT_COOKIE_TIMEOUT;
c->CASIdleTimeout = CAS_DEFAULT_COOKIE_IDLE_TIMEOUT;
c->CASCacheCleanInterval = CAS_DEFAULT_CACHE_CLEAN_INTERVAL;
c->CASCookieDomain = CAS_DEFAULT_COOKIE_DOMAIN;
c->CASCookieHttpOnly = CAS_DEFAULT_COOKIE_HTTPONLY;
c->CASSSOEnabled = CAS_DEFAULT_SSO_ENABLED;
c->CASValidateSAML = CAS_DEFAULT_VALIDATE_SAML;
c->CASAttributeDelimiter = CAS_DEFAULT_ATTRIBUTE_DELIMITER;
c->CASAttributePrefix = CAS_DEFAULT_ATTRIBUTE_PREFIX;
#if MODULE_MAGIC_NUMBER_MAJOR < 20120211
c->CASAuthoritative = CAS_DEFAULT_AUTHORITATIVE;
#endif
cas_setURL(pool, &(c->CASLoginURL), CAS_DEFAULT_LOGIN_URL);
cas_setURL(pool, &(c->CASValidateURL), CAS_DEFAULT_VALIDATE_URL);
cas_setURL(pool, &(c->CASProxyValidateURL), CAS_DEFAULT_PROXY_VALIDATE_URL);
cas_setURL(pool, &(c->CASRootProxiedAs), CAS_DEFAULT_ROOT_PROXIED_AS_URL);
return c;
}
void *cas_merge_server_config(apr_pool_t *pool, void *BASE, void *ADD)
{
cas_cfg *c = apr_pcalloc(pool, sizeof(cas_cfg));
cas_cfg *base = BASE;
cas_cfg *add = ADD;
apr_uri_t test;
memset(&test, '\0', sizeof(apr_uri_t));
c->merged = TRUE;
c->CASVersion = (add->CASVersion != CAS_DEFAULT_VERSION ? add->CASVersion : base->CASVersion);
c->CASDebug = (add->CASDebug != CAS_DEFAULT_DEBUG ? add->CASDebug : base->CASDebug);
c->CASValidateDepth = (add->CASValidateDepth != CAS_DEFAULT_VALIDATE_DEPTH ? add->CASValidateDepth : base->CASValidateDepth);
c->CASCertificatePath = (apr_strnatcasecmp(add->CASCertificatePath,CAS_DEFAULT_CA_PATH) != 0 ? add->CASCertificatePath : base->CASCertificatePath);
c->CASCookiePath = (apr_strnatcasecmp(add->CASCookiePath, CAS_DEFAULT_COOKIE_PATH) != 0 ? add->CASCookiePath : base->CASCookiePath);
c->CASCookieEntropy = (add->CASCookieEntropy != CAS_DEFAULT_COOKIE_ENTROPY ? add->CASCookieEntropy : base->CASCookieEntropy);
c->CASTimeout = (add->CASTimeout != CAS_DEFAULT_COOKIE_TIMEOUT ? add->CASTimeout : base->CASTimeout);
c->CASIdleTimeout = (add->CASIdleTimeout != CAS_DEFAULT_COOKIE_IDLE_TIMEOUT ? add->CASIdleTimeout : base->CASIdleTimeout);
c->CASCacheCleanInterval = (add->CASCacheCleanInterval != CAS_DEFAULT_CACHE_CLEAN_INTERVAL ? add->CASCacheCleanInterval : base->CASCacheCleanInterval);
c->CASCookieDomain = (add->CASCookieDomain != CAS_DEFAULT_COOKIE_DOMAIN ? add->CASCookieDomain : base->CASCookieDomain);
c->CASCookieHttpOnly = (add->CASCookieHttpOnly != CAS_DEFAULT_COOKIE_HTTPONLY ? add->CASCookieHttpOnly : base->CASCookieHttpOnly);
c->CASSSOEnabled = (add->CASSSOEnabled != CAS_DEFAULT_SSO_ENABLED ? add->CASSSOEnabled : base->CASSSOEnabled);
c->CASValidateSAML = (add->CASValidateSAML != CAS_DEFAULT_VALIDATE_SAML ? add->CASValidateSAML : base->CASValidateSAML);
#if MODULE_MAGIC_NUMBER_MAJOR < 20120211
c->CASAuthoritative = (add->CASAuthoritative != CAS_DEFAULT_AUTHORITATIVE ? add->CASAuthoritative : base->CASAuthoritative);
#endif
c->CASAttributeDelimiter = (apr_strnatcasecmp(add->CASAttributeDelimiter, CAS_DEFAULT_ATTRIBUTE_DELIMITER) != 0 ? add->CASAttributeDelimiter : base->CASAttributeDelimiter);
c->CASAttributePrefix = (apr_strnatcasecmp(add->CASAttributePrefix, CAS_DEFAULT_ATTRIBUTE_PREFIX) != 0 ? add->CASAttributePrefix : base->CASAttributePrefix);
/* if add->CASLoginURL == NULL, we want to copy base -- otherwise, copy the one from add, and so on and so forth */
if(memcmp(&add->CASLoginURL, &test, sizeof(apr_uri_t)) == 0)
memcpy(&c->CASLoginURL, &base->CASLoginURL, sizeof(apr_uri_t));
else
memcpy(&c->CASLoginURL, &add->CASLoginURL, sizeof(apr_uri_t));
if(memcmp(&add->CASValidateURL, &test, sizeof(apr_uri_t)) == 0)
memcpy(&c->CASValidateURL, &base->CASValidateURL, sizeof(apr_uri_t));
else
memcpy(&c->CASValidateURL, &add->CASValidateURL, sizeof(apr_uri_t));
if(memcmp(&add->CASProxyValidateURL, &test, sizeof(apr_uri_t)) == 0)
memcpy(&c->CASProxyValidateURL, &base->CASProxyValidateURL, sizeof(apr_uri_t));
else
memcpy(&c->CASProxyValidateURL, &add->CASProxyValidateURL, sizeof(apr_uri_t));
if(memcmp(&add->CASRootProxiedAs, &test, sizeof(apr_uri_t)) == 0)
memcpy(&c->CASRootProxiedAs, &base->CASRootProxiedAs, sizeof(apr_uri_t));
else
memcpy(&c->CASRootProxiedAs, &add->CASRootProxiedAs, sizeof(apr_uri_t));
return c;
}
void *cas_create_dir_config(apr_pool_t *pool, char *path)
{
cas_dir_cfg *c = apr_pcalloc(pool, sizeof(cas_dir_cfg));
c->CASScope = CAS_DEFAULT_SCOPE;
c->CASRenew = CAS_DEFAULT_RENEW;
c->CASGateway = CAS_DEFAULT_GATEWAY;
c->CASCookie = CAS_DEFAULT_COOKIE;
c->CASSecureCookie = CAS_DEFAULT_SCOOKIE;
c->CASGatewayCookie = CAS_DEFAULT_GATEWAY_COOKIE;
c->CASAuthNHeader = CAS_DEFAULT_AUTHN_HEADER;
c->CASScrubRequestHeaders = CAS_DEFAULT_SCRUB_REQUEST_HEADERS;
c->CASDisableRedirectAfterValidation = CAS_DEFAULT_REDIRECT_AFTER_VALIDATION;
return(c);
}
void *cas_merge_dir_config(apr_pool_t *pool, void *BASE, void *ADD)
{
cas_dir_cfg *c = apr_pcalloc(pool, sizeof(cas_dir_cfg));
cas_dir_cfg *base = BASE;
cas_dir_cfg *add = ADD;
/* inherit the previous directory's setting if applicable */
c->CASScope = (add->CASScope != CAS_DEFAULT_SCOPE ?
add->CASScope : base->CASScope);
if(add->CASScope != NULL && apr_strnatcasecmp(add->CASScope, "Off") == 0)
c->CASScope = NULL;
c->CASRenew = (add->CASRenew != CAS_DEFAULT_RENEW ?
add->CASRenew : base->CASRenew);
if(add->CASRenew != NULL && apr_strnatcasecmp(add->CASRenew, "Off") == 0)
c->CASRenew = NULL;
c->CASGateway = (add->CASGateway != CAS_DEFAULT_GATEWAY ?
add->CASGateway : base->CASGateway);
if(add->CASGateway != NULL && apr_strnatcasecmp(add->CASGateway, "Off") == 0)
c->CASGateway = NULL;
c->CASCookie = (apr_strnatcasecmp(add->CASCookie, CAS_DEFAULT_COOKIE) != 0 ?
add->CASCookie : base->CASCookie);
c->CASSecureCookie = (apr_strnatcasecmp(add->CASSecureCookie, CAS_DEFAULT_SCOOKIE) != 0 ?
add->CASSecureCookie : base->CASSecureCookie);
c->CASGatewayCookie = (apr_strnatcasecmp(add->CASGatewayCookie, CAS_DEFAULT_GATEWAY_COOKIE) != 0 ?
add->CASGatewayCookie : base->CASGatewayCookie);
c->CASAuthNHeader = (add->CASAuthNHeader != CAS_DEFAULT_AUTHN_HEADER ?
add->CASAuthNHeader : base->CASAuthNHeader);
if (add->CASAuthNHeader != NULL && apr_strnatcasecmp(add->CASAuthNHeader, "Off") == 0)
c->CASAuthNHeader = NULL;
c->CASScrubRequestHeaders = (add->CASScrubRequestHeaders != CAS_DEFAULT_SCRUB_REQUEST_HEADERS ?
add->CASScrubRequestHeaders :
base->CASScrubRequestHeaders);
if(add->CASScrubRequestHeaders != NULL && apr_strnatcasecmp(add->CASScrubRequestHeaders, "Off") == 0)
c->CASScrubRequestHeaders = NULL;
c->CASDisableRedirectAfterValidation = (add->CASDisableRedirectAfterValidation != CAS_DEFAULT_REDIRECT_AFTER_VALIDATION ?
add->CASDisableRedirectAfterValidation :
base->CASDisableRedirectAfterValidation);
if(add->CASDisableRedirectAfterValidation != NULL && apr_strnatcasecmp(add->CASDisableRedirectAfterValidation, "Off") == 0)
c->CASDisableRedirectAfterValidation = NULL;
return(c);
}
const char *cfg_readCASParameter(cmd_parms *cmd, void *cfg, const char *value)
{
cas_cfg *c = (cas_cfg *) ap_get_module_config(cmd->server->module_config, &auth_cas_module);
apr_finfo_t f;
size_t sz, limit;
int i;
char d;
/* cases determined from valid_cmds in mod_auth_cas.h - the config at this point is initialized to default values */
switch((size_t) cmd->info) {
case cmd_version:
i = atoi(value);
if(i > 0)
c->CASVersion = i;
else
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Invalid CAS version (%s) specified", value));
break;
case cmd_debug:
/* if atoi() is used on value here with AP_INIT_FLAG, it works but results in a compile warning, so we use TAKE1 to avoid it */
if(apr_strnatcasecmp(value, "On") == 0)
c->CASDebug = TRUE;
else if(apr_strnatcasecmp(value, "Off") == 0)
c->CASDebug = FALSE;
else
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Invalid argument to CASDebug - must be 'On' or 'Off'"));
break;
case cmd_validate_saml:
if(apr_strnatcasecmp(value, "On") == 0)
c->CASValidateSAML = TRUE;
else if(apr_strnatcasecmp(value, "Off") == 0)
c->CASValidateSAML = FALSE;
else
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Invalid argument to CASValidateSAML - must be 'On' or 'Off'"));
break;
case cmd_attribute_delimiter:
c->CASAttributeDelimiter = apr_pstrdup(cmd->pool, value);
break;
case cmd_attribute_prefix:
c->CASAttributePrefix = apr_pstrdup(cmd->pool, value);
break;
case cmd_ca_path:
if(apr_stat(&f, value, APR_FINFO_TYPE, cmd->temp_pool) == APR_INCOMPLETE)
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Could not find Certificate Authority file '%s'", value));
if(f.filetype != APR_REG && f.filetype != APR_DIR)
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Certificate Authority file '%s' is not a regular file or directory", value));
c->CASCertificatePath = apr_pstrdup(cmd->pool, value);
break;
case cmd_validate_depth:
i = atoi(value);
if(i > 0)
c->CASValidateDepth = i;
else
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Invalid CASValidateDepth (%s) specified", value));
break;
case cmd_cookie_path:
/* this is probably redundant since the same check is performed in cas_post_config */
if(apr_stat(&f, value, APR_FINFO_TYPE, cmd->temp_pool) == APR_INCOMPLETE)
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Could not find CASCookiePath '%s'", value));
if(f.filetype != APR_DIR || value[strlen(value)-1] != '/')
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: CASCookiePath '%s' is not a directory or does not end in a trailing '/'!", value));
c->CASCookiePath = apr_pstrdup(cmd->pool, value);
break;
case cmd_loginurl:
if(cas_setURL(cmd->pool, &(c->CASLoginURL), value) != TRUE)
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Login URL '%s' could not be parsed!", value));
break;
case cmd_validateurl:
if(cas_setURL(cmd->pool, &(c->CASValidateURL), value) != TRUE)
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Validation URL '%s' could not be parsed!", value));
break;
case cmd_proxyurl:
if(cas_setURL(cmd->pool, &(c->CASProxyValidateURL), value) != TRUE)
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Proxy Validation URL '%s' could not be parsed!", value));
break;
case cmd_root_proxied_as:
if(cas_setURL(cmd->pool, &(c->CASRootProxiedAs), value) != TRUE)
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Root Proxy URL '%s' could not be parsed!", value));
break;
case cmd_cookie_entropy:
i = atoi(value);
if(i > 0)
c->CASCookieEntropy = i;
else
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Invalid CASCookieEntropy (%s) specified - must be numeric", value));
break;
case cmd_session_timeout:
i = atoi(value);
if(i >= 0)
c->CASTimeout = i;
else
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Invalid CASTimeout (%s) specified - must be numeric", value));
break;
case cmd_idle_timeout:
i = atoi(value);
if(i > 0)
c->CASIdleTimeout = i;
else
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Invalid CASIdleTimeout (%s) specified - must be numeric", value));
break;
case cmd_cache_interval:
i = atoi(value);
if(i > 0)
c->CASCacheCleanInterval = i;
else
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Invalid CASCacheCleanInterval (%s) specified - must be numeric", value));
break;
case cmd_cookie_domain:
limit = strlen(value);
for(sz = 0; sz < limit; sz++) {
d = value[sz];
if( (d < '0' || d > '9') &&
(d < 'a' || d > 'z') &&
(d < 'A' || d > 'Z') &&
d != '.' && d != '-') {
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Invalid character (%c) in CASCookieDomain", d));
}
}
c->CASCookieDomain = apr_pstrdup(cmd->pool, value);
break;
case cmd_cookie_httponly:
if(apr_strnatcasecmp(value, "On") == 0)
c->CASCookieHttpOnly = TRUE;
else if(apr_strnatcasecmp(value, "Off") == 0)
c->CASCookieHttpOnly = FALSE;
else
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Invalid argument to CASCookieHttpOnly - must be 'On' or 'Off'"));
break;
case cmd_sso:
if(apr_strnatcasecmp(value, "On") == 0)
c->CASSSOEnabled = TRUE;
else if(apr_strnatcasecmp(value, "Off") == 0)
c->CASSSOEnabled = FALSE;
else
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Invalid argument to CASSSOEnabled - must be 'On' or 'Off'"));
break;
#if MODULE_MAGIC_NUMBER_MAJOR < 20120211
case cmd_authoritative:
if(apr_strnatcasecmp(value, "On") == 0)
c->CASAuthoritative = TRUE;
else if(apr_strnatcasecmp(value, "Off") == 0)
c->CASAuthoritative = FALSE;
else
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Invalid argument to CASAuthoritative - must be 'On' or 'Off'"));
break;
#endif
default:
/* should not happen */
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: invalid command '%s'", cmd->directive->directive));
break;
}
return NULL;
}
/* utility functions to set/retrieve values from the configuration */
apr_byte_t cas_setURL(apr_pool_t *pool, apr_uri_t *uri, const char *url)
{
if(url == NULL) {
uri = apr_pcalloc(pool, sizeof(apr_uri_t));
return FALSE;
}
if(apr_uri_parse(pool, url, uri) != APR_SUCCESS)
return FALSE;
/* set a default port if none was specified - we need this to perform a connect() to these servers for validation later */
if(uri->port == 0)
uri->port = apr_uri_port_of_scheme(uri->scheme);
if(uri->hostname == NULL)
return FALSE;
return TRUE;
}
apr_byte_t isSSL(const request_rec *r)
{
#ifdef APACHE2_0
if(apr_strnatcasecmp("https", ap_http_method(r)) == 0)
#else
if(apr_strnatcasecmp("https", ap_http_scheme(r)) == 0)
#endif
return TRUE;
return FALSE;
}
/* r->parsed_uri.path will return something like /xyz/index.html - this removes
* the file portion
*/
char *getCASPath(request_rec *r)
{
size_t i;
char *p;
p = r->parsed_uri.path;
if (p[0] == '\0')
return apr_pstrdup(r->pool, "/");
for (i = strlen(p) - 1; i > 0; i--)
if (p[i] == '/')
break;
return apr_pstrndup(r->pool, p, i + 1);
}
char *getCASScope(request_rec *r)
{
char *rv = NULL, *requestPath = getCASPath(r);
cas_cfg *c = ap_get_module_config(r->server->module_config, &auth_cas_module);
cas_dir_cfg *d = ap_get_module_config(r->per_dir_config, &auth_cas_module);
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Determining CAS scope (path: %s, CASScope: %s, CASRenew: %s, CASGateway: %s)", requestPath, d->CASScope, d->CASRenew, d->CASGateway);
if (d->CASGateway != NULL) {
/* the gateway path should be a subset of the request path */
if(strncmp(d->CASGateway, requestPath, strlen(d->CASGateway)) == 0)
rv = d->CASGateway;
else
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: CASGateway (%s) not a substring of request path, ignoring", d->CASGateway);
}
if(d->CASRenew != NULL) {
if(rv != NULL)
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: CASRenew (%s) and CASGateway (%s) set, CASRenew superseding.", d->CASRenew, d->CASGateway);
if(strncmp(d->CASRenew, requestPath, strlen(d->CASRenew)) == 0)
rv = d->CASRenew;
else
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: CASRenew (%s) not a substring of request path, ignoring", d->CASRenew);
}
/* neither gateway nor renew was set, or both were set incorrectly */
if(rv == NULL) {
if(d->CASScope != NULL) {
if(strncmp(d->CASScope, requestPath, strlen(d->CASScope)) == 0)
rv = d->CASScope;
else {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: CASScope (%s) not a substring of request path, using request path (%s) for cookie", d->CASScope, requestPath);
rv = requestPath;
}
}
else
rv = requestPath;
}
return (rv);
}
char *getCASGateway(request_rec *r)
{
char *rv = "";
cas_cfg *c = ap_get_module_config(r->server->module_config, &auth_cas_module);
cas_dir_cfg *d = ap_get_module_config(r->per_dir_config, &auth_cas_module);
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "entering getCASGateway()");
if(d->CASGateway != NULL && strncmp(d->CASGateway, r->parsed_uri.path, strlen(d->CASGateway)) == 0 && c->CASVersion > 1) { /* gateway not supported in CAS v1 */
rv = "&gateway=true";
}
return rv;
}
char *getCASRenew(request_rec *r)
{
char *rv = "";
cas_dir_cfg *d = ap_get_module_config(r->per_dir_config, &auth_cas_module);
if(d->CASRenew != NULL && strncmp(d->CASRenew, r->parsed_uri.path, strlen(d->CASRenew)) == 0) {
rv = "&renew=true";
}
return rv;
}
char *getCASLoginURL(request_rec *r, cas_cfg *c)
{
apr_uri_t test;
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "entering getCASLoginURL()");
memset(&test, '\0', sizeof(apr_uri_t));
if(memcmp(&c->CASLoginURL, &test, sizeof(apr_uri_t)) == 0) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: CASLoginURL null (not set?)");
return NULL;
}
/* this is used in the 'Location: [LoginURL]...' header context */
return(apr_uri_unparse(r->pool, &(c->CASLoginURL), APR_URI_UNP_OMITUSERINFO|APR_URI_UNP_OMITQUERY));
}
/*
* Responsible for creating the 'service=' parameter. Constructs this
* based on the contents of the request_rec because r->parsed_uri lacks
* information like hostname, scheme, and port.
*/
char *getCASService(const request_rec *r, const cas_cfg *c)
{
const apr_port_t port = r->connection->local_addr->port;
const apr_byte_t ssl = isSSL(r);
const apr_uri_t *root_proxy = &c->CASRootProxiedAs;
char *scheme, *port_str = "", *service;
apr_byte_t print_port = TRUE;
#ifdef APACHE2_0
scheme = (char *) ap_http_method(r);
#else
scheme = (char *) ap_http_scheme(r);
#endif
if (root_proxy->is_initialized) {
service = apr_psprintf(r->pool, "%s%s%s%s",
escapeString(r, apr_uri_unparse(r->pool, root_proxy, 0)),
escapeString(r, r->uri),
(r->args != NULL ? "%3f" : ""),
escapeString(r, r->args));
} else {
if (ssl && port == 443)
print_port = FALSE;
else if (!ssl && port == 80)
print_port = FALSE;
if (print_port)
port_str = apr_psprintf(r->pool, "%%3a%u", port);
service = apr_pstrcat(r->pool, scheme, "%3a%2f%2f",
r->server->server_hostname,
port_str, escapeString(r, r->uri),
(r->args != NULL && *r->args != '\0' ? "%3f" : ""),
escapeString(r, r->args), NULL);
}
if (c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "CAS Service '%s'", service);
return service;
}
/* utility functions that relate to request handling */
void redirectRequest(request_rec *r, cas_cfg *c)
{
char *destination;
char *service = getCASService(r, c);
char *loginURL = getCASLoginURL(r, c);
char *renew = getCASRenew(r);
char *gateway = getCASGateway(r);
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "entering redirectRequest()");
if(loginURL == NULL) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: Cannot redirect request (no CASLoginURL)");
return;
}
destination = apr_pstrcat(r->pool, loginURL, "?service=", service, renew, gateway, NULL);
apr_table_add(r->headers_out, "Location", destination);
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Adding outgoing header: Location: %s", destination);
}
apr_byte_t removeCASParams(request_rec *r)
{
char *old_args, *p, *ticket, *tmp;
const char *k_ticket_param = "ticket=";
const size_t k_ticket_param_sz = sizeof("ticket=") - 1;
size_t ticket_sz;
apr_byte_t changed = FALSE;
cas_cfg *c = ap_get_module_config(r->server->module_config,
&auth_cas_module);
if (r->args == NULL)
return changed;
ticket = getCASTicket(r);
if (!ticket)
return changed;
ticket_sz = strlen(ticket);
p = old_args = r->args;
while (*old_args != '\0') {
if (strncmp(old_args, k_ticket_param, k_ticket_param_sz) == 0) {
tmp = old_args + k_ticket_param_sz;
if (strncmp(tmp, ticket, ticket_sz) == 0) {
/* destroy the '&' from '&ticket=' if this wasn't r->args[0] */
if (old_args != r->args)
p--;
old_args += k_ticket_param_sz + ticket_sz;
changed = TRUE;
}
}
*p++ = *old_args++;
}
*p = '\0';
if (c->CASDebug && changed == TRUE)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Modified r->args (now '%s')",
r->args);
if (!*r->args)
r->args = NULL;
return changed;
}
apr_byte_t validCASTicketFormat(const char *ticket)
{
enum ticket_state {
ps,
t,
dash,
postfix,
illegal
} state = ps;
if (!*ticket)
goto bail;
while (state != illegal && *ticket) {
switch (state) {
case ps:
if (*ticket != 'P' && *ticket != 'S')
goto bail;
state = t;
break;
case t:
if (*ticket != 'T')
goto bail;
state = dash;
break;
case dash:
if (*ticket != '-')
goto bail;
state = postfix;
break;
case postfix:
if (*ticket != '-' && *ticket != '.' && !isalnum(*ticket))
goto bail;
break;
default:
goto bail;
break;
}
ticket++;
}
return TRUE;
bail:
return FALSE;
}
char *getCASTicket(request_rec *r)
{
char *tokenizer_ctx, *ticket, *args, *rv = NULL;
const char *k_ticket_param = "ticket=";
const size_t k_ticket_param_sz = strlen(k_ticket_param);
if(r->args == NULL || strlen(r->args) == 0)
return NULL;
args = apr_pstrndup(r->pool, r->args, strlen(r->args));
/* tokenize on & to find the 'ticket' parameter */
ticket = apr_strtok(args, "&", &tokenizer_ctx);
do {
if(ticket && strncmp(ticket, k_ticket_param, k_ticket_param_sz) == 0) {
if (validCASTicketFormat(ticket + k_ticket_param_sz)) {
rv = ticket + k_ticket_param_sz;
break;
}
}
ticket = apr_strtok(NULL, "&", &tokenizer_ctx);
} while (ticket);
return rv;
}
char *getCASCookie(request_rec *r, char *cookieName)
{
char *cookie, *tokenizerCtx, *rv = NULL;
char *cookies = apr_pstrdup(r->pool, (char *) apr_table_get(r->headers_in, "Cookie"));
if(cookies != NULL) {
/* tokenize on ; to find the cookie we want */
cookie = apr_strtok(cookies, ";", &tokenizerCtx);
while (cookie != NULL) {
while (*cookie == ' ') {
cookie++;
}
if (strncmp(cookie, cookieName, strlen(cookieName)) == 0) {
/* skip to the meat of the parameter (the value after the '=') */
cookie += (strlen(cookieName)+1);
rv = apr_pstrdup(r->pool, cookie);
break;
}
cookie = apr_strtok(NULL, ";", &tokenizerCtx);
}
}
return rv;
}
void setCASCookie(request_rec *r, char *cookieName, char *cookieValue, apr_byte_t secure, apr_time_t expireTime)
{
char *headerString, *currentCookies, *pathPrefix = "", *expireTimeString = NULL, *errString, *domainString = "";
cas_cfg *c = ap_get_module_config(r->server->module_config, &auth_cas_module);
apr_status_t retVal;
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "entering setCASCookie()");
if(c->CASRootProxiedAs.is_initialized)
pathPrefix = urlEncode(r, c->CASRootProxiedAs.path, " ");
if(CAS_SESSION_EXPIRE_SESSION_SCOPE_TIMEOUT != expireTime) {
expireTimeString = (char *)apr_pcalloc(r->pool, APR_RFC822_DATE_LEN);
retVal = apr_rfc822_date(expireTimeString, expireTime);
if(APR_SUCCESS != retVal) {
errString = (char *)apr_pcalloc(r->pool, CAS_MAX_ERROR_SIZE);
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Problem setting cookie expiry date: %s", apr_strerror(retVal, errString, CAS_MAX_ERROR_SIZE));
}
}
if(NULL != c->CASCookieDomain) {
domainString = apr_psprintf(r->pool, ";Domain=%s", c->CASCookieDomain);
}
headerString = apr_psprintf(r->pool, "%s=%s%s;Path=%s%s%s%s%s",
cookieName,
cookieValue,
(secure ? ";Secure" : ""),
pathPrefix,
urlEncode(r, getCASScope(r), " "),
(c->CASCookieDomain != NULL ? domainString : ""),
(c->CASCookieHttpOnly != FALSE ? "; HttpOnly" : ""),
(NULL == expireTimeString) ? "" : apr_psprintf(r->pool, "; expires=%s", expireTimeString));
/* use r->err_headers_out so we always print our headers (even on 302 redirect) - headers_out only prints on 2xx responses */
apr_table_add(r->err_headers_out, "Set-Cookie", headerString);
/*
* There is a potential problem here. If CASRenew is on and a user requests 'http://example.com/xyz/'
* then they are bounced out to the CAS server and they come back with a ticket. This ticket is validated
* and then this function (setCASCookie) is installed. However, mod_dir will create a subrequest to
* point them to some DirectoryIndex value. mod_auth_cas will see this new request (with no ticket since
* we removed it, but it would be invalid anyway since it was already validated at the CAS server)
* and redirect the user back to the CAS server (this time appending 'index.html' or something similar
* to the request) requiring two logins. By adding this cookie to the incoming headers, when the
* subrequest is sent, they will use their established session.
*/
if((currentCookies = (char *) apr_table_get(r->headers_in, "Cookie")) == NULL)
apr_table_add(r->headers_in, "Cookie", headerString);
else
apr_table_set(r->headers_in, "Cookie", (apr_pstrcat(r->pool, headerString, ";", currentCookies, NULL)));
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Adding outgoing header: Set-Cookie: %s", headerString);
return;
}
/*
* The CAS protocol spec 2.1.1 says the URL value MUST be URL-encoded as described in 2.2 of RFC 1738.
* The rfc1738 array below represents the 'unsafe' characters from that section. No encoding is performed
* on 'control characters' (0x00-0x1F) or characters not used in US-ASCII (0x80-0xFF) - is this a problem?
* 7/25/2009 - add '+' to list of characters to escape
*/
char *escapeString(const request_rec *r, const char *str)
{
char *rfc1738 = "+ <>\"%{}|\\^~[]`;/?:@=&#";
return(urlEncode(r, str, rfc1738));
}
char *urlEncode(const request_rec *r, const char *str,
const char *charsToEncode)
{
char *rv, *p;
const char *q;
size_t i, j, size, limit, newsz;
char escaped = FALSE;
if(str == NULL)
return "";
size = newsz = strlen(str);
limit = strlen(charsToEncode);
for(i = 0; i < size; i++) {
for(j = 0; j < limit; j++) {
if(str[i] == charsToEncode[j]) {
/* allocate 2 extra bytes for the escape sequence (' ' -> '%20') */
newsz += 2;
break;
}
}
}
/* allocate new memory to return the encoded URL */
p = rv = apr_pcalloc(r->pool, newsz + 1); /* +1 for terminating NULL */
q = str;
do {
escaped = FALSE;
for(i = 0; i < limit; i++) {
if(*q == charsToEncode[i]) {
sprintf(p, "%%%x", charsToEncode[i]);
p+= 3;
escaped = TRUE;
break;
}
}
if(escaped == FALSE) {
*p++ = *q;
}
q++;
} while (*q != '\0');
*p = '\0';
return(rv);
}
/* functions related to the local cache */
apr_byte_t readCASCacheFile(request_rec *r, cas_cfg *c, char *name, cas_cache_entry *cache)
{
apr_off_t begin = 0;
apr_file_t *f;
apr_finfo_t fi;
apr_xml_parser *parser;
apr_xml_doc *doc;
apr_xml_elem *e;
apr_status_t rv;
char errbuf[CAS_MAX_ERROR_SIZE];
char *path;
const char *val;
int i;
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "entering readCASCacheFile()");
/* first, validate that cookie looks like an MD5 string */
if(strlen(name) != APR_MD5_DIGESTSIZE*2) {
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Invalid cache cookie length for '%s', (expecting %d, got %d)", name, APR_MD5_DIGESTSIZE*2, (int) strlen(name));
return FALSE;
}
for(i = 0; i < APR_MD5_DIGESTSIZE*2; i++) {
if((name[i] < 'a' || name[i] > 'f') && (name[i] < '0' || name[i] > '9')) {
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Invalid character in cache cookie '%s' (%c)", name, name[i]);
return FALSE;
}
}
/* fix MAS-4 JIRA issue */
if(apr_stat(&fi, c->CASCookiePath, APR_FINFO_TYPE, r->pool) == APR_INCOMPLETE) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: Could not find Cookie Path '%s'", c->CASCookiePath);
return FALSE;
}
if(fi.filetype != APR_DIR || c->CASCookiePath[strlen(c->CASCookiePath)-1] != '/') {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: Cookie Path '%s' is not a directory or does not end in a trailing '/'!", c->CASCookiePath);
return FALSE;
}
/* end MAS-4 JIRA issue */
/* open the file if it exists and make sure that the ticket has not expired */
path = apr_psprintf(r->pool, "%s%s", c->CASCookiePath, name);
if(apr_file_open(&f, path, APR_FOPEN_READ, APR_OS_DEFAULT, r->pool) != APR_SUCCESS) {
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Cache entry '%s' could not be opened", name);
return FALSE;
}
if(cas_flock(f, LOCK_SH, r)) {
if(c->CASDebug) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "MOD_AUTH_CAS: Could not obtain shared lock on %s", name);
}
apr_file_close(f);
return FALSE;
}
/* read the various values we store */
apr_file_seek(f, APR_SET, &begin);
rv = apr_xml_parse_file(r->pool, &parser, &doc, f, CAS_MAX_XML_SIZE);
if(rv != APR_SUCCESS) {
if(parser == NULL) {
/*
* apr_xml_parse_file can fail early enough that the parser value is left uninitialized.
* In this case, we'll use apr_strerror and avoid calling apr_xml_parser_geterror, which
* segfaults with a null parser.
* patch to resolve this provided by Chris Adams of Yale
*/
apr_strerror(rv, errbuf, sizeof(errbuf));
} else {
apr_xml_parser_geterror(parser, errbuf, sizeof(errbuf));
}
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: Error parsing XML content (%s)", errbuf);
if(cas_flock(f, LOCK_UN, r)) {
if(c->CASDebug) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "MOD_AUTH_CAS: Could not release shared lock on %s", name);
}
}
apr_file_close(f);
return FALSE;
}
e = doc->root->first_child;
/* XML structure:
* cacheEntry
* attr
* attr
* ...
*/
/* initialize things to sane values */
cache->user = NULL;
cache->issued = 0;
cache->lastactive = 0;
cache->path = "";
cache->renewed = FALSE;
cache->secure = FALSE;
cache->ticket = NULL;
cache->attrs = NULL;
do {
if(e == NULL)
continue;
/* determine textual content of this element */
apr_xml_to_text(r->pool, e, APR_XML_X2T_INNER, NULL, NULL, &val, NULL);