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