Get rid of /hs package
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / common / provider / ShibbolethTrust.java
1 /*
2  * The Shibboleth License, Version 1. Copyright (c) 2002 University Corporation for Advanced Internet Development, Inc.
3  * All rights reserved Redistribution and use in source and binary forms, with or without modification, are permitted
4  * provided that the following conditions are met: Redistributions of source code must retain the above copyright
5  * notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above
6  * copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials
7  * provided with the distribution, if any, must include the following acknowledgment: "This product includes software
8  * developed by the University Corporation for Advanced Internet Development <http://www.ucaid.edu> Internet2 Project.
9  * Alternately, this acknowledegement may appear in the software itself, if and wherever such third-party
10  * acknowledgments normally appear. Neither the name of Shibboleth nor the names of its contributors, nor Internet2, nor
11  * the University Corporation for Advanced Internet Development, Inc., nor UCAID may be used to endorse or promote
12  * products derived from this software without specific prior written permission. For written permission, please contact
13  * shibboleth@shibboleth.org Products derived from this software may not be called Shibboleth, Internet2, UCAID, or the
14  * University Corporation for Advanced Internet Development, nor may Shibboleth appear in their name, without prior
15  * written permission of the University Corporation for Advanced Internet Development. THIS SOFTWARE IS PROVIDED BY THE
16  * COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE
18  * DISCLAIMED AND THE ENTIRE RISK OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. IN NO
19  * EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC.
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
23  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 package edu.internet2.middleware.shibboleth.common.provider;
27
28 import java.security.GeneralSecurityException;
29 import java.security.cert.CertPathBuilder;
30 import java.security.cert.CertPathValidator;
31 import java.security.cert.CertPathValidatorException;
32 import java.security.cert.CertStore;
33 import java.security.cert.CertificateParsingException;
34 import java.security.cert.CollectionCertStoreParameters;
35 import java.security.cert.PKIXBuilderParameters;
36 import java.security.cert.PKIXCertPathBuilderResult;
37 import java.security.cert.PKIXCertPathValidatorResult;
38 import java.security.cert.TrustAnchor;
39 import java.security.cert.X509CertSelector;
40 import java.security.cert.X509Certificate;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.Collection;
44 import java.util.HashSet;
45 import java.util.Iterator;
46 import java.util.List;
47 import java.util.Set;
48 import java.util.regex.Matcher;
49 import java.util.regex.Pattern;
50
51 import javax.security.auth.x500.X500Principal;
52
53 import org.apache.log4j.Logger;
54 import org.apache.xml.security.exceptions.XMLSecurityException;
55 import org.apache.xml.security.keys.KeyInfo;
56 import org.apache.xml.security.keys.content.KeyName;
57 import org.apache.xml.security.keys.content.X509Data;
58 import org.apache.xml.security.keys.content.x509.XMLX509Certificate;
59
60 import edu.internet2.middleware.shibboleth.common.Trust;
61 import edu.internet2.middleware.shibboleth.metadata.EntitiesDescriptor;
62 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
63 import edu.internet2.middleware.shibboleth.metadata.ExtendedEntitiesDescriptor;
64 import edu.internet2.middleware.shibboleth.metadata.ExtendedEntityDescriptor;
65 import edu.internet2.middleware.shibboleth.metadata.KeyAuthority;
66 import edu.internet2.middleware.shibboleth.metadata.KeyDescriptor;
67 import edu.internet2.middleware.shibboleth.metadata.RoleDescriptor;
68
69 /**
70  * @author Walter Hoehn
71  */
72 public class ShibbolethTrust extends Trust {
73
74         private static Logger log = Logger.getLogger(ShibbolethTrust.class.getName());
75         private static Pattern regex = Pattern.compile(".*?CN=([^,/]+).*");
76
77         public boolean validate(RoleDescriptor descriptor, X509Certificate[] certificateChain, int keyUse) {
78
79                 // If we can successfully validate with an inline key, that's fine
80                 boolean defaultValidation = super.validate(descriptor, certificateChain, keyUse);
81                 if (defaultValidation == true) { return true; }
82
83                 // Make sure we have the data we need
84                 if (descriptor == null || certificateChain == null || certificateChain.length < 1) {
85                         log.error("Appropriate data was not supplied for trust evaluation.");
86                         return false;
87                 }
88                 log.debug("Inline validation was unsuccessful.  Attmping PKIX...");
89                 // If not, try PKIX validation against the shib-custom metadata extensions
90
91                 // First, we want to see if we can match a keyName from the metadata against the cert
92                 // Iterator through all the keys in the metadata
93                 Iterator keyDescriptors = descriptor.getKeyDescriptors();
94                 while (keyDescriptors.hasNext()) {
95                         // Look for a key descriptor with the right usage bits
96                         KeyDescriptor keyDescriptor = (KeyDescriptor) keyDescriptors.next();
97                         if (keyDescriptor.getUse() != KeyDescriptor.UNSPECIFIED && keyDescriptor.getUse() != keyUse) {
98                                 log.debug("Role contains a key descriptor, but the usage specification is not valid for this action.");
99                                 continue;
100                         }
101
102                         // We found one, see if we can match the metadata's keyName against the cert
103                         KeyInfo keyInfo = keyDescriptor.getKeyInfo();
104                         if (keyInfo.containsKeyName()) {
105                                 for (int i = 0; i < keyInfo.lengthKeyName(); i++) {
106                                         try {
107                                                 if (matchKeyName(certificateChain[0], keyInfo.itemKeyName(i))) {
108                                                         // If we find a match, try to do path validation against any key authorities we might have
109                                                         // in the metadata
110                                                         if (pkixValidate(certificateChain, descriptor.getEntityDescriptor())) { return true; }
111                                                 }
112                                         } catch (XMLSecurityException e) {
113                                                 log.error("Problem retrieving key name from metadata: " + e);
114                                         }
115                                 }
116                         }
117                 }
118                 return false;
119         }
120
121         private boolean pkixValidate(X509Certificate[] certChain, EntityDescriptor entity) {
122
123                 if (entity instanceof ExtendedEntityDescriptor) {
124                         Iterator keyAuthorities = ((ExtendedEntityDescriptor) entity).getKeyAuthorities();
125                         // if we have any key authorities, construct a flat list of trust anchors representing each and attempt to
126                         // validate against them in turn
127                         while (keyAuthorities.hasNext()) {
128                                 if (pkixValidate(certChain, (KeyAuthority) keyAuthorities.next())) { return true; }
129                         }
130                 }
131
132                 // We couldn't do path validation based on metadata attached to the entity, we now need to walk up the chain of
133                 // nested entities and attempt to validate at each group level
134                 EntitiesDescriptor group = entity.getEntitiesDescriptor();
135                 if (group != null) {
136                         if (pkixValidate(certChain, group)) { return true; }
137                 }
138
139                 // We've walked the entire metadata chain with no success, so fail
140                 return false;
141         }
142
143         private boolean pkixValidate(X509Certificate[] certChain, EntitiesDescriptor group) {
144
145                 log.debug("Attemping to validate against parent group.");
146                 if (group instanceof ExtendedEntitiesDescriptor) {
147                         Iterator keyAuthorities = ((ExtendedEntitiesDescriptor) group).getKeyAuthorities();
148                         // if we have any key authorities, construct a flat list of trust anchors representing each and attempt to
149                         // validate against them in turn
150                         while (keyAuthorities.hasNext()) {
151                                 if (pkixValidate(certChain, (KeyAuthority) keyAuthorities.next())) { return true; }
152                         }
153                 }
154
155                 // If not, attempt to walk up the chain for validation
156                 EntitiesDescriptor parent = group.getEntitiesDescriptor();
157                 if (parent != null) {
158                         if (pkixValidate(certChain, parent)) { return true; }
159                 }
160
161                 return false;
162         }
163
164         private boolean pkixValidate(X509Certificate[] certChain, KeyAuthority authority) {
165
166                 Set anchors = new HashSet();
167                 Iterator keyInfos = authority.getKeyInfos();
168                 while (keyInfos.hasNext()) {
169                         KeyInfo keyInfo = (KeyInfo) keyInfos.next();
170                         if (keyInfo.containsX509Data()) {
171                                 try {
172                                         for (int i = 0; i < keyInfo.lengthX509Data(); i++) {
173                                                 X509Data data = keyInfo.itemX509Data(i);
174                                                 if (data.containsCertificate()) {
175                                                         for (int j = 0; j < data.lengthCertificate(); j++) {
176                                                                 XMLX509Certificate xmlCert = data.itemCertificate(j);
177                                                                 anchors.add(new TrustAnchor(xmlCert.getX509Certificate(), null));
178                                                         }
179                                                 }
180                                         }
181                                 } catch (XMLSecurityException e) {
182                                         log.error("Encountered an error constructing trust list from shibboleth metadata: " + e);
183                                 }
184                         }
185                 }
186
187                 // alright, if we were able to create a trust list, attempt a pkix validation against the list
188                 if (anchors.size() > 0) {
189                         log.debug("Constructed a trust list from key authority.  Attempting path validation...");
190                         try {
191                                 CertPathValidator validator = CertPathValidator.getInstance("PKIX");
192
193                                 X509CertSelector selector = new X509CertSelector();
194                                 selector.setCertificate(certChain[0]);
195                                 PKIXBuilderParameters params = new PKIXBuilderParameters(anchors, selector);
196                                 params.setMaxPathLength(authority.getVerifyDepth());
197                                 CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays
198                                                 .asList(certChain)));
199                                 List stores = new ArrayList();
200                                 stores.add(store);
201                                 params.setCertStores(stores);
202                                 //TODO hmm... what about revocation
203                                 params.setRevocationEnabled(false);
204
205                                 CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
206                                 PKIXCertPathBuilderResult buildResult = (PKIXCertPathBuilderResult) builder.build(params);
207
208                                 PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(buildResult
209                                                 .getCertPath(), params);
210                                 log.debug("Path successfully validated.");
211                                 return true;
212
213                         } catch (CertPathValidatorException e) {
214                                 log.debug("Path failed to validate: " + e);
215                         } catch (GeneralSecurityException e) {
216                                 log.error("Encountered an error during validation: " + e);
217                         }
218                 }
219                 return false;
220         }
221
222         private static boolean matchKeyName(X509Certificate certificate, KeyName keyName) {
223
224                 // First, try to match DN against metadata
225                 try {
226                         if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(
227                                         new X500Principal(keyName.getKeyName()).getName(X500Principal.RFC2253))) {
228                                 log.debug("Matched against DN.");
229                                 return true;
230                         }
231                 } catch (IllegalArgumentException iae) {
232                         // squelch this runtime exception, since
233                         // this might be a valid case
234                 }
235
236                 // If that doesn't work, we try matching against
237                 // some Subject Alt Names
238                 try {
239                         Collection altNames = certificate.getSubjectAlternativeNames();
240                         if (altNames != null) {
241                                 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
242                                         List altName = (List) nameIterator.next();
243                                         if (altName.get(0).equals(new Integer(2)) || altName.get(0).equals(new Integer(6))) {
244                                                 // 2 is DNS, 6 is URI
245                                                 if (altName.get(0).equals(keyName.getKeyName())) {
246                                                         log.debug("Matched against SubjectAltName.");
247                                                         return true;
248                                                 }
249                                         }
250                                 }
251                         }
252                 } catch (CertificateParsingException e1) {
253                         log.error("Encountered an problem trying to extract Subject Alternate "
254                                         + "Name from supplied certificate: " + e1);
255                 }
256
257                 // If that doesn't work, try to match using
258                 // SSL-style hostname matching
259                 if (getHostNameFromDN(certificate.getSubjectX500Principal()).equals(keyName.getKeyName())) {
260                         log.debug("Matched against hostname.");
261                         return true;
262                 }
263
264                 return false;
265         }
266
267         private static String getHostNameFromDN(X500Principal dn) {
268
269                 Matcher matches = regex.matcher(dn.getName(X500Principal.RFC2253));
270                 if (!matches.find() || matches.groupCount() > 1) {
271                         log.error("Unable to extract host name name from certificate subject DN.");
272                         return null;
273                 }
274                 return matches.group(1);
275         }
276
277 }