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/binding/URLEncoder.h>
34 #include <saml/saml1/core/Assertions.h>
35 #include <saml/util/CommonDomainCookie.h>
37 using namespace shibspconstants;
38 using namespace samlconstants;
39 using namespace shibsp;
40 using namespace opensaml;
41 using namespace xmltooling;
42 using namespace log4cpp;
45 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, Category& log)
46 : AbstractHandler(e, log), m_configNS(SHIB2SPCONFIG_NS),
47 m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
49 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
50 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(getString("Binding").second,e);
53 AssertionConsumerService::~AssertionConsumerService()
58 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
60 SPConfig& conf = SPConfig::getConfig();
61 if (conf.isEnabled(SPConfig::OutOfProcess)) {
62 string relayState, providerId;
63 string key = processMessage(request.getApplication(), request, providerId, relayState);
64 return sendRedirect(request, key.c_str(), providerId.c_str(), relayState.c_str());
67 DDF in = wrap(request);
69 in.addmember("application_id").string(request.getApplication().getId());
70 DDF out=request.getServiceProvider().getListenerService()->send(in);
72 if (!out["key"].isstring())
73 throw FatalProfileException("Remote processing of SAML 1.x Browser profile did not return a usable session key.");
74 return sendRedirect(request, out["key"].string(), out["provider_id"].string(), out["RelayState"].string());
78 void AssertionConsumerService::receive(DDF& in, ostream& out)
81 const char* aid=in["application_id"].string();
82 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
84 // Something's horribly wrong.
85 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
86 throw ConfigurationException("Unable to locate application for new session, deleted?");
89 // Unpack the request.
90 auto_ptr<HTTPRequest> http(getRequest(in));
93 string relayState, providerId;
94 string key = processMessage(*app, *http.get(), providerId, relayState);
96 // Repack for return to caller.
97 DDF ret=DDF(NULL).structure();
99 ret.addmember("key").string(key.c_str());
100 if (!providerId.empty())
101 ret.addmember("provider_id").string(providerId.c_str());
102 if (!relayState.empty())
103 ret.addmember("RelayState").string(relayState.c_str());
107 string AssertionConsumerService::processMessage(
108 const Application& application, const HTTPRequest& httpRequest, string& providerId, string& relayState
111 // Locate policy key.
112 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
114 policyId = application.getString("policyId"); // unqualified in Application(s) element
116 // Access policy properties.
117 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
118 pair<bool,bool> validate = settings->getBool("validate");
120 // Lock metadata for use by policy.
121 Locker metadataLocker(application.getMetadataProvider());
123 // Create the policy.
124 SecurityPolicy policy(
125 application.getServiceProvider().getPolicyRules(policyId.second),
126 application.getMetadataProvider(),
128 application.getTrustEngine(),
129 validate.first && validate.second
132 // Decode the message and process it in a protocol-specific way.
133 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
134 string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
136 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
138 providerId = issuer.get();
143 pair<bool,long> AssertionConsumerService::sendRedirect(
144 SPRequest& request, const char* key, const char* providerId, const char* relayState
149 if (relayState && !strcmp(relayState,"default")) {
150 pair<bool,const char*> homeURL=request.getApplication().getString("homeURL");
151 relayState=homeURL.first ? homeURL.second : "/";
153 else if (!relayState || !strcmp(relayState,"cookie")) {
154 // Pull the value from the "relay state" cookie.
155 pair<string,const char*> relay_cookie = request.getApplication().getCookieNameProps("_shibstate_");
156 relayState = request.getCookie(relay_cookie.first.c_str());
157 if (!relayState || !*relayState) {
158 // No apparent relay state value to use, so fall back on the default.
159 pair<bool,const char*> homeURL=request.getApplication().getString("homeURL");
160 relayState=homeURL.first ? homeURL.second : "/";
163 char* rscopy=strdup(relayState);
164 SAMLConfig::getConfig().getURLEncoder()->decode(rscopy);
167 relayState=s.c_str();
169 request.setCookie(relay_cookie.first.c_str(),relay_cookie.second);
172 // We've got a good session, so set the session cookie.
173 pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
174 k += shib_cookie.second;
175 request.setCookie(shib_cookie.first.c_str(), k.c_str());
178 maintainHistory(request, providerId, shib_cookie.second);
180 // Now redirect to the target.
181 return make_pair(true, request.sendRedirect(relayState));
184 void AssertionConsumerService::checkAddress(
185 const Application& application, const HTTPRequest& httpRequest, const char* issuedTo
188 const PropertySet* props=application.getPropertySet("Sessions");
189 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
190 if (!checkAddress.first)
191 checkAddress.second=true;
193 if (checkAddress.second) {
194 m_log.debug("checking client address");
195 if (httpRequest.getRemoteAddr() != issuedTo) {
196 throw FatalProfileException(
197 "Your client's current address ($client_addr) differs from the one used when you authenticated "
198 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
199 "Please contact your local support staff or help desk for assistance.",
200 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
206 ResolutionContext* AssertionConsumerService::resolveAttributes(
207 const Application& application,
208 const HTTPRequest& httpRequest,
209 const saml2md::EntityDescriptor* issuer,
210 const saml2::NameID& nameid,
211 const vector<const Assertion*>* tokens
214 AttributeResolver* resolver = application.getAttributeResolver();
216 m_log.info("no AttributeResolver available, skipping resolution");
221 m_log.debug("resolving attributes...");
222 auto_ptr<ResolutionContext> ctx(
223 resolver->createResolutionContext(application, httpRequest.getRemoteAddr().c_str(), issuer, nameid, tokens)
225 resolver->resolveAttributes(*ctx.get());
226 return ctx.release();
228 catch (exception& ex) {
229 m_log.error("attribute resolution failed: %s", ex.what());
235 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* providerId, const char* cookieProps) const
240 const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
241 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
242 if (!idpHistory.first || idpHistory.second) {
243 // Set an IdP history cookie locally (essentially just a CDC).
244 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
246 // Either leave in memory or set an expiration.
247 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
248 if (!days.first || days.second==0) {
249 string c = string(cdc.set(providerId)) + cookieProps;
250 request.setCookie(CommonDomainCookie::CDCName, c.c_str());
253 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
256 struct tm* ptime=gmtime_r(&now,&res);
258 struct tm* ptime=gmtime(&now);
261 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
262 string c = string(cdc.set(providerId)) + cookieProps + "; expires=" + timebuf;
263 request.setCookie(CommonDomainCookie::CDCName, c.c_str());