Fixed NullPointer on requests for which no metadata exists.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / provider / SSOHandler.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.text.ParseException;
29 import java.text.SimpleDateFormat;
30 import java.util.Date;
31 import java.util.Iterator;
32
33 import javax.servlet.http.HttpServletRequest;
34
35 import org.apache.log4j.Logger;
36 import org.opensaml.SAMLException;
37 import org.opensaml.SAMLNameIdentifier;
38 import org.w3c.dom.Element;
39
40 import edu.internet2.middleware.shibboleth.common.LocalPrincipal;
41 import edu.internet2.middleware.shibboleth.common.NameIdentifierMapping;
42 import edu.internet2.middleware.shibboleth.common.NameIdentifierMappingException;
43 import edu.internet2.middleware.shibboleth.common.NameMapper;
44 import edu.internet2.middleware.shibboleth.common.RelyingParty;
45 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
46 import edu.internet2.middleware.shibboleth.idp.IdPProtocolHandler;
47 import edu.internet2.middleware.shibboleth.idp.InvalidClientDataException;
48 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
49 import edu.internet2.middleware.shibboleth.metadata.SPSSODescriptor;
50
51 /**
52  * @author Walter Hoehn
53  */
54 public abstract class SSOHandler extends BaseHandler implements IdPProtocolHandler {
55
56         private static Logger log = Logger.getLogger(BaseHandler.class.getName());
57
58         /**
59          * Required DOM-based constructor.
60          */
61         public SSOHandler(Element config) throws ShibbolethConfigurationException {
62
63                 super(config);
64
65         }
66
67         public static void validateEngineData(HttpServletRequest req) throws InvalidClientDataException {
68
69                 if ((req.getRemoteAddr() == null) || (req.getRemoteAddr().equals(""))) { throw new InvalidClientDataException(
70                                 "Unable to obtain client address."); }
71         }
72
73         protected Date getAuthNTime(HttpServletRequest request) throws SAMLException {
74
75                 // Determine, if possible, when the authentication actually happened
76                 String suppliedAuthNInstant = request.getHeader("SAMLAuthenticationInstant");
77                 if (suppliedAuthNInstant != null && !suppliedAuthNInstant.equals("")) {
78                         try {
79                                 return new SimpleDateFormat().parse(suppliedAuthNInstant);
80                         } catch (ParseException e) {
81                                 log.error("An error was encountered while receiving authentication "
82                                                 + "instant from authentication mechanism: " + e);
83                                 throw new SAMLException(SAMLException.RESPONDER, "General error processing request.");
84                         }
85                 } else {
86                         return new Date(System.currentTimeMillis());
87                 }
88         }
89
90         /**
91          * Constructs a SAML Name Identifier of a given principal that is most appropriate to the relying party.
92          * 
93          * @param mapper
94          *            name mapping facility
95          * @param principal
96          *            the principal represented by the name identifier
97          * @param relyingParty
98          *            the party that will consume the name identifier
99          * @param descriptor
100          *            metadata descriptor for the party that will consume the name identifier
101          * @return the SAML Name identifier
102          * @throws NameIdentifierMappingException
103          *             if a name identifier could not be created
104          */
105         protected SAMLNameIdentifier getNameIdentifier(NameMapper mapper, LocalPrincipal principal,
106                         RelyingParty relyingParty, EntityDescriptor descriptor) throws NameIdentifierMappingException {
107
108                 String[] availableMappings = relyingParty.getNameMapperIds();
109
110                 // If we have preferred Name Identifier formats from the metadata, see if the we can find one that is configured
111                 // for this relying party
112                 SPSSODescriptor role;
113                 if (descriptor != null
114                                 && (role = descriptor.getSPSSODescriptor("urn:oasis:names:tc:SAML:1.1:protocol")) != null) {
115                         Iterator spPreferredFormats = role.getNameIDFormats();
116                         while (spPreferredFormats.hasNext()) {
117
118                                 String preferredFormat = (String) spPreferredFormats.next();
119                                 for (int i = 0; availableMappings != null && i < availableMappings.length; i++) {
120                                         NameIdentifierMapping mapping = mapper.getNameIdentifierMappingById(availableMappings[i]);
121                                         if (mapping != null && preferredFormat.equals(mapping.getNameIdentifierFormat().toString())) {
122                                                 log.debug("Found a supported name identifier format that "
123                                                                 + "matches the metadata for the relying party: ("
124                                                                 + mapping.getNameIdentifierFormat().toString() + ").");
125                                                 return mapping.getNameIdentifier(principal, relyingParty, relyingParty.getIdentityProvider());
126                                         }
127                                 }
128                         }
129                 }
130
131                 // If we didn't find any matches, then just use the default for the relying party
132                 String defaultNameMapping = null;
133                 if (availableMappings != null && availableMappings.length > 0) {
134                         defaultNameMapping = availableMappings[0];
135                 }
136                 SAMLNameIdentifier nameId = mapper.getNameIdentifier(defaultNameMapping, principal, relyingParty, relyingParty
137                                 .getIdentityProvider());
138                 log.debug("Using the default name identifier format for this relying party: (" + nameId.getFormat());
139                 return nameId;
140         }
141 }