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