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