Check for a null request, which seems to happen if you issue a GET.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / provider / SAMLv1_AttributeQueryHandler.java
1 /*
2  * Copyright [2005] [University Corporation for Advanced Internet Development, Inc.]
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package edu.internet2.middleware.shibboleth.idp.provider;
18
19 import java.io.IOException;
20 import java.net.URI;
21 import java.net.URISyntaxException;
22 import java.security.Principal;
23 import java.security.cert.X509Certificate;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collections;
27 import java.util.Date;
28 import java.util.Iterator;
29
30 import javax.security.auth.x500.X500Principal;
31 import javax.servlet.ServletException;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
34
35 import org.apache.log4j.Logger;
36 import org.opensaml.SAMLAssertion;
37 import org.opensaml.SAMLAttribute;
38 import org.opensaml.SAMLAttributeDesignator;
39 import org.opensaml.SAMLAttributeQuery;
40 import org.opensaml.SAMLAttributeStatement;
41 import org.opensaml.SAMLAudienceRestrictionCondition;
42 import org.opensaml.SAMLCondition;
43 import org.opensaml.SAMLException;
44 import org.opensaml.SAMLNameIdentifier;
45 import org.opensaml.SAMLRequest;
46 import org.opensaml.SAMLResponse;
47 import org.opensaml.SAMLStatement;
48 import org.opensaml.SAMLSubject;
49 import org.opensaml.XML;
50 import org.w3c.dom.Element;
51
52 import edu.internet2.middleware.shibboleth.aa.AAException;
53 import edu.internet2.middleware.shibboleth.common.InvalidNameIdentifierException;
54 import edu.internet2.middleware.shibboleth.common.NameIdentifierMapping;
55 import edu.internet2.middleware.shibboleth.common.NameIdentifierMappingException;
56 import edu.internet2.middleware.shibboleth.common.RelyingParty;
57 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
58 import edu.internet2.middleware.shibboleth.idp.IdPProtocolHandler;
59 import edu.internet2.middleware.shibboleth.idp.IdPProtocolSupport;
60 import edu.internet2.middleware.shibboleth.metadata.AttributeRequesterDescriptor;
61 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
62 import edu.internet2.middleware.shibboleth.metadata.RoleDescriptor;
63 import edu.internet2.middleware.shibboleth.metadata.SPSSODescriptor;
64
65 /**
66  * @author Walter Hoehn
67  */
68 public class SAMLv1_AttributeQueryHandler extends BaseServiceHandler implements IdPProtocolHandler {
69
70         private static Logger log = Logger.getLogger(SAMLv1_AttributeQueryHandler.class.getName());
71
72         /**
73          * Required DOM-based constructor.
74          */
75         public SAMLv1_AttributeQueryHandler(Element config) throws ShibbolethConfigurationException {
76
77                 super(config);
78         }
79
80         /*
81          * @see edu.internet2.middleware.shibboleth.idp.ProtocolHandler#getHandlerName()
82          */
83         public String getHandlerName() {
84
85                 return "SAML v1.1 Attribute Query";
86         }
87
88         private String authenticateAs(String assertedId, X509Certificate[] chain, IdPProtocolSupport support)
89                         throws InvalidProviderCredentialException {
90                 // See if we have metadata for this provider
91                 EntityDescriptor provider = support.lookup(assertedId);
92                 if (provider == null) {
93                         log.info("No metadata found for providerId: (" + assertedId + ").");
94                         return null;
95                 }
96                 else {
97                         log.info("Metadata found for providerId: (" + assertedId + ").");
98                 }
99                 RoleDescriptor ar_role = provider.getAttributeRequesterDescriptor(XML.SAML11_PROTOCOL_ENUM);
100                 RoleDescriptor sp_role = provider.getSPSSODescriptor(XML.SAML11_PROTOCOL_ENUM);
101                 if (ar_role == null && sp_role == null) {
102                         log.info("SPSSO and Stand-Alone Requester roles not found in metadata for provider: ("
103                                         + assertedId + ").");
104                         return null;
105                 }
106
107                 // Make sure that the supplied credential is valid for the selected provider role.
108                 if ((ar_role != null && support.getTrust().validate(chain[0], chain, ar_role)) ||
109                         (sp_role != null &&     support.getTrust().validate(chain[0], chain, sp_role))) {
110                         log.info("Supplied credentials validated for this provider.");
111                         return assertedId;
112                 } else {
113                         log.error("Supplied credentials ("
114                                         + chain[0].getSubjectX500Principal().getName(X500Principal.RFC2253)
115                                         + ") are NOT valid for provider (" + assertedId + ").");
116                         throw new InvalidProviderCredentialException("Invalid credentials.");
117                 }
118         }
119
120         /*
121          * @see edu.internet2.middleware.shibboleth.idp.ProtocolHandler#processRequest(javax.servlet.http.HttpServletRequest,
122          *      javax.servlet.http.HttpServletResponse, org.opensaml.SAMLRequest,
123          *      edu.internet2.middleware.shibboleth.idp.ProtocolSupport)
124          */
125         public SAMLResponse processRequest(HttpServletRequest request, HttpServletResponse response,
126                         SAMLRequest samlRequest, IdPProtocolSupport support) throws SAMLException, IOException, ServletException {
127
128                 if (samlRequest == null || samlRequest.getQuery() == null || !(samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
129                         log.error("Protocol Handler can only respond to SAML Attribute Queries.");
130                         throw new SAMLException("General error processing request.");
131                 }
132
133                 RelyingParty relyingParty = null;
134                 SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
135
136                 // This is the requester name that will be passed to subsystems
137                 String effectiveName = null;
138
139                 // Log the physical credential supplied, if any.
140                 X509Certificate[] credentials = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
141                 if (credentials == null || credentials.length == 0 ||
142                                 credentials[0].getSubjectX500Principal().getName(X500Principal.RFC2253).equals("")) {
143                         log.info("Request contained no credentials, treating as an unauthenticated service provider.");
144                 }
145                 else {
146                         log.info("Request contains credentials: ("
147                                         + credentials[0].getSubjectX500Principal().getName(X500Principal.RFC2253) + ").");
148
149                         // Try and authenticate the requester as any of the potentially relevant identifiers we know.                   
150                         try {
151                                 if (attributeQuery.getResource() != null) {
152                                         log.info("Remote provider has identified itself as: (" + attributeQuery.getResource() + ").");
153                                         effectiveName = authenticateAs(attributeQuery.getResource(), credentials, support);
154                                 }
155
156                                 if (effectiveName == null) {
157                                         log.info("Remote provider not yet identified, attempting to derive requesting provider from credentials.");
158
159                                         // Try the additional candidates.
160                                         String[] candidateNames = getCredentialNames(credentials[0]);
161                                         for (int c = 0; effectiveName == null && c < candidateNames.length; c++) {
162                                                 effectiveName = authenticateAs(candidateNames[c], credentials, support);
163                                         }
164                                 }
165                         } catch (InvalidProviderCredentialException ipc) {
166                                 throw new SAMLException(SAMLException.REQUESTER, "Invalid credentials for request.");
167                         }
168                 }
169                 
170                 if (effectiveName == null) {
171                         log.info("Unable to locate metadata about provider, treating as an unauthenticated service provider.");
172                         log.debug("Using default Relying Party for unauthenticated provider.");
173                         relyingParty = support.getServiceProviderMapper().getRelyingParty(null);
174                 }
175                 else {
176                         // Identify a Relying Party
177                         log.debug("Mapping authenticated provider (" + effectiveName + ") to Relying Party.");
178                         relyingParty = support.getServiceProviderMapper().getRelyingParty(effectiveName);
179                 }
180
181                 // Fail if we can't honor SAML Subject Confirmation unless the only one supplied is
182                 // bearer, in which case this is probably a Shib 1.1 query, and we'll let it slide for now.
183                 // TODO: remove the compatibility with 1.1 and be strict about this?
184                 boolean hasConfirmationMethod = false;
185                 boolean hasOnlyBearer = true;
186                 Iterator iterator = attributeQuery.getSubject().getConfirmationMethods();
187                 while (iterator.hasNext()) {
188                         String method = (String) iterator.next();
189                         log.info("Request contains SAML Subject Confirmation method: (" + method + ").");
190                         hasConfirmationMethod = true;
191                         if (!method.equals(SAMLSubject.CONF_BEARER))
192                                 hasOnlyBearer = false;
193                 }
194                 if (hasConfirmationMethod && !hasOnlyBearer) {
195                         throw new SAMLException(SAMLException.REQUESTER,
196                                 "This SAML authority cannot honor requests containing the supplied SAML Subject Confirmation Method(s).");
197                 }
198
199                 // Map Subject to local principal
200                 Principal principal = null;
201                 try {
202                         SAMLNameIdentifier nameId = attributeQuery.getSubject().getNameIdentifier();
203                         log.debug("Name Identifier format: (" + nameId.getFormat() + ").");
204                         NameIdentifierMapping mapping = null;
205                         try {
206                                 mapping = support.getNameMapper().getNameIdentifierMapping(new URI(nameId.getFormat()));
207                         } catch (URISyntaxException e) {
208                                 log.error("Invalid Name Identifier format.");
209                         }
210                         if (mapping == null) { throw new NameIdentifierMappingException("Name Identifier format not registered."); }
211
212                         // Don't honor the request if the active relying party configuration does not contain a mapping with the
213                         // name identifier format from the request
214                         if (!Arrays.asList(relyingParty.getNameMapperIds()).contains(mapping.getId())) { throw new NameIdentifierMappingException(
215                                         "Name Identifier format not valid for this relying party."); }
216
217                         principal = mapping.getPrincipal(nameId, relyingParty, relyingParty.getIdentityProvider());
218                         log.info("Request is for principal (" + principal.getName() + ").");
219
220                         // Get attributes from resolver
221                         SAMLAttribute[] attrs;
222                         Iterator requestedAttrsIterator = attributeQuery.getDesignators();
223                         if (requestedAttrsIterator.hasNext()) {
224                                 log.info("Request designates specific attributes, resolving this set.");
225                                 ArrayList requestedAttrs = new ArrayList();
226                                 while (requestedAttrsIterator.hasNext()) {
227                                         SAMLAttributeDesignator attribute = (SAMLAttributeDesignator) requestedAttrsIterator.next();
228                                         try {
229                                                 log.debug("Designated attribute: (" + attribute.getName() + ")");
230                                                 requestedAttrs.add(new URI(attribute.getName()));
231                                         } catch (URISyntaxException use) {
232                                                 log.error("Request designated an attribute name that does not conform "
233                                                                 + "to the required URI syntax (" + attribute.getName() + ").  Ignoring this attribute");
234                                         }
235                                 }
236
237                                 attrs = support.getReleaseAttributes(principal, relyingParty, effectiveName, null,
238                                                 (URI[]) requestedAttrs.toArray(new URI[0]));
239                         } else {
240                                 log.info("Request does not designate specific attributes, resolving all available.");
241                                 attrs = support.getReleaseAttributes(principal, relyingParty, effectiveName, null);
242                         }
243
244                         log.info("Found " + attrs.length + " attribute(s) for " + principal.getName());
245
246                         // Put attributes names in the transaction log when it is set to DEBUG
247                         if (support.getTransactionLog().isDebugEnabled() && attrs.length > 0) {
248                                 StringBuffer attrNameBuffer = new StringBuffer();
249                                 for (int i = 0; i < attrs.length; i++) {
250                                         attrNameBuffer.append("(" + attrs[i].getName() + ")");
251                                 }
252                                 support.getTransactionLog()
253                                                 .debug(
254                                                                 "Attribute assertion generated for provider (" + effectiveName
255                                                                                 + ") on behalf of principal (" + principal.getName()
256                                                                                 + ") with the following attributes: " + attrNameBuffer.toString());
257                         }
258
259                         SAMLResponse samlResponse = null;
260
261                         if (attrs == null || attrs.length == 0) {
262                                 // No attribute found
263                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, null, null);
264
265                         } else {
266                                 // Reference requested subject
267                                 SAMLSubject rSubject = (SAMLSubject) attributeQuery.getSubject().clone();
268
269                                 ArrayList audiences = new ArrayList();
270                                 if (relyingParty.getProviderId() != null) {
271                                         audiences.add(relyingParty.getProviderId());
272                                 }
273                                 if (relyingParty.getName() != null && !relyingParty.getName().equals(relyingParty.getProviderId())) {
274                                         audiences.add(relyingParty.getName());
275                                 }
276
277                                 SAMLCondition condition = new SAMLAudienceRestrictionCondition(audiences);
278
279                                 // Put all attributes into an assertion
280                                 SAMLStatement statement = new SAMLAttributeStatement(rSubject, Arrays.asList(attrs));
281
282                                 // Set assertion expiration to longest attribute expiration
283                                 long max = 0;
284                                 for (int i = 0; i < attrs.length; i++) {
285                                         if (max < attrs[i].getLifetime()) {
286                                                 max = attrs[i].getLifetime();
287                                         }
288                                 }
289                                 Date now = new Date();
290                                 Date then = new Date(now.getTime() + (max * 1000)); // max is in
291                                 // seconds
292
293                                 SAMLAssertion sAssertion = new SAMLAssertion(relyingParty.getIdentityProvider().getProviderId(), now,
294                                                 then, Collections.singleton(condition), null, Collections.singleton(statement));
295
296                                 // Sign the assertions, if necessary
297                                 boolean metaDataIndicatesSignAssertions = false;
298                                 EntityDescriptor descriptor = support.lookup(relyingParty.getProviderId());
299                                 if (descriptor != null) {
300                                         AttributeRequesterDescriptor ar = descriptor
301                                                         .getAttributeRequesterDescriptor(org.opensaml.XML.SAML11_PROTOCOL_ENUM);
302                                         if (ar != null) {
303                                                 if (ar.getWantAssertionsSigned()) {
304                                                         metaDataIndicatesSignAssertions = true;
305                                                 }
306                                         }
307                                         if (!metaDataIndicatesSignAssertions) {
308                                                 SPSSODescriptor sp = descriptor.getSPSSODescriptor(org.opensaml.XML.SAML11_PROTOCOL_ENUM);
309                                                 if (sp != null) {
310                                                         if (sp.getWantAssertionsSigned()) {
311                                                                 metaDataIndicatesSignAssertions = true;
312                                                         }
313                                                 }
314                                         }
315                                 }
316                                 if (relyingParty.wantsAssertionsSigned() || metaDataIndicatesSignAssertions) {
317                                         support.signAssertions(new SAMLAssertion[]{sAssertion}, relyingParty);
318                                 }
319
320                                 samlResponse = new SAMLResponse(samlRequest.getId(), null, Collections.singleton(sAssertion), null);
321                         }
322
323                         if (log.isDebugEnabled()) { // This takes some processing, so only do it if we need to
324                                 log.debug("Dumping generated SAML Response:" + System.getProperty("line.separator")
325                                                 + samlResponse.toString());
326                         }
327
328                         log.info("Successfully created response for principal (" + principal.getName() + ").");
329
330                         if (effectiveName == null) {
331                                 support.getTransactionLog().info(
332                                                 "Attribute assertion issued to anonymous provider at (" + request.getRemoteAddr()
333                                                                 + ") on behalf of principal (" + principal.getName() + ").");
334                         } else {
335                                 support.getTransactionLog().info(
336                                                 "Attribute assertion issued to provider (" + effectiveName + ") on behalf of principal ("
337                                                                 + principal.getName() + ").");
338                         }
339
340                         return samlResponse;
341
342                 } catch (SAMLException e) {
343                         if (relyingParty.passThruErrors()) {
344                                 throw new SAMLException("General error processing request.", e);
345                         } else {
346                                 throw new SAMLException("General error processing request.");
347                         }
348
349                 } catch (InvalidNameIdentifierException e) {
350                         log.error("Could not associate the request's subject with a principal: " + e);
351                         if (relyingParty.passThruErrors()) {
352                                 throw new SAMLException(Arrays.asList(e.getSAMLErrorCodes()), "The supplied Subject was unrecognized.",
353                                                 e);
354                         } else {
355                                 throw new SAMLException(Arrays.asList(e.getSAMLErrorCodes()), "The supplied Subject was unrecognized.");
356                         }
357
358                 } catch (NameIdentifierMappingException e) {
359                         log.error("Encountered an error while mapping the name identifier from the request: " + e);
360                         if (relyingParty.passThruErrors()) {
361                                 throw new SAMLException("General error processing request.", e);
362                         } else {
363                                 throw new SAMLException("General error processing request.");
364                         }
365
366                 } catch (AAException e) {
367                         log.error("Encountered an error while resolving resolving attributes: " + e);
368                         if (relyingParty.passThruErrors()) {
369                                 throw new SAMLException("General error processing request.", e);
370                         } else {
371                                 throw new SAMLException("General error processing request.");
372                         }
373
374                 } catch (CloneNotSupportedException e) {
375                         log.error("Encountered an error while cloning request subject for use in response: " + e);
376                         if (relyingParty.passThruErrors()) {
377                                 throw new SAMLException("General error processing request.", e);
378                         } else {
379                                 throw new SAMLException("General error processing request.");
380                         }
381                 }
382         }
383 }