2 * ServiceProviderConfig.java
4 * A ServiceProviderConfig object holds an instance of the Shibboleth
5 * configuration data from the main configuration file and from all
6 * secondary files referenced by the main file.
8 * The configuration file is typically processed during Context
9 * initialization. In a Servlet environment, this is done from
10 * the ServletContextInitializer, while in JUnit testing it is
11 * done during test setup (unless you are testing configuration
12 * in which case it is part of the test itself). This occurs
13 * during init() processing and is inheritly synchronized.
15 * Initialization is a two step process. First create an
16 * instance of this class, then find a path to the configuration
17 * file and call loadConfigObjects().
19 * In addition to the option of loading external classes that
20 * implement one of the Plugin service interfaces by providing
21 * the name of the class in the type= attribute of the Plugin
22 * configuration XML, there is also a manual wiring interface.
23 * Create an implimenting object yourself, then add it to the
24 * configuration by passing an identifying URI and the object
25 * to a addOrReplaceXXXImplementation() method.
27 * These wiring calls are agressive, while the XML is passive.
28 * If the wiring call is made before loadConfigObject(), then
29 * XML referencing this same URI will find that it has already
30 * been loaded and use it. Alternately, if the call is made
31 * after loadConfigObject() then the XML will have processed
32 * the URI, loaded the file, and built an implimenting object.
33 * However, the wiring call will replace that object with the
34 * one provided in the call. Obviously making these calls
35 * first will be slightly more efficient, and is necessary if
36 * the XML configuration specifies URIs that will be provided
37 * by the wiring call and are not represented by any actual file.
39 * After initialization completes, this object and its arrays
40 * and collections should be structurally immutable. A map or
41 * array should not be changed by adding or removing members.
42 * Thus iteration over the collections can be unsynchronized.
43 * The reference to a value in the map can be swapped for a
44 * new object, because this doesn't effect iteration.
46 * Any method may obtain a copy of the current ServiceProviderConfig
47 * object by calling ServiceProviderContext.getServiceProviderConfig().
48 * This reference should only be held locally (for the duration
49 * of the request). Should the entire Shibboleth configuration file
50 * be reparsed (because of a dynamic update), then a new reference will
51 * be stored in the SPContext. Picking up a new reference for each
52 * request ensures that a program uses the latest configuration.
54 * When a secondary file (Metadata, Trust, AAP, etc.) is reloaded,
55 * a new object is constructed for that interface and the entry in
56 * the corresponding Map of providers of that interface is replaced.
57 * Therefore, non-local variables must only store the URI for such
58 * objects. A method can pass the URI to the Map lookup method and
59 * obtain a local variable reference to the current implementing
60 * object which can be used during the processing of the current
63 * Note: The URI for a secondary file cannot change just by
64 * reloading the file, but it can change if this main configuration
65 * file object is rebuilt. Therefore, if an external object stores
66 * a URI for a plugin object, it must be prepared for the Map lookup
67 * to return null. This would indicate that the main configuration
68 * file has been reloaded and the previously valid URI now no longer
69 * points to any implementing object.
71 * XML configuration data is parsed into two formats. First, it
72 * is processed by an ordinary JAXP XML parser into a W3C DOM format.
73 * The parser may validate the XML against an XSD schema, but the
74 * resulting DOM is "untyped". The XML becomes a tree of Element,
75 * Attribute, and Text nodes. The program must still convert an
76 * attribute or text string to a number, date, boolean, or any other
77 * data type even through the XSD declares that it must be of that
78 * type. The program must also search through the elements of the tree
79 * to find specific names for expected contents.
81 * This module then subjects the DOM to a secondary parse through
82 * some classes generated by compiling the XSD file with tools
83 * provided by the Apache XML Bean project. This turns the valid
84 * XML into strongly typed Java objects. A class is generated to
85 * represent every data type defined in the XSD schemas. Attribute
86 * values and child elements become properties of the objects of
87 * these classes. The XMLBean objects simplify the configuration
90 * If the configuration file directly reflected the program logic,
91 * the XML Bean classes would probably be enough. However, there
92 * are two important considerations:
94 * First, the Metadata is in transition. Currently we support an
95 * ad-hoc format defined by Shibboleth. However, it is expected
96 * that this will change in the next release to support a new
97 * standard accompanying SAML 2.0. The program logic anticipates
98 * this change, and is largely designed around concepts and
99 * structures of the new SAML standard. The actual configuration
100 * file and XML Beans support the old format, which must be mapped
101 * into this new structure.
103 * Second, secondary configuration elements (Credentials, Trust,
104 * Metadata, AAP, etc.) are "Pluggable" components. There is a
105 * built-in implementation of these services based on the XML
106 * configuration described in the Shibboleth documentation.
107 * However, the administrator can provide other classes that
108 * implement the required interfaces by simply coding the class
109 * name in the type= parameter of the XML element referencing the
110 * plugin. In this case we don't know the format of the opaque
111 * XML and simply pass it to the plugin.
114 * Dependencies: Requires XML Beans and the generated classes.
115 * Requires access to XSD schema files for configuration file formats.
116 * Logic depends on the order of enums in the XSD files.
118 * Error Strategy: A failure parsing the main configuration file
119 * prevents further processing. However, a problem parsing a plug-in
120 * configuration file should be noted while processing continues.
121 * This strategy reports all the errors in all the files to the log
122 * rather than stopping at the first error.
124 * --------------------
125 * Copyright 2002, 2004
126 * University Corporation for Advanced Internet Development, Inc.
127 * All rights reserved
128 * [Thats all we have to say to protect ourselves]
129 * Your permission to use this code is governed by "The Shibboleth License".
130 * A copy may be found at http://shibboleth.internet2.edu/license.html
131 * [Nothing in copyright law requires license text in every file.]
134 package edu.internet2.middleware.shibboleth.serviceprovider;
136 import java.net.MalformedURLException;
138 import java.security.cert.X509Certificate;
139 import java.util.ArrayList;
140 import java.util.Collection;
141 import java.util.Iterator;
142 import java.util.Map;
143 import java.util.TreeMap;
145 import org.apache.log4j.Logger;
146 import org.apache.xmlbeans.XmlException;
147 import org.apache.xmlbeans.XmlOptions;
148 import org.opensaml.SAMLAssertion;
149 import org.opensaml.SAMLAttribute;
150 import org.opensaml.SAMLAttributeStatement;
151 import org.opensaml.SAMLException;
152 import org.opensaml.SAMLSignedObject;
153 import org.opensaml.artifact.Artifact;
154 import org.w3c.dom.Document;
155 import org.w3c.dom.Element;
156 import org.w3c.dom.Node;
158 import x0.maceShibboleth1.AttributeAcceptancePolicyDocument;
159 import x0.maceShibbolethTargetConfig1.ApplicationDocument;
160 import x0.maceShibbolethTargetConfig1.LocalConfigurationType;
161 import x0.maceShibbolethTargetConfig1.PluggableType;
162 import x0.maceShibbolethTargetConfig1.RequestMapDocument;
163 import x0.maceShibbolethTargetConfig1.SPConfigDocument;
164 import x0.maceShibbolethTargetConfig1.SPConfigType;
165 import x0.maceShibbolethTargetConfig1.ShibbolethTargetConfigDocument;
166 import x0.maceShibbolethTargetConfig1.ApplicationDocument.Application;
167 import x0.maceShibbolethTargetConfig1.ApplicationsDocument.Applications;
168 import x0.maceShibbolethTargetConfig1.HostDocument.Host;
169 import x0.maceShibbolethTargetConfig1.PathDocument.Path;
170 import edu.internet2.middleware.shibboleth.aap.AAP;
171 import edu.internet2.middleware.shibboleth.aap.AttributeRule;
172 import edu.internet2.middleware.shibboleth.common.Credentials;
173 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
174 import edu.internet2.middleware.shibboleth.common.Trust;
175 import edu.internet2.middleware.shibboleth.common.provider.ShibbolethTrust;
176 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
177 import edu.internet2.middleware.shibboleth.metadata.Metadata;
178 import edu.internet2.middleware.shibboleth.metadata.RoleDescriptor;
179 import edu.internet2.middleware.shibboleth.xml.Parser;
182 * Load the configuration files into objects, index them, and return them on request.
184 * <p>A new instance of the ServiceProviderConfig object can be created to
185 * parse a new version of the configuration file. It can then be swapped
186 * into the ServiceProviderContext reference and will be picked up by
187 * subsequent requests.</p>
189 * @author Howard Gilbert
191 public class ServiceProviderConfig {
194 private static final String INLINEURN = "urn:inlineBS:ID";
195 private static Logger log = Logger.getLogger(ServiceProviderConfig.class);
197 private SPConfigType // The XMLBean from the main config file
198 config = null; // (i.e. shibboleth.xml)
202 * The following Maps reference objects that implement a plugin
203 * interface indexed by their URI. There are builtin objects
204 * created from inline or external XML files, but external
205 * objects implementing the interfaces may be injected by
206 * calling the addOrReplaceXXX method. Public access to these
207 * Maps is indirect, through methods the ApplicationInfo object
208 * for a given configured or default application.
211 private Map/*<String, Metadata>*/ entityLocators =
212 new TreeMap/*<String, Metadata>*/();
214 public void addOrReplaceMetadataImplementor(String uri, Metadata m) {
215 entityLocators.put(uri, m);
218 public Metadata getMetadataImplementor(String uri) {
219 return (Metadata)entityLocators.get(uri);
222 private Map/*<String, AAP>*/ attributePolicies =
223 new TreeMap/*<String, AAP>*/();
225 public void addOrReplaceAAPImplementor(String uri, AAP a) {
226 attributePolicies.put(uri,a);
229 public AAP getAAPImplementor(String uri) {
230 return (AAP) attributePolicies.get(uri);
233 private Map/*<String, Trust>*/ certificateValidators =
234 new TreeMap/*<String, Trust>*/();
236 public void addOrReplaceTrustImplementor(String uri, Trust t) {
237 certificateValidators.put(uri,t);
240 public Trust getTrustImplementor(String uri) {
241 return (Trust) certificateValidators.get(uri);
244 private Trust[] defaultTrust = {new ShibbolethTrust()};
247 * Objects created from the <Application(s)> elements.
248 * They manage collections of URI-Strings that index the
249 * previous maps to return Metadata, Trust, and AAP info
250 * applicable to this applicationId.
252 private Map/*<String, ApplicationInfo>*/ applications =
253 new TreeMap/*<String, ApplicationInfo>*/();
255 // Default application info from <Applications> element
256 private ApplicationInfo defaultApplicationInfo = null;
258 public ApplicationInfo getApplication(String applicationId) {
259 ApplicationInfo app=null;
260 app = (ApplicationInfo) applications.get(applicationId);
261 if (app==null) // If no specific match, return default
262 return defaultApplicationInfo;
267 // Objects created from single configuration file elements
268 private Credentials credentials = null;
269 private RequestMapDocument.RequestMap requestMap = null;
276 private static final String XMLTRUSTPROVIDERTYPE =
277 "edu.internet2.middleware.shibboleth.common.provider.XMLTrust";
278 private static final String XMLAAPPROVIDERTYPE =
279 "edu.internet2.middleware.shibboleth.serviceprovider.XMLAAP";
280 private static final String XMLFEDERATIONPROVIDERTYPE =
281 "edu.internet2.middleware.shibboleth.common.provider.XMLMetadata";
282 private static final String XMLREVOCATIONPROVIDERTYPE =
283 "edu.internet2.middleware.shibboleth.common.provider.XMLRevocation";
284 private static final String XMLREQUESTMAPPROVIDERTYPE =
285 "edu.internet2.middleware.shibboleth.serviceprovider.XMLRequestMap";
286 private static final String XMLCREDENTIALSPROVIDERTYPE =
287 "edu.internet2.middleware.shibboleth.common.Credentials";
293 * The constructor prepares for, but does not parse the configuration.
295 * @throws ShibbolethConfigurationException
296 * if XML Parser cannot be initialized (Classpath problem)
298 public ServiceProviderConfig() {
302 * loadConfigObjects must be called once to parse the configuration.
304 * <p>To reload a modified configuration file, create and load a second
305 * object and swap the reference in the context object.</p>
307 * @param configFilePath URL or resource name of file
308 * @return the DOM Document
309 * @throws ShibbolethConfigurationException
310 * if there was an error loading the file
312 public synchronized void loadConfigObjects(String configFilePath)
313 throws ShibbolethConfigurationException {
316 log.error("ServiceProviderConfig.loadConfigObjects may not be called twice for the same object.");
317 throw new ShibbolethConfigurationException("Cannot reload configuration into same object.");
322 configDoc = Parser.loadDom(configFilePath, true);
323 } catch (Exception e) {
324 throw new ShibbolethConfigurationException("XML error in "+configFilePath);
326 loadConfigBean(configDoc);
332 * Given a URL, determine its ApplicationId from the RequestMap config.
334 * <p>Note: This is not a full implementation of all RequestMap
335 * configuration options. Other functions will be added as needed.</p>
337 public String mapRequest(String urlreq) {
338 String applicationId = "default";
342 url = new URL(urlreq);
343 } catch (MalformedURLException e) {
344 return applicationId;
347 String urlscheme = url.getProtocol();
348 String urlhostname = url.getHost();
349 String urlpath = url.getPath();
350 int urlport = url.getPort();
352 if (urlscheme.equals("http"))
354 else if (urlscheme.equals("https"))
358 // find Host entry for this virtual server
359 Host[] hostArray = requestMap.getHostArray();
360 for (int ihost=0;ihost<hostArray.length;ihost++) {
361 Host host = hostArray[ihost];
362 String hostScheme = host.getScheme().toString();
363 String hostName = host.getName();
364 String hostApplicationId = host.getApplicationId();
365 long hostport = host.getPort();
367 if (hostScheme.equals("http"))
369 else if (hostScheme.equals("https"))
373 if (!urlscheme.equals(hostScheme) ||
374 !urlhostname.equals(hostName)||
378 // find Path entry for this subdirectory
379 Path[] pathArray = host.getPathArray();
380 if (hostApplicationId!=null)
381 applicationId=hostApplicationId;
382 for (int i=0;i<pathArray.length;i++) {
383 String dirname = pathArray[i].getName();
384 if (urlpath.equals(dirname)||
385 urlpath.startsWith(dirname+"/")){
386 String pthid= pathArray[i].getApplicationId();
393 return applicationId;
397 * <p>Parse the main configuration file DOM into XML Bean</p>
399 * <p>Automatically load secondary configuration files designated
400 * by URLs in the main configuration file</p>
402 * @throws ShibbolethConfigurationException
404 private void loadConfigBean(Document configDoc)
405 throws ShibbolethConfigurationException {
406 boolean anyError=false;
408 Element documentElement = configDoc.getDocumentElement();
409 // reprocess the already validated DOM to create a bean with typed fields
410 // dump the trash (comments, processing instructions, extra whitespace)
413 if (documentElement.getLocalName().equals("ShibbolethTargetConfig")) {
414 ShibbolethTargetConfigDocument configBeanDoc;
415 configBeanDoc = ShibbolethTargetConfigDocument.Factory.parse(configDoc,
416 new XmlOptions().setLoadStripComments().setLoadStripProcinsts().setLoadStripWhitespace());
417 config = configBeanDoc.getShibbolethTargetConfig();
418 } else if (documentElement.getLocalName().equals("SPConfig")) {
419 SPConfigDocument configBeanDoc;
420 configBeanDoc = SPConfigDocument.Factory.parse(configDoc,
421 new XmlOptions().setLoadStripComments().setLoadStripProcinsts().setLoadStripWhitespace());
422 config = configBeanDoc.getSPConfig();
424 throw new XmlException("Root element not ShibbolethTargetConfig or SPConfig");
426 } catch (XmlException e) {
427 // Since the DOM was already validated against the schema, errors will not typically occur here
428 log.error("Error while parsing shibboleth configuration");
429 throw new ShibbolethConfigurationException("Error while parsing shibboleth configuration");
433 Applications apps = config.getApplications(); // <Applications>
438 * Create an <Application> id "default" from <Applications>
440 ApplicationDocument defaultAppDoc =
441 // Create a new XMLBeans "Document" level object
442 ApplicationDocument.Factory.newInstance();
443 ApplicationDocument.Application defaultApp =
444 // Add an XMLBeans "root Element" object to the Document
445 defaultAppDoc.addNewApplication();
446 // set or copy over fields from unrelated Applications object
447 defaultApp.setId("default");
448 defaultApp.setAAPProviderArray(apps.getAAPProviderArray());
449 defaultApp.setAttributeDesignatorArray(apps.getAttributeDesignatorArray());
450 defaultApp.setAudienceArray(apps.getAudienceArray());
451 defaultApp.setCredentialUse(apps.getCredentialUse());
452 defaultApp.setErrors(apps.getErrors());
453 defaultApp.setFederationProviderArray(apps.getFederationProviderArray());
454 defaultApp.setMetadataProviderArray(apps.getMetadataProviderArray());
455 defaultApp.setProviderId(apps.getProviderId());
456 defaultApp.setSessions(apps.getSessions());
457 defaultApp.setTrustProviderArray(apps.getTrustProviderArray());
460 * Now process secondary files configured in the applications
462 anyError |= processApplication(defaultApp);
464 Application[] apparray = apps.getApplicationArray();
465 for (int i=0;i<apparray.length;i++){
466 Application tempapp = apparray[i];
467 applications.put(tempapp.getId(),tempapp);
468 anyError |= processApplication(tempapp);
472 * Now process other secondary files
474 anyError |= processCredentials();
475 anyError |= processPluggableRequestMapProvider();
478 throw new ShibbolethConfigurationException("Errors processing configuration file, see log");
483 * Routine to handle CredentialProvider
485 * <p>Note: This only handles in-line XML.
486 * Also, Credentials was an existing IdP class, so it doesn't
487 * implement the new PluggableConfigurationComponent interface and
488 * can't be loaded by generic plugin support.
491 private boolean processCredentials() {
492 boolean anyError=false;
493 PluggableType[] pluggable = config.getCredentialsProviderArray();
494 for (int i=0;i<pluggable.length;i++) {
495 String pluggabletype = pluggable[i].getType();
496 if (!pluggabletype.equals(
497 "edu.internet2.middleware.shibboleth.common.Credentials")) {
498 log.error("Unsupported CredentialsProvider type "+pluggabletype);
502 PluggableType credentialsProvider = pluggable[i];
503 Node fragment = credentialsProvider.newDomNode();
504 // newDomNode returns the current node wrapped in a Fragment
506 Node credentialsProviderNode = fragment.getFirstChild();
507 Node credentialsNode=credentialsProviderNode.getFirstChild();
508 credentials = new Credentials((Element)credentialsNode);
509 } catch(Exception e) {
510 log.error("Cannot process Credentials element of Shibboleth configuration");
520 * Find and load secondary configuration files referenced in an Application(s)
522 * @param app Application object
523 * @throws ShibbolethConfigurationException
525 private boolean processApplication(Application app)
526 throws ShibbolethConfigurationException {
528 boolean anyError=false;
530 String applicationId = app.getId();
532 ApplicationInfo appinfo = new ApplicationInfo(app);
534 anyError |= processPluggableMetadata(appinfo);
535 anyError |= processPluggableAAPs(appinfo);
536 anyError |= processPluggableTrusts(appinfo);
538 applications.put(applicationId, appinfo);
544 * Generic code to create an object of a Pluggable type that implements
545 * a configuration interface.
547 * <p>The configuration schema defines "PluggableType" as a type of
548 * XML element that has opaque contents and attributes "type" and
549 * "uri". If the uri attribute is omitted, then the configuration
550 * data is inline XML content. The XSD files typically define the
551 * format of pluggable configuration elements, but without binding
552 * them to the PluggableType element that may contain them.</p>
554 * <p>The implimentation of pluggable objects is provided by
555 * external classes. There are "builtin" classes provided with
556 * Shibboleth (XMLMetadataImpl, XMLTrustImpl, XMLAAPImpl) that
557 * provide examples of how this is done. By design, others can
558 * provide their own classes just by putting the class name as
559 * the value of the type attribute.</p>
561 * <p>This routine handles the common setup. It creates objects
562 * of one of the builtin types, or it uses Class.forName() to
563 * access a user specified class. It then locates either the
564 * inline XML elements or the external XML file. It passes the
565 * XML to initialize the object. Finally, a reference to the
566 * object is stored in the appropriate Map.</p>
568 * <p>The objects created implement two interfaces. Mostly they
569 * implement a configuration interface (EntityDescriptor, Trust,
570 * AAP, etc). However, for the purpose of this routine they also
571 * must be declared to implement PluggableConfigurationComponent
572 * and provide an initialize() method that parses a DOM Node
573 * containing their root XML configuration element.</p>
575 * @param pluggable XMLBean for element defined in XSD to be of "PluggableType"
576 * @param implclass java.lang.Class of Builtin implementation class
577 * @param interfaceClass java.lang.Class of Interface
578 * @param builtinName alias type to choose Builtin imlementation
579 * @param uriMap ApplicationInfo Map for this interface
585 PluggableType pluggable,
587 Class interfaceClass,
590 Map /*<String,PluggableConfigurationComponent>*/uriMap
593 String pluggabletype = pluggable.getType();
595 if (!pluggabletype.equals(builtinName)) {
596 // Not the builtin type, try to load user class by name
598 implclass = Class.forName(pluggabletype);
599 } catch (ClassNotFoundException e) {
600 log.error("Type value "+pluggabletype+" not found as supplied Java class");
603 if (!interfaceClass.isAssignableFrom(implclass)||
604 !PluggableConfigurationComponent.class.isAssignableFrom(implclass)) {
605 log.error(pluggabletype+" class does not support required interfaces.");
610 PluggableConfigurationComponent impl;
612 impl = (PluggableConfigurationComponent) implclass.newInstance();
613 } catch (Exception e) {
614 log.error("Unable to instantiate "+pluggabletype);
618 String uri = pluggable.getUri();
619 if (uri==null) { // inline
623 Node fragment = pluggable.newDomNode(); // XML-Fragment node
624 Node pluggableNode = fragment.getFirstChild(); // PluggableType
625 Node contentNode=pluggableNode.getFirstChild();// root element
626 impl.initialize(contentNode);
627 } catch (Exception e) {
628 log.error("XML error " + e);
632 } else { // external file
634 if (uriMap.get(uri)!=null) { // Already parsed this file
639 String tempname = impl.getSchemaPathname();
644 Document extdoc = Parser.loadDom(uri,true);
647 impl.initialize(extdoc);
648 } catch (Exception e) {
649 log.error("XML error " + e);
654 uriMap.put(uri,impl);
661 * Handle a FederationProvider
663 private boolean processPluggableMetadata(ApplicationInfo appinfo) {
664 boolean anyError = false;
665 PluggableType[] pluggable1 = appinfo.getApplicationConfig().getFederationProviderArray();
666 PluggableType[] pluggable2 = appinfo.getApplicationConfig().getMetadataProviderArray();
667 PluggableType[] pluggable;
668 if (pluggable1.length==0) {
669 pluggable=pluggable2;
670 } else if (pluggable2.length==0) {
671 pluggable=pluggable1;
673 pluggable = new PluggableType[pluggable1.length+pluggable2.length];
674 for (int i=0;i<pluggable2.length;i++) {
675 pluggable[i]=pluggable2[i];
677 for (int i=0;i<pluggable1.length;i++) {
678 pluggable[i+pluggable2.length]=pluggable1[i];
681 for (int i = 0;i<pluggable.length;i++) {
682 String uri = processPluggable(pluggable[i],
683 XMLMetadataImpl.class,
685 XMLFEDERATIONPROVIDERTYPE,
690 else if (uri.length()>0) {
691 appinfo.addGroupUri(uri);
698 * Reload XML Metadata configuration after file changed.
699 * @param uri Path to Metadata XML configuration
700 * @return true if file reloaded.
702 public boolean reloadFederation(String uri) {
703 if (getMetadataImplementor(uri)!=null||
704 uri.startsWith(INLINEURN))
707 Document sitedoc = Parser.loadDom(uri,true);
710 XMLMetadataImpl impl = new XMLMetadataImpl();
711 impl.initialize(sitedoc);
712 addOrReplaceMetadataImplementor(uri,impl);
713 } catch (Exception e) {
714 log.error("Error while parsing Metadata file "+uri);
715 log.error("XML error " + e);
722 * Handle an AAPProvider element with
723 * type="edu.internet2.middleware.shibboleth.common.provider.XMLAAP"
724 * @throws InternalConfigurationException
726 private boolean processPluggableAAPs(ApplicationInfo appinfo){
727 boolean anyError=false;
728 PluggableType[] pluggable = appinfo.getApplicationConfig().getAAPProviderArray();
729 for (int i = 0;i<pluggable.length;i++) {
730 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 ShibbolethTrust.class,
790 XMLTRUSTPROVIDERTYPE,
792 certificateValidators);
795 else if (uri.length()>0) {
796 appinfo.addTrustUri(uri);
804 private boolean processPluggableRequestMapProvider(){
805 LocalConfigurationType shire = config.getSHIRE();
806 PluggableType mapProvider = shire.getRequestMapProvider();
808 String pluggabletype = mapProvider.getType();
809 if (!pluggabletype.equals(XMLREQUESTMAPPROVIDERTYPE)) {
810 log.error("Unsupported RequestMapProvider type "+pluggabletype);
814 RequestMapDocument requestMapDoc = null;
815 Document mapdoc = null;
816 Element maproot = null;
817 String uri = mapProvider.getUri();
819 if (uri==null) { // inline
823 Node fragment = mapProvider.newDomNode();
824 Node pluggableNode = fragment.getFirstChild();
825 Node contentNode=pluggableNode.getFirstChild();
827 requestMapDoc = RequestMapDocument.Factory.parse(contentNode);
828 } catch (Exception e) {
829 log.error("Error while parsing inline RequestMap");
830 log.error("XML error " + e);
834 } else { // external file
836 mapdoc = Parser.loadDom(uri,true);
839 requestMapDoc = RequestMapDocument.Factory.parse(mapdoc);
840 } catch (Exception e) {
841 log.error("Error while parsing RequestMap file "+uri);
842 log.error("XML error " + e);
847 requestMap = requestMapDoc.getRequestMap();
853 private int inlinenum = 1;
854 private String genDummyUri() {
855 return INLINEURN+Integer.toString(inlinenum++);
864 * ApplicationInfo represents the <Application(s)> object, its fields,
865 * and the pluggable configuration elements under it.
867 * <p>It can return arrays of Metadata, Trust, or AAP providers, but
868 * it also exposes convenience methods that shop the lookup(),
869 * validate(), and trust() calls to each object in the collection
870 * until success or failure is determined.</p>
872 * <p>For all other parameters, such as Session parameters, you
873 * can fetch the XMLBean by calling getApplicationConf() and
874 * query their value directly.
876 public class ApplicationInfo
877 implements Metadata, Trust {
879 private Application applicationConfig;
880 public Application getApplicationConfig() {
881 return applicationConfig;
885 * Construct this object from the XML Bean.
886 * @param application XMLBean for Application element
888 ApplicationInfo(Application application) {
889 this.applicationConfig=application;
894 * Following the general rule, this object may not keep
895 * direct references to the plugin interface implementors,
896 * but must look them up on every call through their URI keys.
897 * So we keep collections of URI strings instead.
899 ArrayList groupUris = new ArrayList();
900 ArrayList trustUris = new ArrayList();
901 ArrayList aapUris = new ArrayList();
903 void addGroupUri(String uri) {
906 void addTrustUri(String uri) {
909 void addAapUri(String uri) {
914 * Return the current array of objects that implement the
915 * ...metadata.Metadata interface
919 Metadata[] getMetadataProviders() {
920 Iterator iuris = groupUris.iterator();
921 int count = groupUris.size();
922 Metadata[] metadatas = new Metadata[count];
923 for (int i=0;i<count;i++) {
924 String uri =(String) iuris.next();
925 metadatas[i]=getMetadataImplementor(uri);
931 * A convenience function based on the Metadata interface.
933 * <p>Look for an entity ID through each implementor until the
934 * first one finds locates a describing object.</p>
936 * <p>Unfortunately, Metadata.lookup() was originally specified to
937 * return a "Provider". In current SAML 2.0 terms, the object
938 * returned should be an EntityDescriptor. So this is the new
939 * function in the new interface that will use the new term, but
940 * it does the same thing.</p>
942 * @param id ID of the IdP entity
943 * @return EntityDescriptor metadata object for that site.
945 public EntityDescriptor lookup(String id) {
946 Iterator iuris = groupUris.iterator();
947 while (iuris.hasNext()) {
948 String uri =(String) iuris.next();
949 Metadata locator=getMetadataImplementor(uri);
950 EntityDescriptor entity = locator.lookup(id);
957 public EntityDescriptor lookup(Artifact artifact) {
958 Iterator iuris = groupUris.iterator();
959 while (iuris.hasNext()) {
960 String uri =(String) iuris.next();
961 Metadata locator=getMetadataImplementor(uri);
962 EntityDescriptor entity = locator.lookup(artifact);
970 * Return the current array of objects that implement the Trust interface
974 public Trust[] getTrustProviders() {
975 Iterator iuris = trustUris.iterator();
976 int count = trustUris.size();
979 Trust[] trusts = new Trust[count];
980 for (int i=0;i<count;i++) {
981 String uri =(String) iuris.next();
982 trusts[i]=getTrustImplementor(uri);
988 * Return the current array of objects that implement the AAP interface
992 public AAP[] getAAPProviders() {
993 Iterator iuris = aapUris.iterator();
994 int count = aapUris.size();
995 AAP[] aaps = new AAP[count];
996 for (int i=0;i<count;i++) {
997 String uri =(String) iuris.next();
998 aaps[i]=getAAPImplementor(uri);
1004 * Convenience function to apply AAP by calling the apply()
1005 * method of each AAP implementor.
1007 * <p>Any AAP implementor can delete an assertion or value.
1008 * Empty SAML elements get removed from the assertion.
1009 * This can yield an AttributeAssertion with no attributes.
1011 * @param assertion SAML Attribute Assertion
1012 * @param role Role that issued the assertion
1013 * @throws SAMLException Raised if assertion is mangled beyond repair
1015 void applyAAP(SAMLAssertion assertion, RoleDescriptor role) throws SAMLException {
1017 // Foreach AAP in the collection
1018 AAP[] providers = getAAPProviders();
1019 if (providers.length == 0) {
1020 log.info("no filters specified, accepting entire assertion");
1023 for (int i=0;i<providers.length;i++) {
1024 AAP aap = providers[i];
1025 if (aap.anyAttribute()) {
1026 log.info("any attribute enabled, accepting entire assertion");
1031 // Foreach Statement in the Assertion
1032 Iterator statements = assertion.getStatements();
1034 while (statements.hasNext()) {
1035 Object statement = statements.next();
1036 if (statement instanceof SAMLAttributeStatement) {
1037 SAMLAttributeStatement attributeStatement = (SAMLAttributeStatement) statement;
1039 // Check each attribute, applying any matching rules.
1040 Iterator attributes = attributeStatement.getAttributes();
1042 while (attributes.hasNext()) {
1043 SAMLAttribute attribute = (SAMLAttribute) attributes.next();
1044 boolean ruleFound = false;
1045 for (int i=0;i<providers.length;i++) {
1046 AttributeRule rule = providers[i].lookup(attribute.getName(),attribute.getNamespace());
1050 rule.apply(attribute,role);
1052 catch (SAMLException ex) {
1053 log.info("no values remain, removing attribute");
1054 attributeStatement.removeAttribute(iattribute--);
1060 log.warn("no rule found for attribute (" + attribute.getName() + "), filtering it out");
1061 attributeStatement.removeAttribute(iattribute--);
1067 attributeStatement.checkValidity();
1070 catch (SAMLException ex) {
1071 // The statement is now defunct.
1072 log.info("no attributes remain, removing statement");
1073 assertion.removeStatement(istatement);
1078 // Now see if we trashed it irrevocably.
1079 assertion.checkValidity();
1084 * Returns a collection of attribute names to request from the AA.
1086 * @return Collection of attribute Name values
1088 public Collection getAttributeDesignators() {
1089 // TODO Not sure where this should come from
1090 return new ArrayList();
1095 * Convenience method implementing Trust.validate() across
1096 * the collection of implementing objects. Returns true if
1097 * any Trust implementor approves the signatures in the object.
1099 * <p>In the interface, validate() is passed several arguments
1100 * that come from this object. In this function, those
1101 * arguments are ignored "this" is used.
1105 SAMLSignedObject token,
1110 Trust[] trustProviders = getTrustProviders();
1111 for (int i=0;i<trustProviders.length;i++) {
1112 Trust trust = trustProviders[i];
1113 if (trust.validate(token,role))
1121 * A method of Trust that we must declare to claim that
1122 * ApplicationInfo implements Trust. However, no code in the
1123 * ServiceProvider calls this (probably an IdP thing).
1125 * @param revocations
1127 * @return This dummy always returns false.
1129 public boolean attach(Iterator revocations, RoleDescriptor role) {
1134 public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain, RoleDescriptor descriptor) {
1135 Trust[] trustProviders = getTrustProviders();
1136 for (int i=0;i<trustProviders.length;i++) {
1137 Trust trust = trustProviders[i];
1138 if (trust.validate(certificateEE,certificateChain,descriptor))
1144 public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain, RoleDescriptor descriptor, boolean checkName) {
1145 Trust[] trustProviders = getTrustProviders();
1146 for (int i=0;i<trustProviders.length;i++) {
1147 Trust trust = trustProviders[i];
1148 if (trust.validate(certificateEE,certificateChain,descriptor,checkName))
1157 private static class InternalConfigurationException extends Exception {
1158 InternalConfigurationException() {