Began major refactoring of IdP servlet in order to allow support for multiple protoco...
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / provider / SAMLv1_1ArtifactQueryHandler.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.io.IOException;
29 import java.security.cert.CertificateParsingException;
30 import java.security.cert.X509Certificate;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.Iterator;
34 import java.util.List;
35
36 import javax.security.auth.x500.X500Principal;
37 import javax.servlet.ServletException;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.servlet.http.HttpServletResponse;
40
41 import org.apache.log4j.Logger;
42 import org.apache.xml.security.exceptions.XMLSecurityException;
43 import org.apache.xml.security.keys.KeyInfo;
44 import org.opensaml.SAMLAssertion;
45 import org.opensaml.SAMLException;
46 import org.opensaml.SAMLRequest;
47 import org.opensaml.SAMLResponse;
48
49 import sun.misc.BASE64Decoder;
50 import edu.internet2.middleware.shibboleth.artifact.ArtifactMapper;
51 import edu.internet2.middleware.shibboleth.artifact.ArtifactMapping;
52 import edu.internet2.middleware.shibboleth.artifact.provider.MemoryArtifactMapper;
53 import edu.internet2.middleware.shibboleth.common.ShibBrowserProfile;
54 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
55 import edu.internet2.middleware.shibboleth.idp.IdPProtocolHandler;
56 import edu.internet2.middleware.shibboleth.idp.IdPProtocolSupport;
57 import edu.internet2.middleware.shibboleth.idp.InvalidClientDataException;
58 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
59 import edu.internet2.middleware.shibboleth.metadata.KeyDescriptor;
60 import edu.internet2.middleware.shibboleth.metadata.SPSSODescriptor;
61
62 /**
63  * @author Walter Hoehn
64  */
65 public class SAMLv1_1ArtifactQueryHandler extends BaseServiceHandler implements IdPProtocolHandler {
66
67         // TODO figure out how to refactor this
68         private ArtifactMapper artifactMapper;
69
70         private static Logger log = Logger.getLogger(SAMLv1_1ArtifactQueryHandler.class.getName());
71
72         SAMLv1_1ArtifactQueryHandler() throws ShibbolethConfigurationException {
73
74                 artifactMapper = new MemoryArtifactMapper();
75         }
76
77         /*
78          * (non-Javadoc)
79          * 
80          * @see edu.internet2.middleware.shibboleth.idp.ProtocolHandler#getHandlerName()
81          */
82         public String getHandlerName() {
83
84                 return "SAML v1.1 Artifact Query";
85         }
86
87         /*
88          * (non-Javadoc)
89          * 
90          * @see edu.internet2.middleware.shibboleth.idp.ProtocolHandler#processRequest(javax.servlet.http.HttpServletRequest,
91          *      javax.servlet.http.HttpServletResponse, edu.internet2.middleware.shibboleth.idp.ProtocolSupport)
92          */
93         public SAMLResponse processRequest(HttpServletRequest request, HttpServletResponse response,
94                         SAMLRequest samlRequest, IdPProtocolSupport support) throws SAMLException, InvalidClientDataException,
95                         IOException, ServletException {
96
97                 // TODO make this jsut test for artifacts... or something
98                 /*
99                  * Iterator artifacts = samlRequest.getArtifacts(); if (artifacts.hasNext()) { artifacts = null; // get rid of
100                  * the iterator log.info("Recieved a request to dereference an assertion artifact."); }
101                  */
102
103                 // TODO how about signatures on artifact dereferencing
104                 // Pull credential from request
105                 X509Certificate credential = getCredentialFromProvider(request);
106                 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
107                         // The spec says that mutual authentication is required for the
108                         // artifact profile
109                         log.info("Request is from an unauthenticated serviceprovider.");
110                         throw new SAMLException(SAMLException.REQUESTER,
111                                         "SAML Artifacts cannot be dereferenced for unauthenticated requesters.");
112                 }
113                 log.info("Request contains credential: (" + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
114                                 + ").");
115                 ArrayList assertions = new ArrayList();
116                 Iterator artifacts = samlRequest.getArtifacts();
117
118                 // TODO error if not artifacts
119
120                 int queriedArtifacts = 0;
121                 StringBuffer dereferencedArtifacts = new StringBuffer();
122                 // for // transaction // log
123                 while (artifacts.hasNext()) {
124                         queriedArtifacts++;
125                         String artifact = (String) artifacts.next();
126                         log.debug("Attempting to dereference artifact: (" + artifact + ").");
127                         ArtifactMapping mapping = artifactMapper.recoverAssertion(artifact);
128                         if (mapping != null) {
129                                 SAMLAssertion assertion = mapping.getAssertion(); // See if we have metadata for this provider
130                                 EntityDescriptor provider = support.lookup(mapping.getServiceProviderId());
131                                 if (provider == null) {
132                                         log.info("No metadata found for provider: (" + mapping.getServiceProviderId() + ").");
133                                         throw new SAMLException(SAMLException.REQUESTER, "Invalid service provider.");
134                                 }
135                                 // Make sure that the suppplied credential is valid for the // provider to which theartifact was issued
136                                 if (!isValidCredential(provider, credential)) {
137                                         log.error("Supplied credential ("
138                                                         + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
139                                                         + ") is NOT valid for provider (" + mapping.getServiceProviderId()
140                                                         + "), to whom this artifact was issued.");
141                                         throw new SAMLException(SAMLException.REQUESTER, "Invalid credential.");
142                                 }
143                                 log.debug("Supplied credential validated for the provider to which this artifact was issued.");
144                                 assertions.add(assertion);
145                                 dereferencedArtifacts.append("(" + artifact + ")");
146                         }
147                 } // The spec requires that if any artifacts are dereferenced, they must
148                 // all be dereferenced
149                 if (assertions.size() > 0 && assertions.size() != queriedArtifacts) { throw new SAMLException(
150                                 SAMLException.REQUESTER, "Unable to successfully dereference all artifacts."); }
151                 // Create and send response
152                 // The spec says that we should send "success" in the case where no // artifacts match
153                 SAMLResponse samlResponse = new SAMLResponse(samlRequest.getId(), null, assertions, null);
154                 if (log.isDebugEnabled()) {
155                         try {
156                                 log.debug("Dumping generated SAML Response:"
157                                                 + System.getProperty("line.separator")
158                                                 + new String(new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
159                                                                 "UTF8"));
160                         } catch (SAMLException e) {
161                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
162                         } catch (IOException e) {
163                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
164                         }
165                 }
166
167                 support.getTransactionLog().info(
168                                 "Succesfully dereferenced the following artifacts: " + dereferencedArtifacts.toString());
169                 return samlResponse;
170         }
171
172         private static boolean isValidCredential(EntityDescriptor provider, X509Certificate certificate) {
173
174                 SPSSODescriptor sp = provider.getSPSSODescriptor(org.opensaml.XML.SAML11_PROTOCOL_ENUM);
175                 if (sp == null) {
176                         log.info("Inappropriate metadata for provider.");
177                         return false;
178                 }
179                 // TODO figure out what to do about this role business here
180                 Iterator descriptors = sp.getKeyDescriptors();
181                 while (descriptors.hasNext()) {
182                         KeyInfo keyInfo = ((KeyDescriptor) descriptors.next()).getKeyInfo();
183                         for (int l = 0; keyInfo.lengthKeyName() > l; l++) {
184                                 try {
185
186                                         // First, try to match DN against metadata
187                                         try {
188                                                 if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(
189                                                                 new X500Principal(keyInfo.itemKeyName(l).getKeyName()).getName(X500Principal.RFC2253))) {
190                                                         log.debug("Matched against DN.");
191                                                         return true;
192                                                 }
193                                         } catch (IllegalArgumentException iae) {
194                                                 // squelch this runtime exception, since
195                                                 // this might be a valid case
196                                         }
197
198                                         // If that doesn't work, we try matching against
199                                         // some Subject Alt Names
200                                         try {
201                                                 Collection altNames = certificate.getSubjectAlternativeNames();
202                                                 if (altNames != null) {
203                                                         for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
204                                                                 List altName = (List) nameIterator.next();
205                                                                 if (altName.get(0).equals(new Integer(2)) || altName.get(0).equals(new Integer(6))) { // 2 is
206                                                                         // DNS,
207                                                                         // 6 is
208                                                                         // URI
209                                                                         if (altName.get(1).equals(keyInfo.itemKeyName(l).getKeyName())) {
210                                                                                 log.debug("Matched against SubjectAltName.");
211                                                                                 return true;
212                                                                         }
213                                                                 }
214                                                         }
215                                                 }
216                                         } catch (CertificateParsingException e1) {
217                                                 log
218                                                                 .error("Encountered an problem trying to extract Subject Alternate Name from supplied certificate: "
219                                                                                 + e1);
220                                         }
221
222                                         // If that doesn't work, try to match using
223                                         // SSL-style hostname matching
224                                         if (ShibBrowserProfile.getHostNameFromDN(certificate.getSubjectX500Principal()).equals(
225                                                         keyInfo.itemKeyName(l).getKeyName())) {
226                                                 log.debug("Matched against hostname.");
227                                                 return true;
228                                         }
229
230                                 } catch (XMLSecurityException e) {
231                                         log.error("Encountered an error reading federation metadata: " + e);
232                                 }
233                         }
234                 }
235                 log.info("Supplied credential not found in metadata.");
236                 return false;
237         }
238
239 }