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