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.
26 package edu.internet2.middleware.shibboleth.idp.provider;
28 import java.io.IOException;
29 import java.net.MalformedURLException;
31 import java.net.URISyntaxException;
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;
41 import javax.security.auth.x500.X500Principal;
42 import javax.servlet.ServletException;
43 import javax.servlet.http.HttpServletRequest;
44 import javax.servlet.http.HttpServletResponse;
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;
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.AttributeRequesterDescriptor;
71 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
72 import edu.internet2.middleware.shibboleth.metadata.RoleDescriptor;
73 import edu.internet2.middleware.shibboleth.metadata.SPSSODescriptor;
76 * @author Walter Hoehn
78 public class SAMLv1_AttributeQueryHandler extends BaseServiceHandler implements IdPProtocolHandler {
80 private static Logger log = Logger.getLogger(SAMLv1_AttributeQueryHandler.class.getName());
83 * Required DOM-based constructor.
85 public SAMLv1_AttributeQueryHandler(Element config) throws ShibbolethConfigurationException {
91 * @see edu.internet2.middleware.shibboleth.idp.ProtocolHandler#getHandlerName()
93 public String getHandlerName() {
95 return "SAML v1.1 Attribute Query";
98 private String getEffectiveName(HttpServletRequest req, RelyingParty relyingParty, IdPProtocolSupport support)
99 throws InvalidProviderCredentialException {
101 X509Certificate credential = getCredentialFromProvider(req);
103 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
104 log.info("Request is from an unauthenticated service provider.");
108 log.info("Request contains credential: ("
109 + credential.getSubjectX500Principal().getName(X500Principal.RFC2253) + ").");
110 // Mockup old requester name for requests from < 1.2 SPs
111 if (fromLegacyProvider(req)) {
112 String legacyName = getHostNameFromDN(credential.getSubjectX500Principal());
113 if (legacyName == null) {
114 log.error("Unable to extract legacy requester name from certificate subject.");
117 log.info("Request from legacy service provider: (" + legacyName + ").");
122 // See if we have metadata for this provider
123 EntityDescriptor provider = support.lookup(relyingParty.getProviderId());
124 if (provider == null) {
125 log.info("No metadata found for provider: (" + relyingParty.getProviderId() + ").");
126 log.info("Treating remote provider as unauthenticated.");
129 RoleDescriptor ar_role = provider.getAttributeRequesterDescriptor("urn:oasis:names:tc:SAML:1.1:protocol");
130 RoleDescriptor sp_role = provider.getSPSSODescriptor("urn:oasis:names:tc:SAML:1.1:protocol");
131 if (ar_role == null && sp_role == null) {
132 log.info("SPSSO and Stand-Alone Requester roles not found in metadata for provider: (" + relyingParty.getProviderId() + ").");
133 log.info("Treating remote provider as unauthenticated.");
137 // Make sure that the suppplied credential is valid for the
138 // selected relying party
139 X509Certificate[] chain = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
140 if (support.getTrust().validate((chain != null && chain.length > 0) ? chain[0] : null, chain, ar_role) ||
141 support.getTrust().validate((chain != null && chain.length > 0) ? chain[0] : null, chain, sp_role)) {
142 log.info("Supplied credential validated for this provider.");
143 log.info("Request from service provider: (" + relyingParty.getProviderId() + ").");
144 return relyingParty.getProviderId();
147 log.error("Supplied credential ("
148 + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
149 + ") is NOT valid for provider (" + relyingParty.getProviderId() + ").");
150 throw new InvalidProviderCredentialException("Invalid credential.");
157 * @see edu.internet2.middleware.shibboleth.idp.ProtocolHandler#processRequest(javax.servlet.http.HttpServletRequest,
158 * javax.servlet.http.HttpServletResponse, org.opensaml.SAMLRequest,
159 * edu.internet2.middleware.shibboleth.idp.ProtocolSupport)
161 public SAMLResponse processRequest(HttpServletRequest request, HttpServletResponse response,
162 SAMLRequest samlRequest, IdPProtocolSupport support) throws SAMLException, IOException, ServletException {
164 if (samlRequest.getQuery() == null || !(samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
165 log.error("Protocol Handler can only respond to SAML Attribute Queries.");
166 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
169 RelyingParty relyingParty = null;
171 SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
173 if (!fromLegacyProvider(request)) {
174 log.info("Remote provider has identified itself as: (" + attributeQuery.getResource() + ").");
177 // This is the requester name that will be passed to subsystems
178 String effectiveName = null;
180 X509Certificate credential = getCredentialFromProvider(request);
181 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
182 log.info("Request is from an unauthenticated service provider.");
185 // Identify a Relying Party
186 relyingParty = support.getServiceProviderMapper().getRelyingParty(attributeQuery.getResource());
189 effectiveName = getEffectiveName(request, relyingParty, support);
190 } catch (InvalidProviderCredentialException ipc) {
191 throw new SAMLException(SAMLException.REQUESTER, "Invalid credentials for request.");
195 if (effectiveName == null) {
196 log.debug("Using default Relying Party for unauthenticated provider.");
197 relyingParty = support.getServiceProviderMapper().getRelyingParty(null);
200 // Fail if we can't honor SAML Subject Confirmation
201 if (!fromLegacyProvider(request)) {
202 Iterator iterator = attributeQuery.getSubject().getConfirmationMethods();
203 boolean hasConfirmationMethod = false;
204 while (iterator.hasNext()) {
205 log.info("Request contains SAML Subject Confirmation method: (" + (String) iterator.next() + ").");
207 if (hasConfirmationMethod) { throw new SAMLException(SAMLException.REQUESTER,
208 "This SAML authority cannot honor requests containing the supplied SAML Subject Confirmation Method."); }
211 // Map Subject to local principal
212 Principal principal = null;
214 SAMLNameIdentifier nameId = attributeQuery.getSubject().getNameIdentifier();
215 log.debug("Name Identifier format: (" + nameId.getFormat() + ").");
216 NameIdentifierMapping mapping = null;
218 mapping = support.getNameMapper().getNameIdentifierMapping(new URI(nameId.getFormat()));
219 } catch (URISyntaxException e) {
220 log.error("Invalid Name Identifier format.");
222 if (mapping == null) { throw new NameIdentifierMappingException("Name Identifier format not registered."); }
224 // Don't honor the request if the active relying party configuration does not contain a mapping with the
225 // name identifier format from the request
226 if (!Arrays.asList(relyingParty.getNameMapperIds()).contains(mapping.getId())) { throw new NameIdentifierMappingException(
227 "Name Identifier format not valid for this relying party."); }
229 principal = mapping.getPrincipal(nameId, relyingParty, relyingParty.getIdentityProvider());
230 log.info("Request is for principal (" + principal.getName() + ").");
233 if (fromLegacyProvider(request)) {
235 resource = new URL(attributeQuery.getResource());
236 } catch (MalformedURLException mue) {
237 log.error("Request from legacy provider contained an improperly formatted resource "
238 + "identifier. Attempting to handle request without one.");
242 // Get attributes from resolver
243 SAMLAttribute[] attrs;
244 Iterator requestedAttrsIterator = attributeQuery.getDesignators();
245 if (requestedAttrsIterator.hasNext()) {
246 log.info("Request designates specific attributes, resolving this set.");
247 ArrayList requestedAttrs = new ArrayList();
248 while (requestedAttrsIterator.hasNext()) {
249 SAMLAttributeDesignator attribute = (SAMLAttributeDesignator) requestedAttrsIterator.next();
251 log.debug("Designated attribute: (" + attribute.getName() + ")");
252 requestedAttrs.add(new URI(attribute.getName()));
253 } catch (URISyntaxException use) {
254 log.error("Request designated an attribute name that does not conform "
255 + "to the required URI syntax (" + attribute.getName() + "). Ignoring this attribute");
259 attrs = support.getReleaseAttributes(principal, relyingParty, effectiveName, resource,
260 (URI[]) requestedAttrs.toArray(new URI[0]));
262 log.info("Request does not designate specific attributes, resolving all available.");
263 attrs = support.getReleaseAttributes(principal, relyingParty, effectiveName, resource);
266 log.info("Found " + attrs.length + " attribute(s) for " + principal.getName());
268 // Put attributes names in the transaction log when it is set to DEBUG
269 if (support.getTransactionLog().isDebugEnabled() && attrs.length > 0) {
270 StringBuffer attrNameBuffer = new StringBuffer();
271 for (int i = 0; i < attrs.length; i++) {
272 attrNameBuffer.append("(" + attrs[i].getName() + ")");
274 support.getTransactionLog()
276 "Attribute assertion generated for provider (" + effectiveName
277 + ") on behalf of principal (" + principal.getName()
278 + ") with the following attributes: " + attrNameBuffer.toString());
281 SAMLResponse samlResponse = null;
283 if (attrs == null || attrs.length == 0) {
284 // No attribute found
285 samlResponse = new SAMLResponse(samlRequest.getId(), null, null, null);
288 // Reference requested subject
289 SAMLSubject rSubject = (SAMLSubject) attributeQuery.getSubject().clone();
291 ArrayList audiences = new ArrayList();
292 if (relyingParty.getProviderId() != null) {
293 audiences.add(relyingParty.getProviderId());
295 if (relyingParty.getName() != null && !relyingParty.getName().equals(relyingParty.getProviderId())) {
296 audiences.add(relyingParty.getName());
298 //String remoteProviderId = request.getParameter("providerId");
299 if (attributeQuery.getResource() != null && !attributeQuery.getResource().equals("") && !audiences.contains(attributeQuery.getResource())) {
300 audiences.add(attributeQuery.getResource());
303 SAMLCondition condition = new SAMLAudienceRestrictionCondition(audiences);
305 // Put all attributes into an assertion
306 SAMLStatement statement = new SAMLAttributeStatement(rSubject, Arrays.asList(attrs));
308 // Set assertion expiration to longest attribute expiration
310 for (int i = 0; i < attrs.length; i++) {
311 if (max < attrs[i].getLifetime()) {
312 max = attrs[i].getLifetime();
315 Date now = new Date();
316 Date then = new Date(now.getTime() + (max * 1000)); // max is in
319 SAMLAssertion sAssertion = new SAMLAssertion(relyingParty.getIdentityProvider().getProviderId(), now,
320 then, Collections.singleton(condition), null, Collections.singleton(statement));
322 // Sign the assertions, if necessary
323 boolean metaDataIndicatesSignAssertions = false;
324 EntityDescriptor descriptor = support.lookup(relyingParty.getProviderId());
325 if (descriptor != null) {
326 AttributeRequesterDescriptor ar = descriptor.getAttributeRequesterDescriptor(org.opensaml.XML.SAML11_PROTOCOL_ENUM);
328 if (ar.getWantAssertionsSigned()) {
329 metaDataIndicatesSignAssertions = true;
332 if (!metaDataIndicatesSignAssertions) {
333 SPSSODescriptor sp = descriptor.getSPSSODescriptor(org.opensaml.XML.SAML11_PROTOCOL_ENUM);
335 if (sp.getWantAssertionsSigned()) {
336 metaDataIndicatesSignAssertions = true;
341 if (relyingParty.wantsAssertionsSigned() || metaDataIndicatesSignAssertions) {
342 support.signAssertions(new SAMLAssertion[]{sAssertion}, relyingParty);
345 samlResponse = new SAMLResponse(samlRequest.getId(), null, Collections.singleton(sAssertion), null);
348 if (log.isDebugEnabled()) { // This takes some processing, so only do it if we need to
349 log.debug("Dumping generated SAML Response:" + System.getProperty("line.separator")
350 + samlResponse.toString());
353 log.info("Successfully created response for principal (" + principal.getName() + ").");
355 if (effectiveName == null) {
356 if (fromLegacyProvider(request)) {
357 support.getTransactionLog().info(
358 "Attribute assertion issued to anonymous legacy provider at (" + request.getRemoteAddr()
359 + ") on behalf of principal (" + principal.getName() + ").");
361 support.getTransactionLog().info(
362 "Attribute assertion issued to anonymous provider at (" + request.getRemoteAddr()
363 + ") on behalf of principal (" + principal.getName() + ").");
366 if (fromLegacyProvider(request)) {
367 support.getTransactionLog().info(
368 "Attribute assertion issued to legacy provider (" + effectiveName
369 + ") on behalf of principal (" + principal.getName() + ").");
371 support.getTransactionLog().info(
372 "Attribute assertion issued to provider (" + effectiveName + ") on behalf of principal ("
373 + principal.getName() + ").");
379 } catch (SAMLException e) {
380 if (relyingParty.passThruErrors()) {
381 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.", e);
383 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
386 } catch (InvalidNameIdentifierException e) {
387 log.error("Could not associate the request's subject with a principal: " + e);
388 if (relyingParty.passThruErrors()) {
389 throw new SAMLException(Arrays.asList(e.getSAMLErrorCodes()), "The supplied Subject was unrecognized.",
392 throw new SAMLException(Arrays.asList(e.getSAMLErrorCodes()), "The supplied Subject was unrecognized.");
395 } catch (NameIdentifierMappingException e) {
396 log.error("Encountered an error while mapping the name identifier from the request: " + e);
397 if (relyingParty.passThruErrors()) {
398 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.", e);
400 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
403 } catch (AAException e) {
404 log.error("Encountered an error while resolving resolving attributes: " + e);
405 if (relyingParty.passThruErrors()) {
406 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.", e);
408 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
411 } catch (CloneNotSupportedException e) {
412 log.error("Encountered an error while cloning request subject for use in response: " + e);
413 if (relyingParty.passThruErrors()) {
414 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.", e);
416 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
421 private static boolean fromLegacyProvider(HttpServletRequest request) {
423 String version = request.getHeader("Shibboleth");
424 if (version != null) {
425 log.debug("Request from Shibboleth version: " + version);
428 log.debug("No version header found.");