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;
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;
39 import javax.security.auth.x500.X500Principal;
40 import javax.servlet.ServletException;
41 import javax.servlet.http.HttpServletRequest;
42 import javax.servlet.http.HttpServletResponse;
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 import org.w3c.dom.Element;
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.ShibbolethConfigurationException;
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 import edu.internet2.middleware.shibboleth.metadata.KeyDescriptor;
68 import edu.internet2.middleware.shibboleth.metadata.RoleDescriptor;
69 import edu.internet2.middleware.shibboleth.metadata.SPSSODescriptor;
72 * @author Walter Hoehn
74 public class SAMLv1_AttributeQueryHandler extends BaseServiceHandler implements IdPProtocolHandler {
76 private static Logger log = Logger.getLogger(SAMLv1_AttributeQueryHandler.class.getName());
79 * Required DOM-based constructor.
81 public SAMLv1_AttributeQueryHandler(Element config) throws ShibbolethConfigurationException {
87 * @see edu.internet2.middleware.shibboleth.idp.ProtocolHandler#getHandlerName()
89 public String getHandlerName() {
91 return "SAML v1.1 Attribute Query";
94 private String getEffectiveName(HttpServletRequest req, RelyingParty relyingParty, IdPProtocolSupport support)
95 throws InvalidProviderCredentialException {
97 X509Certificate credential = getCredentialFromProvider(req);
99 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
100 log.info("Request is from an unauthenticated service provider.");
104 log.info("Request contains credential: ("
105 + credential.getSubjectX500Principal().getName(X500Principal.RFC2253) + ").");
106 // Mockup old requester name for requests from < 1.2 targets
107 if (fromLegacyProvider(req)) {
108 String legacyName = getHostNameFromDN(credential.getSubjectX500Principal());
109 if (legacyName == null) {
110 log.error("Unable to extract legacy requester name from certificate subject.");
113 log.info("Request from legacy service provider: (" + legacyName + ").");
118 // See if we have metadata for this provider
119 EntityDescriptor provider = support.lookup(relyingParty.getProviderId());
120 if (provider == null) {
121 log.info("No metadata found for provider: (" + relyingParty.getProviderId() + ").");
122 log.info("Treating remote provider as unauthenticated.");
125 RoleDescriptor role = provider.getSPSSODescriptor("urn:oasis:names:tc:SAML:1.1:protocol");
127 log.info("SPSSO role not found in metadata for provider: (" + relyingParty.getProviderId() + ").");
128 log.info("Treating remote provider as unauthenticated.");
132 // Make sure that the suppplied credential is valid for the
133 // selected relying party
134 X509Certificate[] chain = (X509Certificate[])req.getAttribute("javax.servlet.request.X509Certificate");
135 if (support.getTrust().validate((chain != null && chain.length > 0) ? chain[0] : null, chain, role)) {
136 log.info("Supplied credential validated for this provider.");
137 log.info("Request from service provider: (" + relyingParty.getProviderId() + ").");
138 return relyingParty.getProviderId();
141 log.error("Supplied credential ("
142 + credential.getSubjectX500Principal().getName(X500Principal.RFC2253)
143 + ") is NOT valid for provider (" + relyingParty.getProviderId() + ").");
144 throw new InvalidProviderCredentialException("Invalid credential.");
151 * @see edu.internet2.middleware.shibboleth.idp.ProtocolHandler#processRequest(javax.servlet.http.HttpServletRequest,
152 * javax.servlet.http.HttpServletResponse, org.opensaml.SAMLRequest,
153 * edu.internet2.middleware.shibboleth.idp.ProtocolSupport)
155 public SAMLResponse processRequest(HttpServletRequest request, HttpServletResponse response,
156 SAMLRequest samlRequest, IdPProtocolSupport support) throws SAMLException, IOException, ServletException {
158 if (samlRequest.getQuery() == null || !(samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
159 log.error("Protocol Handler can only respond to SAML Attribute Queries.");
160 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
163 RelyingParty relyingParty = null;
165 SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
167 if (!fromLegacyProvider(request)) {
168 log.info("Remote provider has identified itself as: (" + attributeQuery.getResource() + ").");
171 // This is the requester name that will be passed to subsystems
172 String effectiveName = null;
174 X509Certificate credential = getCredentialFromProvider(request);
175 if (credential == null || credential.getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
176 log.info("Request is from an unauthenticated service provider.");
179 // Identify a Relying Party
180 relyingParty = support.getServiceProviderMapper().getRelyingParty(attributeQuery.getResource());
183 effectiveName = getEffectiveName(request, relyingParty, support);
184 } catch (InvalidProviderCredentialException ipc) {
185 throw new SAMLException(SAMLException.REQUESTER, "Invalid credentials for request.");
189 if (effectiveName == null) {
190 log.debug("Using default Relying Party for unauthenticated provider.");
191 relyingParty = support.getServiceProviderMapper().getRelyingParty(null);
194 // Fail if we can't honor SAML Subject Confirmation
195 if (!fromLegacyProvider(request)) {
196 Iterator iterator = attributeQuery.getSubject().getConfirmationMethods();
197 boolean hasConfirmationMethod = false;
198 while (iterator.hasNext()) {
199 log.info("Request contains SAML Subject Confirmation method: (" + (String) iterator.next() + ").");
201 if (hasConfirmationMethod) { throw new SAMLException(SAMLException.REQUESTER,
202 "This SAML authority cannot honor requests containing the supplied SAML Subject Confirmation Method."); }
205 // Map Subject to local principal
208 principal = support.getNameMapper().getPrincipal(attributeQuery.getSubject().getNameIdentifier(), relyingParty,
209 relyingParty.getIdentityProvider());
211 log.info("Request is for principal (" + principal.getName() + ").");
213 SAMLAttribute[] attrs;
214 Iterator requestedAttrsIterator = attributeQuery.getDesignators();
215 if (requestedAttrsIterator.hasNext()) {
216 log.info("Request designates specific attributes, resolving this set.");
217 ArrayList requestedAttrs = new ArrayList();
218 while (requestedAttrsIterator.hasNext()) {
219 SAMLAttributeDesignator attribute = (SAMLAttributeDesignator) requestedAttrsIterator.next();
221 log.debug("Designated attribute: (" + attribute.getName() + ")");
222 requestedAttrs.add(new URI(attribute.getName()));
223 } catch (URISyntaxException use) {
224 log.error("Request designated an attribute name that does not conform "
225 + "to the required URI syntax (" + attribute.getName() + "). Ignoring this attribute");
229 attrs = support.getReleaseAttributes(principal, effectiveName, null, (URI[]) requestedAttrs
230 .toArray(new URI[0]));
232 log.info("Request does not designate specific attributes, resolving all available.");
233 attrs = support.getReleaseAttributes(principal, effectiveName, null);
236 log.info("Found " + attrs.length + " attribute(s) for " + principal.getName());
238 SAMLResponse samlResponse = null;
240 if (attrs == null || attrs.length == 0) {
241 // No attribute found
242 samlResponse = new SAMLResponse(samlRequest.getId(), null, null, null);
245 // Reference requested subject
246 SAMLSubject rSubject = (SAMLSubject) attributeQuery.getSubject().clone();
248 ArrayList audiences = new ArrayList();
249 if (relyingParty.getProviderId() != null) {
250 audiences.add(relyingParty.getProviderId());
252 if (relyingParty.getName() != null && !relyingParty.getName().equals(relyingParty.getProviderId())) {
253 audiences.add(relyingParty.getName());
255 SAMLCondition condition = new SAMLAudienceRestrictionCondition(audiences);
257 // Put all attributes into an assertion
258 SAMLStatement statement = new SAMLAttributeStatement(rSubject, Arrays.asList(attrs));
260 // Set assertion expiration to longest attribute expiration
262 for (int i = 0; i < attrs.length; i++) {
263 if (max < attrs[i].getLifetime()) {
264 max = attrs[i].getLifetime();
267 Date now = new Date();
268 Date then = new Date(now.getTime() + (max * 1000)); // max is in
271 SAMLAssertion sAssertion = new SAMLAssertion(relyingParty.getIdentityProvider().getProviderId(), now,
272 then, Collections.singleton(condition), null, Collections.singleton(statement));
274 // Sign the assertions, if necessary
275 boolean metaDataIndicatesSignAssertions = false;
276 EntityDescriptor descriptor = support.lookup(relyingParty.getProviderId());
277 if (descriptor != null) {
278 SPSSODescriptor sp = descriptor.getSPSSODescriptor(org.opensaml.XML.SAML11_PROTOCOL_ENUM);
280 if (sp.getWantAssertionsSigned()) {
281 metaDataIndicatesSignAssertions = true;
285 if (relyingParty.wantsAssertionsSigned() || metaDataIndicatesSignAssertions) {
286 support.signAssertions(new SAMLAssertion[]{sAssertion}, relyingParty);
289 samlResponse = new SAMLResponse(samlRequest.getId(), null, Collections.singleton(sAssertion), null);
292 if (log.isDebugEnabled()) { // This takes some processing, so only do it if we need to
293 log.debug("Dumping generated SAML Response:" + System.getProperty("line.separator")
294 + samlResponse.toString());
297 log.info("Successfully created response for principal (" + principal.getName() + ").");
299 if (effectiveName == null) {
300 if (fromLegacyProvider(request)) {
301 support.getTransactionLog().info(
302 "Attribute assertion issued to anonymous legacy provider at (" + request.getRemoteAddr()
303 + ") on behalf of principal (" + principal.getName() + ").");
305 support.getTransactionLog().info(
306 "Attribute assertion issued to anonymous provider at (" + request.getRemoteAddr()
307 + ") on behalf of principal (" + principal.getName() + ").");
310 if (fromLegacyProvider(request)) {
311 support.getTransactionLog().info(
312 "Attribute assertion issued to legacy provider (" + effectiveName
313 + ") on behalf of principal (" + principal.getName() + ").");
315 support.getTransactionLog().info(
316 "Attribute assertion issued to provider (" + effectiveName + ") on behalf of principal ("
317 + principal.getName() + ").");
323 } catch (SAMLException e) {
324 if (relyingParty.passThruErrors()) {
325 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.", e);
327 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
330 } catch (InvalidNameIdentifierException e) {
331 log.error("Could not associate the request's subject with a principal: " + e);
332 if (relyingParty.passThruErrors()) {
333 throw new SAMLException(Arrays.asList(e.getSAMLErrorCodes()), "The supplied Subject was unrecognized.",
336 throw new SAMLException(Arrays.asList(e.getSAMLErrorCodes()), "The supplied Subject was unrecognized.");
339 } catch (NameIdentifierMappingException e) {
340 log.error("Encountered an error while mapping the name identifier from the request: " + e);
341 if (relyingParty.passThruErrors()) {
342 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.", e);
344 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
347 } catch (AAException e) {
348 log.error("Encountered an error while resolving resolving attributes: " + e);
349 if (relyingParty.passThruErrors()) {
350 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.", e);
352 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
355 } catch (CloneNotSupportedException e) {
356 log.error("Encountered an error while cloning request subject for use in response: " + e);
357 if (relyingParty.passThruErrors()) {
358 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.", e);
360 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
365 private static boolean fromLegacyProvider(HttpServletRequest request) {
367 String version = request.getHeader("Shibboleth");
368 if (version != null) {
369 log.debug("Request from Shibboleth version: " + version);
372 log.debug("No version header found.");