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