First version of resolvertest utility.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / AssertionConsumerService.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  * AssertionConsumerService.cpp
19  * 
20  * Base class for handlers that create sessions by consuming SSO protocol responses. 
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "handler/AssertionConsumerService.h"
28 #include "util/SPConstants.h"
29
30 # include <ctime>
31 #ifndef SHIBSP_LITE
32 # include "attribute/Attribute.h"
33 # include "attribute/filtering/AttributeFilter.h"
34 # include "attribute/filtering/BasicFilteringContext.h"
35 # include "attribute/resolver/AttributeExtractor.h"
36 # include "attribute/resolver/AttributeResolver.h"
37 # include "attribute/resolver/ResolutionContext.h"
38 # include "security/SecurityPolicy.h"
39 # include <saml/SAMLConfig.h>
40 # include <saml/saml1/core/Assertions.h>
41 # include <saml/util/CommonDomainCookie.h>
42 using namespace samlconstants;
43 #else
44 # include "lite/CommonDomainCookie.h"
45 #endif
46
47 using namespace shibspconstants;
48 using namespace shibsp;
49 using namespace opensaml;
50 using namespace xmltooling;
51 using namespace std;
52
53 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
54     : AbstractHandler(e, log)
55 #ifndef SHIBSP_LITE
56         ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
57 #endif
58 {
59     if (!e)
60         return;
61     string address(appId);
62     address += getString("Location").second;
63     setAddress(address.c_str());
64 #ifndef SHIBSP_LITE
65     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
66         m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
67             getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS)
68             );
69         m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
70     }
71 #endif
72 }
73
74 AssertionConsumerService::~AssertionConsumerService()
75 {
76 #ifndef SHIBSP_LITE
77     delete m_decoder;
78 #endif
79 }
80
81 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
82 {
83     string relayState;
84     SPConfig& conf = SPConfig::getConfig();
85     
86     try {
87         if (conf.isEnabled(SPConfig::OutOfProcess)) {
88             // When out of process, we run natively and directly process the message.
89             // RelayState will be fully handled during message processing.
90             string entityID;
91             string key = processMessage(request.getApplication(), request, entityID, relayState);
92             return sendRedirect(request, key.c_str(), entityID.c_str(), relayState.c_str());
93         }
94         else {
95             // When not out of process, we remote all the message processing.
96             DDF out,in = wrap(request);
97             DDFJanitor jin(in), jout(out);
98             
99             try {
100                 out=request.getServiceProvider().getListenerService()->send(in);
101             }
102             catch (XMLToolingException& ex) {
103                 // Try for RelayState recovery.
104                 if (ex.getProperty("RelayState"))
105                     relayState = ex.getProperty("RelayState");
106                 try {
107                     recoverRelayState(request.getApplication(), request, relayState);
108                 }
109                 catch (exception& ex2) {
110                     m_log.error("trapped an error during RelayState recovery while handling an error: %s", ex2.what());
111                 }
112                 throw;
113             }
114                 
115             // We invoke RelayState recovery one last time on this side of the boundary.
116             if (out["RelayState"].isstring())
117                 relayState = out["RelayState"].string(); 
118             recoverRelayState(request.getApplication(), request, relayState);
119     
120             // If it worked, we have a session key.
121             if (!out["key"].isstring())
122                 throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
123             
124             // Take care of cookie business and wrap it up.
125             return sendRedirect(request, out["key"].string(), out["entity_id"].string(), relayState.c_str());
126         }
127     }
128     catch (XMLToolingException& ex) {
129         // Try and preserve RelayState.
130         if (!relayState.empty())
131             ex.addProperty("RelayState", relayState.c_str());
132         throw;
133     }
134 }
135
136 void AssertionConsumerService::receive(DDF& in, ostream& out)
137 {
138     // Find application.
139     const char* aid=in["application_id"].string();
140     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
141     if (!app) {
142         // Something's horribly wrong.
143         m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
144         throw ConfigurationException("Unable to locate application for new session, deleted?");
145     }
146     
147     // Unpack the request.
148     auto_ptr<HTTPRequest> http(getRequest(in));
149     
150     // Do the work.
151     string relayState, entityID;
152     try {
153         string key = processMessage(*app, *http.get(), entityID, relayState);
154
155         // Repack for return to caller.
156         DDF ret=DDF(NULL).structure();
157         DDFJanitor jret(ret);
158         ret.addmember("key").string(key.c_str());
159         if (!entityID.empty())
160             ret.addmember("entity_id").string(entityID.c_str());
161         if (!relayState.empty())
162             ret.addmember("RelayState").string(relayState.c_str());
163         out << ret;
164     }
165     catch (XMLToolingException& ex) {
166         // Try and preserve RelayState if we can.
167         if (!relayState.empty())
168             ex.addProperty("RelayState", relayState.c_str());
169         throw;
170     }
171 }
172
173 string AssertionConsumerService::processMessage(
174     const Application& application, HTTPRequest& httpRequest, string& entityID, string& relayState
175     ) const
176 {
177 #ifndef SHIBSP_LITE
178     // Locate policy key.
179     pair<bool,const char*> policyId = getString("policyId", m_configNS.get());  // namespace-qualified if inside handler element
180     if (!policyId.first)
181         policyId = application.getString("policyId");   // unqualified in Application(s) element
182         
183     // Access policy properties.
184     const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
185     pair<bool,bool> validate = settings->getBool("validate");
186
187     // Lock metadata for use by policy.
188     Locker metadataLocker(application.getMetadataProvider());
189
190     // Create the policy.
191     shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
192     
193     // Decode the message and process it in a protocol-specific way.
194     auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
195     if (!msg.get())
196         throw BindingException("Failed to decode an SSO protocol response.");
197     recoverRelayState(application, httpRequest, relayState);
198     string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
199
200     auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
201     if (issuer.get())
202         entityID = issuer.get();
203     
204     return key;
205 #else
206     throw ConfigurationException("Cannot process message using lite version of shibsp library.");
207 #endif
208 }
209
210 pair<bool,long> AssertionConsumerService::sendRedirect(
211     SPRequest& request, const char* key, const char* entityID, const char* relayState
212     ) const
213 {
214     // We've got a good session, so set the session cookie.
215     pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
216     string k(key);
217     k += shib_cookie.second;
218     request.setCookie(shib_cookie.first.c_str(), k.c_str());
219
220     // History cookie.
221     maintainHistory(request, entityID, shib_cookie.second);
222
223     // Now redirect to the state value. By now, it should be set to *something* usable.
224     return make_pair(true, request.sendRedirect(relayState));
225 }
226
227 void AssertionConsumerService::checkAddress(
228     const Application& application, const HTTPRequest& httpRequest, const char* issuedTo
229     ) const
230 {
231     const PropertySet* props=application.getPropertySet("Sessions");
232     pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
233     if (!checkAddress.first)
234         checkAddress.second=true;
235
236     if (checkAddress.second) {
237         m_log.debug("checking client address");
238         if (httpRequest.getRemoteAddr() != issuedTo) {
239             throw FatalProfileException(
240                "Your client's current address ($client_addr) differs from the one used when you authenticated "
241                 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
242                 "Please contact your local support staff or help desk for assistance.",
243                 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
244                 );
245         }
246     }
247 }
248
249 #ifndef SHIBSP_LITE
250
251 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
252 {
253 public:
254     DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
255     }
256
257     virtual ~DummyContext() {
258         for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
259     }
260
261     vector<Attribute*>& getResolvedAttributes() {
262         return m_attributes;
263     }
264     vector<Assertion*>& getResolvedAssertions() {
265         return m_tokens;
266     }
267
268 private:
269     vector<Attribute*> m_attributes;
270     static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
271 };
272
273 vector<Assertion*> DummyContext::m_tokens;
274
275 ResolutionContext* AssertionConsumerService::resolveAttributes(
276     const Application& application,
277     const saml2md::RoleDescriptor* issuer,
278     const XMLCh* protocol,
279     const saml1::NameIdentifier* v1nameid,
280     const saml2::NameID* nameid,
281     const XMLCh* authncontext_class,
282     const XMLCh* authncontext_decl,
283     const vector<const Assertion*>* tokens
284     ) const
285 {
286     const saml2md::EntityDescriptor* entity = issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : NULL;
287
288     // First we do the extraction of any pushed information, including from metadata.
289     vector<Attribute*> resolvedAttributes;
290     AttributeExtractor* extractor = application.getAttributeExtractor();
291     if (extractor) {
292         Locker extlocker(extractor);
293         if (entity) {
294             pair<bool,const char*> prefix = application.getString("metadataAttributePrefix");
295             if (prefix.first) {
296                 m_log.debug("extracting metadata-derived attributes...");
297                 try {
298                     extractor->extractAttributes(application, issuer, *entity, resolvedAttributes);
299                     for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
300                         vector<string>& ids = (*a)->getAliases();
301                         for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
302                             *id = prefix.second + *id;
303                     }
304                 }
305                 catch (exception& ex) {
306                     m_log.error("caught exception extracting attributes: %s", ex.what());
307                 }
308             }
309         }
310         m_log.debug("extracting pushed attributes...");
311         if (v1nameid) {
312             try {
313                 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
314             }
315             catch (exception& ex) {
316                 m_log.error("caught exception extracting attributes: %s", ex.what());
317             }
318         }
319         else if (nameid) {
320             try {
321                 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
322             }
323             catch (exception& ex) {
324                 m_log.error("caught exception extracting attributes: %s", ex.what());
325             }
326         }
327         if (tokens) {
328             for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
329                 try {
330                     extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
331                 }
332                 catch (exception& ex) {
333                     m_log.error("caught exception extracting attributes: %s", ex.what());
334                 }
335             }
336         }
337
338         AttributeFilter* filter = application.getAttributeFilter();
339         if (filter && !resolvedAttributes.empty()) {
340             BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
341             Locker filtlocker(filter);
342             try {
343                 filter->filterAttributes(fc, resolvedAttributes);
344             }
345             catch (exception& ex) {
346                 m_log.error("caught exception filtering attributes: %s", ex.what());
347                 m_log.error("dumping extracted attributes due to filtering exception");
348                 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
349                 resolvedAttributes.clear();
350             }
351         }
352     }
353     
354     try {
355         AttributeResolver* resolver = application.getAttributeResolver();
356         if (resolver) {
357             m_log.debug("resolving attributes...");
358
359             Locker locker(resolver);
360             auto_ptr<ResolutionContext> ctx(
361                 resolver->createResolutionContext(
362                     application,
363                     entity,
364                     protocol,
365                     nameid,
366                     authncontext_class,
367                     authncontext_decl,
368                     tokens,
369                     &resolvedAttributes
370                     )
371                 );
372             resolver->resolveAttributes(*ctx.get());
373             // Copy over any pushed attributes.
374             if (!resolvedAttributes.empty())
375                 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
376             return ctx.release();
377         }
378     }
379     catch (exception& ex) {
380         m_log.error("attribute resolution failed: %s", ex.what());
381     }
382     
383     if (!resolvedAttributes.empty())
384         return new DummyContext(resolvedAttributes);
385     return NULL;
386 }
387 #endif
388
389 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* entityID, const char* cookieProps) const
390 {
391     if (!entityID)
392         return;
393         
394     const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
395     pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
396     if (!idpHistory.first || idpHistory.second) {
397         // Set an IdP history cookie locally (essentially just a CDC).
398         CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
399
400         // Either leave in memory or set an expiration.
401         pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
402         if (!days.first || days.second==0) {
403             string c = string(cdc.set(entityID)) + cookieProps;
404             request.setCookie(CommonDomainCookie::CDCName, c.c_str());
405         }
406         else {
407             time_t now=time(NULL) + (days.second * 24 * 60 * 60);
408 #ifdef HAVE_GMTIME_R
409             struct tm res;
410             struct tm* ptime=gmtime_r(&now,&res);
411 #else
412             struct tm* ptime=gmtime(&now);
413 #endif
414             char timebuf[64];
415             strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
416             string c = string(cdc.set(entityID)) + cookieProps + "; expires=" + timebuf;
417             request.setCookie(CommonDomainCookie::CDCName, c.c_str());
418         }
419     }
420 }