More work fleshing out the protocol handlers.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / provider / SAMLv1_AttributeQueryHandler.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.net.URI;
30 import java.net.URISyntaxException;
31 import java.security.Principal;
32 import java.security.cert.X509Certificate;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.Collections;
36 import java.util.Date;
37 import java.util.Iterator;
38
39 import javax.security.auth.x500.X500Principal;
40 import javax.servlet.ServletException;
41 import javax.servlet.http.HttpServletRequest;
42 import javax.servlet.http.HttpServletResponse;
43
44 import org.apache.log4j.Logger;
45 import org.opensaml.SAMLAssertion;
46 import org.opensaml.SAMLAttribute;
47 import org.opensaml.SAMLAttributeDesignator;
48 import org.opensaml.SAMLAttributeQuery;
49 import org.opensaml.SAMLAttributeStatement;
50 import org.opensaml.SAMLAudienceRestrictionCondition;
51 import org.opensaml.SAMLCondition;
52 import org.opensaml.SAMLException;
53 import org.opensaml.SAMLRequest;
54 import org.opensaml.SAMLResponse;
55 import org.opensaml.SAMLStatement;
56 import org.opensaml.SAMLSubject;
57
58 import sun.misc.BASE64Decoder;
59 import edu.internet2.middleware.shibboleth.aa.AAException;
60 import edu.internet2.middleware.shibboleth.common.InvalidNameIdentifierException;
61 import edu.internet2.middleware.shibboleth.common.NameIdentifierMappingException;
62 import edu.internet2.middleware.shibboleth.common.RelyingParty;
63 import edu.internet2.middleware.shibboleth.common.ShibBrowserProfile;
64 import edu.internet2.middleware.shibboleth.idp.IdPProtocolHandler;
65 import edu.internet2.middleware.shibboleth.idp.IdPProtocolSupport;
66 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
67
68 /**
69  * @author Walter Hoehn
70  */
71 public class SAMLv1_AttributeQueryHandler extends BaseServiceHandler implements IdPProtocolHandler {
72
73         private static Logger log = Logger.getLogger(SAMLv1_AttributeQueryHandler.class.getName());
74
75         /*
76          * @see edu.internet2.middleware.shibboleth.idp.ProtocolHandler#getHandlerName()
77          */
78         public String getHandlerName() {
79
80                 return "SAML v1.1 Attribute Query";
81         }
82
83         private String getEffectiveName(HttpServletRequest req, RelyingParty relyingParty, IdPProtocolSupport support)
84                         throws InvalidProviderCredentialException {
85
86                 X509Certificate credential = getCredentialFromProvider(req);
87
88                 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
89                         log.info("Request is from an unauthenticated service provider.");
90                         return null;
91
92                 } else {
93                         log.info("Request contains credential: ("
94                                         + credential.getSubjectX500Principal().getName(X500Principal.RFC2253) + ").");
95                         // Mockup old requester name for requests from < 1.2 targets
96                         if (fromLegacyProvider(req)) {
97                                 String legacyName = ShibBrowserProfile.getHostNameFromDN(credential.getSubjectX500Principal());
98                                 if (legacyName == null) {
99                                         log.error("Unable to extract legacy requester name from certificate subject.");
100                                 }
101
102                                 log.info("Request from legacy service provider: (" + legacyName + ").");
103                                 return legacyName;
104
105                         } else {
106
107                                 // See if we have metadata for this provider
108                                 EntityDescriptor provider = support.lookup(relyingParty.getProviderId());
109                                 if (provider == null) {
110                                         log.info("No metadata found for provider: (" + relyingParty.getProviderId() + ").");
111                                         log.info("Treating remote provider as unauthenticated.");
112                                         return null;
113                                 }
114
115                                 // Make sure that the suppplied credential is valid for the
116                                 // selected relying party
117                                 if (isValidCredential(provider, credential)) {
118                                         log.info("Supplied credential validated for this provider.");
119                                         log.info("Request from service provider: (" + relyingParty.getProviderId() + ").");
120                                         return relyingParty.getProviderId();
121                                 } else {
122                                         log.error("Supplied credential ("
123                                                         + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
124                                                         + ") is NOT valid for provider (" + relyingParty.getProviderId() + ").");
125                                         throw new InvalidProviderCredentialException("Invalid credential.");
126                                 }
127                         }
128                 }
129         }
130
131         /*
132          * @see edu.internet2.middleware.shibboleth.idp.ProtocolHandler#processRequest(javax.servlet.http.HttpServletRequest,
133          *      javax.servlet.http.HttpServletResponse, org.opensaml.SAMLRequest,
134          *      edu.internet2.middleware.shibboleth.idp.ProtocolSupport)
135          */
136         public SAMLResponse processRequest(HttpServletRequest request, HttpServletResponse response,
137                         SAMLRequest samlRequest, IdPProtocolSupport support) throws SAMLException, IOException, ServletException {
138
139                 if (samlRequest.getQuery() == null || !(samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
140                         log.error("Protocol Handler can only respond to SAML Attribute Queries.");
141                         throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
142                 }
143
144                 RelyingParty relyingParty = null;
145
146                 SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
147
148                 if (!fromLegacyProvider(request)) {
149                         log.info("Remote provider has identified itself as: (" + attributeQuery.getResource() + ").");
150                 }
151
152                 // This is the requester name that will be passed to subsystems
153                 String effectiveName = null;
154
155                 X509Certificate credential = getCredentialFromProvider(request);
156                 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
157                         log.info("Request is from an unauthenticated service provider.");
158                 } else {
159
160                         // Identify a Relying Party
161                         relyingParty = support.getServiceProviderMapper().getRelyingParty(attributeQuery.getResource());
162
163                         try {
164                                 effectiveName = getEffectiveName(request, relyingParty, support);
165                         } catch (InvalidProviderCredentialException ipc) {
166                                 throw new SAMLException(SAMLException.REQUESTER, "Invalid credentials for request.");
167                         }
168                 }
169
170                 if (effectiveName == null) {
171                         log.debug("Using default Relying Party for unauthenticated provider.");
172                         relyingParty = support.getServiceProviderMapper().getRelyingParty(null);
173                 }
174
175                 // Fail if we can't honor SAML Subject Confirmation
176                 if (!fromLegacyProvider(request)) {
177                         Iterator iterator = attributeQuery.getSubject().getConfirmationMethods();
178                         boolean hasConfirmationMethod = false;
179                         while (iterator.hasNext()) {
180                                 log.info("Request contains SAML Subject Confirmation method: (" + (String) iterator.next() + ").");
181                         }
182                         if (hasConfirmationMethod) { throw new SAMLException(SAMLException.REQUESTER,
183                                         "This SAML authority cannot honor requests containing the supplied SAML Subject Confirmation Method."); }
184                 }
185
186                 // Map Subject to local principal
187                 Principal principal;
188                 try {
189                         principal = support.getNameMapper().getPrincipal(attributeQuery.getSubject().getName(), relyingParty,
190                                         relyingParty.getIdentityProvider());
191
192                         log.info("Request is for principal (" + principal.getName() + ").");
193
194                         SAMLAttribute[] attrs;
195                         Iterator requestedAttrsIterator = attributeQuery.getDesignators();
196                         if (requestedAttrsIterator.hasNext()) {
197                                 log.info("Request designates specific attributes, resolving this set.");
198                                 ArrayList requestedAttrs = new ArrayList();
199                                 while (requestedAttrsIterator.hasNext()) {
200                                         SAMLAttributeDesignator attribute = (SAMLAttributeDesignator) requestedAttrsIterator.next();
201                                         try {
202                                                 log.debug("Designated attribute: (" + attribute.getName() + ")");
203                                                 requestedAttrs.add(new URI(attribute.getName()));
204                                         } catch (URISyntaxException use) {
205                                                 log.error("Request designated an attribute name that does not conform "
206                                                                 + "to the required URI syntax (" + attribute.getName() + ").  Ignoring this attribute");
207                                         }
208                                 }
209
210                                 attrs = support.getReleaseAttributes(principal, effectiveName, null, (URI[]) requestedAttrs
211                                                 .toArray(new URI[0]));
212                         } else {
213                                 log.info("Request does not designate specific attributes, resolving all available.");
214                                 attrs = support.getReleaseAttributes(principal, effectiveName, null);
215                         }
216
217                         log.info("Found " + attrs.length + " attribute(s) for " + principal.getName());
218
219                         SAMLResponse samlResponse = null;
220
221                         if (attrs == null || attrs.length == 0) {
222                                 // No attribute found
223                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, null, null);
224
225                         } else {
226                                 // Reference requested subject
227                                 SAMLSubject rSubject = (SAMLSubject) attributeQuery.getSubject().clone();
228
229                                 ArrayList audiences = new ArrayList();
230                                 if (relyingParty.getProviderId() != null) {
231                                         audiences.add(relyingParty.getProviderId());
232                                 }
233                                 if (relyingParty.getName() != null && !relyingParty.getName().equals(relyingParty.getProviderId())) {
234                                         audiences.add(relyingParty.getName());
235                                 }
236                                 SAMLCondition condition = new SAMLAudienceRestrictionCondition(audiences);
237
238                                 // Put all attributes into an assertion
239                                 SAMLStatement statement = new SAMLAttributeStatement(rSubject, Arrays.asList(attrs));
240
241                                 // Set assertion expiration to longest attribute expiration
242                                 long max = 0;
243                                 for (int i = 0; i < attrs.length; i++) {
244                                         if (max < attrs[i].getLifetime()) {
245                                                 max = attrs[i].getLifetime();
246                                         }
247                                 }
248                                 Date now = new Date();
249                                 Date then = new Date(now.getTime() + (max * 1000)); // max is in
250                                 // seconds
251
252                                 SAMLAssertion sAssertion = new SAMLAssertion(relyingParty.getIdentityProvider().getProviderId(), now,
253                                                 then, Collections.singleton(condition), null, Collections.singleton(statement));
254
255                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, Collections.singleton(sAssertion), null);
256                                 IdPProtocolSupport.addSignatures(samlResponse, relyingParty, support.lookup(relyingParty
257                                                 .getProviderId()), false);
258                         }
259
260                         if (log.isDebugEnabled()) { // This takes some processing, so only do it if we need to
261                                 try {
262                                         log.debug("Dumping generated SAML Response:"
263                                                         + System.getProperty("line.separator")
264                                                         + new String(
265                                                                         new BASE64Decoder().decodeBuffer(new String(samlResponse.toBase64(), "ASCII")),
266                                                                         "UTF8"));
267                                 } catch (SAMLException e) {
268                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
269                                 } catch (IOException e) {
270                                         log.error("Encountered an error while decoding SAMLReponse for logging purposes.");
271                                 }
272                         }
273
274                         log.info("Successfully created response for principal (" + principal.getName() + ").");
275
276                         if (effectiveName == null) {
277                                 if (fromLegacyProvider(request)) {
278                                         support.getTransactionLog().info(
279                                                         "Attribute assertion issued to anonymous legacy provider at (" + request.getRemoteAddr()
280                                                                         + ") on behalf of principal (" + principal.getName() + ").");
281                                 } else {
282                                         support.getTransactionLog().info(
283                                                         "Attribute assertion issued to anonymous provider at (" + request.getRemoteAddr()
284                                                                         + ") on behalf of principal (" + principal.getName() + ").");
285                                 }
286                         } else {
287                                 if (fromLegacyProvider(request)) {
288                                         support.getTransactionLog().info(
289                                                         "Attribute assertion issued to legacy provider (" + effectiveName
290                                                                         + ") on behalf of principal (" + principal.getName() + ").");
291                                 } else {
292                                         support.getTransactionLog().info(
293                                                         "Attribute assertion issued to provider (" + effectiveName + ") on behalf of principal ("
294                                                                         + principal.getName() + ").");
295                                 }
296                         }
297
298                         return samlResponse;
299
300                 } catch (SAMLException e) {
301                         if (relyingParty.passThruErrors()) {
302                                 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.", e);
303                         } else {
304                                 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
305                         }
306
307                 } catch (InvalidNameIdentifierException e) {
308                         log.error("Could not associate the request's subject with a principal: " + e);
309                         if (relyingParty.passThruErrors()) {
310                                 throw new SAMLException(Arrays.asList(e.getSAMLErrorCodes()), "The supplied Subject was unrecognized.",
311                                                 e);
312                         } else {
313                                 throw new SAMLException(Arrays.asList(e.getSAMLErrorCodes()), "The supplied Subject was unrecognized.");
314                         }
315
316                 } catch (NameIdentifierMappingException e) {
317                         log.error("Encountered an error while mapping the name identifier from the request: " + e);
318                         if (relyingParty.passThruErrors()) {
319                                 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.", e);
320                         } else {
321                                 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
322                         }
323
324                 } catch (AAException e) {
325                         log.error("Encountered an error while resolving resolving attributes: " + e);
326                         if (relyingParty.passThruErrors()) {
327                                 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.", e);
328                         } else {
329                                 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
330                         }
331
332                 } catch (CloneNotSupportedException e) {
333                         log.error("Encountered an error while cloning request subject for use in response: " + e);
334                         if (relyingParty.passThruErrors()) {
335                                 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.", e);
336                         } else {
337                                 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
338                         }
339                 }
340         }
341
342         private static boolean fromLegacyProvider(HttpServletRequest request) {
343
344                 String version = request.getHeader("Shibboleth");
345                 if (version != null) {
346                         log.debug("Request from Shibboleth version: " + version);
347                         return false;
348                 }
349                 log.debug("No version header found.");
350                 return true;
351         }
352
353 }