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, const char* appId, 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 string address(appId);
49 address += getString("Location").second;
50 address += "::run::ACS";
51 setAddress(address.c_str());
52 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
53 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(getString("Binding").second,e);
54 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
58 AssertionConsumerService::~AssertionConsumerService()
63 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
66 SPConfig& conf = SPConfig::getConfig();
69 if (conf.isEnabled(SPConfig::OutOfProcess)) {
70 // When out of process, we run natively and directly process the message.
71 // RelayState will be fully handled during message processing.
73 string key = processMessage(request.getApplication(), request, entityID, relayState);
74 return sendRedirect(request, key.c_str(), entityID.c_str(), relayState.c_str());
77 // When not out of process, we remote all the message processing.
78 DDF out,in = wrap(request);
79 DDFJanitor jin(in), jout(out);
81 in.addmember("application_id").string(request.getApplication().getId());
83 out=request.getServiceProvider().getListenerService()->send(in);
85 catch (XMLToolingException& ex) {
86 // Try for RelayState recovery.
87 if (ex.getProperty("RelayState"))
88 relayState = ex.getProperty("RelayState");
90 recoverRelayState(request, relayState);
92 catch (exception& ex2) {
93 m_log.error("trapped an error during RelayState recovery while handling an error: %s", ex2.what());
98 // We invoke RelayState recovery one last time on this side of the boundary.
99 if (out["RelayState"].isstring())
100 relayState = out["RelayState"].string();
101 recoverRelayState(request, relayState);
103 // If it worked, we have a session key.
104 if (!out["key"].isstring())
105 throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
107 // Take care of cookie business and wrap it up.
108 return sendRedirect(request, out["key"].string(), out["entity_id"].string(), relayState.c_str());
111 catch (XMLToolingException& ex) {
112 // Try and preserve RelayState.
113 if (!relayState.empty())
114 ex.addProperty("RelayState", relayState.c_str());
119 void AssertionConsumerService::receive(DDF& in, ostream& out)
122 const char* aid=in["application_id"].string();
123 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
125 // Something's horribly wrong.
126 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
127 throw ConfigurationException("Unable to locate application for new session, deleted?");
130 // Unpack the request.
131 auto_ptr<HTTPRequest> http(getRequest(in));
134 string relayState, entityID;
136 string key = processMessage(*app, *http.get(), entityID, relayState);
138 // Repack for return to caller.
139 DDF ret=DDF(NULL).structure();
140 DDFJanitor jret(ret);
141 ret.addmember("key").string(key.c_str());
142 if (!entityID.empty())
143 ret.addmember("entity_id").string(entityID.c_str());
144 if (!relayState.empty())
145 ret.addmember("RelayState").string(relayState.c_str());
148 catch (XMLToolingException& ex) {
149 // Try and preserve RelayState if we can.
150 if (!relayState.empty())
151 ex.addProperty("RelayState", relayState.c_str());
156 string AssertionConsumerService::processMessage(
157 const Application& application, HTTPRequest& httpRequest, string& entityID, string& relayState
160 // Locate policy key.
161 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
163 policyId = application.getString("policyId"); // unqualified in Application(s) element
165 // Access policy properties.
166 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
167 pair<bool,bool> validate = settings->getBool("validate");
169 // Lock metadata for use by policy.
170 Locker metadataLocker(application.getMetadataProvider());
172 // Create the policy.
173 SecurityPolicy policy(
174 application.getServiceProvider().getPolicyRules(policyId.second),
175 application.getMetadataProvider(),
177 application.getTrustEngine(),
178 validate.first && validate.second
181 // Decode the message and process it in a protocol-specific way.
182 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
184 throw BindingException("Failed to decode an SSO protocol response.");
185 recoverRelayState(httpRequest, relayState);
186 string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
188 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
190 entityID = issuer.get();
195 pair<bool,long> AssertionConsumerService::sendRedirect(
196 SPRequest& request, const char* key, const char* entityID, const char* relayState
199 // We've got a good session, so set the session cookie.
200 pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
202 k += shib_cookie.second;
203 request.setCookie(shib_cookie.first.c_str(), k.c_str());
206 maintainHistory(request, entityID, shib_cookie.second);
208 // Now redirect to the state value. By now, it should be set to *something* usable.
209 return make_pair(true, request.sendRedirect(relayState));
212 void AssertionConsumerService::checkAddress(
213 const Application& application, const HTTPRequest& httpRequest, const char* issuedTo
216 const PropertySet* props=application.getPropertySet("Sessions");
217 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
218 if (!checkAddress.first)
219 checkAddress.second=true;
221 if (checkAddress.second) {
222 m_log.debug("checking client address");
223 if (httpRequest.getRemoteAddr() != issuedTo) {
224 throw FatalProfileException(
225 "Your client's current address ($client_addr) differs from the one used when you authenticated "
226 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
227 "Please contact your local support staff or help desk for assistance.",
228 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
234 ResolutionContext* AssertionConsumerService::resolveAttributes(
235 const Application& application,
236 const HTTPRequest& httpRequest,
237 const saml2md::EntityDescriptor* issuer,
238 const saml2::NameID* nameid,
239 const vector<const Assertion*>* tokens
242 AttributeResolver* resolver = application.getAttributeResolver();
244 m_log.info("no AttributeResolver available, skipping resolution");
249 m_log.debug("resolving attributes...");
250 auto_ptr<ResolutionContext> ctx(
251 resolver->createResolutionContext(application, httpRequest.getRemoteAddr().c_str(), issuer, nameid, tokens)
253 resolver->resolveAttributes(*ctx.get(), application.getAttributeIds());
254 return ctx.release();
256 catch (exception& ex) {
257 m_log.error("attribute resolution failed: %s", ex.what());
263 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* entityID, const char* cookieProps) const
268 const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
269 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
270 if (!idpHistory.first || idpHistory.second) {
271 // Set an IdP history cookie locally (essentially just a CDC).
272 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
274 // Either leave in memory or set an expiration.
275 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
276 if (!days.first || days.second==0) {
277 string c = string(cdc.set(entityID)) + cookieProps;
278 request.setCookie(CommonDomainCookie::CDCName, c.c_str());
281 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
284 struct tm* ptime=gmtime_r(&now,&res);
286 struct tm* ptime=gmtime(&now);
289 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
290 string c = string(cdc.set(entityID)) + cookieProps + "; expires=" + timebuf;
291 request.setCookie(CommonDomainCookie::CDCName, c.c_str());