Reduce catch all handlers, and make them optional.
[shibboleth/cpp-sp.git] / shib-target / ShibHTTPHook.cpp
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 /* ShibHTTPHook.cpp - Shibboleth hook for SAML Binding with SSL callback
18
19    Scott Cantor
20    2/13/05
21    
22    $History:$
23 */
24
25 #include "internal.h"
26
27 #include <saml/version.h>
28 #include <openssl/ssl.h>
29 #include <openssl/x509_vfy.h>
30
31 using namespace shibtarget::logging;
32 using namespace shibtarget;
33 using namespace shibboleth;
34 using namespace saml;
35 using namespace std;
36
37 /*
38  * Our verifier callback is a front-end for invoking each trust plugin until
39  * success, or we run out of plugins.
40  */
41 static int verify_callback(X509_STORE_CTX* x509_ctx, void* arg)
42 {
43     Category::getInstance("OpenSSL").debug("invoking default X509 verify callback");
44 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
45     ShibHTTPHook::ShibHTTPHookCallContext* ctx = reinterpret_cast<ShibHTTPHook::ShibHTTPHookCallContext*>(arg);
46 #else
47     // Yes, this sucks. I'd use TLS, but there's no really obvious spot to put the thread key
48     // and global variables suck too. We can't access the X509_STORE_CTX depth directly because
49     // OpenSSL only copies it into the context if it's >=0, and the unsigned pointer may be
50     // negative in the SSL structure's int member.
51     SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(x509_ctx,SSL_get_ex_data_X509_STORE_CTX_idx()));
52     ShibHTTPHook::ShibHTTPHookCallContext* ctx =
53         reinterpret_cast<ShibHTTPHook::ShibHTTPHookCallContext*>(SSL_get_verify_depth(ssl));
54 #endif
55
56     // Instead of using the supplied verifier, we let the plugins do whatever they want to do
57     // with the untrusted certificates we find in the object. We can save a bit of memory by
58     // just building a vector that points at them inside the supplied structure.
59     vector<void*> chain;
60     for (int i=0; i<sk_X509_num(x509_ctx->untrusted); i++)
61         chain.push_back(sk_X509_value(x509_ctx->untrusted,i));
62     
63     Trust t(ctx->getHook()->getTrustProviders());
64     if (!t.validate(x509_ctx->cert,chain,ctx->getRoleDescriptor(),false)) { // bypass name check (handled for us)
65         x509_ctx->error=X509_V_ERR_APPLICATION_VERIFICATION;     // generic error, check log for plugin specifics
66         return 0;
67     }
68     
69     // Signal success. Hopefully it doesn't matter what's actually in the structure now.
70     return 1;
71 }
72
73 /*
74  * OpenSAML callback is invoked during SSL context setup, before the handshake.
75  * We use it to attach credentials and our own certificate verifier callback above.
76  */
77 static bool ssl_ctx_callback(void* ssl_ctx, void* userptr)
78 {
79 #ifdef _DEBUG
80     saml::NDC("ssl_ctx_callback");
81 #endif
82     Category& log=Category::getInstance(SHIBT_LOGCAT".ShibHTTPHook");
83     
84     try {
85         log.debug("OpenSAML invoked SSL context callback");
86         ShibHTTPHook::ShibHTTPHookCallContext* ctx = reinterpret_cast<ShibHTTPHook::ShibHTTPHookCallContext*>(userptr);
87         const IPropertySet* credUse=ctx->getCredentialUse();
88         pair<bool,const char*> TLS=credUse ? credUse->getString("TLS") : pair<bool,const char*>(false,NULL);
89         if (TLS.first) {
90             Credentials c(ctx->getHook()->getCredentialProviders());
91             const ICredResolver* cr=c.lookup(TLS.second);
92             if (cr)
93                 cr->attach(ssl_ctx);
94             else
95                 log.error("unable to attach credentials to request using (%s), leaving anonymous",TLS.second);
96         }
97         else
98             log.warn("no TLS credentials supplied, leaving anonymous");
99         
100         SSL_CTX_set_verify(reinterpret_cast<SSL_CTX*>(ssl_ctx),SSL_VERIFY_PEER,NULL);
101 #if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
102         // With 0.9.7, we can pass a callback argument directly.
103         SSL_CTX_set_cert_verify_callback(reinterpret_cast<SSL_CTX*>(ssl_ctx),verify_callback,userptr);
104 #else
105         // With 0.9.6, there's no argument, so we're going to use a really embarrassing hack and
106         // stuff the argument in the depth property where it will get copied to the context object
107         // that's handed to the callback.
108         SSL_CTX_set_cert_verify_callback(
109             reinterpret_cast<SSL_CTX*>(ssl_ctx),
110             reinterpret_cast<int (*)()>(verify_callback),
111             NULL
112             );
113         SSL_CTX_set_verify_depth(reinterpret_cast<SSL_CTX*>(ssl_ctx),reinterpret_cast<int>(userptr));
114
115 #endif
116     }
117     catch (SAMLException& e) {
118         log.error(string("caught a SAML exception while attaching credentials to request: ") + e.what());
119         return false;
120     }
121 #ifndef _DEBUG
122     catch (...) {
123         log.error("caught an unknown exception while attaching credentials to request");
124         return false;
125     }
126 #endif
127     
128     return true;
129 }
130
131 bool ShibHTTPHook::outgoing(HTTPClient* conn, void* globalCtx, void* callCtx)
132 {
133     // Sanity check...
134     if (globalCtx != this)
135         return false;
136
137     // Clear authn status.
138     reinterpret_cast<ShibHTTPHookCallContext*>(callCtx)->m_authenticated=false;
139          
140     // The callCtx is our nested context class. Copy in the parent pointer.
141     reinterpret_cast<ShibHTTPHookCallContext*>(callCtx)->m_hook=this;
142     
143     // The hook function is called before connecting to the HTTP server. This
144     // gives us a chance to attach our own SSL callback, and set a version header.
145     if (!conn->setSSLCallback(ssl_ctx_callback,callCtx))
146         return false;
147     
148     if (!conn->setRequestHeader("Shibboleth", PACKAGE_VERSION))
149         return false;
150     if (!conn->setRequestHeader("Xerces-C", XERCES_FULLVERSIONDOT))
151         return false;
152     if (!conn->setRequestHeader("XML-Security-C", XSEC_VERSION))
153         return false;
154     if (!conn->setRequestHeader("OpenSAML-C", OPENSAML_FULLVERSIONDOT))
155         return false;
156
157     // Check for HTTP authentication...
158     const IPropertySet* credUse=reinterpret_cast<ShibHTTPHookCallContext*>(callCtx)->getCredentialUse();
159     pair<bool,const char*> authType=credUse ? credUse->getString("authType") : pair<bool,const char*>(false,NULL);
160     if (authType.first) {
161 #ifdef _DEBUG
162         saml::NDC("outgoing");
163 #endif
164         Category& log=Category::getInstance(SHIBT_LOGCAT".ShibHTTPHook");
165         HTTPClient::auth_t type=HTTPClient::auth_none;
166         pair<bool,const char*> username=credUse->getString("authUsername");
167         pair<bool,const char*> password=credUse->getString("authPassword");
168         if (!username.first || !password.first) {
169             log.error("HTTP authType (%s) specified but authUsername or authPassword was missing", authType.second);
170             return false;
171         }
172         else if (!strcmp(authType.second,"basic"))
173             type = HTTPClient::auth_basic;
174         else if (!strcmp(authType.second,"digest"))
175             type = HTTPClient::auth_digest;
176         else if (!strcmp(authType.second,"ntlm"))
177             type = HTTPClient::auth_ntlm;
178         else if (!strcmp(authType.second,"gss"))
179             type = HTTPClient::auth_gss;
180         else {
181             log.error("Unknown authType (%s) specified in CredentialUse element", authType.second);
182             return false;
183         }
184         log.debug("configured for HTTP authentication (method=%s, username=%s)", authType.second, username.second);
185         return conn->setAuth(type,username.second,password.second);
186     }
187
188     // The best we can do is assume authentication succeeds because when libcurl reuses
189     // SSL and HTTP connections, no callback is made. Since we always authenticate SSL connections,
190     // the caller should check that the protocol is https.
191     reinterpret_cast<ShibHTTPHookCallContext*>(callCtx)->setAuthenticated();
192     return true;
193 }