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