Attempt at a metadata generation handler.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / AbstractHandler.cpp
1 /*
2  *  Copyright 2001-2007 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  * AbstractHandler.cpp
19  * 
20  * Base class for handlers based on a DOMPropertySet. 
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/LogoutHandler.h"
30 #include "remoting/ListenerService.h"
31 #include "util/SPConstants.h"
32
33 #ifndef SHIBSP_LITE
34 # include <saml/SAMLConfig.h>
35 # include <saml/binding/SAMLArtifact.h>
36 # include <saml/saml1/core/Protocols.h>
37 # include <saml/saml2/core/Protocols.h>
38 # include <saml/saml2/metadata/Metadata.h>
39 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
40 # include <saml/util/SAMLConstants.h>
41 # include <xmltooling/util/StorageService.h>
42 using namespace opensaml::saml2md;
43 #else
44 # include "lite/SAMLConstants.h"
45 #endif
46
47 #include <xmltooling/XMLToolingConfig.h>
48 #include <xmltooling/util/URLEncoder.h>
49
50 using namespace shibsp;
51 using namespace samlconstants;
52 using namespace opensaml;
53 using namespace xmltooling;
54 using namespace xercesc;
55 using namespace std;
56
57 namespace shibsp {
58     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML1ConsumerFactory;
59     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ConsumerFactory;
60     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ArtifactResolutionFactory;
61     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory ChainingLogoutInitiatorFactory;
62     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory LocalLogoutInitiatorFactory;
63     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutInitiatorFactory;
64     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutFactory;
65     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AssertionLookupFactory;
66     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory MetadataGeneratorFactory;
67 };
68
69 void SHIBSP_API shibsp::registerHandlers()
70 {
71     SPConfig& conf=SPConfig::getConfig();
72     
73     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);
74     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);
75     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
76     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
77     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
78
79     conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);
80
81     conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);
82     conf.HandlerManager.registerFactory("MetadataGenerator", MetadataGeneratorFactory);
83
84     conf.LogoutInitiatorManager.registerFactory(CHAINING_LOGOUT_INITIATOR, ChainingLogoutInitiatorFactory);
85     conf.LogoutInitiatorManager.registerFactory(LOCAL_LOGOUT_INITIATOR, LocalLogoutInitiatorFactory);
86     conf.LogoutInitiatorManager.registerFactory(SAML2_LOGOUT_INITIATOR, SAML2LogoutInitiatorFactory);
87     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2LogoutFactory);
88     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2LogoutFactory);
89     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2LogoutFactory);
90     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2LogoutFactory);
91     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2LogoutFactory);
92 }
93
94 AbstractHandler::AbstractHandler(
95     const DOMElement* e, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
96     ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
97     load(e,log,filter,remapper);
98 }
99
100 #ifndef SHIBSP_LITE
101
102 void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleDescriptor* role) const
103 {
104     const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
105     if (r2) {
106         const saml2p::Status* status = r2->getStatus();
107         if (status) {
108             const saml2p::StatusCode* sc = status->getStatusCode();
109             const XMLCh* code = sc ? sc->getValue() : NULL;
110             if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
111                 FatalProfileException ex("SAML response contained an error.");
112                 annotateException(&ex, role, status);   // throws it
113             }
114         }
115     }
116
117     const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
118     if (r1) {
119         const saml1p::Status* status = r1->getStatus();
120         if (status) {
121             const saml1p::StatusCode* sc = status->getStatusCode();
122             const QName* code = sc ? sc->getValue() : NULL;
123             if (code && *code != saml1p::StatusCode::SUCCESS) {
124                 FatalProfileException ex("SAML response contained an error.");
125                 ex.addProperty("statusCode", code->toString().c_str());
126                 if (sc->getStatusCode()) {
127                     code = sc->getStatusCode()->getValue();
128                     if (code)
129                         ex.addProperty("statusCode2", code->toString().c_str());
130                 }
131                 if (status->getStatusMessage()) {
132                     auto_ptr_char msg(status->getStatusMessage()->getMessage());
133                     if (msg.get() && *msg.get())
134                         ex.addProperty("statusMessage", msg.get());
135                 }
136                 ex.raise();
137             }
138         }
139     }
140 }
141
142 void AbstractHandler::fillStatus(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const
143 {
144     saml2p::Status* status = saml2p::StatusBuilder::buildStatus();
145     saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();
146     status->setStatusCode(scode);
147     scode->setValue(code);
148     if (subcode) {
149         saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();
150         scode->setStatusCode(ssubcode);
151         ssubcode->setValue(subcode);
152     }
153     if (msg) {
154         pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
155         auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");
156         saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();
157         status->setStatusMessage(sm);
158         sm->setMessage(widemsg.get());
159     }
160     response.setStatus(status);
161 }
162
163 long AbstractHandler::sendMessage(
164     const MessageEncoder& encoder,
165     XMLObject* msg,
166     const char* relayState,
167     const char* destination,
168     const saml2md::RoleDescriptor* role,
169     const Application& application,
170     HTTPResponse& httpResponse,
171     bool signIfPossible
172     ) const
173 {
174     const EntityDescriptor* entity = role ? dynamic_cast<const EntityDescriptor*>(role->getParent()) : NULL;
175     const PropertySet* relyingParty = application.getRelyingParty(entity);
176     pair<bool,const char*> flag = signIfPossible ? make_pair(true,"true") : relyingParty->getString("signing");
177     if (role && flag.first &&
178         (!strcmp(flag.second, "true") ||
179             (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||
180             (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {
181         CredentialResolver* credResolver=application.getCredentialResolver();
182         if (credResolver) {
183             Locker credLocker(credResolver);
184             // Fill in criteria to use.
185             MetadataCredentialCriteria mcc(*role);
186             mcc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
187             pair<bool,const char*> keyName = relyingParty->getString("keyName");
188             if (keyName.first)
189                 mcc.getKeyNames().insert(keyName.second);
190             pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
191             if (sigalg.first)
192                 mcc.setXMLAlgorithm(sigalg.second);
193             const Credential* cred = credResolver->resolve(&mcc);
194             if (cred) {
195                 // Signed request.
196                 return encoder.encode(
197                     httpResponse,
198                     msg,
199                     destination,
200                     entity,
201                     relayState,
202                     &application,
203                     cred,
204                     sigalg.second,
205                     relyingParty->getXMLString("digestAlg").second
206                     );
207             }
208             else {
209                 m_log.warn("no signing credential resolved, leaving message unsigned");
210             }
211         }
212         else {
213             m_log.warn("no credential resolver installed, leaving message unsigned");
214         }
215     }
216
217     // Unsigned request.
218     return encoder.encode(httpResponse, msg, destination, entity, relayState, &application);
219 }
220
221 #endif
222
223 void AbstractHandler::preserveRelayState(const Application& application, HTTPResponse& response, string& relayState) const
224 {
225     if (relayState.empty())
226         return;
227
228     // No setting means just pass it by value.
229     pair<bool,const char*> mech=getString("relayState");
230     if (!mech.first || !mech.second || !*mech.second)
231         return;
232
233     if (!strcmp(mech.second, "cookie")) {
234         // Here we store the state in a cookie and send a fixed
235         // value so we can recognize it on the way back.
236         if (relayState != "cookie") {
237             const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
238             pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibstate_");
239             string stateval = urlenc->encode(relayState.c_str()) + shib_cookie.second;
240             response.setCookie(shib_cookie.first.c_str(),stateval.c_str());
241             relayState = "cookie";
242         }
243     }
244     else if (strstr(mech.second,"ss:")==mech.second) {
245         if (relayState.find("ss:")!=0) {
246             mech.second+=3;
247             if (*mech.second) {
248                 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
249 #ifndef SHIBSP_LITE
250                     StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
251                     if (storage) {
252                         string rsKey;
253                         SAMLConfig::getConfig().generateRandomBytes(rsKey,10);
254                         rsKey = SAMLArtifact::toHex(rsKey);
255                         if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(NULL) + 600))
256                             throw IOException("Attempted to insert duplicate storage key.");
257                         relayState = string(mech.second-3) + ':' + rsKey;
258                     }
259                     else {
260                         m_log.error("Storage-backed RelayState with invalid StorageService ID (%s)", mech.second);
261                         relayState.erase();
262                     }
263 #endif
264                 }
265                 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
266                     DDF out,in = DDF("set::RelayState").structure();
267                     in.addmember("id").string(mech.second);
268                     in.addmember("value").string(relayState.c_str());
269                     DDFJanitor jin(in),jout(out);
270                     out = application.getServiceProvider().getListenerService()->send(in);
271                     if (!out.isstring())
272                         throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
273                     relayState = string(mech.second-3) + ':' + out.string();
274                 }
275             }
276         }
277     }
278     else
279         throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
280 }
281
282 void AbstractHandler::recoverRelayState(const Application& application, HTTPRequest& httpRequest, string& relayState, bool clear) const
283 {
284     SPConfig& conf = SPConfig::getConfig();
285
286     // Look for StorageService-backed state of the form "ss:SSID:key".
287     const char* state = relayState.c_str();
288     if (strstr(state,"ss:")==state) {
289         state += 3;
290         const char* key = strchr(state,':');
291         if (key) {
292             string ssid = relayState.substr(3, key - state);
293             key++;
294             if (!ssid.empty() && *key) {
295                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
296 #ifndef SHIBSP_LITE
297                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
298                     if (storage) {
299                         ssid = key;
300                         if (storage->readString("RelayState",ssid.c_str(),&relayState)>0) {
301                             if (clear)
302                                 storage->deleteString("RelayState",ssid.c_str());
303                             return;
304                         }
305                         else
306                             relayState.erase();
307                     }
308                     else {
309                         Category::getInstance(SHIBSP_LOGCAT".Handler").error(
310                             "Storage-backed RelayState with invalid StorageService ID (%s)", ssid.c_str()
311                             );
312                         relayState.erase();
313                     }
314 #endif
315                 }
316                 else if (conf.isEnabled(SPConfig::InProcess)) {
317                     DDF out,in = DDF("get::RelayState").structure();
318                     in.addmember("id").string(ssid.c_str());
319                     in.addmember("key").string(key);
320                     in.addmember("clear").integer(clear ? 1 : 0);
321                     DDFJanitor jin(in),jout(out);
322                     out = application.getServiceProvider().getListenerService()->send(in);
323                     if (!out.isstring()) {
324                         m_log.error("StorageService-backed RelayState mechanism did not return a state value.");
325                         relayState.erase();
326                     }
327                     else {
328                         relayState = out.string();
329                         return;
330                     }
331                 }
332             }
333         }
334     }
335     
336     if (conf.isEnabled(SPConfig::InProcess)) {
337         if (relayState == "cookie") {
338             // Pull the value from the "relay state" cookie.
339             pair<string,const char*> relay_cookie = application.getCookieNameProps("_shibstate_");
340             // In process, we should be able to cast down to a full SPRequest.
341             SPRequest& request = dynamic_cast<SPRequest&>(httpRequest);
342             const char* state = request.getCookie(relay_cookie.first.c_str());
343             if (state && *state) {
344                 // URL-decode the value.
345                 char* rscopy=strdup(state);
346                 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
347                 relayState = rscopy;
348                 free(rscopy);
349                 
350                 if (clear)
351                     request.setCookie(relay_cookie.first.c_str(),relay_cookie.second);
352                 return;
353             }
354
355             relayState.erase();
356         }
357
358         // Check for "default" value.
359         if (relayState.empty() || relayState == "default") {
360             pair<bool,const char*> homeURL=application.getString("homeURL");
361             relayState=homeURL.first ? homeURL.second : "/";
362             return;
363         }
364     }
365
366     if (relayState == "default")
367         relayState.empty();
368 }