Refactorings on the Trust code. (Extracted an interface and added javadoc.)
[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  * <code>Trust</code> implementation that does PKIX validation against key authorities included in shibboleth-specific
71  * extensions to SAML 2 metadata.
72  * 
73  * @author Walter Hoehn
74  */
75 public class ShibbolethTrust extends BasicTrust implements Trust {
76
77         private static Logger log = Logger.getLogger(ShibbolethTrust.class.getName());
78         private static Pattern regex = Pattern.compile(".*?CN=([^,/]+).*");
79
80         /*
81          * @see edu.internet2.middleware.shibboleth.common.Trust#validate(edu.internet2.middleware.shibboleth.metadata.RoleDescriptor,
82          *      java.security.cert.X509Certificate[], int)
83          */
84         public boolean validate(RoleDescriptor descriptor, X509Certificate[] certificateChain, int keyUse) {
85
86                 // If we can successfully validate with an inline key, that's fine
87                 boolean defaultValidation = super.validate(descriptor, certificateChain, keyUse);
88                 if (defaultValidation == true) { return true; }
89
90                 // Make sure we have the data we need
91                 if (descriptor == null || certificateChain == null || certificateChain.length < 1) {
92                         log.error("Appropriate data was not supplied for trust evaluation.");
93                         return false;
94                 }
95                 log.debug("Inline validation was unsuccessful.  Attmping PKIX...");
96                 // If not, try PKIX validation against the shib-custom metadata extensions
97
98                 // First, we want to see if we can match a keyName from the metadata against the cert
99                 // Iterator through all the keys in the metadata
100                 Iterator keyDescriptors = descriptor.getKeyDescriptors();
101                 while (keyDescriptors.hasNext()) {
102                         // Look for a key descriptor with the right usage bits
103                         KeyDescriptor keyDescriptor = (KeyDescriptor) keyDescriptors.next();
104                         if (keyDescriptor.getUse() != KeyDescriptor.UNSPECIFIED && keyDescriptor.getUse() != keyUse) {
105                                 log.debug("Role contains a key descriptor, but the usage specification is not valid for this action.");
106                                 continue;
107                         }
108
109                         // We found one, see if we can match the metadata's keyName against the cert
110                         KeyInfo keyInfo = keyDescriptor.getKeyInfo();
111                         if (keyInfo.containsKeyName()) {
112                                 for (int i = 0; i < keyInfo.lengthKeyName(); i++) {
113                                         try {
114                                                 if (matchKeyName(certificateChain[0], keyInfo.itemKeyName(i))) {
115                                                         // If we find a match, try to do path validation against any key authorities we might have
116                                                         // in the metadata
117                                                         if (pkixValidate(certificateChain, descriptor.getEntityDescriptor())) { return true; }
118                                                 }
119                                         } catch (XMLSecurityException e) {
120                                                 log.error("Problem retrieving key name from metadata: " + e);
121                                         }
122                                 }
123                         }
124                 }
125                 return false;
126         }
127
128         private boolean pkixValidate(X509Certificate[] certChain, EntityDescriptor entity) {
129
130                 if (entity instanceof ExtendedEntityDescriptor) {
131                         Iterator keyAuthorities = ((ExtendedEntityDescriptor) entity).getKeyAuthorities();
132                         // if we have any key authorities, construct a flat list of trust anchors representing each and attempt to
133                         // validate against them in turn
134                         while (keyAuthorities.hasNext()) {
135                                 if (pkixValidate(certChain, (KeyAuthority) keyAuthorities.next())) { return true; }
136                         }
137                 }
138
139                 // We couldn't do path validation based on metadata attached to the entity, we now need to walk up the chain of
140                 // nested entities and attempt to validate at each group level
141                 EntitiesDescriptor group = entity.getEntitiesDescriptor();
142                 if (group != null) {
143                         if (pkixValidate(certChain, group)) { return true; }
144                 }
145
146                 // We've walked the entire metadata chain with no success, so fail
147                 return false;
148         }
149
150         private boolean pkixValidate(X509Certificate[] certChain, EntitiesDescriptor group) {
151
152                 log.debug("Attemping to validate against parent group.");
153                 if (group instanceof ExtendedEntitiesDescriptor) {
154                         Iterator keyAuthorities = ((ExtendedEntitiesDescriptor) group).getKeyAuthorities();
155                         // if we have any key authorities, construct a flat list of trust anchors representing each and attempt to
156                         // validate against them in turn
157                         while (keyAuthorities.hasNext()) {
158                                 if (pkixValidate(certChain, (KeyAuthority) keyAuthorities.next())) { return true; }
159                         }
160                 }
161
162                 // If not, attempt to walk up the chain for validation
163                 EntitiesDescriptor parent = group.getEntitiesDescriptor();
164                 if (parent != null) {
165                         if (pkixValidate(certChain, parent)) { return true; }
166                 }
167
168                 return false;
169         }
170
171         private boolean pkixValidate(X509Certificate[] certChain, KeyAuthority authority) {
172
173                 Set anchors = new HashSet();
174                 Iterator keyInfos = authority.getKeyInfos();
175                 while (keyInfos.hasNext()) {
176                         KeyInfo keyInfo = (KeyInfo) keyInfos.next();
177                         if (keyInfo.containsX509Data()) {
178                                 try {
179                                         for (int i = 0; i < keyInfo.lengthX509Data(); i++) {
180                                                 X509Data data = keyInfo.itemX509Data(i);
181                                                 if (data.containsCertificate()) {
182                                                         for (int j = 0; j < data.lengthCertificate(); j++) {
183                                                                 XMLX509Certificate xmlCert = data.itemCertificate(j);
184                                                                 anchors.add(new TrustAnchor(xmlCert.getX509Certificate(), null));
185                                                         }
186                                                 }
187                                         }
188                                 } catch (XMLSecurityException e) {
189                                         log.error("Encountered an error constructing trust list from shibboleth metadata: " + e);
190                                 }
191                         }
192                 }
193
194                 // alright, if we were able to create a trust list, attempt a pkix validation against the list
195                 if (anchors.size() > 0) {
196                         log.debug("Constructed a trust list from key authority.  Attempting path validation...");
197                         try {
198                                 CertPathValidator validator = CertPathValidator.getInstance("PKIX");
199
200                                 X509CertSelector selector = new X509CertSelector();
201                                 selector.setCertificate(certChain[0]);
202                                 PKIXBuilderParameters params = new PKIXBuilderParameters(anchors, selector);
203                                 params.setMaxPathLength(authority.getVerifyDepth());
204                                 CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays
205                                                 .asList(certChain)));
206                                 List stores = new ArrayList();
207                                 stores.add(store);
208                                 params.setCertStores(stores);
209                                 //TODO hmm... what about revocation
210                                 params.setRevocationEnabled(false);
211
212                                 CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
213                                 PKIXCertPathBuilderResult buildResult = (PKIXCertPathBuilderResult) builder.build(params);
214
215                                 PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(buildResult
216                                                 .getCertPath(), params);
217                                 log.debug("Path successfully validated.");
218                                 return true;
219
220                         } catch (CertPathValidatorException e) {
221                                 log.debug("Path failed to validate: " + e);
222                         } catch (GeneralSecurityException e) {
223                                 log.error("Encountered an error during validation: " + e);
224                         }
225                 }
226                 return false;
227         }
228
229         private static boolean matchKeyName(X509Certificate certificate, KeyName keyName) {
230
231                 // First, try to match DN against metadata
232                 try {
233                         if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(
234                                         new X500Principal(keyName.getKeyName()).getName(X500Principal.RFC2253))) {
235                                 log.debug("Matched against DN.");
236                                 return true;
237                         }
238                 } catch (IllegalArgumentException iae) {
239                         // squelch this runtime exception, since
240                         // this might be a valid case
241                 }
242
243                 // If that doesn't work, we try matching against
244                 // some Subject Alt Names
245                 try {
246                         Collection altNames = certificate.getSubjectAlternativeNames();
247                         if (altNames != null) {
248                                 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
249                                         List altName = (List) nameIterator.next();
250                                         if (altName.get(0).equals(new Integer(2)) || altName.get(0).equals(new Integer(6))) {
251                                                 // 2 is DNS, 6 is URI
252                                                 if (altName.get(0).equals(keyName.getKeyName())) {
253                                                         log.debug("Matched against SubjectAltName.");
254                                                         return true;
255                                                 }
256                                         }
257                                 }
258                         }
259                 } catch (CertificateParsingException e1) {
260                         log.error("Encountered an problem trying to extract Subject Alternate "
261                                         + "Name from supplied certificate: " + e1);
262                 }
263
264                 // If that doesn't work, try to match using
265                 // SSL-style hostname matching
266                 if (getHostNameFromDN(certificate.getSubjectX500Principal()).equals(keyName.getKeyName())) {
267                         log.debug("Matched against hostname.");
268                         return true;
269                 }
270
271                 return false;
272         }
273
274         private static String getHostNameFromDN(X500Principal dn) {
275
276                 Matcher matches = regex.matcher(dn.getName(X500Principal.RFC2253));
277                 if (!matches.find() || matches.groupCount() > 1) {
278                         log.error("Unable to extract host name name from certificate subject DN.");
279                         return null;
280                 }
281                 return matches.group(1);
282         }
283
284 }