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