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.aap.provider.XMLAAPProvider;
182 import edu.internet2.middleware.shibboleth.common.Credentials;
183 import edu.internet2.middleware.shibboleth.common.PluggableConfigurationComponent;
184 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
185 import edu.internet2.middleware.shibboleth.common.Trust;
186 import edu.internet2.middleware.shibboleth.common.provider.ShibbolethTrust;
187 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
188 import edu.internet2.middleware.shibboleth.metadata.Metadata;
189 import edu.internet2.middleware.shibboleth.metadata.RoleDescriptor;
190 import edu.internet2.middleware.shibboleth.metadata.provider.XMLMetadataProvider;
191 import edu.internet2.middleware.shibboleth.xml.Parser;
194 * Load the configuration files into objects, index them, and return them on request.
196 * <p>A new instance of the ServiceProviderConfig object can be created to
197 * parse a new version of the configuration file. It can then be swapped
198 * into the ServiceProviderContext reference and will be picked up by
199 * subsequent requests.</p>
201 * @author Howard Gilbert
203 public class ServiceProviderConfig {
205 // Map key prefix for inline plugin configuration elements
206 private static final String INLINEURN = "urn:inlineBS:ID";
208 private static Logger initlog = Logger.getLogger(ContextListener.SHIBBOLETH_INIT+".Config");
209 private static Logger reqlog = Logger.getLogger(ServiceProviderConfig.class);
211 private SPConfigType // The XMLBean from the main config file
216 * The following Maps reference objects that implement a plugin
217 * interface indexed by their URI. There are builtin objects
218 * created from inline or external XML files, but external
219 * objects implementing the interfaces may be injected by
220 * calling the addOrReplaceXXX method. Public access to these
221 * Maps is indirect, through methods the ApplicationInfo object
222 * for a given configured or default application.
225 private Map/*<String, Metadata>*/ entityLocators =
226 new TreeMap/*<String, Metadata>*/();
228 public void addOrReplaceMetadataImplementor(String uri, Metadata m) {
229 initlog.info("addOrReplaceMetadataImplementor " + uri+ " as "+m.getClass());
230 entityLocators.put(uri, m);
233 public Metadata getMetadataImplementor(String uri) {
234 return (Metadata)entityLocators.get(uri);
237 private Map/*<String, AAP>*/ attributePolicies =
238 new TreeMap/*<String, AAP>*/();
240 public void addOrReplaceAAPImplementor(String uri, AAP a) {
241 initlog.info("addOrReplaceAAPImplementor " + uri+ " as "+a.getClass());
242 attributePolicies.put(uri,a);
245 public AAP getAAPImplementor(String uri) {
246 return (AAP) attributePolicies.get(uri);
249 private Map/*<String, Trust>*/ certificateValidators =
250 new TreeMap/*<String, Trust>*/();
252 public void addOrReplaceTrustImplementor(String uri, Trust t) {
253 initlog.info("addOrReplaceTrustImplementor " + uri+ " as "+t.getClass());
254 certificateValidators.put(uri,t);
257 public Trust getTrustImplementor(String uri) {
258 return (Trust) certificateValidators.get(uri);
261 private Trust[] defaultTrust = {new ShibbolethTrust()};
264 * Objects created from the <Application(s)> elements.
265 * They manage collections of URI-Strings that index the
266 * previous maps to return Metadata, Trust, and AAP info
267 * applicable to this applicationId.
269 private Map/*<String, ApplicationInfo>*/ applications =
270 new TreeMap/*<String, ApplicationInfo>*/();
272 // Default application info from <Applications> element
273 private ApplicationInfo defaultApplicationInfo = null;
275 public ApplicationInfo getApplication(String applicationId) {
276 ApplicationInfo app=null;
277 app = (ApplicationInfo) applications.get(applicationId);
278 if (app==null) // If no specific match, return default
279 return defaultApplicationInfo;
284 // Objects created from single configuration file elements
285 private Credentials credentials = null;
286 private RequestMapDocument.RequestMap requestMap = null;
293 private static final String XMLTRUSTPROVIDERTYPE =
294 "edu.internet2.middleware.shibboleth.common.provider.ShibbolethTrust";
295 private static final String XMLAAPPROVIDERTYPE =
296 "edu.internet2.middleware.shibboleth.aap.provider.XMLAAP";
297 private static final String XMLFEDERATIONPROVIDERTYPE =
298 "edu.internet2.middleware.shibboleth.metadata.provider.XMLMetadata";
299 private static final String XMLREQUESTMAPPROVIDERTYPE =
300 "edu.internet2.middleware.shibboleth.sp.provider.NativeRequestMapProvider";
301 private static final String XMLCREDENTIALSPROVIDERTYPE =
302 "edu.internet2.middleware.shibboleth.common.Credentials";
308 * The constructor prepares for, but does not parse the configuration.
310 * @throws ShibbolethConfigurationException
311 * if XML Parser cannot be initialized (Classpath problem)
313 public ServiceProviderConfig() {
317 * loadConfigObjects must be called once to parse the configuration.
319 * <p>To reload a modified configuration file, create and load a second
320 * object and swap the reference in the context object.</p>
322 * @param configFilePath URL or resource name of file
323 * @return the DOM Document
324 * @throws ShibbolethConfigurationException
325 * if there was an error loading the file
327 public synchronized void loadConfigObjects(String configFilePath)
328 throws ShibbolethConfigurationException {
331 initlog.error("ServiceProviderConfig.loadConfigObjects may not be called twice for the same object.");
332 throw new ShibbolethConfigurationException("Cannot reload configuration into same object.");
335 initlog.info("Loading SP configuration from "+configFilePath);
339 configDoc = Parser.loadDom(configFilePath, true);
340 } catch (Exception e) {
341 initlog.error("XML Parser error "+e.toString());
342 throw new ShibbolethConfigurationException("XML error in "+configFilePath);
344 loadConfigBean(configDoc);
350 * Given a URL, determine its ApplicationId from the RequestMap config.
352 * <p>Note: This is not a full implementation of all RequestMap
353 * configuration options. Other functions will be added as needed.</p>
355 public String mapRequest(String urlreq) {
356 String applicationId = "default";
360 url = new URL(urlreq);
361 } catch (MalformedURLException e) {
362 return applicationId;
365 String urlscheme = url.getProtocol();
366 String urlhostname = url.getHost();
367 String urlpath = url.getPath();
368 int urlport = url.getPort();
370 // find Host entry for this virtual server
371 Host[] hostArray = requestMap.getHostArray();
372 for (int ihost=0;ihost<hostArray.length;ihost++) {
373 Host host = hostArray[ihost];
374 Enum scheme = host.getScheme();
375 String hostName = host.getName();
376 String hostApplicationId = host.getApplicationId();
377 long hostport = host.getPort();
379 if (scheme != null &&
380 !urlscheme.equals(scheme.toString()))
382 if (!urlhostname.equals(hostName))
389 // find Path entry for this subdirectory
390 Path[] pathArray = host.getPathArray();
391 if (hostApplicationId!=null)
392 applicationId=hostApplicationId;
393 for (int i=0;i<pathArray.length;i++) {
394 String dirname = pathArray[i].getName();
395 if (urlpath.equals(dirname)||
396 urlpath.startsWith(dirname+"/")){
397 String pthid= pathArray[i].getApplicationId();
404 reqlog.debug("mapRequest mapped "+urlreq+" into "+applicationId);
405 return applicationId;
409 * <p>Parse the main configuration file DOM into XML Bean</p>
411 * <p>Automatically load secondary configuration files designated
412 * by URLs in the main configuration file</p>
414 * @throws ShibbolethConfigurationException
416 private void loadConfigBean(Document configDoc)
417 throws ShibbolethConfigurationException {
418 boolean anyError=false;
420 Element documentElement = configDoc.getDocumentElement();
421 // reprocess the already validated DOM to create a bean with typed fields
422 // dump the trash (comments, processing instructions, extra whitespace)
424 if (documentElement.getLocalName().equals("ShibbolethTargetConfig")) {
425 initlog.debug("SP Configuration file is in 1.2 syntax.");
426 ShibbolethTargetConfigDocument configBeanDoc;
427 configBeanDoc = ShibbolethTargetConfigDocument.Factory.parse(configDoc,
428 new XmlOptions().setLoadStripComments().setLoadStripProcinsts().setLoadStripWhitespace());
429 config = configBeanDoc.getShibbolethTargetConfig();
430 } else if (documentElement.getLocalName().equals("SPConfig")) {
431 initlog.debug("SP Configuration file is in 1.3 syntax.");
432 SPConfigDocument configBeanDoc;
433 configBeanDoc = SPConfigDocument.Factory.parse(configDoc,
434 new XmlOptions().setLoadStripComments().setLoadStripProcinsts().setLoadStripWhitespace());
435 config = configBeanDoc.getSPConfig();
437 initlog.error("Root element not ShibbolethTargetConfig or SPConfig");
438 throw new XmlException("Root element not ShibbolethTargetConfig or SPConfig");
440 } catch (XmlException e) {
441 // Since the DOM was already validated against the schema, errors will not typically occur here
442 initlog.error("Error while parsing shibboleth configuration");
443 throw new ShibbolethConfigurationException("Error while parsing shibboleth configuration");
446 String loggerUrlString = config.getLogger();
447 if (loggerUrlString!=null) {
449 URL loggerURL = new URL(loggerUrlString);
450 initlog.warn("logging is being reconfigured by "+ loggerUrlString);
451 PropertyConfigurator.configure(loggerURL);
452 } catch (MalformedURLException e) {
453 // This error is not serious enough to prevent initialization
454 initlog.error("Ignoring invalid value for logger attribute "+loggerUrlString );
458 Applications apps = config.getApplications(); // <Applications>
463 * Create an <Application> id "default" from <Applications>
465 ApplicationDocument defaultAppDoc =
466 // Create a new XMLBeans "Document" level object
467 ApplicationDocument.Factory.newInstance();
468 ApplicationDocument.Application defaultApp =
469 // Add an XMLBeans "root Element" object to the Document
470 defaultAppDoc.addNewApplication();
471 // set or copy over fields from unrelated Applications object
472 defaultApp.setId("default");
473 defaultApp.setAAPProviderArray(apps.getAAPProviderArray());
474 defaultApp.setAttributeDesignatorArray(apps.getAttributeDesignatorArray());
475 defaultApp.setAudienceArray(apps.getAudienceArray());
476 defaultApp.setCredentialUse(apps.getCredentialUse());
477 defaultApp.setErrors(apps.getErrors());
478 defaultApp.setFederationProviderArray(apps.getFederationProviderArray());
479 defaultApp.setMetadataProviderArray(apps.getMetadataProviderArray());
480 defaultApp.setProviderId(apps.getProviderId());
481 defaultApp.setSessions(apps.getSessions());
482 defaultApp.setTrustProviderArray(apps.getTrustProviderArray());
485 * Now process secondary files configured in the applications
487 anyError |= processApplication(defaultApp);
489 Application[] apparray = apps.getApplicationArray();
490 for (int i=0;i<apparray.length;i++){
491 Application tempapp = apparray[i];
492 applications.put(tempapp.getId(),tempapp);
493 anyError |= processApplication(tempapp);
497 * Now process other secondary files
499 anyError |= processCredentials();
500 anyError |= processPluggableRequestMapProvider();
503 initlog.error("SP Initialization terminated due to configuration errors");
504 throw new ShibbolethConfigurationException("Errors processing configuration file, see log");
510 * Routine to handle CredentialProvider
512 * <p>Note: This only handles in-line XML.
513 * Also, Credentials was an existing IdP class, so it doesn't
514 * implement the new PluggableConfigurationComponent interface and
515 * can't be loaded by generic plugin support.
518 private boolean processCredentials() {
519 boolean anyError=false;
520 PluggableType[] pluggable = config.getCredentialsProviderArray();
521 for (int i=0;i<pluggable.length;i++) {
522 String pluggabletype = pluggable[i].getType();
523 if (!pluggabletype.equals(
524 "edu.internet2.middleware.shibboleth.common.Credentials")) {
525 initlog.error("Unsupported CredentialsProvider type "+pluggabletype);
529 PluggableType credentialsProvider = pluggable[i];
530 Node fragment = credentialsProvider.newDomNode();
531 // newDomNode returns the current node wrapped in a Fragment
533 Node credentialsProviderNode = fragment.getFirstChild();
534 Node credentialsNode=credentialsProviderNode.getFirstChild();
535 credentials = new Credentials((Element)credentialsNode);
536 } catch(Exception e) {
537 initlog.error("Cannot process Credentials element of Shibboleth configuration",e);
546 * Find and load secondary configuration files referenced in an Application(s)
548 * @param app Application object
549 * @throws ShibbolethConfigurationException
551 private boolean processApplication(Application app)
552 throws ShibbolethConfigurationException {
554 boolean anyError=false;
556 String applicationId = app.getId();
558 ApplicationInfo appinfo = new ApplicationInfo(app);
560 anyError |= processPluggableMetadata(appinfo);
561 anyError |= processPluggableAAPs(appinfo);
562 anyError |= processPluggableTrusts(appinfo);
564 applications.put(applicationId, appinfo);
570 * Generic code to create an object of a Pluggable type that implements
571 * a configuration interface.
573 * <p>The configuration schema defines "PluggableType" as a type of
574 * XML element that has opaque contents and attributes "type" and
575 * "uri". If the uri attribute is omitted, then the configuration
576 * data is inline XML content. The XSD files typically define the
577 * format of pluggable configuration elements, but without binding
578 * them to the PluggableType element that may contain them.</p>
580 * <p>The implimentation of pluggable objects is provided by
581 * external classes. There are "builtin" classes provided with
582 * Shibboleth (XMLMetadataImpl, XMLTrustImpl, XMLAAPImpl) that
583 * provide examples of how this is done. By design, others can
584 * provide their own classes just by putting the class name as
585 * the value of the type attribute.</p>
587 * <p>This routine handles the common setup. It creates objects
588 * of one of the builtin types, or it uses Class.forName() to
589 * access a user specified class. It then locates either the
590 * inline XML elements or the external XML file. It passes the
591 * XML to initialize the object. Finally, a reference to the
592 * object is stored in the appropriate Map.</p>
594 * <p>The objects created implement two interfaces. Mostly they
595 * implement a configuration interface (EntityDescriptor, Trust,
596 * AAP, etc). However, for the purpose of this routine they also
597 * must be declared to implement PluggableConfigurationComponent
598 * and provide an initialize() method that parses a DOM Node
599 * containing their root XML configuration element.</p>
601 * @param pluggable XMLBean for element defined in XSD to be of "PluggableType"
602 * @param implclass java.lang.Class of Builtin implementation class
603 * @param interfaceClass java.lang.Class of Interface
604 * @param builtinName alias type to choose Builtin imlementation
605 * @param uriMap ApplicationInfo Map for this interface
611 PluggableType pluggable,
613 Class interfaceClass,
615 Map /*<String,PluggableConfigurationComponent>*/uriMap
618 String pluggabletype = pluggable.getType();
620 if (!pluggabletype.equals(builtinName)) {
621 // Not the builtin type, try to load user class by name
622 initlog.info("loading user-specified pluggable class "+pluggabletype);
624 implclass = Class.forName(pluggabletype);
625 } catch (ClassNotFoundException e) {
626 initlog.error("Type value "+pluggabletype+" not found as supplied Java class");
629 if (!interfaceClass.isAssignableFrom(implclass)||
630 !PluggableConfigurationComponent.class.isAssignableFrom(implclass)) {
631 initlog.error(pluggabletype+" class does not support required interfaces.");
636 PluggableConfigurationComponent impl;
638 impl = (PluggableConfigurationComponent) implclass.newInstance();
639 } catch (Exception e) {
640 initlog.error("Unable to instantiate "+pluggabletype);
644 String uri = pluggable.getUri();
645 if (uri==null) { // inline
649 Node fragment = pluggable.newDomNode(); // XML-Fragment node
650 Node pluggableNode = fragment.getFirstChild(); // PluggableType
651 Element contentNode=(Element) pluggableNode.getFirstChild();// root element
652 impl.initialize(contentNode);
653 } catch (Exception e) {
654 initlog.error("XML error " + e);
658 } else { // external file
660 if (uriMap.get(uri)!=null) { // Already parsed this file
665 Document extdoc = Parser.loadDom(uri,true);
668 impl.initialize(extdoc.getDocumentElement());
669 } catch (Exception e) {
670 initlog.error("XML error " + e);
675 uriMap.put(uri,impl);
682 * Handle a FederationProvider
684 private boolean processPluggableMetadata(ApplicationInfo appinfo) {
685 boolean anyError = false;
686 PluggableType[] pluggable1 = appinfo.getApplicationConfig().getFederationProviderArray();
687 PluggableType[] pluggable2 = appinfo.getApplicationConfig().getMetadataProviderArray();
688 PluggableType[] pluggable;
689 if (pluggable1.length==0) {
690 pluggable=pluggable2;
691 } else if (pluggable2.length==0) {
692 pluggable=pluggable1;
694 pluggable = new PluggableType[pluggable1.length+pluggable2.length];
695 for (int i=0;i<pluggable2.length;i++) {
696 pluggable[i]=pluggable2[i];
698 for (int i=0;i<pluggable1.length;i++) {
699 pluggable[i+pluggable2.length]=pluggable1[i];
702 for (int i = 0;i<pluggable.length;i++) {
703 String uri = processPluggable(pluggable[i],
704 XMLMetadataProvider.class,
706 XMLFEDERATIONPROVIDERTYPE,
710 else if (uri.length()>0) {
711 appinfo.addGroupUri(uri);
718 * Reload XML Metadata configuration after file changed.
719 * @param uri Path to Metadata XML configuration
720 * @return true if file reloaded.
722 public boolean reloadFederation(String uri) {
723 if (getMetadataImplementor(uri)!=null||
724 uri.startsWith(INLINEURN))
727 Document sitedoc = Parser.loadDom(uri,true);
730 XMLMetadataProvider impl = new XMLMetadataProvider();
731 impl.initialize(sitedoc.getDocumentElement());
732 addOrReplaceMetadataImplementor(uri,impl);
733 } catch (Exception e) {
734 initlog.error("Error while parsing Metadata file "+uri);
735 initlog.error("XML error " + e);
742 * Handle an AAPProvider element with
743 * type="edu.internet2.middleware.shibboleth.common.provider.XMLAAP"
744 * @throws InternalConfigurationException
746 private boolean processPluggableAAPs(ApplicationInfo appinfo){
747 boolean anyError=false;
748 PluggableType[] pluggable = appinfo.getApplicationConfig().getAAPProviderArray();
749 for (int i = 0;i<pluggable.length;i++) {
750 String uri = processPluggable(pluggable[i],
751 XMLAAPProvider.class,
757 else if (uri.length()>0) {
758 appinfo.addAapUri(uri);
765 * Reload XML AAP configuration after file changed.
766 * @param uri AAP to Trust XML configuration
767 * @return true if file reloaded.
769 public boolean reloadAAP(String uri) {
770 if (getAAPImplementor(uri)!=null||
771 uri.startsWith(INLINEURN))
774 Document aapdoc = Parser.loadDom(uri,true);
777 AttributeAcceptancePolicyDocument aap = AttributeAcceptancePolicyDocument.Factory.parse(aapdoc);
778 XMLAAPProvider impl = new XMLAAPProvider();
779 impl.initialize(aapdoc.getDocumentElement());
780 addOrReplaceAAPImplementor(uri,impl);
781 } catch (Exception e) {
782 initlog.error("Error while parsing AAP file "+uri);
783 initlog.error("XML error " + e);
791 * Handle a TrustProvider element with
792 * type="edu.internet2.middleware.shibboleth.common.provider.XMLTrust"
794 * Note: This code builds the semantic structure of trust. That is, it knows
795 * about certificates and keys. The actual logic of Trust (signature generation
796 * and validation) is implemented in a peer object defined in the external
797 * class XMLTrustImpl.
799 * @throws ShibbolethConfigurationException if X.509 certificate cannot be processed
800 * @throws InternalConfigurationException
802 private boolean processPluggableTrusts(ApplicationInfo appinfo){
803 boolean anyError=false;
804 PluggableType[] pluggable = appinfo.getApplicationConfig().getTrustProviderArray();
805 for (int i = 0;i<pluggable.length;i++) {
806 String uri = processPluggable(pluggable[i],
807 ShibbolethTrust.class,
809 XMLTRUSTPROVIDERTYPE,
810 certificateValidators);
813 else if (uri.length()>0) {
814 appinfo.addTrustUri(uri);
822 private boolean processPluggableRequestMapProvider(){
823 LocalConfigurationType shire = config.getSHIRE();
825 shire = config.getLocal();
827 initlog.error("No SHIRE or Local element.");
830 PluggableType mapProvider = shire.getRequestMapProvider();
832 String pluggabletype = mapProvider.getType();
833 if (!pluggabletype.equals(XMLREQUESTMAPPROVIDERTYPE)) {
834 initlog.error("Unsupported RequestMapProvider type "+pluggabletype);
838 RequestMapDocument requestMapDoc = null;
839 Document mapdoc = null;
840 Element maproot = null;
841 String uri = mapProvider.getUri();
843 if (uri==null) { // inline
847 Node fragment = mapProvider.newDomNode();
848 Node pluggableNode = fragment.getFirstChild();
849 Node contentNode=pluggableNode.getFirstChild();
851 requestMapDoc = RequestMapDocument.Factory.parse(contentNode);
852 } catch (Exception e) {
853 initlog.error("Error while parsing inline RequestMap");
854 initlog.error("XML error " + e);
858 } else { // external file
860 mapdoc = Parser.loadDom(uri,true);
863 requestMapDoc = RequestMapDocument.Factory.parse(mapdoc);
864 } catch (Exception e) {
865 initlog.error("Error while parsing RequestMap file "+uri);
866 initlog.error("XML error " + e);
871 requestMap = requestMapDoc.getRequestMap();
876 // Generate Map keys for inline plugin configuration Elements
877 private int inlinenum = 1;
878 private String genDummyUri() {
879 return INLINEURN+Integer.toString(inlinenum++);
888 * ApplicationInfo represents the <Application(s)> object, its fields,
889 * and the pluggable configuration elements under it.
891 * <p>It can return arrays of Metadata, Trust, or AAP providers, but
892 * it also exposes convenience methods that shop the lookup(),
893 * validate(), and trust() calls to each object in the collection
894 * until success or failure is determined.</p>
896 * <p>For all other parameters, such as Session parameters, you
897 * can fetch the XMLBean by calling getApplicationConf() and
898 * query their value directly.
900 public class ApplicationInfo
901 implements Metadata, Trust {
903 private Application applicationConfig;
904 public Application getApplicationConfig() {
905 return applicationConfig;
909 * Construct this object from the XML Bean.
910 * @param application XMLBean for Application element
912 ApplicationInfo(Application application) {
913 this.applicationConfig=application;
918 * Following the general rule, this object may not keep
919 * direct references to the plugin interface implementors,
920 * but must look them up on every call through their URI keys.
921 * So we keep collections of URI strings instead.
923 ArrayList groupUris = new ArrayList();
924 ArrayList trustUris = new ArrayList();
925 ArrayList aapUris = new ArrayList();
927 void addGroupUri(String uri) {
930 void addTrustUri(String uri) {
933 void addAapUri(String uri) {
938 * Return the current array of objects that implement the
939 * ...metadata.Metadata interface
943 Metadata[] getMetadataProviders() {
944 Iterator iuris = groupUris.iterator();
945 int count = groupUris.size();
946 Metadata[] metadatas = new Metadata[count];
947 for (int i=0;i<count;i++) {
948 String uri =(String) iuris.next();
949 metadatas[i]=getMetadataImplementor(uri);
955 * A convenience function based on the Metadata interface.
957 * <p>Look for an entity ID through each implementor until the
958 * first one finds locates a describing object.</p>
960 * <p>Unfortunately, Metadata.lookup() was originally specified to
961 * return a "Provider". In current SAML 2.0 terms, the object
962 * returned should be an EntityDescriptor. So this is the new
963 * function in the new interface that will use the new term, but
964 * it does the same thing.</p>
966 * @param id ID of the IdP entity
967 * @return EntityDescriptor metadata object for that site.
969 public EntityDescriptor lookup(String id) {
970 Iterator iuris = groupUris.iterator();
971 while (iuris.hasNext()) {
972 String uri =(String) iuris.next();
973 Metadata locator=getMetadataImplementor(uri);
974 EntityDescriptor entity = locator.lookup(id);
976 reqlog.debug("Metadata.lookup resolved Entity "+ id);
980 reqlog.warn("Metadata.lookup failed to resolve Entity "+ id);
984 public EntityDescriptor lookup(Artifact artifact) {
985 Iterator iuris = groupUris.iterator();
986 while (iuris.hasNext()) {
987 String uri =(String) iuris.next();
988 Metadata locator=getMetadataImplementor(uri);
989 EntityDescriptor entity = locator.lookup(artifact);
991 reqlog.debug("Metadata.lookup resolved Artifact "+ artifact);
995 reqlog.warn("Metadata.lookup failed to resolve Artifact "+ artifact);
1000 * Return the current array of objects that implement the Trust interface
1004 public Trust[] getTrustProviders() {
1005 Iterator iuris = trustUris.iterator();
1006 int count = trustUris.size();
1008 return defaultTrust;
1009 Trust[] trusts = new Trust[count];
1010 for (int i=0;i<count;i++) {
1011 String uri =(String) iuris.next();
1012 trusts[i]=getTrustImplementor(uri);
1018 * Return the current array of objects that implement the AAP interface
1022 public AAP[] getAAPProviders() {
1023 Iterator iuris = aapUris.iterator();
1024 int count = aapUris.size();
1025 AAP[] aaps = new AAP[count];
1026 for (int i=0;i<count;i++) {
1027 String uri =(String) iuris.next();
1028 aaps[i]=getAAPImplementor(uri);
1034 * Convenience function to apply AAP by calling the apply()
1035 * method of each AAP implementor.
1037 * <p>Any AAP implementor can delete an assertion or value.
1038 * Empty SAML elements get removed from the assertion.
1039 * This can yield an AttributeAssertion with no attributes.
1041 * @param assertion SAML Attribute Assertion
1042 * @param role Role that issued the assertion
1043 * @throws SAMLException Raised if assertion is mangled beyond repair
1045 void applyAAP(SAMLAssertion assertion, RoleDescriptor role) throws SAMLException {
1047 // Foreach AAP in the collection
1048 AAP[] providers = getAAPProviders();
1049 if (providers.length == 0) {
1050 reqlog.info("no filters specified, accepting entire assertion");
1053 for (int i=0;i<providers.length;i++) {
1054 AAP aap = providers[i];
1055 if (aap.anyAttribute()) {
1056 reqlog.info("any attribute enabled, accepting entire assertion");
1061 // Foreach Statement in the Assertion
1062 Iterator statements = assertion.getStatements();
1064 while (statements.hasNext()) {
1065 Object statement = statements.next();
1066 if (statement instanceof SAMLAttributeStatement) {
1067 SAMLAttributeStatement attributeStatement = (SAMLAttributeStatement) statement;
1069 // Check each attribute, applying any matching rules.
1070 Iterator attributes = attributeStatement.getAttributes();
1072 while (attributes.hasNext()) {
1073 SAMLAttribute attribute = (SAMLAttribute) attributes.next();
1074 boolean ruleFound = false;
1075 for (int i=0;i<providers.length;i++) {
1076 AttributeRule rule = providers[i].lookup(attribute.getName(),attribute.getNamespace());
1080 rule.apply(attribute,role);
1082 catch (SAMLException ex) {
1083 reqlog.info("no values remain, removing attribute");
1084 attributeStatement.removeAttribute(iattribute--);
1090 reqlog.warn("no rule found for attribute (" + attribute.getName() + "), filtering it out");
1091 attributeStatement.removeAttribute(iattribute--);
1097 attributeStatement.checkValidity();
1100 catch (SAMLException ex) {
1101 // The statement is now defunct.
1102 reqlog.info("no attributes remain, removing statement");
1103 assertion.removeStatement(istatement);
1108 // Now see if we trashed it irrevocably.
1109 assertion.checkValidity();
1114 * Returns a collection of attribute names to request from the AA.
1116 * @return Collection of attribute Name values
1118 public Collection getAttributeDesignators() {
1119 // TODO Not sure where this should come from
1120 return new ArrayList();
1125 * Convenience method implementing Trust.validate() across
1126 * the collection of implementing objects. Returns true if
1127 * any Trust implementor approves the signatures in the object.
1129 * <p>In the interface, validate() is passed several arguments
1130 * that come from this object. In this function, those
1131 * arguments are ignored "this" is used.
1135 SAMLSignedObject token,
1140 Trust[] trustProviders = getTrustProviders();
1141 for (int i=0;i<trustProviders.length;i++) {
1142 Trust trust = trustProviders[i];
1143 if (trust.validate(token,role))
1146 reqlog.warn("SAML object failed Trust validation.");
1152 * A method of Trust that we must declare to claim that
1153 * ApplicationInfo implements Trust. However, no code in the
1154 * ServiceProvider calls this (probably an IdP thing).
1156 * @param revocations
1158 * @return This dummy always returns false.
1160 public boolean attach(Iterator revocations, RoleDescriptor role) {
1165 public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain, RoleDescriptor descriptor) {
1166 Trust[] trustProviders = getTrustProviders();
1167 for (int i=0;i<trustProviders.length;i++) {
1168 Trust trust = trustProviders[i];
1169 if (trust.validate(certificateEE,certificateChain,descriptor))
1172 reqlog.warn("X.509 Certificate failed Trust validate");
1176 public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain, RoleDescriptor descriptor, boolean checkName) {
1177 Trust[] trustProviders = getTrustProviders();
1178 for (int i=0;i<trustProviders.length;i++) {
1179 Trust trust = trustProviders[i];
1180 if (trust.validate(certificateEE,certificateChain,descriptor,checkName))
1183 reqlog.warn("X.509 Certificate failed Trust validate");
1187 public String getProviderId() {
1188 String entityId = this.applicationConfig.getProviderId();
1189 if (entityId==null && this!=defaultApplicationInfo) {
1190 entityId = defaultApplicationInfo.getProviderId();
1198 private static class InternalConfigurationException extends Exception {
1199 InternalConfigurationException() {
1206 public Credentials getCredentials() {