2 * Copyright 2001-2005 Internet2
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 * shib-target.h -- top-level header file for the SHIB Common Target Library
20 * Created by: Derek Atkins <derek@ihtfp.com>
28 #include <saml/saml.h>
29 #include <shib/shib.h>
30 #include <shib/shib-threads.h>
33 # ifndef SHIBTARGET_EXPORTS
34 # define SHIBTARGET_EXPORTS __declspec(dllimport)
36 # define SHIB_SCHEMAS "/opt/shibboleth-sp/share/xml/shibboleth"
37 # define SHIB_CONFIG "/opt/shibboleth-sp/etc/shibboleth/shibboleth.xml"
39 # include <shib-target/shib-paths.h>
40 # define SHIBTARGET_EXPORTS
43 #include <shib-target/ddf.h>
45 namespace shibtarget {
47 DECLARE_SAML_EXCEPTION(SHIBTARGET_EXPORTS,ListenerException,SAMLException);
48 DECLARE_SAML_EXCEPTION(SHIBTARGET_EXPORTS,ConfigurationException,SAMLException);
50 // Abstract APIs for access to configuration information
53 * Interface to a generic set of typed properties or a DOM container of additional
56 struct SHIBTARGET_EXPORTS IPropertySet
58 virtual std::pair<bool,bool> getBool(const char* name, const char* ns=NULL) const=0;
59 virtual std::pair<bool,const char*> getString(const char* name, const char* ns=NULL) const=0;
60 virtual std::pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const=0;
61 virtual std::pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const=0;
62 virtual std::pair<bool,int> getInt(const char* name, const char* ns=NULL) const=0;
63 virtual const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const=0;
64 virtual const DOMElement* getElement() const=0;
65 virtual ~IPropertySet() {}
68 // Forward declaration
69 class SHIBTARGET_EXPORTS ShibTarget;
72 * Interface to a protocol handler
74 * Protocol handlers perform system functions such as processing SAML protocol
75 * messages to create and logout sessions or creating protocol requests.
77 struct SHIBTARGET_EXPORTS IHandler : public virtual saml::IPlugIn
79 IHandler() : m_props(NULL) {}
80 virtual ~IHandler() {}
81 virtual const IPropertySet* getProperties() const { return m_props; }
82 virtual void setProperties(const IPropertySet* properties) { m_props=properties; }
83 virtual std::pair<bool,void*> run(ShibTarget* st, bool isHandler=true) const=0;
85 const IPropertySet* m_props;
89 * Interface to Shibboleth Applications, which exposes most of the functionality
90 * required to process web requests or security protocol messages for resources
91 * associated with them.
93 * Applications are implementation-specific, but generally correspond to collections
94 * of resources related to one another in logical ways, such as a virtual host or
95 * a Java servlet context. Most complex configuration data is associated with an
96 * Application. Implementations should always expose an application named "default"
99 struct SHIBTARGET_EXPORTS IApplication : public virtual IPropertySet
101 virtual const char* getId() const=0;
102 virtual const char* getHash() const=0;
104 virtual saml::Iterator<saml::SAMLAttributeDesignator*> getAttributeDesignators() const=0;
105 virtual saml::Iterator<shibboleth::IAAP*> getAAPProviders() const=0;
106 virtual saml::Iterator<shibboleth::IMetadata*> getMetadataProviders() const=0;
107 virtual saml::Iterator<shibboleth::ITrust*> getTrustProviders() const=0;
108 virtual saml::Iterator<const XMLCh*> getAudiences() const=0;
109 virtual const IPropertySet* getCredentialUse(const shibboleth::IEntityDescriptor* provider) const=0;
111 // caller is borrowing object, must use within scope of config lock
112 virtual const saml::SAMLBrowserProfile* getBrowserProfile() const=0;
113 virtual const saml::SAMLBinding* getBinding(const XMLCh* binding) const=0;
115 // caller is given ownership of object, must use and delete within scope of config lock
116 virtual saml::SAMLBrowserProfile::ArtifactMapper* getArtifactMapper() const=0;
118 // Used to locate a default or designated session initiator for automatic sessions
119 virtual const IHandler* getDefaultSessionInitiator() const=0;
120 virtual const IHandler* getSessionInitiatorById(const char* id) const=0;
122 // Used by session initiators to get endpoint to forward to IdP/WAYF
123 virtual const IHandler* getDefaultAssertionConsumerService() const=0;
124 virtual const IHandler* getAssertionConsumerServiceByIndex(unsigned short index) const=0;
125 virtual saml::Iterator<const IHandler*> getAssertionConsumerServicesByBinding(const XMLCh* binding) const=0;
127 // Used by dispatcher to locate the handler(s) for a request
128 virtual saml::Iterator<const IHandler*> getHandlers(const char* path) const=0;
130 virtual ~IApplication() {}
133 // Instead of wrapping the binding to deal with mutual authentication, we
134 // just use the HTTP hook functionality offered by OpenSAML. The hook will
135 // register "itself" as a globalCtx pointer with the SAML binding and the caller
136 // will declare and pass the embedded struct as callCtx for use by the hook.
137 class ShibHTTPHook : virtual public saml::SAMLSOAPHTTPBinding::HTTPHook
140 ShibHTTPHook(const saml::Iterator<shibboleth::ITrust*>& trusts, const saml::Iterator<shibboleth::ICredentials*>& creds)
141 : m_trusts(trusts), m_creds(creds) {}
142 virtual ~ShibHTTPHook() {}
144 // Only hook we need here is for outgoing connection to server.
145 virtual bool outgoing(saml::HTTPClient* conn, void* globalCtx=NULL, void* callCtx=NULL);
147 // Client declares a context object and pass as callCtx to send() method.
148 class ShibHTTPHookCallContext {
150 ShibHTTPHookCallContext(const IPropertySet* credUse, const shibboleth::IRoleDescriptor* role)
151 : m_credUse(credUse), m_role(role), m_hook(NULL), m_authenticated(false) {}
152 const ShibHTTPHook* getHook() {return m_hook;}
153 const IPropertySet* getCredentialUse() {return m_credUse;}
154 const shibboleth::IRoleDescriptor* getRoleDescriptor() {return m_role;}
155 bool isAuthenticated() const {return m_authenticated;}
156 void setAuthenticated() {m_authenticated=true;}
159 const IPropertySet* m_credUse;
160 const shibboleth::IRoleDescriptor* m_role;
161 ShibHTTPHook* m_hook;
162 bool m_authenticated;
163 friend class ShibHTTPHook;
166 const saml::Iterator<shibboleth::ITrust*>& getTrustProviders() const {return m_trusts;}
167 const saml::Iterator<shibboleth::ICredentials*>& getCredentialProviders() const {return m_creds;}
169 saml::Iterator<shibboleth::ITrust*> m_trusts;
170 saml::Iterator<shibboleth::ICredentials*> m_creds;
174 * Interface to a cached user session.
176 * Cache entries provide implementations with access to the raw SAML information they
177 * need to publish or provide access to the data for applications to use. All creation
178 * or access to entries is through the ISessionCache interface, and callers must unlock
179 * the entry when finished using it, rather than explicitly freeing them.
181 struct SHIBTARGET_EXPORTS ISessionCacheEntry : public virtual saml::ILockable
183 virtual const char* getClientAddress() const=0;
184 virtual const char* getProviderId() const=0;
185 virtual std::pair<const char*,const saml::SAMLSubject*> getSubject(bool xml=true, bool obj=false) const=0;
186 virtual const char* getAuthnContext() const=0;
187 virtual std::pair<const char*,const saml::SAMLResponse*> getTokens(bool xml=true, bool obj=false) const=0;
188 virtual std::pair<const char*,const saml::SAMLResponse*> getFilteredTokens(bool xml=true, bool obj=false) const=0;
189 virtual ~ISessionCacheEntry() {}
193 * Interface to the session cache.
195 * The session cache abstracts a persistent (meaning across requests) cache of
196 * instances of the ISessionCacheEntry interface. Creation of new entries and entry
197 * lookup are confined to this interface to enable implementations to flexibly
198 * remote and/or optimize calls by implementing custom versions of the
199 * ISessionCacheEntry interface as required.
201 struct SHIBTARGET_EXPORTS ISessionCache : public virtual saml::IPlugIn
203 virtual std::string insert(
204 const IApplication* application,
205 const shibboleth::IRoleDescriptor* source,
206 const char* client_addr,
207 const saml::SAMLSubject* subject,
208 const char* authnContext,
209 saml::SAMLResponse* tokens
211 virtual ISessionCacheEntry* find(const char* key, const IApplication* application, const char* client_addr)=0;
212 virtual void remove(const char* key, const IApplication* application, const char* client_addr)=0;
213 virtual ~ISessionCache() {}
216 // used by cache implementations to load raw cache entry, as from disk or other back-end
219 const IApplication* application,
220 const shibboleth::IRoleDescriptor* source,
221 const char* client_addr,
222 const char* providerId,
224 const char* authnContext,
234 * Interface to a remoted service
236 * Plugins that support remoted messages delivered by the IListener runtime
237 * support this interface and register themselves with the runtime to receive
238 * particular messages.
240 struct SHIBTARGET_EXPORTS IRemoted : public virtual saml::IPlugIn
242 virtual DDF receive(const DDF& in)=0;
243 virtual ~IRemoted() {}
247 * Interface to the remoting engine
249 * A listener supports the remoting of DDF objects, which are dynamic data trees
250 * that interface implementations can use to remote themselves by calling an
251 * out-of-process peer implementation with arbitrary data to carry out tasks
252 * on the implementation's behalf that require isolation from the dynamic process
253 * fluctuations that web servers are prone to. The ability to pass arbitrary data
254 * trees across the boundary allows arbitrary separation of duty between the
255 * in-process and out-of-process "halves". The implementation is responsible
256 * for marshalling and transmitting messages, as well as managing connections
257 * and communication errors.
259 class SHIBTARGET_EXPORTS IListener : public virtual IRemoted
262 virtual DDF send(const DDF& in)=0;
263 virtual DDF receive(const DDF& in);
264 virtual ~IListener() {}
266 // Remoted classes register and unregister for messages using these methods.
267 // Registration returns any existing listeners, allowing message hooking.
268 virtual IRemoted* regListener(const char* address, IRemoted* listener);
269 virtual bool unregListener(const char* address, IRemoted* current, IRemoted* restore=NULL);
270 virtual IRemoted* lookup(const char* address) const;
272 // OutOfProcess servers can implement server-side transport handling by
273 // calling the run method and supplying a flag to monitor for shutdown.
274 virtual bool run(bool* shutdown)=0;
277 std::map<std::string,IRemoted*> m_listenerMap;
281 * Interface to an access control plugin
283 * Access control plugins return authorization decisions based on the intersection
284 * of the resource request and the active session. They can be implemented through
285 * cross-platform or platform-specific mechanisms.
287 struct SHIBTARGET_EXPORTS IAccessControl : public virtual saml::ILockable, public virtual saml::IPlugIn
289 virtual bool authorized(ShibTarget* st, ISessionCacheEntry* entry) const=0;
290 virtual ~IAccessControl() {}
294 * Interface to a request mapping plugin
296 * Request mapping plugins return configuration settings that apply to resource requests.
297 * They can be implemented through cross-platform or platform-specific mechanisms.
299 struct SHIBTARGET_EXPORTS IRequestMapper : public virtual saml::ILockable, public virtual saml::IPlugIn
301 typedef std::pair<const IPropertySet*,IAccessControl*> Settings;
302 virtual Settings getSettings(ShibTarget* st) const=0;
303 virtual ~IRequestMapper() {}
306 struct SHIBTARGET_EXPORTS IConfig : public virtual saml::ILockable, public virtual IPropertySet, public virtual saml::IPlugIn
308 // loads initial configuration
309 virtual void init()=0;
311 virtual IListener* getListener() const=0;
312 virtual ISessionCache* getSessionCache() const=0;
313 virtual saml::IReplayCache* getReplayCache() const=0;
314 virtual IRequestMapper* getRequestMapper() const=0;
315 virtual const IApplication* getApplication(const char* applicationId) const=0;
316 virtual saml::Iterator<shibboleth::ICredentials*> getCredentialsProviders() const=0;
317 virtual ~IConfig() {}
320 class SHIBTARGET_EXPORTS ShibTargetConfig
323 ShibTargetConfig() : m_ini(NULL), m_features(0) {}
324 virtual ~ShibTargetConfig() {}
326 virtual bool init(const char* schemadir) = 0;
327 virtual bool load(const char* config) = 0;
328 virtual void shutdown() = 0;
342 void setFeatures(long enabled) {m_features = enabled;}
343 bool isEnabled(components_t feature) {return (m_features & feature)>0;}
344 virtual IConfig* getINI() const {return m_ini;}
346 static ShibTargetConfig& getConfig();
352 unsigned long m_features;
355 // Helper class for SAML 2.0 Common Domain Cookie operations
356 class CommonDomainCookie
359 CommonDomainCookie(const char* cookie);
360 ~CommonDomainCookie() {}
361 saml::Iterator<std::string> get() {return m_list;}
362 const char* set(const char* providerId);
363 static const char CDCName[];
365 std::string m_encoded;
366 std::vector<std::string> m_list;
370 class ShibTargetPriv;
371 class SHIBTARGET_EXPORTS ShibTarget {
373 ShibTarget(const IApplication* app);
374 virtual ~ShibTarget(void);
376 // These are defined here so the subclass does not need to specifically
377 // depend on log4cpp. We could use log4cpp::Priority::PriorityLevel
378 // but this is just as easy, IMHO. It's just a case statement in the
379 // implementation to handle the event level.
388 // Note: subclasses MUST implement ALL of these virtual methods
391 // Send a message to the Webserver log
392 virtual void log(ShibLogLevel level, const std::string &msg)=0;
394 void log(ShibLogLevel level, const char* msg) {
399 // Get/Set a cookie for this request
400 virtual std::string getCookies() const=0;
401 virtual void setCookie(const std::string& name, const std::string& value)=0;
402 virtual const char* getCookie(const std::string& name) const;
403 void setCookie(const char* name, const char* value) {
404 std::string ns = name;
405 std::string vs = value;
408 void setCookie(const char* name, const std::string& value) {
409 std::string ns = name;
410 setCookie(ns, value);
413 // Get any URL-encoded arguments or the raw POST body from the server
414 virtual const char* getQueryString() const=0;
415 virtual const char* getRequestBody() const=0;
416 virtual const char* getRequestParameter(const char* param, size_t index=0) const;
418 // Clear a header, set a header
419 // These APIs are used for exporting the Assertions into the
420 // Headers. It will clear some well-known headers first to make
421 // sure none remain. Then it will process the set of assertions
422 // and export them via setHeader().
423 virtual void clearHeader(const std::string& name)=0;
424 virtual void setHeader(const std::string& name, const std::string& value)=0;
425 virtual std::string getHeader(const std::string& name)=0;
426 virtual void setRemoteUser(const std::string& user)=0;
427 virtual std::string getRemoteUser()=0;
429 void clearHeader(const char* n) {
433 void setHeader(const char* n, const char* v) {
438 void setHeader(const std::string& n, const char* v) {
442 void setHeader(const char* n, const std::string& v) {
446 std::string getHeader(const char* n) {
450 void setRemoteUser(const char* n) {
455 // We're done. Finish up. Send specific result content or a redirect.
456 // If there are no headers supplied assume the content-type is text/html
457 typedef std::pair<std::string, std::string> header_t;
458 virtual void* sendPage(
459 const std::string& msg,
461 const std::string& content_type = "text/html",
462 const saml::Iterator<header_t>& headers = EMPTY(header_t)
464 void* sendPage(const char* msg) {
468 virtual void* sendRedirect(const std::string& url)=0;
470 // These next two APIs are used to obtain the module-specific "OK"
471 // and "Decline" results. OK means "we believe that this request
472 // should be accepted". Declined means "we believe that this is
473 // not a shibbolized request so we have no comment".
475 virtual void* returnDecline();
476 virtual void* returnOK();
479 // Note: Subclasses need not implement anything below this line
482 // These functions implement the server-agnostic shibboleth engine
483 // The web server modules implement a subclass and then call into
484 // these methods once they instantiate their request object.
487 // these APIs will always return the result of sendPage(), sendRedirect(),
488 // returnDecline(), or returnOK() in the void* portion of the return code.
489 // Exactly what those values are is module- (subclass-) implementation
490 // specific. The 'bool' part of the return value declares whether the
491 // void* is valid or not. If the bool is true then the void* is valid.
492 // If the bool is false then the API did not call any callback, the void*
493 // is not valid, and the caller should continue processing (the API Call
494 // finished successfully).
496 // The handleProfile argument declares whether doCheckAuthN() should
497 // automatically call doHandlePOST() when it encounters a request for
498 // the ShireURL; if false it will call returnOK() instead.
500 std::pair<bool,void*> doCheckAuthN(bool handler = false);
501 std::pair<bool,void*> doHandler();
502 std::pair<bool,void*> doCheckAuthZ();
503 std::pair<bool,void*> doExportAssertions(bool requireSession = true);
505 // Basic request access in case any plugins need the info
506 virtual const IConfig* getConfig() const;
507 virtual const IApplication* getApplication() const;
508 const char* getRequestMethod() const {return m_method.c_str();}
509 const char* getProtocol() const {return m_protocol.c_str();}
510 const char* getHostname() const {return m_hostname.c_str();}
511 int getPort() const {return m_port;}
512 const char* getRequestURI() const {return m_uri.c_str();}
513 const char* getContentType() const {return m_content_type.c_str();}
514 const char* getRemoteAddr() const {return m_remote_addr.c_str();}
515 const char* getRequestURL() const {return m_url.c_str();}
517 // Advanced methods useful to profile handlers implemented outside core
519 // Get per-application session and state cookie name and properties
520 virtual std::pair<std::string,const char*> getCookieNameProps(const char* prefix) const;
522 // Determine the effective handler URL based on the resource URL
523 virtual std::string getHandlerURL(const char* resource) const;
525 static void url_decode(char* s);
526 static std::string url_encode(const char* s);
533 // Initialize the request from the parsed URL
534 // protocol == http, https, etc
535 // hostname == server name
536 // port == server port
537 // uri == resource path
538 // method == GET, POST, etc.
540 const char* protocol,
541 const char* hostname,
544 const char* content_type,
545 const char* remote_addr,
549 std::string m_url, m_method, m_protocol, m_hostname, m_uri, m_content_type, m_remote_addr;
553 mutable ShibTargetPriv* m_priv;
554 friend class ShibTargetPriv;
557 struct SHIBTARGET_EXPORTS XML
559 static const XMLCh SHIBTARGET_NS[];
560 static const XMLCh SHIBTARGET_SCHEMA_ID[];
561 static const XMLCh SAML2ASSERT_NS[];
562 static const XMLCh SAML2ASSERT_SCHEMA_ID[];
563 static const XMLCh SAML2META_NS[];
564 static const XMLCh SAML2META_SCHEMA_ID[];
565 static const XMLCh XMLENC_NS[];
566 static const XMLCh XMLENC_SCHEMA_ID[];
568 // Session cache implementations
569 static const char MemorySessionCacheType[];
570 static const char MySQLSessionCacheType[];
572 // Replay cache implementations
573 static const char MySQLReplayCacheType[];
575 // Request mapping/settings implementations
576 static const char XMLRequestMapType[]; // portable XML-based map
577 static const char NativeRequestMapType[]; // Native web server command override of XML-based map
578 static const char LegacyRequestMapType[]; // older designation of XML map, hijacked by web server
580 // Access control implementations
581 static const char htAccessControlType[]; // Apache-specific .htaccess authz module
582 static const char XMLAccessControlType[]; // Proprietary but portable XML authz syntax
584 // Listener implementations
585 static const char TCPListenerType[]; // ONC RPC via TCP socket
586 static const char UnixListenerType[]; // ONC RPC via domain socker
587 static const char MemoryListenerType[]; // "faked" in-process marshalling
589 struct SHIBTARGET_EXPORTS Literals
591 static const XMLCh AAPProvider[];
592 static const XMLCh AccessControl[];
593 static const XMLCh AccessControlProvider[];
594 static const XMLCh acl[];
595 static const XMLCh AND[];
596 static const XMLCh applicationId[];
597 static const XMLCh Application[];
598 static const XMLCh Applications[];
599 static const XMLCh AssertionConsumerService[];
600 static const XMLCh AttributeFactory[];
601 static const XMLCh config[];
602 static const XMLCh CredentialsProvider[];
603 static const XMLCh CredentialUse[];
604 static const XMLCh DiagnosticService[];
605 static const XMLCh echo[];
606 static const XMLCh Extensions[];
607 static const XMLCh fatal[];
608 static const XMLCh FederationProvider[];
609 static const XMLCh Global[];
610 static const XMLCh Host[];
611 static const XMLCh htaccess[];
612 static const XMLCh Implementation[];
613 static const XMLCh index[];
614 static const XMLCh InProcess[];
615 static const XMLCh isDefault[];
616 static const XMLCh Library[];
617 static const XMLCh Listener[];
618 static const XMLCh Local[];
619 static const XMLCh log[];
620 static const XMLCh logger[];
621 static const XMLCh MemorySessionCache[];
622 static const XMLCh MetadataProvider[];
623 static const XMLCh MySQLReplayCache[];
624 static const XMLCh MySQLSessionCache[];
625 static const XMLCh name[];
626 static const XMLCh Name[];
627 static const XMLCh NOT[];
628 static const XMLCh OR[];
629 static const XMLCh OutOfProcess[];
630 static const XMLCh Path[];
631 static const XMLCh path[];
632 static const XMLCh RelyingParty[];
633 static const XMLCh ReplayCache[];
634 static const XMLCh RequestMap[];
635 static const XMLCh RequestMapProvider[];
636 static const XMLCh require[];
637 static const XMLCh Rule[];
638 static const XMLCh SessionCache[];
639 static const XMLCh SessionInitiator[];
640 static const XMLCh SHAR[];
641 static const XMLCh ShibbolethTargetConfig[];
642 static const XMLCh SHIRE[];
643 static const XMLCh Signing[];
644 static const XMLCh SingleLogoutService[];
645 static const XMLCh SPConfig[];
646 static const XMLCh TCPListener[];
647 static const XMLCh TLS[];
648 static const XMLCh TrustProvider[];
649 static const XMLCh type[];
650 static const XMLCh UnixListener[];
655 #endif /* SHIB_TARGET_H */