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.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.metadata.provider.XMLMetadataProvider;
190 import edu.internet2.middleware.shibboleth.xml.Parser;
193 * Load the configuration files into objects, index them, and return them on request.
195 * <p>A new instance of the ServiceProviderConfig object can be created to
196 * parse a new version of the configuration file. It can then be swapped
197 * into the ServiceProviderContext reference and will be picked up by
198 * subsequent requests.</p>
200 * @author Howard Gilbert
202 public class ServiceProviderConfig {
204 // Map key prefix for inline plugin configuration elements
205 private static final String INLINEURN = "urn:inlineBS:ID";
207 private static Logger initlog = Logger.getLogger(ContextListener.SHIBBOLETH_INIT+".Config");
208 private static Logger reqlog = Logger.getLogger(ServiceProviderConfig.class);
210 private SPConfigType // The XMLBean from the main config file
215 * The following Maps reference objects that implement a plugin
216 * interface indexed by their URI. There are builtin objects
217 * created from inline or external XML files, but external
218 * objects implementing the interfaces may be injected by
219 * calling the addOrReplaceXXX method. Public access to these
220 * Maps is indirect, through methods the ApplicationInfo object
221 * for a given configured or default application.
224 private Map/*<String, Metadata>*/ entityLocators =
225 new TreeMap/*<String, Metadata>*/();
227 public void addOrReplaceMetadataImplementor(String uri, Metadata m) {
228 initlog.info("addOrReplaceMetadataImplementor " + uri+ " as "+m.getClass());
229 entityLocators.put(uri, m);
232 public Metadata getMetadataImplementor(String uri) {
233 return (Metadata)entityLocators.get(uri);
236 private Map/*<String, AAP>*/ attributePolicies =
237 new TreeMap/*<String, AAP>*/();
239 public void addOrReplaceAAPImplementor(String uri, AAP a) {
240 initlog.info("addOrReplaceAAPImplementor " + uri+ " as "+a.getClass());
241 attributePolicies.put(uri,a);
244 public AAP getAAPImplementor(String uri) {
245 return (AAP) attributePolicies.get(uri);
248 private Map/*<String, Trust>*/ certificateValidators =
249 new TreeMap/*<String, Trust>*/();
251 public void addOrReplaceTrustImplementor(String uri, Trust t) {
252 initlog.info("addOrReplaceTrustImplementor " + uri+ " as "+t.getClass());
253 certificateValidators.put(uri,t);
256 public Trust getTrustImplementor(String uri) {
257 return (Trust) certificateValidators.get(uri);
260 private Trust[] defaultTrust = {new ShibbolethTrust()};
263 * Objects created from the <Application(s)> elements.
264 * They manage collections of URI-Strings that index the
265 * previous maps to return Metadata, Trust, and AAP info
266 * applicable to this applicationId.
268 private Map/*<String, ApplicationInfo>*/ applications =
269 new TreeMap/*<String, ApplicationInfo>*/();
271 // Default application info from <Applications> element
272 private ApplicationInfo defaultApplicationInfo = null;
274 public ApplicationInfo getApplication(String applicationId) {
275 ApplicationInfo app=null;
276 app = (ApplicationInfo) applications.get(applicationId);
277 if (app==null) // If no specific match, return default
278 return defaultApplicationInfo;
283 // Objects created from single configuration file elements
284 private Credentials credentials = null;
285 private RequestMapDocument.RequestMap requestMap = null;
292 private static final String XMLTRUSTPROVIDERTYPE =
293 "edu.internet2.middleware.shibboleth.common.provider.ShibbolethTrust";
294 private static final String XMLAAPPROVIDERTYPE =
295 "edu.internet2.middleware.shibboleth.aap.provider.XMLAAP";
296 private static final String XMLFEDERATIONPROVIDERTYPE =
297 "edu.internet2.middleware.shibboleth.metadata.provider.XMLMetadata";
298 private static final String XMLREQUESTMAPPROVIDERTYPE =
299 "edu.internet2.middleware.shibboleth.sp.provider.NativeRequestMapProvider";
300 private static final String XMLCREDENTIALSPROVIDERTYPE =
301 "edu.internet2.middleware.shibboleth.common.Credentials";
307 * The constructor prepares for, but does not parse the configuration.
309 * @throws ShibbolethConfigurationException
310 * if XML Parser cannot be initialized (Classpath problem)
312 public ServiceProviderConfig() {
316 * loadConfigObjects must be called once to parse the configuration.
318 * <p>To reload a modified configuration file, create and load a second
319 * object and swap the reference in the context object.</p>
321 * @param configFilePath URL or resource name of file
322 * @return the DOM Document
323 * @throws ShibbolethConfigurationException
324 * if there was an error loading the file
326 public synchronized void loadConfigObjects(String configFilePath)
327 throws ShibbolethConfigurationException {
330 initlog.error("ServiceProviderConfig.loadConfigObjects may not be called twice for the same object.");
331 throw new ShibbolethConfigurationException("Cannot reload configuration into same object.");
334 initlog.info("Loading SP configuration from "+configFilePath);
338 configDoc = Parser.loadDom(configFilePath, true);
339 } catch (Exception e) {
340 initlog.error("XML Parser error "+e.toString());
341 throw new ShibbolethConfigurationException("XML error in "+configFilePath);
343 loadConfigBean(configDoc);
349 * Given a URL, determine its ApplicationId from the RequestMap config.
351 * <p>Note: This is not a full implementation of all RequestMap
352 * configuration options. Other functions will be added as needed.</p>
354 public String mapRequest(String urlreq) {
355 String applicationId = "default";
359 url = new URL(urlreq);
360 } catch (MalformedURLException e) {
361 return applicationId;
364 String urlscheme = url.getProtocol();
365 String urlhostname = url.getHost();
366 String urlpath = url.getPath();
367 int urlport = url.getPort();
369 // find Host entry for this virtual server
370 Host[] hostArray = requestMap.getHostArray();
371 for (int ihost=0;ihost<hostArray.length;ihost++) {
372 Host host = hostArray[ihost];
373 Enum scheme = host.getScheme();
374 String hostName = host.getName();
375 String hostApplicationId = host.getApplicationId();
376 long hostport = host.getPort();
378 if (scheme != null &&
379 !urlscheme.equals(scheme.toString()))
381 if (!urlhostname.equals(hostName))
388 // find Path entry for this subdirectory
389 Path[] pathArray = host.getPathArray();
390 if (hostApplicationId!=null)
391 applicationId=hostApplicationId;
392 for (int i=0;i<pathArray.length;i++) {
393 String dirname = pathArray[i].getName();
394 if (urlpath.equals(dirname)||
395 urlpath.startsWith(dirname+"/")){
396 String pthid= pathArray[i].getApplicationId();
403 reqlog.debug("mapRequest mapped "+urlreq+" into "+applicationId);
404 return applicationId;
408 * <p>Parse the main configuration file DOM into XML Bean</p>
410 * <p>Automatically load secondary configuration files designated
411 * by URLs in the main configuration file</p>
413 * @throws ShibbolethConfigurationException
415 private void loadConfigBean(Document configDoc)
416 throws ShibbolethConfigurationException {
417 boolean anyError=false;
419 Element documentElement = configDoc.getDocumentElement();
420 // reprocess the already validated DOM to create a bean with typed fields
421 // dump the trash (comments, processing instructions, extra whitespace)
423 if (documentElement.getLocalName().equals("ShibbolethTargetConfig")) {
424 initlog.debug("SP Configuration file is in 1.2 syntax.");
425 ShibbolethTargetConfigDocument configBeanDoc;
426 configBeanDoc = ShibbolethTargetConfigDocument.Factory.parse(configDoc,
427 new XmlOptions().setLoadStripComments().setLoadStripProcinsts().setLoadStripWhitespace());
428 config = configBeanDoc.getShibbolethTargetConfig();
429 } else if (documentElement.getLocalName().equals("SPConfig")) {
430 initlog.debug("SP Configuration file is in 1.3 syntax.");
431 SPConfigDocument configBeanDoc;
432 configBeanDoc = SPConfigDocument.Factory.parse(configDoc,
433 new XmlOptions().setLoadStripComments().setLoadStripProcinsts().setLoadStripWhitespace());
434 config = configBeanDoc.getSPConfig();
436 initlog.error("Root element not ShibbolethTargetConfig or SPConfig");
437 throw new XmlException("Root element not ShibbolethTargetConfig or SPConfig");
439 } catch (XmlException e) {
440 // Since the DOM was already validated against the schema, errors will not typically occur here
441 initlog.error("Error while parsing shibboleth configuration");
442 throw new ShibbolethConfigurationException("Error while parsing shibboleth configuration");
445 String loggerUrlString = config.getLogger();
446 if (loggerUrlString!=null) {
448 URL loggerURL = new URL(loggerUrlString);
449 initlog.warn("logging is being reconfigured by "+ loggerUrlString);
450 PropertyConfigurator.configure(loggerURL);
451 } catch (MalformedURLException e) {
452 // This error is not serious enough to prevent initialization
453 initlog.error("Ignoring invalid value for logger attribute "+loggerUrlString );
457 Applications apps = config.getApplications(); // <Applications>
462 * Create an <Application> id "default" from <Applications>
464 ApplicationDocument defaultAppDoc =
465 // Create a new XMLBeans "Document" level object
466 ApplicationDocument.Factory.newInstance();
467 ApplicationDocument.Application defaultApp =
468 // Add an XMLBeans "root Element" object to the Document
469 defaultAppDoc.addNewApplication();
470 // set or copy over fields from unrelated Applications object
471 defaultApp.setId("default");
472 defaultApp.setAAPProviderArray(apps.getAAPProviderArray());
473 defaultApp.setAttributeDesignatorArray(apps.getAttributeDesignatorArray());
474 defaultApp.setAudienceArray(apps.getAudienceArray());
475 defaultApp.setCredentialUse(apps.getCredentialUse());
476 defaultApp.setErrors(apps.getErrors());
477 defaultApp.setFederationProviderArray(apps.getFederationProviderArray());
478 defaultApp.setMetadataProviderArray(apps.getMetadataProviderArray());
479 defaultApp.setProviderId(apps.getProviderId());
480 defaultApp.setSessions(apps.getSessions());
481 defaultApp.setTrustProviderArray(apps.getTrustProviderArray());
484 * Now process secondary files configured in the applications
486 anyError |= processApplication(defaultApp);
488 Application[] apparray = apps.getApplicationArray();
489 for (int i=0;i<apparray.length;i++){
490 Application tempapp = apparray[i];
491 applications.put(tempapp.getId(),tempapp);
492 anyError |= processApplication(tempapp);
496 * Now process other secondary files
498 anyError |= processCredentials();
499 anyError |= processPluggableRequestMapProvider();
502 initlog.error("SP Initialization terminated due to configuration errors");
503 throw new ShibbolethConfigurationException("Errors processing configuration file, see log");
509 * Routine to handle CredentialProvider
511 * <p>Note: This only handles in-line XML.
512 * Also, Credentials was an existing IdP class, so it doesn't
513 * implement the new PluggableConfigurationComponent interface and
514 * can't be loaded by generic plugin support.
517 private boolean processCredentials() {
518 boolean anyError=false;
519 PluggableType[] pluggable = config.getCredentialsProviderArray();
520 for (int i=0;i<pluggable.length;i++) {
521 String pluggabletype = pluggable[i].getType();
522 if (!pluggabletype.equals(
523 "edu.internet2.middleware.shibboleth.common.Credentials")) {
524 initlog.error("Unsupported CredentialsProvider type "+pluggabletype);
528 PluggableType credentialsProvider = pluggable[i];
529 Node fragment = credentialsProvider.newDomNode();
530 // newDomNode returns the current node wrapped in a Fragment
532 Node credentialsProviderNode = fragment.getFirstChild();
533 Node credentialsNode=credentialsProviderNode.getFirstChild();
534 credentials = new Credentials((Element)credentialsNode);
535 } catch(Exception e) {
536 initlog.error("Cannot process Credentials element of Shibboleth configuration",e);
545 * Find and load secondary configuration files referenced in an Application(s)
547 * @param app Application object
548 * @throws ShibbolethConfigurationException
550 private boolean processApplication(Application app)
551 throws ShibbolethConfigurationException {
553 boolean anyError=false;
555 String applicationId = app.getId();
557 ApplicationInfo appinfo = new ApplicationInfo(app);
559 anyError |= processPluggableMetadata(appinfo);
560 anyError |= processPluggableAAPs(appinfo);
561 anyError |= processPluggableTrusts(appinfo);
563 applications.put(applicationId, appinfo);
569 * Generic code to create an object of a Pluggable type that implements
570 * a configuration interface.
572 * <p>The configuration schema defines "PluggableType" as a type of
573 * XML element that has opaque contents and attributes "type" and
574 * "uri". If the uri attribute is omitted, then the configuration
575 * data is inline XML content. The XSD files typically define the
576 * format of pluggable configuration elements, but without binding
577 * them to the PluggableType element that may contain them.</p>
579 * <p>The implimentation of pluggable objects is provided by
580 * external classes. There are "builtin" classes provided with
581 * Shibboleth (XMLMetadataImpl, XMLTrustImpl, XMLAAPImpl) that
582 * provide examples of how this is done. By design, others can
583 * provide their own classes just by putting the class name as
584 * the value of the type attribute.</p>
586 * <p>This routine handles the common setup. It creates objects
587 * of one of the builtin types, or it uses Class.forName() to
588 * access a user specified class. It then locates either the
589 * inline XML elements or the external XML file. It passes the
590 * XML to initialize the object. Finally, a reference to the
591 * object is stored in the appropriate Map.</p>
593 * <p>The objects created implement two interfaces. Mostly they
594 * implement a configuration interface (EntityDescriptor, Trust,
595 * AAP, etc). However, for the purpose of this routine they also
596 * must be declared to implement PluggableConfigurationComponent
597 * and provide an initialize() method that parses a DOM Node
598 * containing their root XML configuration element.</p>
600 * @param pluggable XMLBean for element defined in XSD to be of "PluggableType"
601 * @param implclass java.lang.Class of Builtin implementation class
602 * @param interfaceClass java.lang.Class of Interface
603 * @param builtinName alias type to choose Builtin imlementation
604 * @param uriMap ApplicationInfo Map for this interface
610 PluggableType pluggable,
612 Class interfaceClass,
614 Map /*<String,PluggableConfigurationComponent>*/uriMap
617 String pluggabletype = pluggable.getType();
619 if (!pluggabletype.equals(builtinName)) {
620 // Not the builtin type, try to load user class by name
621 initlog.info("loading user-specified pluggable class "+pluggabletype);
623 implclass = Class.forName(pluggabletype);
624 } catch (ClassNotFoundException e) {
625 initlog.error("Type value "+pluggabletype+" not found as supplied Java class");
628 if (!interfaceClass.isAssignableFrom(implclass)||
629 !PluggableConfigurationComponent.class.isAssignableFrom(implclass)) {
630 initlog.error(pluggabletype+" class does not support required interfaces.");
635 PluggableConfigurationComponent impl;
637 impl = (PluggableConfigurationComponent) implclass.newInstance();
638 } catch (Exception e) {
639 initlog.error("Unable to instantiate "+pluggabletype);
643 String uri = pluggable.getUri();
644 if (uri==null) { // inline
648 Node fragment = pluggable.newDomNode(); // XML-Fragment node
649 Node pluggableNode = fragment.getFirstChild(); // PluggableType
650 Element contentNode=(Element) pluggableNode.getFirstChild();// root element
651 impl.initialize(contentNode);
652 } catch (Exception e) {
653 initlog.error("XML error " + e);
657 } else { // external file
659 if (uriMap.get(uri)!=null) { // Already parsed this file
664 Document extdoc = Parser.loadDom(uri,true);
667 impl.initialize(extdoc.getDocumentElement());
668 } catch (Exception e) {
669 initlog.error("XML error " + e);
674 uriMap.put(uri,impl);
681 * Handle a FederationProvider
683 private boolean processPluggableMetadata(ApplicationInfo appinfo) {
684 boolean anyError = false;
685 PluggableType[] pluggable1 = appinfo.getApplicationConfig().getFederationProviderArray();
686 PluggableType[] pluggable2 = appinfo.getApplicationConfig().getMetadataProviderArray();
687 PluggableType[] pluggable;
688 if (pluggable1.length==0) {
689 pluggable=pluggable2;
690 } else if (pluggable2.length==0) {
691 pluggable=pluggable1;
693 pluggable = new PluggableType[pluggable1.length+pluggable2.length];
694 for (int i=0;i<pluggable2.length;i++) {
695 pluggable[i]=pluggable2[i];
697 for (int i=0;i<pluggable1.length;i++) {
698 pluggable[i+pluggable2.length]=pluggable1[i];
701 for (int i = 0;i<pluggable.length;i++) {
702 String uri = processPluggable(pluggable[i],
703 XMLMetadataProvider.class,
705 XMLFEDERATIONPROVIDERTYPE,
709 else if (uri.length()>0) {
710 appinfo.addGroupUri(uri);
717 * Reload XML Metadata configuration after file changed.
718 * @param uri Path to Metadata XML configuration
719 * @return true if file reloaded.
721 public boolean reloadFederation(String uri) {
722 if (getMetadataImplementor(uri)!=null||
723 uri.startsWith(INLINEURN))
726 Document sitedoc = Parser.loadDom(uri,true);
729 XMLMetadataProvider impl = new XMLMetadataProvider();
730 impl.initialize(sitedoc.getDocumentElement());
731 addOrReplaceMetadataImplementor(uri,impl);
732 } catch (Exception e) {
733 initlog.error("Error while parsing Metadata file "+uri);
734 initlog.error("XML error " + e);
741 * Handle an AAPProvider element with
742 * type="edu.internet2.middleware.shibboleth.common.provider.XMLAAP"
743 * @throws InternalConfigurationException
745 private boolean processPluggableAAPs(ApplicationInfo appinfo){
746 boolean anyError=false;
747 PluggableType[] pluggable = appinfo.getApplicationConfig().getAAPProviderArray();
748 for (int i = 0;i<pluggable.length;i++) {
749 String uri = processPluggable(pluggable[i],
750 XMLAAPProvider.class,
756 else if (uri.length()>0) {
757 appinfo.addAapUri(uri);
764 * Reload XML AAP configuration after file changed.
765 * @param uri AAP to Trust XML configuration
766 * @return true if file reloaded.
768 public boolean reloadAAP(String uri) {
769 if (getAAPImplementor(uri)!=null||
770 uri.startsWith(INLINEURN))
773 Document aapdoc = Parser.loadDom(uri,true);
776 AttributeAcceptancePolicyDocument aap = AttributeAcceptancePolicyDocument.Factory.parse(aapdoc);
777 XMLAAPProvider impl = new XMLAAPProvider();
778 impl.initialize(aapdoc.getDocumentElement());
779 addOrReplaceAAPImplementor(uri,impl);
780 } catch (Exception e) {
781 initlog.error("Error while parsing AAP file "+uri);
782 initlog.error("XML error " + e);
790 * Handle a TrustProvider element with
791 * type="edu.internet2.middleware.shibboleth.common.provider.XMLTrust"
793 * Note: This code builds the semantic structure of trust. That is, it knows
794 * about certificates and keys. The actual logic of Trust (signature generation
795 * and validation) is implemented in a peer object defined in the external
796 * class XMLTrustImpl.
798 * @throws ShibbolethConfigurationException if X.509 certificate cannot be processed
799 * @throws InternalConfigurationException
801 private boolean processPluggableTrusts(ApplicationInfo appinfo){
802 boolean anyError=false;
803 PluggableType[] pluggable = appinfo.getApplicationConfig().getTrustProviderArray();
804 for (int i = 0;i<pluggable.length;i++) {
805 String uri = processPluggable(pluggable[i],
806 ShibbolethTrust.class,
808 XMLTRUSTPROVIDERTYPE,
809 certificateValidators);
812 else if (uri.length()>0) {
813 appinfo.addTrustUri(uri);
821 private boolean processPluggableRequestMapProvider(){
822 LocalConfigurationType shire = config.getSHIRE();
824 shire = config.getLocal();
826 initlog.error("No SHIRE or Local element.");
829 PluggableType mapProvider = shire.getRequestMapProvider();
831 String pluggabletype = mapProvider.getType();
832 if (!pluggabletype.equals(XMLREQUESTMAPPROVIDERTYPE)) {
833 initlog.error("Unsupported RequestMapProvider type "+pluggabletype);
837 RequestMapDocument requestMapDoc = null;
838 Document mapdoc = null;
839 Element maproot = null;
840 String uri = mapProvider.getUri();
842 if (uri==null) { // inline
846 Node fragment = mapProvider.newDomNode();
847 Node pluggableNode = fragment.getFirstChild();
848 Node contentNode=pluggableNode.getFirstChild();
850 requestMapDoc = RequestMapDocument.Factory.parse(contentNode);
851 } catch (Exception e) {
852 initlog.error("Error while parsing inline RequestMap");
853 initlog.error("XML error " + e);
857 } else { // external file
859 mapdoc = Parser.loadDom(uri,true);
862 requestMapDoc = RequestMapDocument.Factory.parse(mapdoc);
863 } catch (Exception e) {
864 initlog.error("Error while parsing RequestMap file "+uri);
865 initlog.error("XML error " + e);
870 requestMap = requestMapDoc.getRequestMap();
875 // Generate Map keys for inline plugin configuration Elements
876 private int inlinenum = 1;
877 private String genDummyUri() {
878 return INLINEURN+Integer.toString(inlinenum++);
887 * ApplicationInfo represents the <Application(s)> object, its fields,
888 * and the pluggable configuration elements under it.
890 * <p>It can return arrays of Metadata, Trust, or AAP providers, but
891 * it also exposes convenience methods that shop the lookup(),
892 * validate(), and trust() calls to each object in the collection
893 * until success or failure is determined.</p>
895 * <p>For all other parameters, such as Session parameters, you
896 * can fetch the XMLBean by calling getApplicationConf() and
897 * query their value directly.
899 public class ApplicationInfo
900 implements Metadata, Trust {
902 private Application applicationConfig;
903 public Application getApplicationConfig() {
904 return applicationConfig;
908 * Construct this object from the XML Bean.
909 * @param application XMLBean for Application element
911 ApplicationInfo(Application application) {
912 this.applicationConfig=application;
917 * Following the general rule, this object may not keep
918 * direct references to the plugin interface implementors,
919 * but must look them up on every call through their URI keys.
920 * So we keep collections of URI strings instead.
922 ArrayList groupUris = new ArrayList();
923 ArrayList trustUris = new ArrayList();
924 ArrayList aapUris = new ArrayList();
926 void addGroupUri(String uri) {
929 void addTrustUri(String uri) {
932 void addAapUri(String uri) {
937 * Return the current array of objects that implement the
938 * ...metadata.Metadata interface
942 Metadata[] getMetadataProviders() {
943 Iterator iuris = groupUris.iterator();
944 int count = groupUris.size();
945 Metadata[] metadatas = new Metadata[count];
946 for (int i=0;i<count;i++) {
947 String uri =(String) iuris.next();
948 metadatas[i]=getMetadataImplementor(uri);
954 * A convenience function based on the Metadata interface.
956 * <p>Look for an entity ID through each implementor until the
957 * first one finds locates a describing object.</p>
959 * <p>Unfortunately, Metadata.lookup() was originally specified to
960 * return a "Provider". In current SAML 2.0 terms, the object
961 * returned should be an EntityDescriptor. So this is the new
962 * function in the new interface that will use the new term, but
963 * it does the same thing.</p>
965 * @param id ID of the IdP entity
966 * @return EntityDescriptor metadata object for that site.
968 public EntityDescriptor lookup(String id) {
969 Iterator iuris = groupUris.iterator();
970 while (iuris.hasNext()) {
971 String uri =(String) iuris.next();
972 Metadata locator=getMetadataImplementor(uri);
973 EntityDescriptor entity = locator.lookup(id);
975 reqlog.debug("Metadata.lookup resolved Entity "+ id);
979 reqlog.warn("Metadata.lookup failed to resolve Entity "+ id);
983 public EntityDescriptor lookup(Artifact artifact) {
984 Iterator iuris = groupUris.iterator();
985 while (iuris.hasNext()) {
986 String uri =(String) iuris.next();
987 Metadata locator=getMetadataImplementor(uri);
988 EntityDescriptor entity = locator.lookup(artifact);
990 reqlog.debug("Metadata.lookup resolved Artifact "+ artifact);
994 reqlog.warn("Metadata.lookup failed to resolve Artifact "+ artifact);
999 * Return the current array of objects that implement the Trust interface
1003 public Trust[] getTrustProviders() {
1004 Iterator iuris = trustUris.iterator();
1005 int count = trustUris.size();
1007 return defaultTrust;
1008 Trust[] trusts = new Trust[count];
1009 for (int i=0;i<count;i++) {
1010 String uri =(String) iuris.next();
1011 trusts[i]=getTrustImplementor(uri);
1017 * Return the current array of objects that implement the AAP interface
1021 public AAP[] getAAPProviders() {
1022 Iterator iuris = aapUris.iterator();
1023 int count = aapUris.size();
1024 AAP[] aaps = new AAP[count];
1025 for (int i=0;i<count;i++) {
1026 String uri =(String) iuris.next();
1027 aaps[i]=getAAPImplementor(uri);
1033 * Convenience function to apply AAP by calling the apply()
1034 * method of each AAP implementor.
1036 * <p>Any AAP implementor can delete an assertion or value.
1037 * Empty SAML elements get removed from the assertion.
1038 * This can yield an AttributeAssertion with no attributes.
1040 * @param assertion SAML Attribute Assertion
1041 * @param role Role that issued the assertion
1042 * @throws SAMLException Raised if assertion is mangled beyond repair
1044 void applyAAP(SAMLAssertion assertion, RoleDescriptor role) throws SAMLException {
1046 // Foreach AAP in the collection
1047 AAP[] providers = getAAPProviders();
1048 if (providers.length == 0) {
1049 reqlog.info("no filters specified, accepting entire assertion");
1052 for (int i=0;i<providers.length;i++) {
1053 AAP aap = providers[i];
1054 if (aap.anyAttribute()) {
1055 reqlog.info("any attribute enabled, accepting entire assertion");
1060 // Foreach Statement in the Assertion
1061 Iterator statements = assertion.getStatements();
1063 while (statements.hasNext()) {
1064 Object statement = statements.next();
1065 if (statement instanceof SAMLAttributeStatement) {
1066 SAMLAttributeStatement attributeStatement = (SAMLAttributeStatement) statement;
1068 // Check each attribute, applying any matching rules.
1069 Iterator attributes = attributeStatement.getAttributes();
1071 while (attributes.hasNext()) {
1072 SAMLAttribute attribute = (SAMLAttribute) attributes.next();
1073 boolean ruleFound = false;
1074 for (int i=0;i<providers.length;i++) {
1075 AttributeRule rule = providers[i].lookup(attribute.getName(),attribute.getNamespace());
1079 rule.apply(attribute,role);
1081 catch (SAMLException ex) {
1082 reqlog.info("no values remain, removing attribute");
1083 attributeStatement.removeAttribute(iattribute--);
1089 reqlog.warn("no rule found for attribute (" + attribute.getName() + "), filtering it out");
1090 attributeStatement.removeAttribute(iattribute--);
1096 attributeStatement.checkValidity();
1099 catch (SAMLException ex) {
1100 // The statement is now defunct.
1101 reqlog.info("no attributes remain, removing statement");
1102 assertion.removeStatement(istatement);
1107 // Now see if we trashed it irrevocably.
1108 assertion.checkValidity();
1113 * Returns a collection of attribute names to request from the AA.
1115 * @return Collection of attribute Name values
1117 public Collection getAttributeDesignators() {
1118 // TODO Not sure where this should come from
1119 return new ArrayList();
1124 * Convenience method implementing Trust.validate() across
1125 * the collection of implementing objects. Returns true if
1126 * any Trust implementor approves the signatures in the object.
1128 * <p>In the interface, validate() is passed several arguments
1129 * that come from this object. In this function, those
1130 * arguments are ignored "this" is used.
1134 SAMLSignedObject token,
1139 Trust[] trustProviders = getTrustProviders();
1140 for (int i=0;i<trustProviders.length;i++) {
1141 Trust trust = trustProviders[i];
1142 if (trust.validate(token,role))
1145 reqlog.warn("SAML object failed Trust validation.");
1151 * A method of Trust that we must declare to claim that
1152 * ApplicationInfo implements Trust. However, no code in the
1153 * ServiceProvider calls this (probably an IdP thing).
1155 * @param revocations
1157 * @return This dummy always returns false.
1159 public boolean attach(Iterator revocations, RoleDescriptor role) {
1164 public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain, RoleDescriptor descriptor) {
1165 Trust[] trustProviders = getTrustProviders();
1166 for (int i=0;i<trustProviders.length;i++) {
1167 Trust trust = trustProviders[i];
1168 if (trust.validate(certificateEE,certificateChain,descriptor))
1171 reqlog.warn("X.509 Certificate failed Trust validate");
1175 public boolean validate(X509Certificate certificateEE, X509Certificate[] certificateChain, RoleDescriptor descriptor, boolean checkName) {
1176 Trust[] trustProviders = getTrustProviders();
1177 for (int i=0;i<trustProviders.length;i++) {
1178 Trust trust = trustProviders[i];
1179 if (trust.validate(certificateEE,certificateChain,descriptor,checkName))
1182 reqlog.warn("X.509 Certificate failed Trust validate");
1186 public String getProviderId() {
1187 String entityId = this.applicationConfig.getProviderId();
1188 if (entityId==null && this!=defaultApplicationInfo) {
1189 entityId = defaultApplicationInfo.getProviderId();
1197 private static class InternalConfigurationException extends Exception {
1198 InternalConfigurationException() {
1205 public Credentials getCredentials() {