Changed default paths.
[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 #include <saml/saml.h>
29 #include <shib/shib.h>
30 #include <shib/shib-threads.h>
31
32 #ifdef WIN32
33 # ifndef SHIBTARGET_EXPORTS
34 #  define SHIBTARGET_EXPORTS __declspec(dllimport)
35 # endif
36 # define SHIB_SCHEMAS "/opt/shibboleth-sp/share/xml/shibboleth"
37 # define SHIB_CONFIG "/opt/shibboleth-sp/etc/shibboleth/shibboleth.xml"
38 # include <winsock.h>
39 #else
40 # include <shib-target/shib-paths.h>
41 # define SHIBTARGET_EXPORTS
42 #endif
43
44
45 namespace shibtarget {
46   
47     DECLARE_SAML_EXCEPTION(SHIBTARGET_EXPORTS,ListenerException,SAMLException);
48     DECLARE_SAML_EXCEPTION(SHIBTARGET_EXPORTS,ConfigurationException,SAMLException);
49
50     enum ShibProfile {
51       PROFILE_UNSPECIFIED = 0,
52       SAML10_POST = 1,
53       SAML10_ARTIFACT = 2,
54       SAML11_POST = 4,
55       SAML11_ARTIFACT = 8,
56       SAML20_SSO = 16
57     };
58
59     // Abstract APIs for access to configuration information
60     
61     struct SHIBTARGET_EXPORTS IPropertySet
62     {
63         virtual std::pair<bool,bool> getBool(const char* name, const char* ns=NULL) const=0;
64         virtual std::pair<bool,const char*> getString(const char* name, const char* ns=NULL) const=0;
65         virtual std::pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const=0;
66         virtual std::pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const=0;
67         virtual std::pair<bool,int> getInt(const char* name, const char* ns=NULL) const=0;
68         virtual const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const=0;
69         virtual const DOMElement* getElement() const=0;
70         virtual ~IPropertySet() {}
71     };
72
73     struct SHIBTARGET_EXPORTS IApplication : public virtual IPropertySet
74     {
75         virtual const char* getId() const=0;
76         virtual const char* getHash() const=0;
77         
78         virtual saml::Iterator<saml::SAMLAttributeDesignator*> getAttributeDesignators() const=0;
79         virtual saml::Iterator<shibboleth::IAAP*> getAAPProviders() const=0;
80         virtual saml::Iterator<shibboleth::IMetadata*> getMetadataProviders() const=0;
81         virtual saml::Iterator<shibboleth::ITrust*> getTrustProviders() const=0;
82         virtual saml::Iterator<const XMLCh*> getAudiences() const=0;
83         virtual const IPropertySet* getCredentialUse(const shibboleth::IEntityDescriptor* provider) const=0;
84
85         // caller is borrowing object, must use within scope of config lock
86         virtual const saml::SAMLBrowserProfile* getBrowserProfile() const=0;
87         virtual const saml::SAMLBinding* getBinding(const XMLCh* binding) const=0;
88
89         // caller is given ownership of object, must use and delete within scope of config lock
90         virtual saml::SAMLBrowserProfile::ArtifactMapper* getArtifactMapper() const=0;
91
92         // Used to locate a default or designated session initiator for automatic sessions
93         virtual const IPropertySet* getDefaultSessionInitiator() const=0;
94         virtual const IPropertySet* getSessionInitiatorById(const char* id) const=0;
95         
96         // Used by session initiators to get endpoint to forward to IdP/WAYF
97         virtual const IPropertySet* getDefaultAssertionConsumerService() const=0;
98         virtual const IPropertySet* getAssertionConsumerServiceByIndex(unsigned short index) const=0;
99         
100         // Used by dispatcher to locate the handler configuration for a Shibboleth request
101         virtual const IPropertySet* getHandlerConfig(const char* path) const=0;
102
103         virtual ~IApplication() {}
104     };
105
106     // Instead of wrapping the binding to deal with mutual authentication, we
107     // just use the HTTP hook functionality offered by OpenSAML. The hook will
108     // register "itself" as a globalCtx pointer with the SAML binding and the caller
109     // will declare and pass the embedded struct as callCtx for use by the hook.
110     class ShibHTTPHook : virtual public saml::SAMLSOAPHTTPBinding::HTTPHook
111     {
112     public:
113         ShibHTTPHook(const saml::Iterator<shibboleth::ITrust*>& trusts, const saml::Iterator<shibboleth::ICredentials*>& creds)
114             : m_trusts(trusts), m_creds(creds) {}
115         virtual ~ShibHTTPHook() {}
116         
117         // Only hook we need here is for outgoing connection to server.
118         virtual bool outgoing(saml::HTTPClient* conn, void* globalCtx=NULL, void* callCtx=NULL);
119
120         // Client declares a context object and pass as callCtx to send() method.
121         class ShibHTTPHookCallContext {
122         public:
123             ShibHTTPHookCallContext(const IPropertySet* credUse, const shibboleth::IRoleDescriptor* role)
124                 : m_credUse(credUse), m_role(role), m_hook(NULL), m_authenticated(false) {}
125             const ShibHTTPHook* getHook() {return m_hook;}
126             const IPropertySet* getCredentialUse() {return m_credUse;}
127             const shibboleth::IRoleDescriptor* getRoleDescriptor() {return m_role;}
128             bool isAuthenticated() const {return m_authenticated;}
129             void setAuthenticated() {m_authenticated=true;}
130             
131         private:
132             const IPropertySet* m_credUse;
133             const shibboleth::IRoleDescriptor* m_role;
134             ShibHTTPHook* m_hook;
135             bool m_authenticated;
136             friend class ShibHTTPHook;
137         };
138         
139         const saml::Iterator<shibboleth::ITrust*>& getTrustProviders() const {return m_trusts;}
140         const saml::Iterator<shibboleth::ICredentials*>& getCredentialProviders() const {return m_creds;}
141     private:
142         saml::Iterator<shibboleth::ITrust*> m_trusts;
143         saml::Iterator<shibboleth::ICredentials*> m_creds;
144     };
145
146     struct SHIBTARGET_EXPORTS ISessionCacheEntry : public virtual saml::ILockable
147     {
148         virtual bool isValid(time_t lifetime, time_t timeout) const=0;
149         virtual const char* getClientAddress() const=0;
150         virtual ShibProfile getProfile() const=0;
151         virtual const char* getProviderId() const=0;
152         virtual const saml::SAMLAuthenticationStatement* getAuthnStatement() const=0;
153         struct SHIBTARGET_EXPORTS CachedResponse {
154             CachedResponse(const saml::SAMLResponse* unfiltered, const saml::SAMLResponse* filtered) {
155                 this->unfiltered=unfiltered;
156                 this->filtered=filtered;
157             }
158             bool empty() {return unfiltered==NULL;}
159             const saml::SAMLResponse* unfiltered;
160             const saml::SAMLResponse* filtered;
161         };
162         virtual CachedResponse getResponse()=0;
163         virtual ~ISessionCacheEntry() {}
164     };
165
166     struct SHIBTARGET_EXPORTS ISessionCache : public virtual saml::IPlugIn
167     {
168         virtual void thread_init()=0;
169         virtual void thread_end()=0;
170         virtual std::string generateKey() const=0;
171         virtual void insert(
172             const char* key,
173             const IApplication* application,
174             const char* client_addr,
175             ShibProfile profile,
176             const char* providerId,
177             saml::SAMLAuthenticationStatement* s,
178             saml::SAMLResponse* r=NULL,
179             const shibboleth::IRoleDescriptor* source=NULL,
180             time_t created=0,
181             time_t accessed=0
182             )=0;
183         virtual ISessionCacheEntry* find(const char* key, const IApplication* application)=0;
184         virtual void remove(const char* key)=0;
185         virtual ~ISessionCache() {}
186     };
187
188     struct SHIBTARGET_EXPORTS IListener : public virtual saml::IPlugIn
189     {
190         // The socket APIs should really be somewhere else, but compatibility
191         // with older configuration files dictates that the Listener handles
192         // both client and server socket handling. We can fix this for 2.0...?
193 #ifdef WIN32
194         typedef SOCKET ShibSocket;
195 #else
196         typedef int ShibSocket;
197 #endif
198         virtual bool create(ShibSocket& s) const=0;
199         virtual bool bind(ShibSocket& s, bool force=false) const=0;
200         virtual bool connect(ShibSocket& s) const=0;
201         virtual bool close(ShibSocket& s) const=0;
202         virtual bool accept(ShibSocket& listener, ShibSocket& s) const=0;
203
204         // The "real" Listener API abstracts the primitive operations that make up
205         // the meat of the SP's job. Right now, that's session create/read/delete.
206         virtual void sessionNew(
207             const IApplication* application,
208             int supported_profiles,
209             const char* recipient,
210             const char* packet,
211             const char* ip,
212             std::string& target,
213             std::string& cookie,
214             std::string& provider_id
215             ) const=0;
216     
217         virtual void sessionGet(
218             const IApplication* application,
219             const char* cookie,
220             const char* ip,
221             ISessionCacheEntry** pentry
222             ) const=0;
223     
224         virtual void sessionEnd(
225             const IApplication* application,
226             const char* cookie
227             ) const=0;
228             
229         virtual void ping(int& i) const=0;
230         
231         virtual ~IListener() {}
232     };
233
234     class SHIBTARGET_EXPORTS ShibTarget;
235
236     struct SHIBTARGET_EXPORTS IAccessControl : public virtual saml::ILockable, public virtual saml::IPlugIn
237     {
238         virtual bool authorized(ShibTarget* st, ISessionCacheEntry* entry) const=0;
239         virtual ~IAccessControl() {}
240     };
241
242     struct SHIBTARGET_EXPORTS IRequestMapper : public virtual saml::ILockable, public virtual saml::IPlugIn
243     {
244         typedef std::pair<const IPropertySet*,IAccessControl*> Settings;
245         virtual Settings getSettings(ShibTarget* st) const=0;
246         virtual ~IRequestMapper() {}
247     };
248     
249     struct SHIBTARGET_EXPORTS IHandler : public virtual saml::IPlugIn
250     {
251         virtual std::pair<bool,void*> run(ShibTarget* st, const IPropertySet* config, bool isHandler=true)=0;
252         virtual ~IHandler() {}
253     };
254     
255     struct SHIBTARGET_EXPORTS IConfig : public virtual saml::ILockable, public virtual IPropertySet, public virtual saml::IPlugIn
256     {
257         virtual const IListener* getListener() const=0;
258         virtual ISessionCache* getSessionCache() const=0;
259         virtual saml::IReplayCache* getReplayCache() const=0;
260         virtual IRequestMapper* getRequestMapper() const=0;
261         virtual const IApplication* getApplication(const char* applicationId) const=0;
262         virtual saml::Iterator<shibboleth::ICredentials*> getCredentialsProviders() const=0;
263         virtual ~IConfig() {}
264     };
265
266     class SHIBTARGET_EXPORTS ShibTargetConfig
267     {
268     public:
269         ShibTargetConfig() : m_ini(NULL), m_features(0) {}
270         virtual ~ShibTargetConfig() {}
271         
272         virtual bool init(const char* schemadir) = 0;
273         virtual bool load(const char* config) = 0;
274         virtual void shutdown() = 0;
275
276         enum components_t {
277             Listener = 1,
278             Caching = 2,
279             Metadata = 4,
280             Trust = 8,
281             Credentials = 16,
282             AAP = 32,
283             RequestMapper = 64,
284             GlobalExtensions = 128,
285             LocalExtensions = 256,
286             Logging = 512
287         };
288         void setFeatures(long enabled) {m_features = enabled;}
289         bool isEnabled(components_t feature) {return (m_features & feature)>0;}
290         virtual IConfig* getINI() const {return m_ini;}
291
292         static ShibTargetConfig& getConfig();
293
294     protected:
295         IConfig* m_ini;
296         
297     private:
298         unsigned long m_features;
299     };
300
301   class ShibTargetPriv;
302   class SHIBTARGET_EXPORTS ShibTarget {
303   public:
304     ShibTarget(const IApplication *app);
305     virtual ~ShibTarget(void);
306
307     // These are defined here so the subclass does not need to specifically
308     // depend on log4cpp.  We could use log4cpp::Priority::PriorityLevel
309     // but this is just as easy, IMHO.  It's just a case statement in the
310     // implementation to handle the event level.
311     enum ShibLogLevel {
312       LogLevelDebug,
313       LogLevelInfo,
314       LogLevelWarn,
315       LogLevelError
316     };
317
318     //
319     // Note: subclasses MUST implement ALL of these virtual methods
320     //
321     
322     // Send a message to the Webserver log
323     virtual void log(ShibLogLevel level, const std::string &msg)=0;
324
325     void log(ShibLogLevel level, const char *msg) {
326       std::string s = msg;
327       log(level, s);
328     }
329
330     // Get/Set a cookie for this request
331     virtual std::string getCookies() const=0;
332     virtual void setCookie(const std::string &name, const std::string &value)=0;
333     virtual const char* getCookie(const std::string& name) const;
334     void setCookie(const char *name, const char *value) {
335       std::string ns = name;
336       std::string vs = value;
337       setCookie(ns, vs);
338     }
339     void setCookie(const char *name, const std::string &value) {
340       std::string ns = name;
341       setCookie(ns, value);
342     }
343
344
345     // Get the request's GET arguments or POST data from the server
346     virtual std::string getArgs(void)=0;
347     virtual std::string getPostData(void)=0;
348
349     // Clear a header, set a header
350     // These APIs are used for exporting the Assertions into the
351     // Headers.  It will clear some well-known headers first to make
352     // sure none remain.  Then it will process the set of assertions
353     // and export them via setHeader().
354     virtual void clearHeader(const std::string &name)=0;
355     virtual void setHeader(const std::string &name, const std::string &value)=0;
356     virtual std::string getHeader(const std::string &name)=0;
357     virtual void setRemoteUser(const std::string &user)=0;
358     virtual std::string getRemoteUser(void)=0;
359
360     void clearHeader(const char *n) {
361       std::string s = n;
362       clearHeader(s);
363     }
364     void setHeader(const char *n, const char *v) {
365       std::string ns = n;
366       std::string vs = v;
367       setHeader(ns, vs);
368     }
369     void setHeader(const std::string &n, const char *v) {
370       std::string vs = v;
371       setHeader(n, vs);
372     }
373     void setHeader(const char *n, const std::string &v) {
374       std::string ns = n;
375       setHeader(ns, v);
376     }
377     std::string getHeader(const char *n) {
378       std::string s = n;
379       return getHeader(s);
380     }
381     void setRemoteUser(const char *n) {
382       std::string s = n;
383       setRemoteUser(s);
384     }
385
386     // We're done.  Finish up.  Send specific result content or a redirect.
387     // If there are no headers supplied assume the content-type is text/html
388     typedef std::pair<std::string, std::string> header_t;
389     virtual void* sendPage(
390         const std::string& msg,
391         int code = 200,
392         const std::string& content_type = "text/html",
393         const saml::Iterator<header_t>& headers = EMPTY(header_t)
394         )=0;
395     void* sendPage(const char *msg) {
396       std::string m = msg;
397       return sendPage(m);
398     }
399     virtual void* sendRedirect(const std::string& url)=0;
400     
401     // These next two APIs are used to obtain the module-specific "OK"
402     // and "Decline" results.  OK means "we believe that this request
403     // should be accepted".  Declined means "we believe that this is
404     // not a shibbolized request so we have no comment".
405
406     virtual void* returnDecline(void);
407     virtual void* returnOK(void);
408
409     //
410     // Note:  Subclasses need not implement anything below this line
411     //
412
413     // These functions implement the server-agnostic shibboleth engine
414     // The web server modules implement a subclass and then call into 
415     // these methods once they instantiate their request object.
416     // 
417     // Return value:
418     //   these APIs will always return the result of sendPage(), sendRedirect(),
419     //   returnDecline(), or returnOK() in the void* portion of the return code.
420     //   Exactly what those values are is module- (subclass-) implementation
421     //   specific.  The 'bool' part of the return value declares whether the
422     //   void* is valid or not.  If the bool is true then the void* is valid.
423     //   If the bool is false then the API did not call any callback, the void*
424     //   is not valid, and the caller should continue processing (the API Call
425     //   finished successfully).
426     //
427     //   The handleProfile argument declares whether doCheckAuthN() should
428     //   automatically call doHandlePOST() when it encounters a request for
429     //   the ShireURL;  if false it will call returnOK() instead.
430     //
431     std::pair<bool,void*> doCheckAuthN(bool handler = false);
432     std::pair<bool,void*> doHandler();
433     std::pair<bool,void*> doCheckAuthZ();
434     std::pair<bool,void*> doExportAssertions(bool requireSession = true);
435
436     // Basic request access in case any plugins need the info
437     virtual const IConfig* getConfig() const;
438     virtual const IApplication* getApplication() const;
439     const char* getRequestMethod() const {return m_method.c_str();}
440     const char* getProtocol() const {return m_protocol.c_str();}
441     const char* getHostname() const {return m_hostname.c_str();}
442     int getPort() const {return m_port;}
443     const char* getRequestURI() const {return m_uri.c_str();}
444     const char* getContentType() const {return m_content_type.c_str();}
445     const char* getRemoteAddr() const {return m_remote_addr.c_str();}
446     const char* getRequestURL() const {return m_url.c_str();}
447     
448     // Advanced methods useful to profile handlers implemented outside core
449     
450     // Get per-application session and state cookie name and properties
451     virtual std::pair<std::string,const char*> getCookieNameProps(const char* prefix) const;
452     
453     // Determine the effective handler URL based on the resource URL
454     virtual std::string getHandlerURL(const char* resource) const;
455
456   protected:
457     ShibTarget();
458
459     // Internal APIs
460
461     // Initialize the request from the parsed URL
462     // protocol == http, https, etc
463     // hostname == server name
464     // port == server port
465     // uri == resource path
466     // method == GET, POST, etc.
467     void init(
468         const char* protocol,
469         const char* hostname,
470         int port,
471         const char* uri,
472         const char* content_type,
473         const char* remote_addr,
474         const char* method
475         );
476
477     std::string m_url, m_method, m_protocol, m_hostname, m_uri, m_content_type, m_remote_addr;
478     int m_port;
479
480   private:
481     mutable ShibTargetPriv* m_priv;
482     friend class ShibTargetPriv;
483   };
484
485     struct SHIBTARGET_EXPORTS XML
486     {
487         static const XMLCh SHIBTARGET_NS[];
488         static const XMLCh SHIBTARGET_SCHEMA_ID[];
489         static const XMLCh SAML2ASSERT_NS[];
490         static const XMLCh SAML2ASSERT_SCHEMA_ID[];
491         static const XMLCh SAML2META_NS[];
492         static const XMLCh SAML2META_SCHEMA_ID[];
493         static const XMLCh XMLENC_NS[];
494         static const XMLCh XMLENC_SCHEMA_ID[];
495     
496         // Session cache implementations
497         static const char MemorySessionCacheType[];
498         static const char MySQLSessionCacheType[];
499         
500         // Replay cache implementations
501         static const char MySQLReplayCacheType[];
502         
503         // Request mapping/settings implementations
504         static const char XMLRequestMapType[];      // portable XML-based map
505         static const char NativeRequestMapType[];   // Native web server command override of XML-based map
506         static const char LegacyRequestMapType[];   // older designation of XML map, hijacked by web server
507         
508         // Access control implementations
509         static const char htAccessControlType[];    // Apache-specific .htaccess authz module
510         static const char XMLAccessControlType[];   // Proprietary but portable XML authz syntax
511
512         // Listener implementations
513         static const char TCPListenerType[];        // ONC RPC via TCP socket
514         static const char UnixListenerType[];       // ONC RPC via domain socker
515         static const char MemoryListenerType[];     // "faked" in-process marshalling
516     
517         struct SHIBTARGET_EXPORTS Literals
518         {
519             static const XMLCh AAPProvider[];
520             static const XMLCh AccessControl[];
521             static const XMLCh AccessControlProvider[];
522             static const XMLCh acl[];
523             static const XMLCh AND[];
524             static const XMLCh applicationId[];
525             static const XMLCh Application[];
526             static const XMLCh Applications[];
527             static const XMLCh AssertionConsumerService[];
528             static const XMLCh AttributeFactory[];
529             static const XMLCh config[];
530             static const XMLCh CredentialsProvider[];
531             static const XMLCh CredentialUse[];
532             static const XMLCh DiagnosticService[];
533             static const XMLCh echo[];
534             static const XMLCh Extensions[];
535             static const XMLCh fatal[];
536             static const XMLCh FederationProvider[];
537             static const XMLCh Global[];
538             static const XMLCh Host[];
539             static const XMLCh htaccess[];
540             static const XMLCh Implementation[];
541             static const XMLCh index[];
542             static const XMLCh isDefault[];
543             static const XMLCh Library[];
544             static const XMLCh Listener[];
545             static const XMLCh Local[];
546             static const XMLCh log[];
547             static const XMLCh logger[];
548             static const XMLCh MemorySessionCache[];
549             static const XMLCh MetadataProvider[];
550             static const XMLCh MySQLReplayCache[];
551             static const XMLCh MySQLSessionCache[];
552             static const XMLCh name[];
553             static const XMLCh Name[];
554             static const XMLCh NOT[];
555             static const XMLCh OR[];
556             static const XMLCh Path[];
557             static const XMLCh path[];
558             static const XMLCh RelyingParty[];
559             static const XMLCh ReplayCache[];
560             static const XMLCh RequestMap[];
561             static const XMLCh RequestMapProvider[];
562             static const XMLCh require[];
563             static const XMLCh Rule[];
564             static const XMLCh SessionCache[];
565             static const XMLCh SessionInitiator[];
566             static const XMLCh SHAR[];
567             static const XMLCh ShibbolethTargetConfig[];
568             static const XMLCh SHIRE[];
569             static const XMLCh Signing[];
570             static const XMLCh SingleLogoutService[];
571             static const XMLCh SPConfig[];
572             static const XMLCh TCPListener[];
573             static const XMLCh TLS[];
574             static const XMLCh TrustProvider[];
575             static const XMLCh type[];
576             static const XMLCh UnixListener[];
577         };
578     };
579 }
580
581 #endif /* SHIB_TARGET_H */