Imported the beginnings of a unified SAML responder servlet that handles multiple...
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / IdPResponder.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;
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.UnavailableException;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
41
42 import org.apache.log4j.Logger;
43 import org.apache.log4j.MDC;
44 import org.apache.xml.security.exceptions.XMLSecurityException;
45 import org.apache.xml.security.keys.KeyInfo;
46 import org.opensaml.SAMLAssertion;
47 import org.opensaml.SAMLAttributeQuery;
48 import org.opensaml.SAMLBinding;
49 import org.opensaml.SAMLException;
50 import org.opensaml.SAMLIdentifier;
51 import org.opensaml.SAMLRequest;
52 import org.opensaml.SAMLResponse;
53
54 import sun.misc.BASE64Decoder;
55
56 import edu.internet2.middleware.shibboleth.common.SAMLBindingFactory;
57 import edu.internet2.middleware.shibboleth.common.ServiceProvider;
58 import edu.internet2.middleware.shibboleth.common.ShibPOSTProfile;
59 import edu.internet2.middleware.shibboleth.common.TargetFederationComponent;
60 import edu.internet2.middleware.shibboleth.hs.HSRelyingParty;
61 import edu.internet2.middleware.shibboleth.metadata.AttributeConsumerRole;
62 import edu.internet2.middleware.shibboleth.metadata.KeyDescriptor;
63 import edu.internet2.middleware.shibboleth.metadata.Provider;
64 import edu.internet2.middleware.shibboleth.metadata.ProviderRole;
65
66 /**
67  * Primary entrypoint for requests to the SAML IdP. Listens on multiple endpoints, routes requests to the appropriate
68  * IdP processing components, and delivers proper protocol responses.
69  * 
70  * @author Walter Hoehn
71  */
72
73 public class IdPResponder extends TargetFederationComponent {
74
75         private static Logger           transactionLog  = Logger.getLogger("Shibboleth-TRANSACTION");
76         private static Logger           log                             = Logger.getLogger(IdPResponder.class.getName());
77         private SAMLBinding                     binding;
78         private ArtifactRepository      artifactRepository;
79
80         public void init() throws ServletException {
81
82                 super.init();
83                 MDC.put("serviceId", "[IdP] Core");
84                 log.info("Initializing Identity Provider.");
85
86                 try {
87                         binding = SAMLBindingFactory.getInstance(SAMLBinding.SAML_SOAP_HTTPS);
88                         log.info("Identity Provider initialization complete.");
89
90                 } catch (SAMLException se) {
91                         log.fatal("SAML SOAP binding could not be loaded: " + se);
92                         throw new UnavailableException("Identity Provider failed to initialize.");
93                 }
94         }
95
96         public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
97
98                 MDC.put("serviceId", "[IdP] " + new SAMLIdentifier().toString());
99                 MDC.put("remoteAddr", request.getRemoteAddr());
100                 log.debug("Recieved a request via POST.");
101
102                 // Parse SOAP request and marshall SAML request object
103                 try {
104                         SAMLRequest samlRequest = null;
105                         try {
106                                 samlRequest = binding.receive(request);
107                         } catch (SAMLException e) {
108                                 log.fatal("Unable to parse request: " + e);
109                                 throw new SAMLException("Invalid request data.");
110                         }
111
112                         // Determine the request type
113                         Iterator artifacts = samlRequest.getArtifacts();
114                         if (artifacts.hasNext()) {
115                                 log.info("Recieved a request to dereference an assertion artifact.");
116                                 processArtifactDereference(samlRequest, request, response);
117                                 return;
118                         }
119
120                         if (samlRequest.getQuery() != null && (samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
121                                 log.info("Recieved an attribute query.");
122                                 processAttributeQuery(samlRequest, request, response);
123                                 return;
124                         }
125
126                         throw new SAMLException(SAMLException.REQUESTER,
127                                         "Identity Provider unable to respond to this SAML Request type.");
128
129                 } catch (SAMLException e) {
130                         // TODO handle properly, like in the AA stuff
131                 }
132         }
133
134         private void processAttributeQuery(SAMLRequest samlRequest, HttpServletRequest request, HttpServletResponse response) {
135         //TODO validate that the endpoint is valid for the request type
136         //TODO implement
137         }
138
139         private void processArtifactDereference(SAMLRequest samlRequest, HttpServletRequest request,
140                         HttpServletResponse response) throws SAMLException, IOException {
141                 //TODO validate that the endpoint is valid for the request type
142
143                 // Pull credential from request
144                 X509Certificate credential = getCredentialFromProvider(request);
145                 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
146                         log.info("Request is from an unauthenticated service provider.");
147                         throw new SAMLException(SAMLException.REQUESTER,
148                                         "SAML Artifacts cannot be dereferenced for unauthenticated requesters.");
149                 }
150
151                 log.info("Request contains credential: (" + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
152                                 + ").");
153
154                 ArrayList assertions = new ArrayList();
155                 Iterator artifacts = samlRequest.getArtifacts();
156
157                 int queriedArtifacts = 0;
158                 StringBuffer dereferencedArtifacts = new StringBuffer(); //for transaction log
159                 while (artifacts.hasNext()) {
160                         queriedArtifacts++;
161                         String artifact = (String) artifacts.next();
162                         log.debug("Attempting to dereference artifact: (" + artifact + ").");
163                         ArtifactMapping mapping = artifactRepository.recoverAssertion(artifact);
164                         if (mapping != null) {
165                                 SAMLAssertion assertion = mapping.getAssertion();
166
167                                 //See if we have metadata for this provider
168                                 Provider provider = lookup(mapping.getServiceProviderId());
169                                 if (provider == null) {
170                                         log.info("No metadata found for provider: (" + mapping.getServiceProviderId() + ").");
171                                         throw new SAMLException(SAMLException.REQUESTER, "Invalid service provider.");
172                                 }
173
174                                 //Make sure that the suppplied credential is valid for the provider to which the artifact was issued
175                                 if (!isValidCredential(provider, credential)) {
176                                         log.error("Supplied credential ("
177                                                         + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
178                                                         + ") is NOT valid for provider (" + mapping.getServiceProviderId()
179                                                         + "), to whom this artifact was issued.");
180                                         throw new SAMLException(SAMLException.REQUESTER, "Invalid credential.");
181                                 }
182
183                                 log.debug("Supplied credential validated for the provider to which this artifact was issued.");
184
185                                 assertions.add(assertion);
186                                 dereferencedArtifacts.append("(" + artifact + ")");
187                         }
188                 }
189
190                 //The spec requires that if any artifacts are dereferenced, they must all be dereferenced
191                 if (assertions.size() > 0 & assertions.size() != queriedArtifacts) { throw new SAMLException(
192                                 SAMLException.REQUESTER, "Unable to successfully dereference all artifacts."); }
193
194                 //Create and send response
195                 SAMLResponse samlResponse = new SAMLResponse(samlRequest.getId(), null, assertions, null);
196
197                 if (log.isDebugEnabled()) {
198                         try {
199                                 log.debug("Dumping generated SAML Response:"
200                                                 + System.getProperty("line.separator")
201                                                 + new String(new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
202                                                                 "UTF8"));
203                         } catch (SAMLException e) {
204                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
205                         } catch (IOException e) {
206                                 log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
207                         }
208                 }
209
210                 binding.respond(response, samlResponse, null);
211
212                 transactionLog.info("Succesfully dereferenced the following artifacts: " + dereferencedArtifacts.toString());
213                 /*
214                  * } catch (Exception e) { log.error("Error while processing request: " + e); try { sendFailure(res,
215                  * samlRequest, new SAMLException(SAMLException.RESPONDER, "General error processing request.")); return; }
216                  * catch (Exception ee) { log.fatal("Could not construct a SAML error response: " + ee); throw new
217                  * ServletException("Handle Service response failure."); } }
218                  */
219         }
220
221         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
222
223                 MDC.put("serviceId", "[IdP] " + new SAMLIdentifier().toString());
224                 MDC.put("remoteAddr", request.getRemoteAddr());
225                 log.debug("Recieved a request via GET.");
226         }
227
228         private X509Certificate getCredentialFromProvider(HttpServletRequest req) {
229                 X509Certificate[] certArray = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
230                 if (certArray != null && certArray.length > 0) { return certArray[0]; }
231                 return null;
232         }
233
234         private boolean isValidCredential(Provider provider, X509Certificate certificate) {
235
236                 ProviderRole[] roles = provider.getRoles();
237                 if (roles.length == 0) {
238                         log.info("Inappropriate metadata for provider.");
239                         return false;
240                 }
241                 //TODO figure out what to do about this role business here
242                 for (int i = 0; roles.length > i; i++) {
243                         if (roles[i] instanceof AttributeConsumerRole) {
244                                 KeyDescriptor[] descriptors = roles[i].getKeyDescriptors();
245                                 for (int j = 0; descriptors.length > j; j++) {
246                                         KeyInfo[] keyInfo = descriptors[j].getKeyInfo();
247                                         for (int k = 0; keyInfo.length > k; k++) {
248                                                 for (int l = 0; keyInfo[k].lengthKeyName() > l; l++) {
249                                                         try {
250
251                                                                 //First, try to match DN against metadata
252                                                                 try {
253                                                                         if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253).equals(
254                                                                                         new X500Principal(keyInfo[k].itemKeyName(l).getKeyName())
255                                                                                                         .getName(X500Principal.RFC2253))) {
256                                                                                 log.debug("Matched against DN.");
257                                                                                 return true;
258                                                                         }
259                                                                 } catch (IllegalArgumentException iae) {
260                                                                         //squelch this runtime exception, since this might be a valid case
261                                                                 }
262
263                                                                 //If that doesn't work, we try matching against some Subject Alt Names
264                                                                 try {
265                                                                         Collection altNames = certificate.getSubjectAlternativeNames();
266                                                                         if (altNames != null) {
267                                                                                 for (Iterator nameIterator = altNames.iterator(); nameIterator.hasNext();) {
268                                                                                         List altName = (List) nameIterator.next();
269                                                                                         if (altName.get(0).equals(new Integer(2))
270                                                                                                         || altName.get(0).equals(new Integer(6))) { //2 is DNS, 6 is URI
271                                                                                                 if (altName.get(1).equals(keyInfo[k].itemKeyName(l).getKeyName())) {
272                                                                                                         log.debug("Matched against SubjectAltName.");
273                                                                                                         return true;
274                                                                                                 }
275                                                                                         }
276                                                                                 }
277                                                                         }
278                                                                 } catch (CertificateParsingException e1) {
279                                                                         log
280                                                                                         .error("Encountered an problem trying to extract Subject Alternate Name from supplied certificate: "
281                                                                                                         + e1);
282                                                                 }
283
284                                                                 //If that doesn't work, try to match using SSL-style hostname matching
285                                                                 if (ShibPOSTProfile.getHostNameFromDN(certificate.getSubjectX500Principal()).equals(
286                                                                                 keyInfo[k].itemKeyName(l).getKeyName())) {
287                                                                         log.debug("Matched against hostname.");
288                                                                         return true;
289                                                                 }
290
291                                                         } catch (XMLSecurityException e) {
292                                                                 log.error("Encountered an error reading federation metadata: " + e);
293                                                         }
294                                                 }
295                                         }
296                                 }
297                         }
298                 }
299                 log.info("Supplied credential not found in metadata.");
300                 return false;
301         }
302
303         abstract class ArtifactRepository {
304
305                 // TODO figure out what to do about this interface long term
306                 abstract String addAssertion(SAMLAssertion assertion, HSRelyingParty relyingParty);
307
308                 abstract ArtifactMapping recoverAssertion(String artifact);
309         }
310
311         class ArtifactMapping {
312
313                 //TODO figure out what to do about this interface long term
314                 private String                  assertionHandle;
315                 private long                    expirationTime;
316                 private SAMLAssertion   assertion;
317                 private String                  serviceProviderId;
318
319                 ArtifactMapping(String assertionHandle, SAMLAssertion assertion, ServiceProvider sp) {
320                         this.assertionHandle = assertionHandle;
321                         this.assertion = assertion;
322                         expirationTime = System.currentTimeMillis() + (1000 * 60 * 5); //in 5 minutes
323                         serviceProviderId = sp.getProviderId();
324                 }
325
326                 boolean isExpired() {
327                         if (System.currentTimeMillis() > expirationTime) { return true; }
328                         return false;
329                 }
330
331                 boolean isCorrectProvider(ServiceProvider sp) {
332                         if (sp.getProviderId().equals(serviceProviderId)) { return true; }
333                         return false;
334                 }
335
336                 SAMLAssertion getAssertion() {
337                         return assertion;
338                 }
339
340                 String getServiceProviderId() {
341                         return serviceProviderId;
342                 }
343         }
344 }