2 * Copyright [2005] [University Corporation for Advanced Internet Development, Inc.]
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * ServiceProviderConfig.java
20 * A ServiceProviderConfig object holds an instance of the Shibboleth
21 * configuration data from the main configuration file and from all
22 * secondary files referenced by the main file.
24 * The configuration file is typically processed during Context
25 * initialization. In a Servlet environment, this is done from
26 * the ServletContextInitializer, while in JUnit testing it is
27 * done during test setup (unless you are testing configuration
28 * in which case it is part of the test itself). This occurs
29 * during init() processing and is inheritly synchronized.
31 * Initialization is a two step process. First create an
32 * instance of this class, then find a path to the configuration
33 * file and call loadConfigObjects().
35 * In addition to the option of loading external classes that
36 * implement one of the Plugin service interfaces by providing
37 * the name of the class in the type= attribute of the Plugin
38 * configuration XML, there is also a manual wiring interface.
39 * Create an implimenting object yourself, then add it to the
40 * configuration by passing an identifying URI and the object
41 * to a addOrReplaceXXXImplementation() method.
43 * These wiring calls are agressive, while the XML is passive.
44 * If the wiring call is made before loadConfigObject(), then
45 * XML referencing this same URI will find that it has already
46 * been loaded and use it. Alternately, if the call is made
47 * after loadConfigObject() then the XML will have processed
48 * the URI, loaded the file, and built an implimenting object.
49 * However, the wiring call will replace that object with the
50 * one provided in the call. Obviously making these calls
51 * first will be slightly more efficient, and is necessary if
52 * the XML configuration specifies URIs that will be provided
53 * by the wiring call and are not represented by any actual file.
55 * After initialization completes, this object and its arrays
56 * and collections should be structurally immutable. A map or
57 * array should not be changed by adding or removing members.
58 * Thus iteration over the collections can be unsynchronized.
59 * The reference to a value in the map can be swapped for a
60 * new object, because this doesn't effect iteration.
62 * Any method may obtain a copy of the current ServiceProviderConfig
63 * object by calling ServiceProviderContext.getServiceProviderConfig().
64 * This reference should only be held locally (for the duration
65 * of the request). Should the entire Shibboleth configuration file
66 * be reparsed (because of a dynamic update), then a new reference will
67 * be stored in the SPContext. Picking up a new reference for each
68 * request ensures that a program uses the latest configuration.
70 * When a secondary file (Metadata, Trust, AAP, etc.) is reloaded,
71 * a new object is constructed for that interface and the entry in
72 * the corresponding Map of providers of that interface is replaced.
73 * Therefore, non-local variables must only store the URI for such
74 * objects. A method can pass the URI to the Map lookup method and
75 * obtain a local variable reference to the current implementing
76 * object which can be used during the processing of the current
79 * Note: The URI for a secondary file cannot change just by
80 * reloading the file, but it can change if this main configuration
81 * file object is rebuilt. Therefore, if an external object stores
82 * a URI for a plugin object, it must be prepared for the Map lookup
83 * to return null. This would indicate that the main configuration
84 * file has been reloaded and the previously valid URI now no longer
85 * points to any implementing object.
87 * XML configuration data is parsed into two formats. First, it
88 * is processed by an ordinary JAXP XML parser into a W3C DOM format.
89 * The parser may validate the XML against an XSD schema, but the
90 * resulting DOM is "untyped". The XML becomes a tree of Element,
91 * Attribute, and Text nodes. The program must still convert an
92 * attribute or text string to a number, date, boolean, or any other
93 * data type even through the XSD declares that it must be of that
94 * type. The program must also search through the elements of the tree
95 * to find specific names for expected contents.
97 * This module then subjects the DOM to a secondary parse through
98 * some classes generated by compiling the XSD file with tools
99 * provided by the Apache XML Bean project. This turns the valid
100 * XML into strongly typed Java objects. A class is generated to
101 * represent every data type defined in the XSD schemas. Attribute
102 * values and child elements become properties of the objects of
103 * these classes. The XMLBean objects simplify the configuration
106 * If the configuration file directly reflected the program logic,
107 * the XML Bean classes would probably be enough. However, there
108 * are two important considerations:
110 * First, the Metadata is in transition. Currently we support an
111 * ad-hoc format defined by Shibboleth. However, it is expected
112 * that this will change in the next release to support a new
113 * standard accompanying SAML 2.0. The program logic anticipates
114 * this change, and is largely designed around concepts and
115 * structures of the new SAML standard. The actual configuration
116 * file and XML Beans support the old format, which must be mapped
117 * into this new structure.
119 * Second, secondary configuration elements (Credentials, Trust,
120 * Metadata, AAP, etc.) are "Pluggable" components. There is a
121 * built-in implementation of these services based on the XML
122 * configuration described in the Shibboleth documentation.
123 * However, the administrator can provide other classes that
124 * implement the required interfaces by simply coding the class
125 * name in the type= parameter of the XML element referencing the
126 * plugin. In this case we don't know the format of the opaque
127 * XML and simply pass it to the plugin.
130 * Dependencies: Requires XML Beans and the generated classes.
131 * Requires access to XSD schema files for configuration file formats.
132 * Logic depends on the order of enums in the XSD files.
134 * Error Strategy: A failure parsing the main configuration file
135 * prevents further processing. However, a problem parsing a plug-in
136 * configuration file should be noted while processing continues.
137 * This strategy reports all the errors in all the files to the log
138 * rather than stopping at the first error.
141 package edu.internet2.middleware.shibboleth.serviceprovider;
143 import java.net.MalformedURLException;
145 import java.security.cert.X509Certificate;
146 import java.util.ArrayList;
147 import java.util.Collection;
148 import java.util.Iterator;
149 import java.util.Map;
150 import java.util.TreeMap;
152 import org.apache.log4j.Logger;
153 import org.apache.log4j.PropertyConfigurator;
154 import org.apache.xmlbeans.XmlException;
155 import org.apache.xmlbeans.XmlOptions;
156 import org.opensaml.SAMLAssertion;
157 import org.opensaml.SAMLAttribute;
158 import org.opensaml.SAMLAttributeStatement;
159 import org.opensaml.SAMLException;
160 import org.opensaml.SAMLSignedObject;
161 import org.opensaml.artifact.Artifact;
162 import org.w3c.dom.Document;
163 import org.w3c.dom.Element;
164 import org.w3c.dom.Node;
166 import x0.maceShibboleth1.AttributeAcceptancePolicyDocument;
167 import x0.maceShibbolethTargetConfig1.ApplicationDocument;
168 import x0.maceShibbolethTargetConfig1.LocalConfigurationType;
169 import x0.maceShibbolethTargetConfig1.PluggableType;
170 import x0.maceShibbolethTargetConfig1.RequestMapDocument;
171 import x0.maceShibbolethTargetConfig1.SPConfigDocument;
172 import x0.maceShibbolethTargetConfig1.SPConfigType;
173 import x0.maceShibbolethTargetConfig1.ShibbolethTargetConfigDocument;
174 import x0.maceShibbolethTargetConfig1.ApplicationDocument.Application;
175 import x0.maceShibbolethTargetConfig1.ApplicationsDocument.Applications;
176 import x0.maceShibbolethTargetConfig1.HostDocument.Host;
177 import x0.maceShibbolethTargetConfig1.HostDocument.Host.Scheme.Enum;
178 import x0.maceShibbolethTargetConfig1.PathDocument.Path;
179 import edu.internet2.middleware.shibboleth.aap.AAP;
180 import edu.internet2.middleware.shibboleth.aap.AttributeRule;
181 import edu.internet2.middleware.shibboleth.common.Credentials;
182 import edu.internet2.middleware.shibboleth.common.ShibResource;
183 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
184 import edu.internet2.middleware.shibboleth.common.Trust;
185 import edu.internet2.middleware.shibboleth.common.provider.ShibbolethTrust;
186 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
187 import edu.internet2.middleware.shibboleth.metadata.Metadata;
188 import edu.internet2.middleware.shibboleth.metadata.RoleDescriptor;
189 import edu.internet2.middleware.shibboleth.xml.Parser;
192 * Load the configuration files into objects, index them, and return them on request.
194 * <p>A new instance of the ServiceProviderConfig object can be created to
195 * parse a new version of the configuration file. It can then be swapped
196 * into the ServiceProviderContext reference and will be picked up by
197 * subsequent requests.</p>
199 * @author Howard Gilbert
201 public class ServiceProviderConfig {
203 // Map key prefix for inline plugin configuration elements
204 private static final String INLINEURN = "urn:inlineBS:ID";
206 private static Logger log = Logger.getLogger(ContextListener.SHIBBOLETH_INIT+".Config");
208 private SPConfigType // The XMLBean from the main config file
213 * The following Maps reference objects that implement a plugin
214 * interface indexed by their URI. There are builtin objects
215 * created from inline or external XML files, but external
216 * objects implementing the interfaces may be injected by
217 * calling the addOrReplaceXXX method. Public access to these
218 * Maps is indirect, through methods the ApplicationInfo object
219 * for a given configured or default application.
222 private Map/*<String, Metadata>*/ entityLocators =
223 new TreeMap/*<String, Metadata>*/();
225 public void addOrReplaceMetadataImplementor(String uri, Metadata m) {
226 entityLocators.put(uri, m);
229 public Metadata getMetadataImplementor(String uri) {
230 return (Metadata)entityLocators.get(uri);
233 private Map/*<String, AAP>*/ attributePolicies =
234 new TreeMap/*<String, AAP>*/();
236 public void addOrReplaceAAPImplementor(String uri, AAP a) {
237 attributePolicies.put(uri,a);
240 public AAP getAAPImplementor(String uri) {
241 return (AAP) attributePolicies.get(uri);
244 private Map/*<String, Trust>*/ certificateValidators =
245 new TreeMap/*<String, Trust>*/();
247 public void addOrReplaceTrustImplementor(String uri, Trust t) {
248 certificateValidators.put(uri,t);
251 public Trust getTrustImplementor(String uri) {
252 return (Trust) certificateValidators.get(uri);
255 private Trust[] defaultTrust = {new ShibbolethTrust()};
258 * Objects created from the <Application(s)> elements.
259 * They manage collections of URI-Strings that index the
260 * previous maps to return Metadata, Trust, and AAP info
261 * applicable to this applicationId.
263 private Map/*<String, ApplicationInfo>*/ applications =
264 new TreeMap/*<String, ApplicationInfo>*/();
266 // Default application info from <Applications> element
267 private ApplicationInfo defaultApplicationInfo = null;
269 public ApplicationInfo getApplication(String applicationId) {
270 ApplicationInfo app=null;
271 app = (ApplicationInfo) applications.get(applicationId);
272 if (app==null) // If no specific match, return default
273 return defaultApplicationInfo;
278 // Objects created from single configuration file elements
279 private Credentials credentials = null;
280 private RequestMapDocument.RequestMap requestMap = null;
287 private static final String XMLTRUSTPROVIDERTYPE =
288 "edu.internet2.middleware.shibboleth.common.provider.ShibbolethTrust";
289 private static final String XMLAAPPROVIDERTYPE =
290 "edu.internet2.middleware.shibboleth.aap.provider.XMLAAP";
291 private static final String XMLFEDERATIONPROVIDERTYPE =
292 "edu.internet2.middleware.shibboleth.metadata.provider.XMLMetadata";
293 private static final String XMLREQUESTMAPPROVIDERTYPE =
294 "edu.internet2.middleware.shibboleth.sp.provider.NativeRequestMapProvider";
295 private static final String XMLCREDENTIALSPROVIDERTYPE =
296 "edu.internet2.middleware.shibboleth.common.Credentials";
302 * The constructor prepares for, but does not parse the configuration.
304 * @throws ShibbolethConfigurationException
305 * if XML Parser cannot be initialized (Classpath problem)
307 public ServiceProviderConfig() {
311 * loadConfigObjects must be called once to parse the configuration.
313 * <p>To reload a modified configuration file, create and load a second
314 * object and swap the reference in the context object.</p>
316 * @param configFilePath URL or resource name of file
317 * @return the DOM Document
318 * @throws ShibbolethConfigurationException
319 * if there was an error loading the file
321 public synchronized void loadConfigObjects(String configFilePath)
322 throws ShibbolethConfigurationException {
325 log.error("ServiceProviderConfig.loadConfigObjects may not be called twice for the same object.");
326 throw new ShibbolethConfigurationException("Cannot reload configuration into same object.");
331 configDoc = Parser.loadDom(configFilePath, true);
332 } catch (Exception e) {
333 throw new ShibbolethConfigurationException("XML error in "+configFilePath);
335 loadConfigBean(configDoc);
341 * Given a URL, determine its ApplicationId from the RequestMap config.
343 * <p>Note: This is not a full implementation of all RequestMap
344 * configuration options. Other functions will be added as needed.</p>
346 public String mapRequest(String urlreq) {
347 String applicationId = "default";
351 url = new URL(urlreq);
352 } catch (MalformedURLException e) {
353 return applicationId;
356 String urlscheme = url.getProtocol();
357 String urlhostname = url.getHost();
358 String urlpath = url.getPath();
359 int urlport = url.getPort();
361 // find Host entry for this virtual server
362 Host[] hostArray = requestMap.getHostArray();
363 for (int ihost=0;ihost<hostArray.length;ihost++) {
364 Host host = hostArray[ihost];
365 Enum scheme = host.getScheme();
366 String hostName = host.getName();
367 String hostApplicationId = host.getApplicationId();
368 long hostport = host.getPort();
370 if (scheme != null &&
371 !urlscheme.equals(scheme.toString()))
373 if (!urlhostname.equals(hostName))
380 // find Path entry for this subdirectory
381 Path[] pathArray = host.getPathArray();
382 if (hostApplicationId!=null)
383 applicationId=hostApplicationId;
384 for (int i=0;i<pathArray.length;i++) {
385 String dirname = pathArray[i].getName();
386 if (urlpath.equals(dirname)||
387 urlpath.startsWith(dirname+"/")){
388 String pthid= pathArray[i].getApplicationId();
395 return applicationId;
399 * <p>Parse the main configuration file DOM into XML Bean</p>
401 * <p>Automatically load secondary configuration files designated
402 * by URLs in the main configuration file</p>
404 * @throws ShibbolethConfigurationException
406 private void loadConfigBean(Document configDoc)
407 throws ShibbolethConfigurationException {
408 boolean anyError=false;
410 Element documentElement = configDoc.getDocumentElement();
411 // reprocess the already validated DOM to create a bean with typed fields
412 // dump the trash (comments, processing instructions, extra whitespace)
415 if (documentElement.getLocalName().equals("ShibbolethTargetConfig")) {
416 ShibbolethTargetConfigDocument configBeanDoc;
417 configBeanDoc = ShibbolethTargetConfigDocument.Factory.parse(configDoc,
418 new XmlOptions().setLoadStripComments().setLoadStripProcinsts().setLoadStripWhitespace());
419 config = configBeanDoc.getShibbolethTargetConfig();
420 } else if (documentElement.getLocalName().equals("SPConfig")) {
421 SPConfigDocument configBeanDoc;
422 configBeanDoc = SPConfigDocument.Factory.parse(configDoc,
423 new XmlOptions().setLoadStripComments().setLoadStripProcinsts().setLoadStripWhitespace());
424 config = configBeanDoc.getSPConfig();
426 throw new XmlException("Root element not ShibbolethTargetConfig or SPConfig");
428 } catch (XmlException e) {
429 // Since the DOM was already validated against the schema, errors will not typically occur here
430 log.error("Error while parsing shibboleth configuration");
431 throw new ShibbolethConfigurationException("Error while parsing shibboleth configuration");
435 String loggerUrl = config.getLogger();
436 PropertyConfigurator.configure(new URL(loggerUrl));
437 } catch (Exception e) {
438 log.error("Cannot process logger attribute of SP configuration file.",e);
441 Applications apps = config.getApplications(); // <Applications>
446 * Create an <Application> id "default" from <Applications>
448 ApplicationDocument defaultAppDoc =
449 // Create a new XMLBeans "Document" level object
450 ApplicationDocument.Factory.newInstance();
451 ApplicationDocument.Application defaultApp =
452 // Add an XMLBeans "root Element" object to the Document
453 defaultAppDoc.addNewApplication();
454 // set or copy over fields from unrelated Applications object
455 defaultApp.setId("default");
456 defaultApp.setAAPProviderArray(apps.getAAPProviderArray());
457 defaultApp.setAttributeDesignatorArray(apps.getAttributeDesignatorArray());
458 defaultApp.setAudienceArray(apps.getAudienceArray());
459 defaultApp.setCredentialUse(apps.getCredentialUse());
460 defaultApp.setErrors(apps.getErrors());
461 defaultApp.setFederationProviderArray(apps.getFederationProviderArray());
462 defaultApp.setMetadataProviderArray(apps.getMetadataProviderArray());
463 defaultApp.setProviderId(apps.getProviderId());
464 defaultApp.setSessions(apps.getSessions());
465 defaultApp.setTrustProviderArray(apps.getTrustProviderArray());
468 * Now process secondary files configured in the applications
470 anyError |= processApplication(defaultApp);
472 Application[] apparray = apps.getApplicationArray();
473 for (int i=0;i<apparray.length;i++){
474 Application tempapp = apparray[i];
475 applications.put(tempapp.getId(),tempapp);
476 anyError |= processApplication(tempapp);
480 * Now process other secondary files
482 anyError |= processCredentials();
483 anyError |= processPluggableRequestMapProvider();
486 throw new ShibbolethConfigurationException("Errors processing configuration file, see log");
491 * Routine to handle CredentialProvider
493 * <p>Note: This only handles in-line XML.
494 * Also, Credentials was an existing IdP class, so it doesn't
495 * implement the new PluggableConfigurationComponent interface and
496 * can't be loaded by generic plugin support.
499 private boolean processCredentials() {
500 boolean anyError=false;
501 PluggableType[] pluggable = config.getCredentialsProviderArray();
502 for (int i=0;i<pluggable.length;i++) {
503 String pluggabletype = pluggable[i].getType();
504 if (!pluggabletype.equals(
505 "edu.internet2.middleware.shibboleth.common.Credentials")) {
506 log.error("Unsupported CredentialsProvider type "+pluggabletype);
510 PluggableType credentialsProvider = pluggable[i];
511 Node fragment = credentialsProvider.newDomNode();
512 // newDomNode returns the current node wrapped in a Fragment
514 Node credentialsProviderNode = fragment.getFirstChild();
515 Node credentialsNode=credentialsProviderNode.getFirstChild();
516 credentials = new Credentials((Element)credentialsNode);
517 } catch(Exception e) {
518 log.error("Cannot process Credentials element of Shibboleth configuration");
528 * Find and load secondary configuration files referenced in an Application(s)
530 * @param app Application object
531 * @throws ShibbolethConfigurationException
533 private boolean processApplication(Application app)
534 throws ShibbolethConfigurationException {
536 boolean anyError=false;
538 String applicationId = app.getId();
540 ApplicationInfo appinfo = new ApplicationInfo(app);
542 anyError |= processPluggableMetadata(appinfo);
543 anyError |= processPluggableAAPs(appinfo);
544 anyError |= processPluggableTrusts(appinfo);
546 applications.put(applicationId, appinfo);
552 * Generic code to create an object of a Pluggable type that implements
553 * a configuration interface.
555 * <p>The configuration schema defines "PluggableType" as a type of
556 * XML element that has opaque contents and attributes "type" and
557 * "uri". If the uri attribute is omitted, then the configuration
558 * data is inline XML content. The XSD files typically define the
559 * format of pluggable configuration elements, but without binding
560 * them to the PluggableType element that may contain them.</p>
562 * <p>The implimentation of pluggable objects is provided by
563 * external classes. There are "builtin" classes provided with
564 * Shibboleth (XMLMetadataImpl, XMLTrustImpl, XMLAAPImpl) that
565 * provide examples of how this is done. By design, others can
566 * provide their own classes just by putting the class name as
567 * the value of the type attribute.</p>
569 * <p>This routine handles the common setup. It creates objects
570 * of one of the builtin types, or it uses Class.forName() to
571 * access a user specified class. It then locates either the
572 * inline XML elements or the external XML file. It passes the
573 * XML to initialize the object. Finally, a reference to the
574 * object is stored in the appropriate Map.</p>
576 * <p>The objects created implement two interfaces. Mostly they
577 * implement a configuration interface (EntityDescriptor, Trust,
578 * AAP, etc). However, for the purpose of this routine they also
579 * must be declared to implement PluggableConfigurationComponent
580 * and provide an initialize() method that parses a DOM Node
581 * containing their root XML configuration element.</p>
583 * @param pluggable XMLBean for element defined in XSD to be of "PluggableType"
584 * @param implclass java.lang.Class of Builtin implementation class
585 * @param interfaceClass java.lang.Class of Interface
586 * @param builtinName alias type to choose Builtin imlementation
587 * @param uriMap ApplicationInfo Map for this interface
593 PluggableType pluggable,
595 Class interfaceClass,
597 Map /*<String,PluggableConfigurationComponent>*/uriMap
600 String pluggabletype = pluggable.getType();
602 if (!pluggabletype.equals(builtinName)) {
603 // Not the builtin type, try to load user class by name
605 implclass = Class.forName(pluggabletype);
606 } catch (ClassNotFoundException e) {
607 log.error("Type value "+pluggabletype+" not found as supplied Java class");
610 if (!interfaceClass.isAssignableFrom(implclass)||
611 !PluggableConfigurationComponent.class.isAssignableFrom(implclass)) {
612 log.error(pluggabletype+" class does not support required interfaces.");
617 PluggableConfigurationComponent impl;
619 impl = (PluggableConfigurationComponent) implclass.newInstance();
620 } catch (Exception e) {
621 log.error("Unable to instantiate "+pluggabletype);
625 String uri = pluggable.getUri();
626 if (uri==null) { // inline
630 Node fragment = pluggable.newDomNode(); // XML-Fragment node
631 Node pluggableNode = fragment.getFirstChild(); // PluggableType
632 Node contentNode=pluggableNode.getFirstChild();// root element
633 impl.initialize(contentNode);
634 } catch (Exception e) {
635 log.error("XML error " + e);
639 } else { // external file
641 if (uriMap.get(uri)!=null) { // Already parsed this file
646 Document extdoc = Parser.loadDom(uri,true);
649 impl.initialize(extdoc);
650 } catch (Exception e) {
651 log.error("XML error " + e);
656 uriMap.put(uri,impl);
663 * Handle a FederationProvider
665 private boolean processPluggableMetadata(ApplicationInfo appinfo) {
666 boolean anyError = false;
667 PluggableType[] pluggable1 = appinfo.getApplicationConfig().getFederationProviderArray();
668 PluggableType[] pluggable2 = appinfo.getApplicationConfig().getMetadataProviderArray();
669 PluggableType[] pluggable;
670 if (pluggable1.length==0) {
671 pluggable=pluggable2;
672 } else if (pluggable2.length==0) {
673 pluggable=pluggable1;
675 pluggable = new PluggableType[pluggable1.length+pluggable2.length];
676 for (int i=0;i<pluggable2.length;i++) {
677 pluggable[i]=pluggable2[i];
679 for (int i=0;i<pluggable1.length;i++) {
680 pluggable[i+pluggable2.length]=pluggable1[i];
683 for (int i = 0;i<pluggable.length;i++) {
684 String uri = processPluggable(pluggable[i],
685 XMLMetadataImpl.class,
687 XMLFEDERATIONPROVIDERTYPE,
691 else if (uri.length()>0) {
692 appinfo.addGroupUri(uri);
699 * Reload XML Metadata configuration after file changed.
700 * @param uri Path to Metadata XML configuration
701 * @return true if file reloaded.
703 public boolean reloadFederation(String uri) {
704 if (getMetadataImplementor(uri)!=null||
705 uri.startsWith(INLINEURN))
708 Document sitedoc = Parser.loadDom(uri,true);
711 XMLMetadataImpl impl = new XMLMetadataImpl();
712 impl.initialize(sitedoc);
713 addOrReplaceMetadataImplementor(uri,impl);
714 } catch (Exception e) {
715 log.error("Error while parsing Metadata file "+uri);
716 log.error("XML error " + e);
723 * Handle an AAPProvider element with
724 * type="edu.internet2.middleware.shibboleth.common.provider.XMLAAP"
725 * @throws InternalConfigurationException
727 private boolean processPluggableAAPs(ApplicationInfo appinfo){
728 boolean anyError=false;
729 PluggableType[] pluggable = appinfo.getApplicationConfig().getAAPProviderArray();
730 for (int i = 0;i<pluggable.length;i++) {
731 String uri = processPluggable(pluggable[i],
738 else if (uri.length()>0) {
739 appinfo.addAapUri(uri);
746 * Reload XML AAP configuration after file changed.
747 * @param uri AAP to Trust XML configuration
748 * @return true if file reloaded.
750 public boolean reloadAAP(String uri) {
751 if (getAAPImplementor(uri)!=null||
752 uri.startsWith(INLINEURN))
755 Document aapdoc = Parser.loadDom(uri,true);
758 AttributeAcceptancePolicyDocument aap = AttributeAcceptancePolicyDocument.Factory.parse(aapdoc);
759 XMLAAPImpl impl = new XMLAAPImpl();
760 impl.initialize(aapdoc);
761 addOrReplaceAAPImplementor(uri,impl);
762 } catch (Exception e) {
763 log.error("Error while parsing AAP file "+uri);
764 log.error("XML error " + e);
772 * Handle a TrustProvider element with
773 * type="edu.internet2.middleware.shibboleth.common.provider.XMLTrust"
775 * Note: This code builds the semantic structure of trust. That is, it knows
776 * about certificates and keys. The actual logic of Trust (signature generation
777 * and validation) is implemented in a peer object defined in the external
778 * class XMLTrustImpl.
780 * @throws ShibbolethConfigurationException if X.509 certificate cannot be processed
781 * @throws InternalConfigurationException
783 private boolean processPluggableTrusts(ApplicationInfo appinfo){
784 boolean anyError=false;
785 PluggableType[] pluggable = appinfo.getApplicationConfig().getTrustProviderArray();
786 for (int i = 0;i<pluggable.length;i++) {
787 String uri = processPluggable(pluggable[i],
788 ShibbolethTrustPluggable.class,
790 XMLTRUSTPROVIDERTYPE,
791 certificateValidators);
794 else if (uri.length()>0) {
795 appinfo.addTrustUri(uri);
803 private boolean processPluggableRequestMapProvider(){
804 LocalConfigurationType shire = config.getSHIRE();
806 shire = config.getLocal();
808 log.error("No Local element.");
811 PluggableType mapProvider = shire.getRequestMapProvider();
813 String pluggabletype = mapProvider.getType();
814 if (!pluggabletype.equals(XMLREQUESTMAPPROVIDERTYPE)) {
815 log.error("Unsupported RequestMapProvider type "+pluggabletype);
819 RequestMapDocument requestMapDoc = null;
820 Document mapdoc = null;
821 Element maproot = null;
822 String uri = mapProvider.getUri();
824 if (uri==null) { // inline
828 Node fragment = mapProvider.newDomNode();
829 Node pluggableNode = fragment.getFirstChild();
830 Node contentNode=pluggableNode.getFirstChild();
832 requestMapDoc = RequestMapDocument.Factory.parse(contentNode);
833 } catch (Exception e) {
834 log.error("Error while parsing inline RequestMap");
835 log.error("XML error " + e);
839 } else { // external file
841 mapdoc = Parser.loadDom(uri,true);
844 requestMapDoc = RequestMapDocument.Factory.parse(mapdoc);
845 } catch (Exception e) {
846 log.error("Error while parsing RequestMap file "+uri);
847 log.error("XML error " + e);
852 requestMap = requestMapDoc.getRequestMap();
857 // Generate Map keys for inline plugin configuration Elements
858 private int inlinenum = 1;
859 private String genDummyUri() {
860 return INLINEURN+Integer.toString(inlinenum++);
869 * ApplicationInfo represents the <Application(s)> object, its fields,
870 * and the pluggable configuration elements under it.
872 * <p>It can return arrays of Metadata, Trust, or AAP providers, but
873 * it also exposes convenience methods that shop the lookup(),
874 * validate(), and trust() calls to each object in the collection
875 * until success or failure is determined.</p>
877 * <p>For all other parameters, such as Session parameters, you
878 * can fetch the XMLBean by calling getApplicationConf() and
879 * query their value directly.
881 public class ApplicationInfo
882 implements Metadata, Trust {
884 private Application applicationConfig;
885 public Application getApplicationConfig() {
886 return applicationConfig;
890 * Construct this object from the XML Bean.
891 * @param application XMLBean for Application element
893 ApplicationInfo(Application application) {
894 this.applicationConfig=application;
899 * Following the general rule, this object may not keep
900 * direct references to the plugin interface implementors,
901 * but must look them up on every call through their URI keys.
902 * So we keep collections of URI strings instead.
904 ArrayList groupUris = new ArrayList();
905 ArrayList trustUris = new ArrayList();
906 ArrayList aapUris = new ArrayList();
908 void addGroupUri(String uri) {
911 void addTrustUri(String uri) {
914 void addAapUri(String uri) {
919 * Return the current array of objects that implement the
920 * ...metadata.Metadata interface
924 Metadata[] getMetadataProviders() {
925 Iterator iuris = groupUris.iterator();
926 int count = groupUris.size();
927 Metadata[] metadatas = new Metadata[count];
928 for (int i=0;i<count;i++) {
929 String uri =(String) iuris.next();
930 metadatas[i]=getMetadataImplementor(uri);
936 * A convenience function based on the Metadata interface.
938 * <p>Look for an entity ID through each implementor until the
939 * first one finds locates a describing object.</p>
941 * <p>Unfortunately, Metadata.lookup() was originally specified to
942 * return a "Provider". In current SAML 2.0 terms, the object
943 * returned should be an EntityDescriptor. So this is the new
944 * function in the new interface that will use the new term, but
945 * it does the same thing.</p>
947 * @param id ID of the IdP entity
948 * @return EntityDescriptor metadata object for that site.
950 public EntityDescriptor lookup(String id) {
951 Iterator iuris = groupUris.iterator();
952 while (iuris.hasNext()) {
953 String uri =(String) iuris.next();
954 Metadata locator=getMetadataImplementor(uri);
955 EntityDescriptor entity = locator.lookup(id);
962 public EntityDescriptor lookup(Artifact artifact) {
963 Iterator iuris = groupUris.iterator();
964 while (iuris.hasNext()) {
965 String uri =(String) iuris.next();
966 Metadata locator=getMetadataImplementor(uri);
967 EntityDescriptor entity = locator.lookup(artifact);
975 * Return the current array of objects that implement the Trust interface
979 public Trust[] getTrustProviders() {
980 Iterator iuris = trustUris.iterator();
981 int count = trustUris.size();
984 Trust[] trusts = new Trust[count];
985 for (int i=0;i<count;i++) {
986 String uri =(String) iuris.next();
987 trusts[i]=getTrustImplementor(uri);
993 * Return the current array of objects that implement the AAP interface
997 public AAP[] getAAPProviders() {
998 Iterator iuris = aapUris.iterator();
999 int count = aapUris.size();
1000 AAP[] aaps = new AAP[count];
1001 for (int i=0;i<count;i++) {
1002 String uri =(String) iuris.next();
1003 aaps[i]=getAAPImplementor(uri);
1009 * Convenience function to apply AAP by calling the apply()
1010 * method of each AAP implementor.
1012 * <p>Any AAP implementor can delete an assertion or value.
1013 * Empty SAML elements get removed from the assertion.
1014 * This can yield an AttributeAssertion with no attributes.
1016 * @param assertion SAML Attribute Assertion
1017 * @param role Role that issued the assertion
1018 * @throws SAMLException Raised if assertion is mangled beyond repair
1020 void applyAAP(SAMLAssertion assertion, RoleDescriptor role) throws SAMLException {
1022 // Foreach AAP in the collection
1023 AAP[] providers = getAAPProviders();
1024 if (providers.length == 0) {
1025 log.info("no filters specified, accepting entire assertion");
1028 for (int i=0;i<providers.length;i++) {
1029 AAP aap = providers[i];
1030 if (aap.anyAttribute()) {
1031 log.info("any attribute enabled, accepting entire assertion");
1036 // Foreach Statement in the Assertion
1037 Iterator statements = assertion.getStatements();
1039 while (statements.hasNext()) {
1040 Object statement = statements.next();
1041 if (statement instanceof SAMLAttributeStatement) {
1042 SAMLAttributeStatement attributeStatement = (SAMLAttributeStatement) statement;
1044 // Check each attribute, applying any matching rules.
1045 Iterator attributes = attributeStatement.getAttributes();
1047 while (attributes.hasNext()) {
1048 SAMLAttribute attribute = (SAMLAttribute) attributes.next();
1049 boolean ruleFound = false;
1050 for (int i=0;i<providers.length;i++) {
1051 AttributeRule rule = providers[i].lookup(attribute.getName(),attribute.getNamespace());
1055 rule.apply(attribute,role);
1057 catch (SAMLException ex) {
1058 log.info("no values remain, removing attribute");
1059 attributeStatement.removeAttribute(iattribute--);
1065 log.warn("no rule found for attribute (" + attribute.getName() + "), filtering it out");
1066 attributeStatement.removeAttribute(iattribute--);
1072 attributeStatement.checkValidity();
1075 catch (SAMLException ex) {
1076 // The statement is now defunct.
1077 log.info("no attributes remain, removing statement");
1078 assertion.removeStatement(istatement);
1083 // Now see if we trashed it irrevocably.
1084 assertion.checkValidity();
1089 * Returns a collection of attribute names to request from the AA.
1091 * @return Collection of attribute Name values
1093 public Collection getAttributeDesignators() {
1094 // TODO Not sure where this should come from
1095 return new ArrayList();
1100 * Convenience method implementing Trust.validate() across
1101 * the collection of implementing objects. Returns true if
1102 * any Trust implementor approves the signatures in the object.
1104 * <p>In the interface, validate() is passed several arguments
1105 * that come from this object. In this function, those
1106 * arguments are ignored "this" is used.
1110 SAMLSignedObject token,
1115 Trust[] trustProviders = getTrustProviders();
1116 for (int i=0;i<trustProviders.length;i++) {
1117 Trust trust = trustProviders[i];
1118 if (trust.validate(token,role))
1126 * A method of Trust that we must declare to claim that
1127 * ApplicationInfo implements Trust. However, no code in the
1128 * ServiceProvider calls this (probably an IdP thing).
1130 * @param revocations
1132 * @return This dummy always returns false.
1134 public boolean attach(Iterator revocations, RoleDescriptor role) {
1139 public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain, RoleDescriptor descriptor) {
1140 Trust[] trustProviders = getTrustProviders();
1141 for (int i=0;i<trustProviders.length;i++) {
1142 Trust trust = trustProviders[i];
1143 if (trust.validate(certificateEE,certificateChain,descriptor))
1149 public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain, RoleDescriptor descriptor, boolean checkName) {
1150 Trust[] trustProviders = getTrustProviders();
1151 for (int i=0;i<trustProviders.length;i++) {
1152 Trust trust = trustProviders[i];
1153 if (trust.validate(certificateEE,certificateChain,descriptor,checkName))
1159 public String getProviderId() {
1160 String entityId = this.applicationConfig.getProviderId();
1161 if (entityId==null && this!=defaultApplicationInfo) {
1162 entityId = defaultApplicationInfo.getProviderId();
1170 private static class InternalConfigurationException extends Exception {
1171 InternalConfigurationException() {
1178 public Credentials getCredentials() {