Small refactoring.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / IdPProtocolSupport.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;
27
28 import java.net.URI;
29 import java.net.URL;
30 import java.security.Principal;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Iterator;
34
35 import org.apache.log4j.Logger;
36 import org.apache.xml.security.signature.XMLSignature;
37 import org.opensaml.InvalidCryptoException;
38 import org.opensaml.SAMLAssertion;
39 import org.opensaml.SAMLAttribute;
40 import org.opensaml.SAMLException;
41 import org.opensaml.SAMLResponse;
42 import org.opensaml.artifact.Artifact;
43 import org.w3c.dom.Element;
44
45 import edu.internet2.middleware.shibboleth.aa.AAAttribute;
46 import edu.internet2.middleware.shibboleth.aa.AAAttributeSet;
47 import edu.internet2.middleware.shibboleth.aa.AAException;
48 import edu.internet2.middleware.shibboleth.aa.arp.ArpEngine;
49 import edu.internet2.middleware.shibboleth.aa.arp.ArpProcessingException;
50 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
51 import edu.internet2.middleware.shibboleth.artifact.ArtifactMapper;
52 import edu.internet2.middleware.shibboleth.artifact.provider.MemoryArtifactMapper;
53 import edu.internet2.middleware.shibboleth.common.Credential;
54 import edu.internet2.middleware.shibboleth.common.NameMapper;
55 import edu.internet2.middleware.shibboleth.common.RelyingParty;
56 import edu.internet2.middleware.shibboleth.common.ServiceProviderMapper;
57 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
58 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
59 import edu.internet2.middleware.shibboleth.metadata.Metadata;
60 import edu.internet2.middleware.shibboleth.metadata.MetadataException;
61
62 /**
63  * Delivers core IdP functionality (Attribute resolution, ARP filtering, Metadata lookup, Signing, Mapping between local &
64  * SAML identifiers, etc.) to components that process protocol-specific requests.
65  * 
66  * @author Walter Hoehn
67  */
68 public class IdPProtocolSupport implements Metadata {
69
70         private static Logger log = Logger.getLogger(IdPProtocolSupport.class.getName());
71         private Logger transactionLog;
72         private IdPConfig config;
73         private ArrayList fedMetadata = new ArrayList();
74         private NameMapper nameMapper;
75         private ServiceProviderMapper spMapper;
76         private ArpEngine arpEngine;
77         private AttributeResolver resolver;
78         private ArtifactMapper artifactMapper;
79         private Semaphore throttle;
80
81         IdPProtocolSupport(IdPConfig config, Logger transactionLog, NameMapper nameMapper, ServiceProviderMapper spMapper,
82                         ArpEngine arpEngine, AttributeResolver resolver) throws ShibbolethConfigurationException {
83
84                 this.transactionLog = transactionLog;
85                 this.config = config;
86                 this.nameMapper = nameMapper;
87                 this.spMapper = spMapper;
88                 spMapper.setMetadata(this);
89                 this.arpEngine = arpEngine;
90                 this.resolver = resolver;
91                 // TODO make this pluggable... and clean up memory impl
92                 artifactMapper = new MemoryArtifactMapper();
93
94                 // Load a semaphore that throttles how many requests the IdP will handle at once
95                 throttle = new Semaphore(config.getMaxThreads());
96         }
97
98         public Logger getTransactionLog() {
99
100                 return transactionLog;
101         }
102
103         public IdPConfig getIdPConfig() {
104
105                 return config;
106         }
107
108         public NameMapper getNameMapper() {
109
110                 return nameMapper;
111         }
112
113         public ServiceProviderMapper getServiceProviderMapper() {
114
115                 return spMapper;
116         }
117
118         public void signAssertions(SAMLAssertion[] assertions, RelyingParty relyingParty) throws InvalidCryptoException,
119                         SAMLException {
120
121                 if (relyingParty.getIdentityProvider().getSigningCredential() == null
122                                 || relyingParty.getIdentityProvider().getSigningCredential().getPrivateKey() == null) { throw new InvalidCryptoException(
123                                 SAMLException.RESPONDER, "Invalid signing credential."); }
124
125                 for (int i = 0; i < assertions.length; i++) {
126                         String assertionAlgorithm;
127                         if (relyingParty.getIdentityProvider().getSigningCredential().getCredentialType() == Credential.RSA) {
128                                 assertionAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
129                         } else if (relyingParty.getIdentityProvider().getSigningCredential().getCredentialType() == Credential.DSA) {
130                                 assertionAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
131                         } else {
132                                 throw new InvalidCryptoException(SAMLException.RESPONDER,
133                                                 "The Shibboleth IdP currently only supports signing with RSA and DSA keys.");
134                         }
135
136                         try {
137                                 throttle.enter();
138                                 assertions[i].sign(assertionAlgorithm, relyingParty.getIdentityProvider().getSigningCredential()
139                                                 .getPrivateKey(), Arrays.asList(relyingParty.getIdentityProvider().getSigningCredential()
140                                                 .getX509CertificateChain()));
141                         } finally {
142                                 throttle.exit();
143                         }
144                 }
145         }
146
147         public void signResponse(SAMLResponse response, RelyingParty relyingParty) throws SAMLException {
148
149                 // Make sure we have an appropriate credential
150                 if (relyingParty.getIdentityProvider().getSigningCredential() == null
151                                 || relyingParty.getIdentityProvider().getSigningCredential().getPrivateKey() == null) { throw new InvalidCryptoException(
152                                 SAMLException.RESPONDER, "Invalid signing credential."); }
153
154                 // Sign the response
155                 String responseAlgorithm;
156                 if (relyingParty.getIdentityProvider().getSigningCredential().getCredentialType() == Credential.RSA) {
157                         responseAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
158                 } else if (relyingParty.getIdentityProvider().getSigningCredential().getCredentialType() == Credential.DSA) {
159                         responseAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
160                 } else {
161                         throw new InvalidCryptoException(SAMLException.RESPONDER,
162                                         "The Shibboleth IdP currently only supports signing with RSA and DSA keys.");
163                 }
164                 try {
165                         throttle.enter();
166                         response.sign(responseAlgorithm, relyingParty.getIdentityProvider().getSigningCredential().getPrivateKey(),
167                                         Arrays.asList(relyingParty.getIdentityProvider().getSigningCredential().getX509CertificateChain()));
168                 } finally {
169                         throttle.exit();
170                 }
171         }
172
173         protected void addFederationProvider(Element element) {
174
175                 log.debug("Found Federation Provider configuration element.");
176                 if (!element.getTagName().equals("FederationProvider")) {
177                         log.error("Error while attemtping to load Federation Provider.  Malformed provider specificaion.");
178                         return;
179                 }
180
181                 try {
182                         fedMetadata.add(FederationProviderFactory.loadProvider(element));
183                 } catch (MetadataException e) {
184                         log.error("Unable to load Federation Provider.  Skipping...");
185                 }
186         }
187
188         public int providerCount() {
189
190                 return fedMetadata.size();
191         }
192
193         public EntityDescriptor lookup(String providerId) {
194
195                 Iterator iterator = fedMetadata.iterator();
196                 while (iterator.hasNext()) {
197                         EntityDescriptor provider = ((Metadata) iterator.next()).lookup(providerId);
198                         if (provider != null) { return provider; }
199                 }
200                 return null;
201         }
202
203         public EntityDescriptor lookup(Artifact artifact) {
204
205                 Iterator iterator = fedMetadata.iterator();
206                 while (iterator.hasNext()) {
207                         EntityDescriptor provider = ((Metadata) iterator.next()).lookup(artifact);
208                         if (provider != null) { return provider; }
209                 }
210                 return null;
211         }
212
213         public SAMLAttribute[] getReleaseAttributes(Principal principal, String requester, URL resource) throws AAException {
214
215                 try {
216                         URI[] potentialAttributes = arpEngine.listPossibleReleaseAttributes(principal, requester, resource);
217                         return getReleaseAttributes(principal, requester, resource, potentialAttributes);
218
219                 } catch (ArpProcessingException e) {
220                         log.error("An error occurred while processing the ARPs for principal (" + principal.getName() + ") :"
221                                         + e.getMessage());
222                         throw new AAException("Error retrieving data for principal.");
223                 }
224         }
225
226         public SAMLAttribute[] getReleaseAttributes(Principal principal, String requester, URL resource,
227                         URI[] attributeNames) throws AAException {
228
229                 try {
230                         AAAttributeSet attributeSet = new AAAttributeSet();
231                         for (int i = 0; i < attributeNames.length; i++) {
232                                 AAAttribute attribute = new AAAttribute(attributeNames[i].toString());
233                                 attributeSet.add(attribute);
234                         }
235
236                         return resolveAttributes(principal, requester, resource, attributeSet);
237
238                 } catch (SAMLException e) {
239                         log.error("An error occurred while creating attributes for principal (" + principal.getName() + ") :"
240                                         + e.getMessage());
241                         throw new AAException("Error retrieving data for principal.");
242
243                 } catch (ArpProcessingException e) {
244                         log.error("An error occurred while processing the ARPs for principal (" + principal.getName() + ") :"
245                                         + e.getMessage());
246                         throw new AAException("Error retrieving data for principal.");
247                 }
248         }
249
250         private SAMLAttribute[] resolveAttributes(Principal principal, String requester, URL resource,
251                         AAAttributeSet attributeSet) throws ArpProcessingException {
252
253                 resolver.resolveAttributes(principal, requester, attributeSet);
254                 arpEngine.filterAttributes(attributeSet, principal, requester, resource);
255                 return attributeSet.getAttributes();
256         }
257
258         /**
259          * Cleanup resources that won't be released when this object is garbage-collected
260          */
261         public void destroy() {
262
263                 resolver.destroy();
264                 arpEngine.destroy();
265         }
266
267         public ArtifactMapper getArtifactMapper() {
268
269                 return artifactMapper;
270         }
271
272         private class Semaphore {
273
274                 private int value;
275
276                 public Semaphore(int value) {
277
278                         this.value = value;
279                 }
280
281                 public synchronized void enter() {
282
283                         --value;
284                         if (value < 0) {
285                                 try {
286                                         wait();
287                                 } catch (InterruptedException e) {
288                                         // squelch and continue
289                                 }
290                         }
291                 }
292
293                 public synchronized void exit() {
294
295                         ++value;
296                         notify();
297                 }
298         }
299 }