69fd4b97e982a7e2186fb121fc6514c6cb399c45
[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 using opensaml::saml2md::MetadataProvider;
44 using opensaml::saml2md::RoleDescriptor;
45 using opensaml::saml2md::EntityDescriptor;
46 using opensaml::saml2md::IDPSSODescriptor;
47 using opensaml::saml2md::SPSSODescriptor;
48 #else
49 # include "lite/CommonDomainCookie.h"
50 #endif
51
52 using namespace shibspconstants;
53 using namespace shibsp;
54 using namespace opensaml;
55 using namespace xmltooling;
56 using namespace std;
57
58 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
59     : AbstractHandler(e, log)
60 #ifndef SHIBSP_LITE
61         ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
62 #endif
63 {
64     if (!e)
65         return;
66     string address(appId);
67     address += getString("Location").second;
68     setAddress(address.c_str());
69 #ifndef SHIBSP_LITE
70     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
71         m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
72             getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
73             );
74         m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
75     }
76 #endif
77 }
78
79 AssertionConsumerService::~AssertionConsumerService()
80 {
81 #ifndef SHIBSP_LITE
82     delete m_decoder;
83 #endif
84 }
85
86 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
87 {
88     string relayState;
89     SPConfig& conf = SPConfig::getConfig();
90     
91     if (conf.isEnabled(SPConfig::OutOfProcess)) {
92         // When out of process, we run natively and directly process the message.
93         return processMessage(request.getApplication(), request, request);
94     }
95     else {
96         // When not out of process, we remote all the message processing.
97         vector<string> headers(1, "Cookie");
98         DDF out,in = wrap(request, &headers);
99         DDFJanitor jin(in), jout(out);
100         out=request.getServiceProvider().getListenerService()->send(in);
101         return unwrap(request, out);
102     }
103 }
104
105 void AssertionConsumerService::receive(DDF& in, ostream& out)
106 {
107     // Find application.
108     const char* aid=in["application_id"].string();
109     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
110     if (!app) {
111         // Something's horribly wrong.
112         m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
113         throw ConfigurationException("Unable to locate application for new session, deleted?");
114     }
115     
116     // Unpack the request.
117     auto_ptr<HTTPRequest> req(getRequest(in));
118
119     // Wrap a response shim.
120     DDF ret(NULL);
121     DDFJanitor jout(ret);
122     auto_ptr<HTTPResponse> resp(getResponse(ret));
123
124     // Since we're remoted, the result should either be a throw, a false/0 return,
125     // which we just return as an empty structure, or a response/redirect,
126     // which we capture in the facade and send back.
127     processMessage(*app, *req.get(), *resp.get());
128     out << ret;
129 }
130
131 pair<bool,long> AssertionConsumerService::processMessage(
132     const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
133     ) const
134 {
135 #ifndef SHIBSP_LITE
136     // Locate policy key.
137     pair<bool,const char*> policyId = getString("policyId", m_configNS.get());  // namespace-qualified if inside handler element
138     if (!policyId.first)
139         policyId = application.getString("policyId");   // unqualified in Application(s) element
140         
141     // Access policy properties.
142     const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
143     pair<bool,bool> validate = settings->getBool("validate");
144
145     // Lock metadata for use by policy.
146     Locker metadataLocker(application.getMetadataProvider());
147
148     // Create the policy.
149     shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
150     
151     string relayState;
152
153     try {
154         // Decode the message and process it in a protocol-specific way.
155         auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
156         if (!msg.get())
157             throw BindingException("Failed to decode an SSO protocol response.");
158         recoverRelayState(application, httpRequest, httpResponse, relayState);
159         implementProtocol(application, httpRequest, httpResponse, policy, settings, *msg.get());
160
161         auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
162         
163         // History cookie.
164         if (issuer.get() && *issuer.get())
165             maintainHistory(application, httpRequest, httpResponse, issuer.get());
166
167         // Now redirect to the state value. By now, it should be set to *something* usable.
168         return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
169     }
170     catch (XMLToolingException& ex) {
171         if (!relayState.empty())
172             ex.addProperty("RelayState", relayState.c_str());
173         throw;
174     }
175 #else
176     throw ConfigurationException("Cannot process message using lite version of shibsp library.");
177 #endif
178 }
179
180 void AssertionConsumerService::checkAddress(const Application& application, const HTTPRequest& httpRequest, const char* issuedTo) const
181 {
182     const PropertySet* props=application.getPropertySet("Sessions");
183     pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
184     if (!checkAddress.first)
185         checkAddress.second=true;
186
187     if (checkAddress.second) {
188         m_log.debug("checking client address");
189         if (httpRequest.getRemoteAddr() != issuedTo) {
190             throw FatalProfileException(
191                "Your client's current address ($client_addr) differs from the one used when you authenticated "
192                 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
193                 "Please contact your local support staff or help desk for assistance.",
194                 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
195                 );
196         }
197     }
198 }
199
200 #ifndef SHIBSP_LITE
201
202 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
203     const char* loc = getString("Location").second;
204     string hurl(handlerURL);
205     if (*loc != '/')
206         hurl += '/';
207     hurl += loc;
208     auto_ptr_XMLCh widen(hurl.c_str());
209     saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
210     ep->setLocation(widen.get());
211     ep->setBinding(getXMLString("Binding").second);
212     ep->setIndex(getXMLString("index").second);
213     role.getAssertionConsumerServices().push_back(ep);
214 }
215
216 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
217 {
218 public:
219     DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
220     }
221
222     virtual ~DummyContext() {
223         for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
224     }
225
226     vector<Attribute*>& getResolvedAttributes() {
227         return m_attributes;
228     }
229     vector<Assertion*>& getResolvedAssertions() {
230         return m_tokens;
231     }
232
233 private:
234     vector<Attribute*> m_attributes;
235     static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
236 };
237
238 vector<Assertion*> DummyContext::m_tokens;
239
240 ResolutionContext* AssertionConsumerService::resolveAttributes(
241     const Application& application,
242     const saml2md::RoleDescriptor* issuer,
243     const XMLCh* protocol,
244     const saml1::NameIdentifier* v1nameid,
245     const saml2::NameID* nameid,
246     const XMLCh* authncontext_class,
247     const XMLCh* authncontext_decl,
248     const vector<const Assertion*>* tokens
249     ) const
250 {
251     const saml2md::EntityDescriptor* entity = issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : NULL;
252
253     // First we do the extraction of any pushed information, including from metadata.
254     vector<Attribute*> resolvedAttributes;
255     AttributeExtractor* extractor = application.getAttributeExtractor();
256     if (extractor) {
257         Locker extlocker(extractor);
258         if (entity) {
259             pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
260             if (mprefix.first) {
261                 m_log.debug("extracting metadata-derived attributes...");
262                 try {
263                     extractor->extractAttributes(application, issuer, *entity, resolvedAttributes);
264                     for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
265                         vector<string>& ids = (*a)->getAliases();
266                         for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
267                             *id = mprefix.second + *id;
268                     }
269                 }
270                 catch (exception& ex) {
271                     m_log.error("caught exception extracting attributes: %s", ex.what());
272                 }
273             }
274         }
275         m_log.debug("extracting pushed attributes...");
276         if (v1nameid) {
277             try {
278                 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
279             }
280             catch (exception& ex) {
281                 m_log.error("caught exception extracting attributes: %s", ex.what());
282             }
283         }
284         else if (nameid) {
285             try {
286                 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
287             }
288             catch (exception& ex) {
289                 m_log.error("caught exception extracting attributes: %s", ex.what());
290             }
291         }
292         if (tokens) {
293             for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
294                 try {
295                     extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
296                 }
297                 catch (exception& ex) {
298                     m_log.error("caught exception extracting attributes: %s", ex.what());
299                 }
300             }
301         }
302
303         AttributeFilter* filter = application.getAttributeFilter();
304         if (filter && !resolvedAttributes.empty()) {
305             BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
306             Locker filtlocker(filter);
307             try {
308                 filter->filterAttributes(fc, resolvedAttributes);
309             }
310             catch (exception& ex) {
311                 m_log.error("caught exception filtering attributes: %s", ex.what());
312                 m_log.error("dumping extracted attributes due to filtering exception");
313                 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
314                 resolvedAttributes.clear();
315             }
316         }
317     }
318     
319     try {
320         AttributeResolver* resolver = application.getAttributeResolver();
321         if (resolver) {
322             m_log.debug("resolving attributes...");
323
324             Locker locker(resolver);
325             auto_ptr<ResolutionContext> ctx(
326                 resolver->createResolutionContext(
327                     application,
328                     entity,
329                     protocol,
330                     nameid,
331                     authncontext_class,
332                     authncontext_decl,
333                     tokens,
334                     &resolvedAttributes
335                     )
336                 );
337             resolver->resolveAttributes(*ctx.get());
338             // Copy over any pushed attributes.
339             if (!resolvedAttributes.empty())
340                 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
341
342             // Attach global prefix if needed.
343             pair<bool,const char*> prefix = application.getString("attributePrefix");
344             if (prefix.first) {
345                 for (vector<Attribute*>::iterator a = ctx->getResolvedAttributes().begin(); a != ctx->getResolvedAttributes().end(); ++a) {
346                     vector<string>& ids = (*a)->getAliases();
347                     for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
348                         *id = prefix.second + *id;
349                 }
350             }
351
352             return ctx.release();
353         }
354     }
355     catch (exception& ex) {
356         m_log.error("attribute resolution failed: %s", ex.what());
357     }
358     
359     if (!resolvedAttributes.empty()) {
360         // Attach global prefix if needed.
361         pair<bool,const char*> prefix = application.getString("attributePrefix");
362         if (prefix.first) {
363             for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
364                 vector<string>& ids = (*a)->getAliases();
365                 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
366                     *id = prefix.second + *id;
367             }
368         }
369
370         return new DummyContext(resolvedAttributes);
371     }
372     return NULL;
373 }
374
375 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
376 {
377     policy.setMessageID(assertion.getID());
378     policy.setIssueInstant(assertion.getIssueInstantEpoch());
379
380     if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
381         const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
382         if (a2) {
383             m_log.debug("extracting issuer from SAML 2.0 assertion");
384             policy.setIssuer(a2->getIssuer());
385         }
386     }
387     else {
388         const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
389         if (a1) {
390             m_log.debug("extracting issuer from SAML 1.x assertion");
391             policy.setIssuer(a1->getIssuer());
392         }
393     }
394
395     if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
396         if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
397             m_log.warn("non-system entity issuer, skipping metadata lookup");
398             return;
399         }
400         m_log.debug("searching metadata for assertion issuer...");
401         MetadataProvider::Criteria mc(policy.getIssuer()->getName(), &IDPSSODescriptor::ELEMENT_QNAME, protocol);
402         pair<const EntityDescriptor*,const RoleDescriptor*> entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
403         if (!entity.first) {
404             auto_ptr_char iname(policy.getIssuer()->getName());
405             m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
406         }
407         else if (!entity.second) {
408             m_log.warn("unable to find compatible IdP role in metadata");
409         }
410         else {
411             policy.setIssuerMetadata(entity.second);
412         }
413     }
414 }
415
416 #endif
417
418 void AssertionConsumerService::maintainHistory(
419     const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
420     ) const
421 {
422     static const char* defProps="; path=/";
423
424     const PropertySet* sessionProps=application.getPropertySet("Sessions");
425     pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
426
427     if (!idpHistory.first || idpHistory.second) {
428         pair<bool,const char*> cookieProps=sessionProps->getString("cookieProps");
429         if (!cookieProps.first)
430             cookieProps.second=defProps;
431
432         // Set an IdP history cookie locally (essentially just a CDC).
433         CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
434
435         // Either leave in memory or set an expiration.
436         pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
437         if (!days.first || days.second==0) {
438             string c = string(cdc.set(entityID)) + cookieProps.second;
439             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
440         }
441         else {
442             time_t now=time(NULL) + (days.second * 24 * 60 * 60);
443 #ifdef HAVE_GMTIME_R
444             struct tm res;
445             struct tm* ptime=gmtime_r(&now,&res);
446 #else
447             struct tm* ptime=gmtime(&now);
448 #endif
449             char timebuf[64];
450             strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
451             string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
452             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
453         }
454     }
455 }