2 * Copyright 2001-2007 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * AssertionConsumerService.cpp
20 * Base class for handlers that create sessions by consuming SSO protocol responses.
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "attribute/resolver/AttributeResolver.h"
28 #include "attribute/resolver/ResolutionContext.h"
29 #include "handler/AssertionConsumerService.h"
30 #include "util/SPConstants.h"
32 #include <saml/SAMLConfig.h>
33 #include <saml/saml1/core/Assertions.h>
34 #include <saml/util/CommonDomainCookie.h>
36 using namespace shibspconstants;
37 using namespace samlconstants;
38 using namespace shibsp;
39 using namespace opensaml;
40 using namespace xmltooling;
41 using namespace log4cpp;
44 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, Category& log)
45 : AbstractHandler(e, log), m_decoder(NULL), m_configNS(SHIB2SPCONFIG_NS),
46 m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
48 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
49 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(getString("Binding").second,e);
52 AssertionConsumerService::~AssertionConsumerService()
57 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
60 SPConfig& conf = SPConfig::getConfig();
63 if (conf.isEnabled(SPConfig::OutOfProcess)) {
64 // When out of process, we run natively and directly process the message.
65 // RelayState will be fully handled during message processing.
67 string key = processMessage(request.getApplication(), request, providerId, relayState);
68 return sendRedirect(request, key.c_str(), providerId.c_str(), relayState.c_str());
71 // When not out of process, we remote all the message processing.
72 DDF out,in = wrap(request);
73 DDFJanitor jin(in), jout(out);
75 in.addmember("application_id").string(request.getApplication().getId());
77 out=request.getServiceProvider().getListenerService()->send(in);
79 catch (XMLToolingException& ex) {
80 // Try for RelayState recovery.
81 if (ex.getProperty("RelayState"))
82 relayState = ex.getProperty("RelayState");
84 recoverRelayState(request, relayState);
86 catch (exception& ex2) {
87 m_log.error("trapped an error during RelayState recovery while handling an error: %s", ex2.what());
92 // We invoke RelayState recovery one last time on this side of the boundary.
93 if (out["RelayState"].isstring())
94 relayState = out["RelayState"].string();
95 recoverRelayState(request, relayState);
97 // If it worked, we have a session key.
98 if (!out["key"].isstring())
99 throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
101 // Take care of cookie business and wrap it up.
102 return sendRedirect(request, out["key"].string(), out["provider_id"].string(), relayState.c_str());
105 catch (XMLToolingException& ex) {
106 // Try and preserve RelayState.
107 if (!relayState.empty())
108 ex.addProperty("RelayState", relayState.c_str());
113 void AssertionConsumerService::receive(DDF& in, ostream& out)
116 const char* aid=in["application_id"].string();
117 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
119 // Something's horribly wrong.
120 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
121 throw ConfigurationException("Unable to locate application for new session, deleted?");
124 // Unpack the request.
125 auto_ptr<HTTPRequest> http(getRequest(in));
128 string relayState, providerId;
130 string key = processMessage(*app, *http.get(), providerId, relayState);
132 // Repack for return to caller.
133 DDF ret=DDF(NULL).structure();
134 DDFJanitor jret(ret);
135 ret.addmember("key").string(key.c_str());
136 if (!providerId.empty())
137 ret.addmember("provider_id").string(providerId.c_str());
138 if (!relayState.empty())
139 ret.addmember("RelayState").string(relayState.c_str());
142 catch (XMLToolingException& ex) {
143 // Try and preserve RelayState if we can.
144 if (!relayState.empty())
145 ex.addProperty("RelayState", relayState.c_str());
150 string AssertionConsumerService::processMessage(
151 const Application& application, HTTPRequest& httpRequest, string& providerId, string& relayState
154 // Locate policy key.
155 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
157 policyId = application.getString("policyId"); // unqualified in Application(s) element
159 // Access policy properties.
160 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
161 pair<bool,bool> validate = settings->getBool("validate");
163 // Lock metadata for use by policy.
164 Locker metadataLocker(application.getMetadataProvider());
166 // Create the policy.
167 SecurityPolicy policy(
168 application.getServiceProvider().getPolicyRules(policyId.second),
169 application.getMetadataProvider(),
171 application.getTrustEngine(),
172 validate.first && validate.second
175 // Decode the message and process it in a protocol-specific way.
176 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
178 throw BindingException("Failed to decode an SSO protocol response.");
179 recoverRelayState(httpRequest, relayState);
180 string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
182 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
184 providerId = issuer.get();
189 pair<bool,long> AssertionConsumerService::sendRedirect(
190 SPRequest& request, const char* key, const char* providerId, const char* relayState
193 // We've got a good session, so set the session cookie.
194 pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
196 k += shib_cookie.second;
197 request.setCookie(shib_cookie.first.c_str(), k.c_str());
200 maintainHistory(request, providerId, shib_cookie.second);
202 // Now redirect to the state value. By now, it should be set to *something* usable.
203 return make_pair(true, request.sendRedirect(relayState));
206 void AssertionConsumerService::checkAddress(
207 const Application& application, const HTTPRequest& httpRequest, const char* issuedTo
210 const PropertySet* props=application.getPropertySet("Sessions");
211 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
212 if (!checkAddress.first)
213 checkAddress.second=true;
215 if (checkAddress.second) {
216 m_log.debug("checking client address");
217 if (httpRequest.getRemoteAddr() != issuedTo) {
218 throw FatalProfileException(
219 "Your client's current address ($client_addr) differs from the one used when you authenticated "
220 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
221 "Please contact your local support staff or help desk for assistance.",
222 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
228 ResolutionContext* AssertionConsumerService::resolveAttributes(
229 const Application& application,
230 const HTTPRequest& httpRequest,
231 const saml2md::EntityDescriptor* issuer,
232 const saml2::NameID& nameid,
233 const vector<const Assertion*>* tokens
236 AttributeResolver* resolver = application.getAttributeResolver();
238 m_log.info("no AttributeResolver available, skipping resolution");
243 m_log.debug("resolving attributes...");
244 auto_ptr<ResolutionContext> ctx(
245 resolver->createResolutionContext(application, httpRequest.getRemoteAddr().c_str(), issuer, nameid, tokens)
247 resolver->resolveAttributes(*ctx.get());
248 return ctx.release();
250 catch (exception& ex) {
251 m_log.error("attribute resolution failed: %s", ex.what());
257 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* providerId, const char* cookieProps) const
262 const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
263 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
264 if (!idpHistory.first || idpHistory.second) {
265 // Set an IdP history cookie locally (essentially just a CDC).
266 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
268 // Either leave in memory or set an expiration.
269 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
270 if (!days.first || days.second==0) {
271 string c = string(cdc.set(providerId)) + cookieProps;
272 request.setCookie(CommonDomainCookie::CDCName, c.c_str());
275 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
278 struct tm* ptime=gmtime_r(&now,&res);
280 struct tm* ptime=gmtime(&now);
283 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
284 string c = string(cdc.set(providerId)) + cookieProps + "; expires=" + timebuf;
285 request.setCookie(CommonDomainCookie::CDCName, c.c_str());