-
Notifications
You must be signed in to change notification settings - Fork 2
/
mod_auth_cas.c
1825 lines (1545 loc) · 67 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 2009 Phillip Ames / Matt Smith
*
* 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.8
*
* Author:
* Phil Ames <modauthcas [at] gmail [dot] com>
* Designers:
* Phil Ames <modauthcas [at] gmail [dot] com>
* Matt Smith <matt [dot] smith [at] uconn [dot] edu>
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#endif
#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 "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 "apr_buckets.h"
#include "apr_file_info.h"
#include "apr_md5.h"
#include "apr_strings.h"
#include "apr_xml.h"
#include "mod_auth_cas.h"
/* mod_auth_cas configuration specific functions */
static void *cas_create_server_config(apr_pool_t *pool, server_rec *svr)
{
cas_cfg *c = apr_pcalloc(pool, sizeof(cas_cfg));
c->CASVersion = CAS_DEFAULT_VERSION;
c->CASDebug = CAS_DEFAULT_DEBUG;
c->CASValidateServer = CAS_DEFAULT_VALIDATE_SERVER;
c->CASValidateDepth = CAS_DEFAULT_VALIDATE_DEPTH;
c->CASAllowWildcardCert = CAS_DEFAULT_ALLOW_WILDCARD_CERT;
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;
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);
return c;
}
static 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->CASVersion = (add->CASVersion != CAS_DEFAULT_VERSION ? add->CASVersion : base->CASVersion);
c->CASDebug = (add->CASDebug != CAS_DEFAULT_DEBUG ? add->CASDebug : base->CASDebug);
c->CASValidateServer = (add->CASValidateServer != CAS_DEFAULT_VALIDATE_SERVER ? add->CASValidateServer : base->CASValidateServer);
c->CASValidateDepth = (add->CASValidateDepth != CAS_DEFAULT_VALIDATE_DEPTH ? add->CASValidateDepth : base->CASValidateDepth);
c->CASAllowWildcardCert = (add->CASAllowWildcardCert != CAS_DEFAULT_ALLOW_WILDCARD_CERT ? add->CASAllowWildcardCert : base->CASAllowWildcardCert);
c->CASCertificatePath = (add->CASCertificatePath != CAS_DEFAULT_CA_PATH ? add->CASCertificatePath : base->CASCertificatePath);
c->CASCookiePath = (add->CASCookiePath != CAS_DEFAULT_COOKIE_PATH ? 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->CASCookieHttpOnly = (add->CASSSOEnabled != CAS_DEFAULT_SSO_ENABLED ? add->CASSSOEnabled : base->CASSSOEnabled);
/* 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));
return c;
}
static 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;
return(c);
}
static void *cas_merge_dir_config(apr_pool_t *pool, void *BASE, void *ADD)
{
cas_dir_cfg *c = apr_pcalloc(pool, sizeof(cas_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 && strcasecmp(add->CASScope, "Off") == 0)
c->CASScope = NULL;
c->CASRenew = (add->CASRenew != CAS_DEFAULT_RENEW ? add->CASRenew : base->CASRenew);
if(add->CASRenew != NULL && strcasecmp(add->CASRenew, "Off") == 0)
c->CASRenew = NULL;
c->CASGateway = (add->CASGateway != CAS_DEFAULT_GATEWAY ? add->CASGateway : base->CASGateway);
if(add->CASGateway != NULL && strcasecmp(add->CASGateway, "Off") == 0)
c->CASGateway = NULL;
c->CASCookie = (add->CASCookie != CAS_DEFAULT_COOKIE ? add->CASCookie : base->CASCookie);
c->CASSecureCookie = (add->CASSecureCookie != CAS_DEFAULT_SCOOKIE ? add->CASSecureCookie : base->CASSecureCookie);
c->CASGatewayCookie = (add->CASGatewayCookie != CAS_DEFAULT_GATEWAY_COOKIE ? add->CASGatewayCookie : base->CASGatewayCookie);
c->CASAuthNHeader = (add->CASAuthNHeader != CAS_DEFAULT_AUTHN_HEADER ? add->CASAuthNHeader : base->CASAuthNHeader);
return(c);
}
static 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;
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_server:
/* 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->CASValidateServer = TRUE;
else if(apr_strnatcasecmp(value, "Off") == 0)
c->CASValidateServer = FALSE;
else
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Invalid argument to CASValidateServer - must be 'On' or 'Off'"));
break;
case cmd_wildcard_cert:
/* 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->CASAllowWildcardCert = TRUE;
else if(apr_strnatcasecmp(value, "Off") == 0)
c->CASAllowWildcardCert = FALSE;
else
return(apr_psprintf(cmd->pool, "MOD_AUTH_CAS: Invalid argument to CASAllowWildcardCert - must be 'On' or 'Off'"));
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_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:
for(i = 0; i < strlen(value); i++) {
d = value[i];
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;
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 */
static 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;
}
static apr_byte_t isSSL(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 */
static char *getCASPath(request_rec *r)
{
char *p = r->parsed_uri.path, *rv;
size_t i, l = 0;
for(i = 0; i < strlen(p); i++) {
if(p[i] == '/')
l = i;
}
rv = apr_pstrndup(r->pool, p, (l+1));
return(rv);
}
static 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, using request path (%s) for cookie", d->CASGateway, requestPath);
rv = requestPath;
}
}
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 superceding.", 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, using request path (%s) for cookie", d->CASRenew, requestPath);
rv = requestPath;
}
}
/* neither gateway nor renew was set */
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);
}
static char *getCASGateway(request_rec *r)
{
cas_dir_cfg *d;
char *rv = "";
cas_cfg *c = ap_get_module_config(r->server->module_config, &auth_cas_module);
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "entering getCASGateway()");
d = ap_get_module_config(r->per_dir_config, &auth_cas_module);
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;
}
static 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;
}
static char *getCASValidateURL(request_rec *r, cas_cfg *c)
{
apr_uri_t test;
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "entering getCASValidateURL()");
memset(&test, '\0', sizeof(apr_uri_t));
if(memcmp(&c->CASValidateURL, &test, sizeof(apr_uri_t)) == 0) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: CASValidateURL null (not set?)");
return NULL;
}
/* this is used in the 'GET /[validateURL]...' context */
return(apr_uri_unparse(r->pool, &(c->CASValidateURL), APR_URI_UNP_OMITSITEPART|APR_URI_UNP_OMITUSERINFO|APR_URI_UNP_OMITQUERY));
}
static 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));
}
/*
* Create the 'service=...' parameter
* The reason this is not an apr_uri_t based on r->parsed_uri is that Apache does not fill out several things
* in the apr_uri_t structure... unimportant things, like 'hostname', and 'scheme', and 'port'... so we must
* implement a trimmed down version of apr_uri_unparse
*/
static char *getCASService(request_rec *r, cas_cfg *c)
{
char *scheme, *service;
apr_port_t port = r->connection->local_addr->port;
apr_byte_t printPort = FALSE;
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "entering getCASService()");
if(isSSL(r)) {
if(port != 443)
printPort = TRUE;
} else if(port != 80) {
printPort = TRUE;
}
#ifdef APACHE2_0
scheme = (char *) ap_http_method(r);
#else
scheme = (char *) ap_http_scheme(r);
#endif
if(printPort == TRUE)
service = apr_psprintf(r->pool, "%s%%3a%%2f%%2f%s%%3a%u%s%s%s", scheme, r->server->server_hostname, port, escapeString(r, r->uri), (r->args != NULL ? "%3f" : ""), escapeString(r, r->args));
else
service = apr_psprintf(r->pool, "%s%%3a%%2f%%2f%s%s%s%s", scheme, r->server->server_hostname, escapeString(r, r->uri), (r->args != NULL ? "%3f" : ""), escapeString(r, r->args));
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 */
static 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);
}
static apr_byte_t removeCASParams(request_rec *r)
{
char *newArgs, *oldArgs, *p;
apr_byte_t copy = TRUE;
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;
oldArgs = r->args;
p = newArgs = apr_pcalloc(r->pool, strlen(oldArgs) + 1); /* add 1 for terminating NULL */
while(*oldArgs != '\0') {
/* stop copying when a CAS parameter is encountered */
if(strncmp(oldArgs, "ticket=", 7) == 0) {
copy = FALSE;
changed = TRUE;
}
if(strncmp(oldArgs, "renew=", 6) == 0) {
copy = FALSE;
changed = TRUE;
}
if(strncmp(oldArgs, "gateway=", 8) == 0) {
copy = FALSE;
changed = TRUE;
}
if(copy)
*p++ = *oldArgs++;
/* restart copying on a new parameter */
else if(*oldArgs++ == '&')
copy = TRUE;
}
/* if the last character is a ? or &, strip it */
if(strlen(newArgs) >= 1 && (*(p-1) == '&' || *(p-1) == '?'))
p--;
/* null terminate the string */
*p = '\0';
if(c->CASDebug && changed == TRUE)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Modified r->args (old '%s', new '%s')", r->args, newArgs);
if(strlen(newArgs) != 0 && changed == TRUE)
/* r->args is by definition larger or the same size than newArgs, so strcpy() is safe */
strcpy(r->args, newArgs);
else if(strlen(newArgs) == 0)
r->args = NULL;
return changed;
}
static char *getCASTicket(request_rec *r)
{
char *tokenizerCtx, *ticket, *args, *rv = NULL;
apr_byte_t ticketFound = FALSE;
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, "&", &tokenizerCtx);
do {
if(strncmp(ticket, "ticket=", 7) == 0) {
ticketFound = TRUE;
/* skip to the meat of the parameter (the value after the '=') */
ticket += 7;
rv = apr_pstrdup(r->pool, ticket);
break;
}
ticket = apr_strtok(NULL, "&", &tokenizerCtx);
/* no more parameters */
if(ticket == NULL)
break;
} while (ticketFound == FALSE);
return rv;
}
static char *getCASCookie(request_rec *r, char *cookieName)
{
char *cookie, *tokenizerCtx, *rv = NULL;
apr_byte_t cookieFound = FALSE;
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);
do {
while (cookie != NULL && *cookie == ' ')
cookie++;
if(strncmp(cookie, cookieName, strlen(cookieName)) == 0) {
cookieFound = TRUE;
/* skip to the meat of the parameter (the value after the '=') */
cookie += (strlen(cookieName)+1);
rv = apr_pstrdup(r->pool, cookie);
}
cookie = apr_strtok(NULL, ";", &tokenizerCtx);
/* no more parameters */
if(cookie == NULL)
break;
} while (cookieFound == FALSE);
}
return rv;
}
static void setCASCookie(request_rec *r, char *cookieName, char *cookieValue, apr_byte_t secure)
{
char *headerString, *currentCookies;
cas_cfg *c = ap_get_module_config(r->server->module_config, &auth_cas_module);
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "entering setCASCookie()");
headerString = apr_psprintf(r->pool, "%s=%s%s;Path=%s%s%s%s", cookieName, cookieValue, (secure ? ";Secure" : ""), getCASScope(r), (c->CASCookieDomain != NULL ? ";Domain=" : ""), (c->CASCookieDomain != NULL ? c->CASCookieDomain : ""), (c->CASCookieHttpOnly != FALSE ? "; HttpOnly" : ""));
/* 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?
*/
static char *escapeString(request_rec *r, char *str)
{
char *rfc1738 = " <>\"%{}|\\^~[]`;/?:@=&#", *rv, *p, *q;
size_t i, j, size;
char escaped = FALSE;
if(str == NULL)
return "";
size = strlen(str) + 1; /* add 1 for terminating NULL */
for(i = 0; i < size; i++) {
for(j = 0; j < strlen(rfc1738); j++) {
if(str[i] == rfc1738[j]) {
/* allocate 2 extra bytes for the escape sequence (' ' -> '%20') */
size += 2;
break;
}
}
}
/* allocate new memory to return the encoded URL */
p = rv = apr_pcalloc(r->pool, size);
q = str;
do {
escaped = FALSE;
for(i = 0; i < strlen(rfc1738); i++) {
if(*q == rfc1738[i]) {
sprintf(p, "%%%x", rfc1738[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 */
static 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, *val;
int i;
int rc;
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;
}
apr_file_lock(f, APR_FLOCK_SHARED);
/* 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 for '%s' (%s)", name, errbuf);
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;
do {
if(e == NULL)
continue;
/* first_cdata.first is NULL on empty attributes (<attr />) */
if(e->first_cdata.first != NULL)
val = (char *) e->first_cdata.first->text;
else
val = NULL;
if (apr_strnatcasecmp(e->name, "user") == 0)
cache->user = apr_pstrndup(r->pool, val, strlen(val));
else if (apr_strnatcasecmp(e->name, "issued") == 0) {
if(sscanf(val, "%" APR_TIME_T_FMT, &(cache->issued)) != 1)
return FALSE;
} else if (apr_strnatcasecmp(e->name, "lastactive") == 0) {
if(sscanf(val, "%" APR_TIME_T_FMT, &(cache->lastactive)) != 1)
return FALSE;
} else if (apr_strnatcasecmp(e->name, "path") == 0)
cache->path = apr_pstrndup(r->pool, val, strlen(val));
else if (apr_strnatcasecmp(e->name, "renewed") == 0)
cache->renewed = TRUE;
else if (apr_strnatcasecmp(e->name, "secure") == 0)
cache->secure = TRUE;
else if (apr_strnatcasecmp(e->name, "ticket") == 0)
cache->ticket = apr_pstrndup(r->pool, val, strlen(val));
else
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: Unknown cookie attribute '%s'", e->name);
e = e->next;
} while (e != NULL);
apr_file_unlock(f);
apr_file_close(f);
return TRUE;
}
static void CASCleanCache(request_rec *r, cas_cfg *c)
{
apr_time_t lastClean;
apr_off_t begin = 0;
char *path;
apr_file_t *metaFile, *cacheFile;
char line[64];
apr_status_t i;
cas_cache_entry cache;
apr_dir_t *cacheDir;
apr_finfo_t fi;
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "entering CASCleanCache()");
path = apr_psprintf(r->pool, "%s.metadata", c->CASCookiePath);
if(apr_file_open(&metaFile, path, APR_FOPEN_READ|APR_FOPEN_WRITE, APR_FPROT_UREAD|APR_FPROT_UWRITE, r->pool) != APR_SUCCESS) {
/* file does not exist or cannot be opened - try and create it */
if((i = apr_file_open(&metaFile, path, (APR_FOPEN_WRITE|APR_FOPEN_CREATE), (APR_FPROT_UREAD|APR_FPROT_UWRITE), r->pool)) != APR_SUCCESS) {
apr_strerror(i, line, sizeof(line));
ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server, "MOD_AUTH_CAS: Could not create cache metadata file '%s': %s", path, line);
return;
}
}
apr_file_lock(metaFile, APR_FLOCK_EXCLUSIVE);
apr_file_seek(metaFile, APR_SET, &begin);
/* if the file was not created on this method invocation (APR_FOPEN_READ is not used above during creation) see if it is time to clean the cache */
if((apr_file_flags_get(metaFile) & APR_FOPEN_READ) != 0) {
apr_file_gets(line, sizeof(line), metaFile);
if(sscanf(line, "%" APR_TIME_T_FMT, &lastClean) != 1) { /* corrupt file */
apr_file_close(metaFile);
apr_file_remove(path, r->pool);
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Cache metadata file is corrupt");
return;
}
if(lastClean > (apr_time_now()-(c->CASCacheCleanInterval*((apr_time_t) APR_USEC_PER_SEC)))) { /* not enough time has elapsed */
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Insufficient time elapsed since last cache clean");
return;
}
apr_file_seek(metaFile, APR_SET, &begin);
apr_file_trunc(metaFile, begin);
}
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Beginning cache clean");
apr_file_printf(metaFile, "%" APR_TIME_T_FMT "\n", apr_time_now());
apr_file_unlock(metaFile);
apr_file_close(metaFile);
/* read all the files in the directory */
if(apr_dir_open(&cacheDir, c->CASCookiePath, r->pool) != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server, "MOD_AUTH_CAS: Error opening cache directory '%s' for cleaning", c->CASCookiePath);
}
do {
i = apr_dir_read(&fi, APR_FINFO_NAME, cacheDir);
if(i == APR_SUCCESS) {
if(fi.name[0] == '.') /* skip hidden files and parent directories */
continue;
path = apr_psprintf(r->pool, "%s%s", c->CASCookiePath, fi.name);
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Processing cache file '%s'", fi.name);
if(apr_file_open(&cacheFile, path, APR_FOPEN_READ, APR_OS_DEFAULT, r->pool) != APR_SUCCESS) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: Unable to clean cache entry '%s'", path);
continue;
}
if(readCASCacheFile(r, c, (char *) fi.name, &cache) == TRUE) {
if(cache.issued < (apr_time_now()-(c->CASTimeout*((apr_time_t) APR_USEC_PER_SEC))) || cache.lastactive < (apr_time_now()-(c->CASIdleTimeout*((apr_time_t) APR_USEC_PER_SEC)))) {
/* delete this file since it is no longer valid */
apr_file_close(cacheFile);
deleteCASCacheFile(r, (char *) fi.name);
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Removing expired cache entry '%s'", fi.name);
}
} else {
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Removing corrupt cache entry '%s'", fi.name);
/* corrupt file */
apr_file_close(cacheFile);
deleteCASCacheFile(r, (char *) fi.name);
}
}
} while (i == APR_SUCCESS);
apr_dir_close(cacheDir);
}
static apr_byte_t writeCASCacheEntry(request_rec *r, char *name, cas_cache_entry *cache, apr_byte_t exists)
{
char *path;
apr_file_t *f;
apr_off_t begin = 0;
int i;
apr_byte_t lock = FALSE;
cas_cfg *c = ap_get_module_config(r->server->module_config, &auth_cas_module);
if(c->CASDebug)
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "entering writeCASCacheEntry()");
path = apr_psprintf(r->pool, "%s%s", c->CASCookiePath, name);
if(exists == FALSE) {
if((i = apr_file_open(&f, path, APR_FOPEN_CREATE|APR_FOPEN_WRITE|APR_EXCL, APR_FPROT_UREAD|APR_FPROT_UWRITE, r->pool)) != APR_SUCCESS) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: Cookie file '%s' could not be created: %s", path, apr_strerror(i, name, strlen(name)));
return FALSE;
}
} else {
if((i = apr_file_open(&f, path, APR_FOPEN_READ|APR_FOPEN_WRITE, APR_FPROT_UREAD|APR_FPROT_UWRITE, r->pool)) != APR_SUCCESS) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: Cookie file '%s' could not be opened: %s", path, apr_strerror(i, name, strlen(name)));
return FALSE;
}
/* update the file with a new idle time if a write lock can be obtained */
if(apr_file_lock(f, APR_FLOCK_EXCLUSIVE) != APR_SUCCESS) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MOD_AUTH_CAS: could not obtain an exclusive lock on %s", path);
apr_file_close(f);
return FALSE;
} else {
lock = TRUE;
}
apr_file_seek(f, APR_SET, &begin);
apr_file_trunc(f, begin);
}
apr_file_flush(f);
/* this is ultra-ghetto, but the APR really doesn't provide any facilities for easy DOM-style XML creation. */
if (c->CASDebug) {