Some small refactorings and cleanups.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / provider / BaseServiceHandler.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.idp.provider;
27
28 import java.security.cert.CertificateParsingException;
29 import java.security.cert.X509Certificate;
30 import java.util.Collection;
31 import java.util.Iterator;
32 import java.util.List;
33
34 import javax.security.auth.x500.X500Principal;
35 import javax.servlet.http.HttpServletRequest;
36
37 import org.apache.log4j.Logger;
38 import org.apache.xml.security.exceptions.XMLSecurityException;
39 import org.apache.xml.security.keys.KeyInfo;
40 import org.w3c.dom.Element;
41
42 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
43 import edu.internet2.middleware.shibboleth.idp.IdPProtocolHandler;
44 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
45 import edu.internet2.middleware.shibboleth.metadata.KeyDescriptor;
46 import edu.internet2.middleware.shibboleth.metadata.SPSSODescriptor;
47
48 /**
49  * @author Walter Hoehn
50  */
51 public abstract class BaseServiceHandler extends BaseHandler implements IdPProtocolHandler {
52
53         /**
54          * Required DOM-based constructor.
55          */
56         public BaseServiceHandler(Element config) throws ShibbolethConfigurationException {
57
58                 super(config);
59         }
60
61         private static Logger log = Logger.getLogger(BaseServiceHandler.class.getName());
62
63         protected static X509Certificate getCredentialFromProvider(HttpServletRequest req) {
64
65                 X509Certificate[] certArray = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
66                 if (certArray != null && certArray.length > 0) { return certArray[0]; }
67                 return null;
68         }
69
70         protected static boolean isValidCredential(EntityDescriptor provider, X509Certificate certificate) {
71
72                 SPSSODescriptor sp = provider.getSPSSODescriptor(org.opensaml.XML.SAML11_PROTOCOL_ENUM);
73                 if (sp == null) {
74                         log.info("Inappropriate metadata for provider.");
75                         return false;
76                 }
77
78                 Iterator descriptors = sp.getKeyDescriptors();
79                 while (descriptors.hasNext()) {
80                         KeyInfo keyInfo = ((KeyDescriptor) descriptors.next()).getKeyInfo();
81                         for (int l = 0; keyInfo.lengthKeyName() > l; l++) {
82                                 try {
83
84                                         // First, try to match DN against metadata
85                                         try {
86                                                 if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(
87                                                                 new X500Principal(keyInfo.itemKeyName(l).getKeyName()).getName(X500Principal.RFC2253))) {
88                                                         log.debug("Matched against DN.");
89                                                         return true;
90                                                 }
91                                         } catch (IllegalArgumentException iae) {
92                                                 // squelch this runtime exception, since
93                                                 // this might be a valid case
94                                         }
95
96                                         // If that doesn't work, we try matching against
97                                         // some Subject Alt Names
98                                         try {
99                                                 Collection altNames = certificate.getSubjectAlternativeNames();
100                                                 if (altNames != null) {
101                                                         for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
102                                                                 List altName = (List) nameIterator.next();
103                                                                 if (altName.get(0).equals(new Integer(2)) || altName.get(0).equals(new Integer(6))) {
104                                                                         // 2 is DNS, 6 is URI
105                                                                         if (altName.get(1).equals(keyInfo.itemKeyName(l).getKeyName())) {
106                                                                                 log.debug("Matched against SubjectAltName.");
107                                                                                 return true;
108                                                                         }
109                                                                 }
110                                                         }
111                                                 }
112                                         } catch (CertificateParsingException e1) {
113                                                 log.error("Encountered an problem trying to extract Subject Alternate "
114                                                                 + "Name from supplied certificate: " + e1);
115                                         }
116
117                                         // If that doesn't work, try to match using
118                                         // SSL-style hostname matching
119                                         if (getHostNameFromDN(certificate.getSubjectX500Principal()).equals(
120                                                         keyInfo.itemKeyName(l).getKeyName())) {
121                                                 log.debug("Matched against hostname.");
122                                                 return true;
123                                         }
124
125                                 } catch (XMLSecurityException e) {
126                                         log.error("Encountered an error reading federation metadata: " + e);
127                                 }
128                         }
129                 }
130                 log.info("Supplied credential not found in metadata.");
131                 return false;
132         }
133
134         protected class InvalidProviderCredentialException extends Exception {
135
136                 public InvalidProviderCredentialException(String message) {
137
138                         super(message);
139                 }
140         }
141 }