c1c9fa4119083f71f16bf0d61e63d276679cd9d1
[shibboleth/cpp-sp.git] / shib-target / shib-target.h
1 /*
2  *  Copyright 2001-2005 Internet2
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /*
18  * shib-target.h -- top-level header file for the SHIB Common Target Library
19  *
20  * Created by:  Derek Atkins <derek@ihtfp.com>
21  *
22  * $Id$
23  */
24
25 #ifndef SHIB_TARGET_H
26 #define SHIB_TARGET_H
27
28 // New headers
29 #include <saml/base.h>
30 #include <shibsp/ListenerService.h>
31 #include <shibsp/PropertySet.h>
32
33 // Old headers
34 #include <saml/saml.h>
35 #include <shib/shib.h>
36
37 #ifdef WIN32
38 # ifndef SHIBTARGET_EXPORTS
39 #  define SHIBTARGET_EXPORTS __declspec(dllimport)
40 # endif
41 # define SHIB_SCHEMAS "/opt/shibboleth-sp/share/xml/shibboleth"
42 # define SHIB_CONFIG "/opt/shibboleth-sp/etc/shibboleth/shibboleth.xml"
43 #else
44 # include <shib-target/shib-paths.h>
45 # define SHIBTARGET_EXPORTS
46 #endif
47
48 namespace shibtarget {
49   
50     DECLARE_SAML_EXCEPTION(SHIBTARGET_EXPORTS,ListenerException,SAMLException);
51     DECLARE_SAML_EXCEPTION(SHIBTARGET_EXPORTS,ConfigurationException,SAMLException);
52
53     // Abstract APIs for access to configuration information
54     
55     // Forward declaration
56     class SHIBTARGET_EXPORTS ShibTarget;
57
58     /**
59      * Interface to a protocol handler
60      * 
61      * Protocol handlers perform system functions such as processing SAML protocol
62      * messages to create and logout sessions or creating protocol requests.
63      */
64     struct SHIBTARGET_EXPORTS IHandler : public virtual saml::IPlugIn
65     {
66         IHandler() : m_props(NULL) {}
67         virtual ~IHandler() {}
68         virtual const shibsp::PropertySet* getProperties() const { return m_props; }
69         virtual void setProperties(const shibsp::PropertySet* properties) { m_props=properties; }
70         virtual std::pair<bool,void*> run(ShibTarget* st, bool isHandler=true) const=0;
71     private:
72         const shibsp::PropertySet* m_props;
73     };
74     
75     /**
76      * Interface to Shibboleth Applications, which exposes most of the functionality
77      * required to process web requests or security protocol messages for resources
78      * associated with them.
79      * 
80      * Applications are implementation-specific, but generally correspond to collections
81      * of resources related to one another in logical ways, such as a virtual host or
82      * a Java servlet context. Most complex configuration data is associated with an
83      * Application. Implementations should always expose an application named "default"
84      * as a last resort.
85      */
86     struct SHIBTARGET_EXPORTS IApplication : public virtual shibsp::PropertySet,
87         public virtual shibboleth::ShibBrowserProfile::ITokenValidator
88     {
89         virtual const char* getId() const=0;
90         virtual const char* getHash() const=0;
91         
92         virtual saml::Iterator<saml::SAMLAttributeDesignator*> getAttributeDesignators() const=0;
93         virtual saml::Iterator<shibboleth::IAAP*> getAAPProviders() const=0;
94         virtual saml::Iterator<shibboleth::IMetadata*> getMetadataProviders() const=0;
95         virtual saml::Iterator<shibboleth::ITrust*> getTrustProviders() const=0;
96         virtual saml::Iterator<const XMLCh*> getAudiences() const=0;
97         virtual const shibsp::PropertySet* getCredentialUse(const shibboleth::IEntityDescriptor* provider) const=0;
98
99         // caller is borrowing object, must use within scope of config lock
100         virtual const saml::SAMLBrowserProfile* getBrowserProfile() const=0;
101         virtual const saml::SAMLBinding* getBinding(const XMLCh* binding) const=0;
102
103         // caller is given ownership of object, must use and delete within scope of config lock
104         virtual saml::SAMLBrowserProfile::ArtifactMapper* getArtifactMapper() const=0;
105
106         // general token validation based on conditions, signatures, etc.
107         virtual void validateToken(
108             saml::SAMLAssertion* token,
109             time_t t=0,
110             const shibboleth::IRoleDescriptor* role=NULL,
111             const saml::Iterator<shibboleth::ITrust*>& trusts=EMPTY(shibboleth::ITrust*)
112             ) const=0;
113
114         // Used to locate a default or designated session initiator for automatic sessions
115         virtual const IHandler* getDefaultSessionInitiator() const=0;
116         virtual const IHandler* getSessionInitiatorById(const char* id) const=0;
117         
118         // Used by session initiators to get endpoint to forward to IdP/WAYF
119         virtual const IHandler* getDefaultAssertionConsumerService() const=0;
120         virtual const IHandler* getAssertionConsumerServiceByIndex(unsigned short index) const=0;
121         virtual saml::Iterator<const IHandler*> getAssertionConsumerServicesByBinding(const XMLCh* binding) const=0;
122         
123         // Used by dispatcher to locate the handler for a request
124         virtual const IHandler* getHandler(const char* path) const=0;
125
126         virtual ~IApplication() {}
127     };
128
129     /**
130      * OpenSAML binding hook
131      *
132      * Instead of wrapping the binding to deal with mutual authentication, we
133      * just use the HTTP hook functionality offered by OpenSAML. The hook will
134      * register "itself" as a globalCtx pointer with the SAML binding and the caller
135      * will declare and pass the embedded struct as callCtx for use by the hook.
136      */
137     class ShibHTTPHook : virtual public saml::SAMLSOAPHTTPBinding::HTTPHook
138     {
139     public:
140         ShibHTTPHook(const saml::Iterator<shibboleth::ITrust*>& trusts, const saml::Iterator<shibboleth::ICredentials*>& creds)
141             : m_trusts(trusts), m_creds(creds) {}
142         virtual ~ShibHTTPHook() {}
143         
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);
146
147         // Client declares a context object and pass as callCtx to send() method.
148         class ShibHTTPHookCallContext {
149         public:
150             ShibHTTPHookCallContext(const shibsp::PropertySet* 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 shibsp::PropertySet* 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;}
157             
158         private:
159             const shibsp::PropertySet* m_credUse;
160             const shibboleth::IRoleDescriptor* m_role;
161             ShibHTTPHook* m_hook;
162             bool m_authenticated;
163             friend class ShibHTTPHook;
164         };
165         
166         const saml::Iterator<shibboleth::ITrust*>& getTrustProviders() const {return m_trusts;}
167         const saml::Iterator<shibboleth::ICredentials*>& getCredentialProviders() const {return m_creds;}
168     private:
169         saml::Iterator<shibboleth::ITrust*> m_trusts;
170         saml::Iterator<shibboleth::ICredentials*> m_creds;
171     };
172
173     /**
174      * Interface to a cached user session.
175      * 
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.
180      */
181     struct SHIBTARGET_EXPORTS ISessionCacheEntry : public virtual saml::ILockable
182     {
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() {}
190     };
191
192     /**
193      * Interface to a sink for session cache events.
194      *
195      * All caches support registration of a backing store that can be informed
196      * of significant events in the lifecycle of a cache entry.
197      */
198     struct SHIBTARGET_EXPORTS ISessionCacheStore
199     {
200         virtual HRESULT onCreate(
201             const char* key,
202             const IApplication* application,
203             const ISessionCacheEntry* entry,
204             int majorVersion,
205             int minorVersion,
206             time_t created
207             )=0;
208         virtual HRESULT onRead(
209             const char* key,
210             std::string& applicationId,
211             std::string& clientAddress,
212             std::string& providerId,
213             std::string& subject,
214             std::string& authnContext,
215             std::string& tokens,
216             int& majorVersion,
217             int& minorVersion,
218             time_t& created,
219             time_t& accessed
220             )=0;
221         virtual HRESULT onRead(const char* key, time_t& accessed)=0;
222         virtual HRESULT onRead(const char* key, std::string& tokens)=0;
223         virtual HRESULT onUpdate(const char* key, const char* tokens=NULL, time_t lastAccess=0)=0;
224         virtual HRESULT onDelete(const char* key)=0;
225         virtual ~ISessionCacheStore() {}
226     };
227
228     /**
229      * Interface to the session cache.
230      * 
231      * The session cache abstracts a persistent (meaning across requests) cache of
232      * instances of the ISessionCacheEntry interface. Creation of new entries and entry
233      * lookup are confined to this interface to enable implementations to flexibly
234      * remote and/or optimize calls by implementing custom versions of the
235      * ISessionCacheEntry interface as required.
236      */
237     struct SHIBTARGET_EXPORTS ISessionCache : public virtual saml::IPlugIn
238     {
239         virtual std::string insert(
240             const IApplication* application,
241             const shibboleth::IEntityDescriptor* source,
242             const char* client_addr,
243             const saml::SAMLSubject* subject,
244             const char* authnContext,
245             const saml::SAMLResponse* tokens
246             )=0;
247         virtual ISessionCacheEntry* find(
248             const char* key, const IApplication* application, const char* client_addr
249             )=0;
250         virtual void remove(
251             const char* key, const IApplication* application, const char* client_addr
252             )=0;
253
254         virtual bool setBackingStore(ISessionCacheStore* store)=0;
255         virtual ~ISessionCache() {}
256     };
257
258     /**
259      * Interface to an access control plugin
260      * 
261      * Access control plugins return authorization decisions based on the intersection
262      * of the resource request and the active session. They can be implemented through
263      * cross-platform or platform-specific mechanisms.
264      */
265     struct SHIBTARGET_EXPORTS IAccessControl : public virtual saml::ILockable, public virtual saml::IPlugIn
266     {
267         virtual bool authorized(ShibTarget* st, ISessionCacheEntry* entry) const=0;
268         virtual ~IAccessControl() {}
269     };
270
271     /**
272      * Interface to a request mapping plugin
273      * 
274      * Request mapping plugins return configuration settings that apply to resource requests.
275      * They can be implemented through cross-platform or platform-specific mechanisms.
276      */
277     struct SHIBTARGET_EXPORTS IRequestMapper : public virtual saml::ILockable, public virtual saml::IPlugIn
278     {
279         typedef std::pair<const shibsp::PropertySet*,IAccessControl*> Settings;
280         virtual Settings getSettings(ShibTarget* st) const=0;
281         virtual ~IRequestMapper() {}
282     };
283     
284     struct SHIBTARGET_EXPORTS IConfig : public virtual saml::ILockable, public virtual shibsp::PropertySet, public virtual saml::IPlugIn
285     {
286         // loads initial configuration
287         virtual void init()=0;
288
289         virtual shibsp::ListenerService* getListener() const=0;
290         virtual ISessionCache* getSessionCache() const=0;
291         virtual saml::IReplayCache* getReplayCache() const=0;
292         virtual IRequestMapper* getRequestMapper() const=0;
293         virtual const IApplication* getApplication(const char* applicationId) const=0;
294         virtual saml::Iterator<shibboleth::ICredentials*> getCredentialsProviders() const=0;
295         virtual ~IConfig() {}
296     };
297
298     class SHIBTARGET_EXPORTS ShibTargetConfig
299     {
300     public:
301         ShibTargetConfig() : m_ini(NULL) {}
302         virtual ~ShibTargetConfig() {}
303         
304         virtual bool init(const char* schemadir) = 0;
305         virtual bool load(const char* config) = 0;
306         virtual void shutdown() = 0;
307
308         virtual IConfig* getINI() const {return m_ini;}
309
310         static ShibTargetConfig& getConfig();
311
312     protected:
313         IConfig* m_ini;
314     };
315
316     class ShibTargetPriv;
317     class SHIBTARGET_EXPORTS ShibTarget {
318     public:
319         ShibTarget(const IApplication* app);
320         virtual ~ShibTarget(void);
321
322         // These are defined here so the subclass does not need to specifically
323         // depend on log4cpp.  We could use log4cpp::Priority::PriorityLevel
324         // but this is just as easy, IMHO.  It's just a case statement in the
325         // implementation to handle the event level.
326         enum ShibLogLevel {
327           LogLevelDebug,
328           LogLevelInfo,
329           LogLevelWarn,
330           LogLevelError
331         };
332
333         //
334         // Note: subclasses MUST implement ALL of these virtual methods
335         //
336         
337         // Send a message to the Webserver log
338         virtual void log(ShibLogLevel level, const std::string &msg)=0;
339
340         void log(ShibLogLevel level, const char* msg) {
341           std::string s = msg;
342           log(level, s);
343         }
344
345         // Get/Set a cookie for this request
346         virtual std::string getCookies() const=0;
347         virtual void setCookie(const std::string& name, const std::string& value)=0;
348         virtual const char* getCookie(const std::string& name) const;
349         void setCookie(const char* name, const char* value) {
350           std::string ns = name;
351           std::string vs = value;
352           setCookie(ns, vs);
353         }
354         void setCookie(const char* name, const std::string& value) {
355           std::string ns = name;
356           setCookie(ns, value);
357         }
358
359         // Get any URL-encoded arguments or the raw POST body from the server
360         virtual const char* getQueryString() const=0;
361         virtual const char* getRequestBody() const=0;
362         virtual const char* getRequestParameter(const char* param, size_t index=0) const;
363
364         // Clear a header, set a header
365         // These APIs are used for exporting the Assertions into the
366         // Headers.  It will clear some well-known headers first to make
367         // sure none remain.  Then it will process the set of assertions
368         // and export them via setHeader().
369         virtual void clearHeader(const std::string& name)=0;
370         virtual void setHeader(const std::string& name, const std::string& value)=0;
371         virtual std::string getHeader(const std::string& name)=0;
372         virtual void setRemoteUser(const std::string& user)=0;
373         virtual std::string getRemoteUser()=0;
374
375         void clearHeader(const char* n) {
376           std::string s = n;
377           clearHeader(s);
378         }
379         void setHeader(const char* n, const char* v) {
380           std::string ns = n;
381           std::string vs = v;
382           setHeader(ns, vs);
383         }
384         void setHeader(const std::string& n, const char* v) {
385           std::string vs = v;
386           setHeader(n, vs);
387         }
388         void setHeader(const char* n, const std::string& v) {
389           std::string ns = n;
390           setHeader(ns, v);
391         }
392         std::string getHeader(const char* n) {
393           std::string s = n;
394           return getHeader(s);
395         }
396         void setRemoteUser(const char* n) {
397           std::string s = n;
398           setRemoteUser(s);
399         }
400
401         // We're done.  Finish up.  Send specific result content or a redirect.
402         // If there are no headers supplied assume the content-type is text/html
403         typedef std::pair<std::string, std::string> header_t;
404         virtual void* sendPage(
405             const std::string& msg,
406             int code = 200,
407             const std::string& content_type = "text/html",
408             const saml::Iterator<header_t>& headers = EMPTY(header_t)
409             )=0;
410         void* sendPage(const char* msg) {
411           std::string m = msg;
412           return sendPage(m);
413         }
414         virtual void* sendRedirect(const std::string& url)=0;
415         
416         // These next two APIs are used to obtain the module-specific "OK"
417         // and "Decline" results.  OK means "we believe that this request
418         // should be accepted".  Declined means "we believe that this is
419         // not a shibbolized request so we have no comment".
420
421         virtual void* returnDecline();
422         virtual void* returnOK();
423
424         //
425         // Note:  Subclasses need not implement anything below this line
426         //
427
428         // These functions implement the server-agnostic shibboleth engine
429         // The web server modules implement a subclass and then call into 
430         // these methods once they instantiate their request object.
431         // 
432         // Return value:
433         //   these APIs will always return the result of sendPage(), sendRedirect(),
434         //   returnDecline(), or returnOK() in the void* portion of the return code.
435         //   Exactly what those values are is module- (subclass-) implementation
436         //   specific.  The 'bool' part of the return value declares whether the
437         //   void* is valid or not.  If the bool is true then the void* is valid.
438         //   If the bool is false then the API did not call any callback, the void*
439         //   is not valid, and the caller should continue processing (the API Call
440         //   finished successfully).
441         //
442         //   The handleProfile argument declares whether doCheckAuthN() should
443         //   automatically call doHandlePOST() when it encounters a request for
444         //   the ShireURL;  if false it will call returnOK() instead.
445         //
446         std::pair<bool,void*> doCheckAuthN(bool handler = false);
447         std::pair<bool,void*> doHandler();
448         std::pair<bool,void*> doCheckAuthZ();
449         std::pair<bool,void*> doExportAssertions(bool requireSession = true);
450
451         // Basic request access in case any plugins need the info
452         virtual const IConfig* getConfig() const;
453         virtual const IApplication* getApplication() const;
454         const char* getRequestMethod() const {return m_method.c_str();}
455         const char* getProtocol() const {return m_protocol.c_str();}
456         const char* getHostname() const {return m_hostname.c_str();}
457         int getPort() const {return m_port;}
458         const char* getRequestURI() const {return m_uri.c_str();}
459         const char* getContentType() const {return m_content_type.c_str();}
460         const char* getRemoteAddr() const {return m_remote_addr.c_str();}
461         const char* getRequestURL() const {return m_url.c_str();}
462         
463         // Advanced methods useful to profile handlers implemented outside core
464         
465         // Get per-application session and state cookie name and properties
466         virtual std::pair<std::string,const char*> getCookieNameProps(const char* prefix) const;
467         
468         // Determine the effective handler URL based on the resource URL
469         virtual std::string getHandlerURL(const char* resource) const;
470
471     protected:
472         ShibTarget();
473
474         // Internal APIs
475
476         // Initialize the request from the parsed URL
477         // protocol == http, https, etc
478         // hostname == server name
479         // port == server port
480         // uri == resource path
481         // method == GET, POST, etc.
482         void init(
483             const char* protocol,
484             const char* hostname,
485             int port,
486             const char* uri,
487             const char* content_type,
488             const char* remote_addr,
489             const char* method
490             );
491
492         std::string m_url, m_method, m_protocol, m_hostname, m_uri, m_content_type, m_remote_addr;
493         int m_port;
494
495     private:
496         mutable ShibTargetPriv* m_priv;
497         friend class ShibTargetPriv;
498     };
499
500     struct SHIBTARGET_EXPORTS XML
501     {
502         static const XMLCh SHIBTARGET_NS[];
503         static const XMLCh SHIBTARGET_SCHEMA_ID[];
504         static const XMLCh SAML2ASSERT_NS[];
505         static const XMLCh SAML2ASSERT_SCHEMA_ID[];
506         static const XMLCh SAML2META_NS[];
507         static const XMLCh SAML2META_SCHEMA_ID[];
508         static const XMLCh XMLENC_NS[];
509         static const XMLCh XMLENC_SCHEMA_ID[];
510     
511         // Session cache implementations
512         static const char MemorySessionCacheType[];
513         static const char MySQLSessionCacheType[];
514         static const char ODBCSessionCacheType[];
515         
516         // Replay cache implementations
517         static const char MySQLReplayCacheType[];
518         static const char ODBCReplayCacheType[];
519         
520         // Request mapping/settings implementations
521         static const char XMLRequestMapType[];      // portable XML-based map
522         static const char NativeRequestMapType[];   // Native web server command override of XML-based map
523         static const char LegacyRequestMapType[];   // older designation of XML map, hijacked by web server
524         
525         // Access control implementations
526         static const char htAccessControlType[];    // Apache-specific .htaccess authz module
527         static const char XMLAccessControlType[];   // Proprietary but portable XML authz syntax
528
529         struct SHIBTARGET_EXPORTS Literals
530         {
531             static const XMLCh AAPProvider[];
532             static const XMLCh AccessControl[];
533             static const XMLCh AccessControlProvider[];
534             static const XMLCh acl[];
535             static const XMLCh AND[];
536             static const XMLCh applicationId[];
537             static const XMLCh Application[];
538             static const XMLCh Applications[];
539             static const XMLCh AssertionConsumerService[];
540             static const XMLCh AttributeFactory[];
541             static const XMLCh config[];
542             static const XMLCh CredentialsProvider[];
543             static const XMLCh CredentialUse[];
544             static const XMLCh DiagnosticService[];
545             static const XMLCh echo[];
546             static const XMLCh Extensions[];
547             static const XMLCh fatal[];
548             static const XMLCh FederationProvider[];
549             static const XMLCh Global[];
550             static const XMLCh Host[];
551             static const XMLCh htaccess[];
552             static const XMLCh Implementation[];
553             static const XMLCh index[];
554             static const XMLCh InProcess[];
555             static const XMLCh isDefault[];
556             static const XMLCh Library[];
557             static const XMLCh Listener[];
558             static const XMLCh Local[];
559             static const XMLCh log[];
560             static const XMLCh logger[];
561             static const XMLCh MemorySessionCache[];
562             static const XMLCh MetadataProvider[];
563             static const XMLCh MySQLReplayCache[];
564             static const XMLCh MySQLSessionCache[];
565             static const XMLCh name[];
566             static const XMLCh Name[];
567             static const XMLCh NOT[];
568             static const XMLCh ODBCReplayCache[];
569             static const XMLCh ODBCSessionCache[];
570             static const XMLCh OR[];
571             static const XMLCh OutOfProcess[];
572             static const XMLCh Path[];
573             static const XMLCh path[];
574             static const XMLCh RelyingParty[];
575             static const XMLCh ReplayCache[];
576             static const XMLCh RequestMap[];
577             static const XMLCh RequestMapProvider[];
578             static const XMLCh require[];
579             static const XMLCh Rule[];
580             static const XMLCh SessionCache[];
581             static const XMLCh SessionInitiator[];
582             static const XMLCh SHAR[];
583             static const XMLCh ShibbolethTargetConfig[];
584             static const XMLCh SHIRE[];
585             static const XMLCh Signing[];
586             static const XMLCh SingleLogoutService[];
587             static const XMLCh SPConfig[];
588             static const XMLCh TCPListener[];
589             static const XMLCh TLS[];
590             static const XMLCh TrustProvider[];
591             static const XMLCh type[];
592             static const XMLCh UnixListener[];
593         };
594     };
595 }
596
597 #endif /* SHIB_TARGET_H */