forked from OpenRock/OpenAM
/
SAMLUtils.java
1842 lines (1708 loc) · 70 KB
/
SAMLUtils.java
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
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2006 Sun Microsystems Inc. All Rights Reserved
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the License at
* https://opensso.dev.java.net/public/CDDLv1.0.html or
* opensso/legal/CDDLv1.0.txt
* See the License for the specific language governing
* permission and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* Header Notice in each file and include the License file
* at opensso/legal/CDDLv1.0.txt.
* If applicable, add the following below the CDDL Header,
* with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* $Id: SAMLUtils.java,v 1.16 2010/01/09 19:41:06 qcheng Exp $
*
* Portions Copyrighted 2012-2016 ForgeRock AS.
*/
package com.sun.identity.saml.common;
import static org.forgerock.openam.utils.Time.*;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.Enumeration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.text.StringCharacterIterator;
import java.text.CharacterIterator;
import java.io.UnsupportedEncodingException;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.security.MessageDigest;
import java.net.URL;
import java.net.MalformedURLException;
import org.w3c.dom.*;
import com.sun.identity.common.PeriodicGroupRunnable;
import com.sun.identity.common.ScheduleableGroupAction;
import com.sun.identity.common.SystemConfigurationUtil;
import com.sun.identity.common.SystemConfigurationException;
import com.sun.identity.common.SystemTimerPool;
import com.sun.identity.common.TaskRunnable;
import com.sun.identity.common.TimerPool;
import com.sun.identity.shared.xml.XMLUtils;
import com.sun.identity.shared.encode.URLEncDec;
import com.sun.identity.shared.encode.Base64;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.MimeHeader;
import com.sun.identity.saml.assertion.SubjectConfirmation;
import com.sun.identity.saml.assertion.Assertion;
import com.sun.identity.saml.assertion.Attribute;
import com.sun.identity.saml.assertion.AttributeStatement;
import com.sun.identity.saml.assertion.AuthenticationStatement;
import com.sun.identity.saml.assertion.AudienceRestrictionCondition;
import com.sun.identity.saml.assertion.Condition;
import com.sun.identity.saml.assertion.Conditions;
import com.sun.identity.saml.assertion.Statement;
import com.sun.identity.saml.assertion.SubjectStatement;
import com.sun.identity.saml.xmlsig.XMLSignatureManager;
import com.sun.identity.saml.plugins.PartnerAccountMapper;
import com.sun.identity.saml.protocol.*;
import com.sun.identity.saml.servlet.POSTCleanUpRunnable;
import com.sun.identity.plugin.session.SessionException;
import com.sun.identity.plugin.session.SessionManager;
import com.sun.identity.plugin.session.SessionProvider;
import com.sun.identity.saml.assertion.Subject;
import com.sun.identity.saml.SAMLClient;
import com.sun.identity.federation.common.FSUtils;
import javax.xml.parsers.DocumentBuilder;
import org.apache.xml.security.c14n.Canonicalizer;
/**
* This class contains some utility methods for processing SAML protocols.
*
*
*/
public class SAMLUtils extends SAMLUtilsCommon {
/**
* Attribute that specifies maximum content length for SAML request in
* <code>AMConfig.properties</code> file.
*/
public static final String HTTP_MAX_CONTENT_LENGTH =
"com.sun.identity.saml.request.maxContentLength";
/**
* Default maximum content length is set to 16k.
*/
public static final int defaultMaxLength = 16384;
/**
* Default maximum content length in string format.
*/
public static final String DEFAULT_CONTENT_LENGTH =
String.valueOf(defaultMaxLength);
private static final String ERROR_JSP = "/saml2/jsp/autosubmittingerror.jsp";
private static int maxContentLength = 0;
private static Map idTimeMap = Collections.synchronizedMap(new HashMap());
private static TaskRunnable cGoThrough = null;
private static TaskRunnable cPeriodic = null;
private static Object ssoToken;
static {
org.apache.xml.security.Init.init();
if (SystemConfigurationUtil.isServerMode()) {
long period = ((Integer) SAMLServiceManager.getAttribute(
SAMLConstants.CLEANUP_INTERVAL_NAME)).intValue() * 1000;
cGoThrough = new POSTCleanUpRunnable(period, idTimeMap);
TimerPool timerPool = SystemTimerPool.getTimerPool();
timerPool.schedule(cGoThrough, new Date(((currentTimeMillis()
+ period) / 1000) * 1000));
ScheduleableGroupAction periodicAction = new
ScheduleableGroupAction() {
public void doGroupAction(Object obj) {
idTimeMap.remove(obj);
}
};
cPeriodic = new PeriodicGroupRunnable(periodicAction, period,
180000, true);
timerPool.schedule(cPeriodic, new Date(((currentTimeMillis() +
period) / 1000) * 1000));
}
try {
maxContentLength = Integer.parseInt(SystemConfigurationUtil.
getProperty(SAMLUtils.HTTP_MAX_CONTENT_LENGTH,
SAMLUtils.DEFAULT_CONTENT_LENGTH));
} catch (NumberFormatException ne) {
SAMLUtils.debug.error("Wrong format of SAML request max content "
+ "length. Take default value.");
maxContentLength= SAMLUtils.defaultMaxLength;
}
}
/**
* Constructor
* iPlanet-PRIVATE-DEFAULT-CONSTRUCTOR
*/
private SAMLUtils() {
}
/**
* Generates an ID String with length of SAMLConstants.ID_LENGTH.
* @return string the ID String; or null if it fails.
*/
public static String generateAssertionID() {
String encodedID = generateID();
if (encodedID == null) {
return null;
}
String id = null;
try {
id = SystemConfigurationUtil.getServerID(
SAMLServiceManager.getServerProtocol(),
SAMLServiceManager.getServerHost(),
Integer.parseInt(SAMLServiceManager.getServerPort()),
SAMLServiceManager.getServerURI());
} catch (Exception ex) {
if (SAMLUtils.debug.messageEnabled()) {
SAMLUtils.debug.message("SAMLUtil:generateAssertionID: "
+ "exception obtain serverID:", ex);
}
}
if (id == null) {
return encodedID;
} else {
return (encodedID + id);
}
}
/**
* Verifies if an element is a type of a specific query.
* Currently, this method is used by class AuthenticationQuery,
* AuthorizationDecisionQuery, and AttributeQuery.
* @param element a DOM Element which needs to be verified.
* @param queryname A specific name of a query, for example,
* AuthenticationQuery, AuthorizationDecisionQuery, or
* AttributeQuery.
* @return true if the element is a type of the specified query; false
* otherwise.
*/
public static boolean checkQuery(Element element, String queryname) {
String tag = element.getLocalName();
if (tag == null) {
return false;
} else if (tag.equals("Query") || tag.equals("SubjectQuery")) {
NamedNodeMap nm = element.getAttributes();
int len = nm.getLength();
String attrName;
Attr attr;
boolean found = false;
for (int j = 0; j < len; j++) {
attr = (Attr) nm.item(j);
attrName = attr.getLocalName();
if ((attrName != null) && (attrName.equals("type")) &&
(attr.getNodeValue().equals(queryname + "Type"))) {
found = true;
break;
}
}
if (!found) {
return false;
}
} else if (!tag.equals(queryname)) {
return false;
}
return true;
}
/**
* Generates sourceID of a site.
* @param siteURL a String that uniquely identifies a site.
* @return <code>Base64</code> encoded SHA digest of siteURL.
*/
public static String generateSourceID(String siteURL) {
if ((siteURL == null) || (siteURL.length() == 0)) {
SAMLUtils.debug.error("SAMLUtils.genrateSourceID: empty siteURL.");
return null;
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA");
} catch (Exception e) {
SAMLUtils.debug.error("SAMLUtils.generateSourceID: Exception when"
+ " generating digest:",e);
return null;
}
md.update(SAMLUtils.stringToByteArray(siteURL));
byte byteResult[] = md.digest();
String result = null;
try {
result = Base64.encode(byteResult).trim();
} catch (Exception e) {
SAMLUtils.debug.error("SAMLUtils.generateSourceID: Exception:",e);
}
return result;
}
/**
* Generates assertion handle.
* @return 20-byte random string to be used to form an artifact.
*/
public static String generateAssertionHandle() {
if (random == null) {
return null;
}
byte bytes[] = new byte[SAMLConstants.ID_LENGTH];
random.nextBytes(bytes);
String id = null;
try {
id = SystemConfigurationUtil.getServerID(
SAMLServiceManager.getServerProtocol(),
SAMLServiceManager.getServerHost(),
Integer.parseInt(SAMLServiceManager.getServerPort()),
SAMLServiceManager.getServerURI());
} catch (Exception ex) {
if (SAMLUtils.debug.messageEnabled()) {
SAMLUtils.debug.message("SAMLUtil:generateAssertionHandle: "
+ "exception obtain serverID:", ex);
}
}
if (id != null) {
byte idBytes[] = stringToByteArray(id);
// TODO: should we check if idBytes.length == 2 ?
if (idBytes.length < bytes.length) {
for (int i = 1; i <= idBytes.length; i++) {
bytes[bytes.length - i] = idBytes[idBytes.length - i];
}
}
}
return byteArrayToString(bytes);
}
/**
* Converts a HEX encoded string to a byte array.
* @param hexString HEX encoded string
* @return byte array.
*/
public static byte[] hexStringToByteArray(String hexString) {
int read = hexString.length();
byte[] byteArray = new byte[read/2];
for (int i=0, j=0; i < read; i++, j++) {
String part = hexString.substring(i,i+2);
byteArray[j] =
new Short(Integer.toString(Integer.parseInt(part,16))).
byteValue();
i++;
}
return byteArray;
}
/**
* Converts HEX encoded string to Base64 encoded string.
* @param hexString HEX encoded string.
* @return Base64 encoded string.
*/
public static String hexStringToBase64(String hexString) {
int read = hexString.length();
byte[] byteArray = new byte[read/2];
for (int i=0, j=0; i < read; i++, j++) {
String part = hexString.substring(i,i+2);
byteArray[j] =
new Short(Integer.toString(Integer.parseInt(part,16))).
byteValue();
i++;
}
String encodedID = null;
try {
encodedID = Base64.encode(byteArray).trim();
} catch (Exception e) {
if (SAMLUtils.debug.messageEnabled()) {
SAMLUtils.debug.message("SAMLUtil:hexStringToBase64: "
+ "exception encode input:", e);
}
}
if (SAMLUtils.debug.messageEnabled()) {
SAMLUtils.debug.message("base 64 source id is :"+encodedID);
}
return encodedID;
}
/**
* Gets sourceSite corresponding to an issuer from the partner URL list.
* @param issuer The issuer string.
* @return SAMLServiceManager.SOAPEntry of the issuer if it's on the list;
* null otherwise.
*/
public static SAMLServiceManager.SOAPEntry getSourceSite(String issuer) {
if (issuer == null) {
return null;
}
Map entries = (Map) SAMLServiceManager.getAttribute(
SAMLConstants.PARTNER_URLS);
if (entries == null) {
SAMLUtils.debug.error("SAMLUtils.isOnPartnerURLList: PartnerURL "
+ "list is null.");
return null;
}
Iterator entryIter = entries.values().iterator();
boolean found = false;
SAMLServiceManager.SOAPEntry srcSite = null;
String theIssuer = null;
while (entryIter.hasNext()) {
srcSite = (SAMLServiceManager.SOAPEntry) entryIter.next();
if ((srcSite != null) &&
((theIssuer = srcSite.getIssuer()) != null) &&
(theIssuer.equals(issuer))) {
found = true;
break;
}
}
if (found) {
return srcSite;
} else {
return null;
}
}
/**
* Returns site ID based on the host name. The site ID
* will be in Base64 encoded format. This method will print out site ID
* to the standard output
* @param args host name
*/
public static void main(String args[]) {
if (args.length != 1) {
System.out.println("usage : java SAMLUtils <host_name>");
return;
}
System.out.println(generateSourceID(args[0]));
}
/**
* Checks if a <code>SubjectConfirmation</code> is correct.
* @param sc <code>SubjectConfirmation</code> instance to be checked.
* @return true if the <code>SubjectConfirmation</code> instance passed in
* has only one <code>ConfirmationMethod</code>, and this
* <code>ConfirmationMethod</code> is set to
* <code>SAMLConstants.CONFIRMATION_METHOD_IS</code>.
*/
public static boolean isCorrectConfirmationMethod(SubjectConfirmation sc) {
if (sc == null) {
return false;
}
Set cmSet = sc.getConfirmationMethod();
if ((cmSet == null) || (cmSet.size() != 1)) {
if (SAMLUtils.debug.messageEnabled()) {
SAMLUtils.debug.message("SAMLUtils.isCorrectConfirmationMethod:"
+ " missing ConfirmationMethod in the Subject.");
}
return false;
}
String conMethod = (String) cmSet.iterator().next();
if ((conMethod == null) ||
(!conMethod.equals(SAMLConstants.CONFIRMATION_METHOD_IS))) {
if (SAMLUtils.debug.messageEnabled()) {
SAMLUtils.debug.message("SAMLUtils.isCorrectConfirmationMethod:"
+ " wrong ConfirmationMethod value.");
}
return false;
}
return true;
}
/**
* Returns true if the assertion is valid both time wise and
* signature wise, and contains at least one AuthenticationStatement.
* @param assertion <code>Assertion</code> instance to be checked.
* @return <code>true</code> if the assertion is valid both time wise and
* signature wise, and contains at least one AuthenticationStatement.
*/
public static boolean isAuthNAssertion(Assertion assertion) {
if (assertion == null) {
return false;
}
if ((!assertion.isTimeValid()) || (!assertion.isSignatureValid())) {
return false;
}
Set statements = assertion.getStatement();
Statement statement = null;
Iterator iterator = statements.iterator();
while (iterator.hasNext()) {
statement = (Statement) iterator.next();
if (statement.getStatementType() ==
Statement.AUTHENTICATION_STATEMENT) {
return true;
}
} // loop through statements
return false;
}
/**
* Converts a string to a byte array.
* @param input a String to be converted.
* @return result byte array.
*/
public static byte[] stringToByteArray(String input) {
char chars[] = input.toCharArray();
byte bytes[] = new byte[chars.length];
for (int i = 0; i < chars.length; i++) {
bytes[i] = (byte) chars[i];
}
return bytes;
}
/**
* Returns server ID.
* @param idTypeString An ID string
* @return server ID part of the id.
*/
public static String getServerID(String idTypeString) {
if (idTypeString == null) {
return null;
}
int len = idTypeString.length();
String id = null;
if (len >= SAMLConstants.SERVER_ID_LENGTH) {
id = idTypeString.substring((len - SAMLConstants.SERVER_ID_LENGTH),
len);
return id;
} else {
return null;
}
}
/**
* Returns server url of a site.
* @param str Server ID.
* @return Server url corresponding to the server id.
*/
public static String getServerURL(String str) {
String id = SAMLUtils.getServerID(str);
if (id == null) {
return null;
}
if (SAMLUtils.debug.messageEnabled()) {
SAMLUtils.debug.message("SAMLUtils.getServerURL: id=" + id);
}
String remoteUrl = null;
try {
remoteUrl = SystemConfigurationUtil.getServerFromID(id);
} catch (SystemConfigurationException se) {
if (SAMLUtils.debug.messageEnabled()) {
SAMLUtils.debug.message("SAMLUtils.getServerURL: ServerEntry" +
"NotFoundException for " + id);
}
return null;
}
String thisUrl = SAMLServiceManager.getServerURL();
if (SAMLUtils.debug.messageEnabled()) {
SAMLUtils.debug.message("SAMLUtils.getServerURL: remoteUrl=" +
remoteUrl + ", thisUrl=" + thisUrl);
}
if ((remoteUrl == null) || (thisUrl == null) ||
(remoteUrl.equalsIgnoreCase(thisUrl))) {
return null;
} else {
return remoteUrl;
}
}
/**
* Returns full service url.
* @param shortUrl short URL of the service.
* @return full service url.
*/
public static String getFullServiceURL(String shortUrl) {
String result = null;
try {
URL u = new URL(shortUrl);
URL weburl = SystemConfigurationUtil.getServiceURL(
SAMLConstants.SAML_AM_NAMING, u.getProtocol(), u.getHost(),
u.getPort(), u.getPath());
result = weburl.toString();
if (SAMLUtils.debug.messageEnabled()) {
SAMLUtils.debug.message("SAMLUtils.getFullServiceURL:" +
"full remote URL is: " + result);
}
} catch (Exception e) {
if (SAMLUtils.debug.warningEnabled()) {
SAMLUtils.debug.warning("SAMLUtils.getFullServiceURL:" +
"Exception:", e);
}
}
return result;
}
/**
* Returns attributes included in <code>AttributeStatement</code> of the
* assertion.
* @param envParameters return map which includes name value pairs of
* attributes included in <code>AttributeStatement</code> of the assertion
* @param assertion an <code>Assertion</code> object which contains
* <code>AttributeStatement</code>
* @param subject the <code>Subject</code> instance from
* <code>AuthenticationStatement</code>. The <code>Subject</code>
* included in <code>AttributeStatement</code> must match this
* <code>Subject</code> instance.
*/
public static void addEnvParamsFromAssertion(Map envParameters,
Assertion assertion,
com.sun.identity.saml.assertion.Subject subject) {
Set statements = assertion.getStatement();
Statement statement = null;
Iterator stmtIter = null;
List attrs = null;
Iterator attrIter = null;
Attribute attribute = null;
Element attrValue = null;
List attrValues = null;
String attrName = null;
String attrValueString = null;
if ((statements != null) && (!statements.isEmpty())) {
stmtIter = statements.iterator();
while (stmtIter.hasNext()) {
statement = (Statement) stmtIter.next();
if (statement.getStatementType() ==
Statement.ATTRIBUTE_STATEMENT) {
// check for subject
if (!subject.equals(
((AttributeStatement)statement).getSubject())) {
continue;
}
attrs = ((AttributeStatement) statement).getAttribute();
attrIter = attrs.iterator();
while (attrIter.hasNext()) {
attribute = (Attribute) attrIter.next();
try {
attrValues = attribute.getAttributeValue();
} catch (Exception e) {
debug.error("SAMLUtils.addEnvParamsFromAssertion:"+
" cannot obtain attribute value:", e);
continue;
}
attrName = attribute.getAttributeName();
List attrValueList = null;
for(Iterator avIter = attrValues.iterator();
avIter.hasNext(); ) {
attrValue = (Element) avIter.next();
if (!XMLUtils.hasElementChild(attrValue)) {
attrValueString =
XMLUtils.getElementValue(attrValue);
if (attrValueList == null) {
attrValueList = new ArrayList();
}
attrValueList.add(attrValueString);
}
}
if (attrValueList != null) {
if (debug.messageEnabled()) {
debug.message(
"SAMLUtils.addEnvParamsFromAssertion:" +
" attrName = " + attrName +
" attrValue = " + attrValueList);
}
String[] attrValueStrs = (String[])attrValueList.
toArray(new String[attrValueList.size()]);
try {
envParameters.put(attrName, attrValueStrs);
} catch (Exception ex) {
if (debug.messageEnabled()) {
debug.message(
"SAMLUtils.addEnvParamsFromAssertion:",
ex);
}
}
} else if (debug.messageEnabled()) {
if (debug.messageEnabled()) {
debug.message(
"SAMLUtils.addEnvParamsFromAssertion:" +
" attrName = " + attrName +
" has no value");
}
}
}
} // if it's an attribute statement
}
}
}
/**
* Returns maximum content length of a SAML request.
* @return maximum content length of a SAML request.
*/
public static int getMaxContentLength() {
return maxContentLength;
}
// ************************************************************************
// Methods used by SAML Servlets
// ************************************************************************
/**
* Checks content length of a http request to avoid dos attack.
* In case SAML inter-op with other SAML vendor who may not provide content
* length in HttpServletRequest. We decide to support no length restriction
* for Http communication. Here, we use a special value (e.g. 0) to
* indicate that no enforcement is required.
* @param request <code>HttpServletRequest</code> instance to be checked.
* @exception ServletException if context length of the request exceeds
* maximum content length allowed.
*/
public static void checkHTTPContentLength(HttpServletRequest request)
throws ServletException {
if (maxContentLength != 0) {
int length = request.getContentLength();
if (SAMLUtils.debug.messageEnabled()) {
SAMLUtils.debug.message("HttpRequest content length= " +length);
}
if (length > maxContentLength) {
if (SAMLUtils.debug.messageEnabled()) {
SAMLUtils.debug.message(
"content length too large" + length);
}
throw new ServletException(
SAMLUtils.bundle.getString("largeContentLength"));
}
}
}
/**
* Post assertions and attributes to the target url.
* This method opens a URL connection to the target specified and POSTs
* assertions to it using the passed HttpServletResponse object. It POSTs
* multiple parameter names "assertion" with value being each of the
* <code>Assertion</code> in the passed Set.
* @param response <code>HttpServletResponse</code> object
* @param out The print writer which for content is to be written too.
* @param assertion List of <code>Assertion</code>s to be posted.
* @param targeturl target url
* @param attrMap Map of attributes to be posted to the target
*/
public static void postToTarget(HttpServletResponse response, PrintWriter out,
List assertion, String targeturl, Map attrMap) throws IOException {
out.println("<HTML>");
out.println("<HEAD>\n");
out.println("<TITLE>Access rights validated</TITLE>\n");
out.println("</HEAD>\n");
out.println("<BODY Onload=\"document.forms[0].submit()\">");
Iterator it = null;
if (SAMLUtils.debug.messageEnabled()) {
out.println("<H1>Access rights validated</H1>\n");
out.println("<meta http-equiv=\"refresh\" content=\"20\">\n");
out.println("<P>We have verified your access rights <STRONG>" +
"</STRONG> according to the assertion shown "
+"below. \n");
out.println("You are being redirected to the resource.\n");
out.println("Please wait ......\n");
out.println("</P>\n");
out.println("<HR><P>\n");
if (assertion != null) {
it = assertion.iterator();
while (it.hasNext()) {
out.println(SAMLUtils.displayXML((String)it.next()));
}
}
out.println("</P>\n");
}
out.println("<FORM METHOD=\"POST\" ACTION=\"" + targeturl + "\">");
if (assertion != null) {
it = assertion.iterator();
while (it.hasNext()) {
out.println("<INPUT TYPE=\"HIDDEN\" NAME=\""+
SAMLConstants.POST_ASSERTION_NAME + "\"");
out.println("VALUE=\"" +
URLEncDec.encode((String)it.next()) + "\">");
}
}
if (attrMap != null && !attrMap.isEmpty()) {
StringBuffer attrNamesSB = new StringBuffer();
Set entrySet = attrMap.entrySet();
for(Iterator iter = entrySet.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next();
String attrName = HTMLEncode((String)entry.getKey(), '\"');
String attrValue = HTMLEncode((String)entry.getValue(), '\"');
out.println("<INPUT TYPE=\"HIDDEN\" NAME=\""+ attrName +
"\" VALUE=\"" + attrValue + "\">");
if (attrNamesSB.length() > 0) {
attrNamesSB.append(":");
}
attrNamesSB.append(attrName);
}
out.println("<INPUT TYPE=\"HIDDEN\" NAME=\""+
SAMLConstants.POST_ATTR_NAMES + "\" VALUE=\"" +
attrNamesSB + "\">");
}
out.println("</FORM>");
out.println("</BODY></HTML>");
out.close();
}
/**
* Returns true of false based on whether the target passed as parameter
* accepts form POST.
* @param targetIn url to be checked
* @return true if it should post assertion to the target passed in; false
* otherwise.
*/
public static boolean postYN(String targetIn) {
SAMLUtils.debug.message("Inside postYN()");
if ((targetIn == null) || (targetIn.length() == 0)) {
return false;
}
Set targets = (Set) SAMLServiceManager.
getAttribute(SAMLConstants.POST_TO_TARGET_URLS);
if ((targets == null) || (targets.size() == 0)) {
return false;
}
URL targetUrl = null;
try {
targetUrl = new URL(targetIn);
} catch (MalformedURLException me ) {
SAMLUtils.debug.error("SAMLUtils:postYN(): Malformed URL passed");
return false;
}
String targetInHost = targetUrl.getHost();
int targetInPort = targetUrl.getPort();
String targetInPath = targetUrl.getPath();
// making target string without protocol
String targetToCompare = new StringBuffer(targetInHost.toLowerCase())
.append(":").append(String.valueOf(targetInPort))
.append("/").append(targetInPath).toString();
if (targets.contains(targetToCompare)) {
return true;
} else {
return false;
}
}
/**
* Replaces every occurence of ch with
* "&#<ascii code of ch>;"
* @param srcStr orginal string to to be encoded.
* @param ch the charactor needs to be encoded.
* @return encoded string
*/
public static String HTMLEncode(String srcStr, char ch) {
if (srcStr == null) {
return null;
}
int fromIndex = 0;
int toIndex;
StringBuffer dstSB = new StringBuffer();
while((toIndex = srcStr.indexOf(ch, fromIndex)) != -1) {
dstSB.append(srcStr.substring(fromIndex, toIndex))
.append("&#" + (int)ch + ";");
fromIndex = toIndex + 1;
}
dstSB.append(srcStr.substring(fromIndex));
return dstSB.toString();
}
/**
* Displays an XML string.
* This is a utility function used to hack up an HTML display of an XML
* string.
* @param input original string
* @return encoded string so it can be displayed properly by html.
*/
public static String displayXML(String input) {
debug.message("In displayXML ");
StringCharacterIterator iter = new StringCharacterIterator(input);
StringBuffer buf = new StringBuffer();
for(char c = iter.first();c != CharacterIterator.DONE;c = iter.next()) {
if (c=='>') {
buf.append(">");
} else if (c=='<') {
buf.append("<");
} else if (c=='\n'){
buf.append("<BR>\n");
} else {
buf.append(c);
}
}
return buf.toString();
}
/**
* Gets the list of <code>Assertion</code> objects from a list of
* 'String' assertions.
* @param assertions List of assertions in string format
* @return List of <code>Assertion</code> objects
*/
public static List getListOfAssertions(List assertions) {
List returnAssertions = new ArrayList();
try {
if (assertions != null) {
Iterator it = assertions.iterator();
while (it.hasNext()) {
Document doc = XMLUtils.toDOMDocument((String)it.next(),
debug);
Element root = doc.getDocumentElement();
if (root != null) {
Assertion assertion = new Assertion(root);
returnAssertions.add(assertion);
}
}
}
} catch (Exception e) {
if (debug.messageEnabled()) {
debug.message("SAMLUtils.getListOfAssertions : " +
"Exception : ", e);
}
}
return returnAssertions;
}
// ************************************************************************
// Methods used / shared by SAML Authentication Module and SAML Servlets
// ************************************************************************
/**
* Returns byte array from a SAML <code>Response</code>.
* @param samlResponse <code>Response</code> object
* @return byte array
* @exception SAMLException if error occurrs during the process.
*/
public static byte[] getResponseBytes(Response samlResponse)
throws SAMLException
{
byte ret[] = null;
try {
ret = samlResponse.toString(true, true, true).
getBytes(SAMLConstants.DEFAULT_ENCODING);
} catch (UnsupportedEncodingException ue) {
if (debug.messageEnabled()) {
debug.message("getResponseBytes : " , ue);
}
throw new SAMLException(ue.getMessage());
}
return ret;
}
/**
* Returns <code>Response</code> object from byte array.
* @param bytes byte array
* @return <code>Response</code> object
*/
public static Response getResponse(byte [] bytes) {
Response temp = null;
if (bytes == null) {
return null;
}
try {
temp = Response.parseXML(new ByteArrayInputStream(bytes));
} catch (SAMLException se) {
debug.error("getResponse : " , se);
}
return temp;
}
/**
* Verifies a <code>Response</code>.
* @param response SAML <code>Response</code> object
* @param requestUrl this server's POST profile URL
* @param request <code>HttpServletRequest</code> object
* @return true if the response is valid; false otherwise.
*/
public static boolean verifyResponse(Response response,
String requestUrl, HttpServletRequest request) {
if (!response.isSignatureValid()) {
debug.message("verifyResponse: Response's signature is invalid.");
return false;
}
// check Recipient == this server's POST profile URL(requestURL)
String recipient = response.getRecipient();
if ((recipient == null) || (recipient.length() == 0) ||
((!equalURL(recipient, requestUrl)) &&
(!equalURL(recipient,getLBURL(requestUrl, request))))) {
debug.error("verifyResponse : Incorrect Recipient.");
return false;
}
// check status of the Response
if (!response.getStatus().getStatusCode().getValue().endsWith(
SAMLConstants.STATUS_CODE_SUCCESS_NO_PREFIX)) {
debug.error("verifyResponse : Incorrect StatusCode value.");
return false;
}
return true;
}
private static String getLBURL(String requestUrl,
HttpServletRequest request)
{
String host = request.getHeader("host");
if (host == null) {
return requestUrl;
}
int index = requestUrl.indexOf("//");
if (index == -1) {
return requestUrl;
}
StringBuffer sb = new StringBuffer(200);
sb.append(requestUrl.substring(0, index + 2)).append(host);
String rest = requestUrl.substring(index +2, requestUrl.length());
if ((index = rest.indexOf("/")) != -1) {
sb.append(rest.substring(index, rest.length()));
}
if (debug.messageEnabled()) {
debug.message("getLBURL: LBURL = " + sb.toString());
}
return sb.toString().trim();
}