45fc12a53c49d331894f188c65c5a7f0e9f8a49c
[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.X509Certificate;
30 import java.util.ArrayList;
31 import java.util.Iterator;
32
33 import javax.security.auth.x500.X500Principal;
34 import javax.servlet.ServletException;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.servlet.http.HttpServletResponse;
37
38 import org.apache.log4j.Logger;
39 import org.opensaml.SAMLAssertion;
40 import org.opensaml.SAMLException;
41 import org.opensaml.SAMLRequest;
42 import org.opensaml.SAMLResponse;
43
44 import sun.misc.BASE64Decoder;
45 import edu.internet2.middleware.shibboleth.artifact.ArtifactMapper;
46 import edu.internet2.middleware.shibboleth.artifact.ArtifactMapping;
47 import edu.internet2.middleware.shibboleth.artifact.provider.MemoryArtifactMapper;
48 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
49 import edu.internet2.middleware.shibboleth.idp.IdPProtocolHandler;
50 import edu.internet2.middleware.shibboleth.idp.IdPProtocolSupport;
51 import edu.internet2.middleware.shibboleth.idp.InvalidClientDataException;
52 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
53
54 /**
55  * @author Walter Hoehn
56  */
57 public class SAMLv1_1ArtifactQueryHandler extends BaseServiceHandler implements IdPProtocolHandler {
58
59         // TODO figure out how to refactor this
60         private ArtifactMapper  artifactMapper;
61
62         private static Logger   log     = Logger.getLogger(SAMLv1_1ArtifactQueryHandler.class.getName());
63
64         SAMLv1_1ArtifactQueryHandler() throws ShibbolethConfigurationException {
65
66                 artifactMapper = new MemoryArtifactMapper();
67         }
68
69         /*
70          * (non-Javadoc)
71          * 
72          * @see edu.internet2.middleware.shibboleth.idp.ProtocolHandler#getHandlerName()
73          */
74         public String getHandlerName() {
75
76                 return "SAML v1.1 Artifact Query";
77         }
78
79         /*
80          * @see edu.internet2.middleware.shibboleth.idp.ProtocolHandler#processRequest(javax.servlet.http.HttpServletRequest,
81          *      javax.servlet.http.HttpServletResponse, edu.internet2.middleware.shibboleth.idp.ProtocolSupport)
82          */
83         public SAMLResponse processRequest(HttpServletRequest request, HttpServletResponse response,
84                         SAMLRequest samlRequest, IdPProtocolSupport support) throws SAMLException, InvalidClientDataException,
85                         IOException, ServletException {
86
87                 log.info("Recieved a request to dereference an assertion artifact.");
88
89                 // TODO how about signatures on artifact dereferencing
90                 // Pull credential from request
91                 X509Certificate credential = getCredentialFromProvider(request);
92                 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
93                         // The spec says that mutual authentication is required for the
94                         // artifact profile
95                         log.info("Request is from an unauthenticated serviceprovider.");
96                         throw new SAMLException(SAMLException.REQUESTER,
97                                         "SAML Artifacts cannot be dereferenced for unauthenticated requesters.");
98                 }
99                 log.info("Request contains credential: (" + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
100                                 + ").");
101                 ArrayList assertions = new ArrayList();
102                 Iterator artifacts = samlRequest.getArtifacts();
103
104                 // TODO error if not artifacts
105
106                 int queriedArtifacts = 0;
107                 StringBuffer dereferencedArtifacts = new StringBuffer();
108                 // for // transaction // log
109                 while (artifacts.hasNext()) {
110                         queriedArtifacts++;
111                         String artifact = (String) artifacts.next();
112                         log.debug("Attempting to dereference artifact: (" + artifact + ").");
113                         ArtifactMapping mapping = artifactMapper.recoverAssertion(artifact);
114                         if (mapping != null) {
115                                 SAMLAssertion assertion = mapping.getAssertion(); // See if we have metadata for this provider
116                                 EntityDescriptor provider = support.lookup(mapping.getServiceProviderId());
117                                 if (provider == null) {
118                                         log.info("No metadata found for provider: (" + mapping.getServiceProviderId() + ").");
119                                         throw new SAMLException(SAMLException.REQUESTER, "Invalid service provider.");
120                                 }
121                                 // Make sure that the suppplied credential is valid for the // provider to which theartifact was issued
122                                 if (!isValidCredential(provider, credential)) {
123                                         log.error("Supplied credential ("
124                                                         + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
125                                                         + ") is NOT valid for provider (" + mapping.getServiceProviderId()
126                                                         + "), to whom this artifact was issued.");
127                                         throw new SAMLException(SAMLException.REQUESTER, "Invalid credential.");
128                                 }
129                                 log.debug("Supplied credential validated for the provider to which this artifact was issued.");
130                                 assertions.add(assertion);
131                                 dereferencedArtifacts.append("(" + artifact + ")");
132                         }
133                 } // The spec requires that if any artifacts are dereferenced, they must
134                 // all be dereferenced
135                 if (assertions.size() > 0 && assertions.size() != queriedArtifacts) { throw new SAMLException(
136                                 SAMLException.REQUESTER, "Unable to successfully dereference all artifacts."); }
137                 // Create and send response
138                 // The spec says that we should send "success" in the case where no // artifacts match
139                 SAMLResponse samlResponse = new SAMLResponse(samlRequest.getId(), null, assertions, null);
140                 if (log.isDebugEnabled()) {
141                         try {
142                                 log.debug("Dumping generated SAML Response:"
143                                                 + System.getProperty("line.separator")
144                                                 + new String(new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
145                                                                 "UTF8"));
146                         } catch (SAMLException e) {
147                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
148                         } catch (IOException e) {
149                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
150                         }
151                 }
152
153                 support.getTransactionLog().info(
154                                 "Succesfully dereferenced the following artifacts: " + dereferencedArtifacts.toString());
155                 return samlResponse;
156         }
157
158 }