6c9b6fcbbb5dda6ce6a0b990f37cbc3a67abe505
[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/resolver/AttributeResolver.h"
33 # include "attribute/resolver/ResolutionContext.h"
34 # include "security/SecurityPolicy.h"
35 # include <saml/SAMLConfig.h>
36 # include <saml/saml1/core/Assertions.h>
37 # include <saml/util/CommonDomainCookie.h>
38 using namespace samlconstants;
39 #else
40 # include "lite/CommonDomainCookie.h"
41 #endif
42
43 using namespace shibspconstants;
44 using namespace shibsp;
45 using namespace opensaml;
46 using namespace xmltooling;
47 using namespace log4cpp;
48 using namespace std;
49
50 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
51     : AbstractHandler(e, log),
52 #ifndef SHIBSP_LITE
53         m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME),
54 #endif
55         m_configNS(SHIB2SPCONFIG_NS)
56         
57 {
58     string address(appId);
59     address += getString("Location").second;
60     address += "::run::ACS";
61     setAddress(address.c_str());
62 #ifndef SHIBSP_LITE
63     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
64         m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(getString("Binding").second,e);
65         m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
66     }
67 #endif
68 }
69
70 AssertionConsumerService::~AssertionConsumerService()
71 {
72 #ifndef SHIBSP_LITE
73     delete m_decoder;
74 #endif
75 }
76
77 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
78 {
79     string relayState;
80     SPConfig& conf = SPConfig::getConfig();
81     
82     try {
83         if (conf.isEnabled(SPConfig::OutOfProcess)) {
84             // When out of process, we run natively and directly process the message.
85             // RelayState will be fully handled during message processing.
86             string entityID;
87             string key = processMessage(request.getApplication(), request, entityID, relayState);
88             return sendRedirect(request, key.c_str(), entityID.c_str(), relayState.c_str());
89         }
90         else {
91             // When not out of process, we remote all the message processing.
92             DDF out,in = wrap(request);
93             DDFJanitor jin(in), jout(out);
94             
95             in.addmember("application_id").string(request.getApplication().getId());
96             try {
97                 out=request.getServiceProvider().getListenerService()->send(in);
98             }
99             catch (XMLToolingException& ex) {
100                 // Try for RelayState recovery.
101                 if (ex.getProperty("RelayState"))
102                     relayState = ex.getProperty("RelayState");
103                 try {
104                     recoverRelayState(request.getApplication(), request, relayState);
105                 }
106                 catch (exception& ex2) {
107                     m_log.error("trapped an error during RelayState recovery while handling an error: %s", ex2.what());
108                 }
109                 throw;
110             }
111                 
112             // We invoke RelayState recovery one last time on this side of the boundary.
113             if (out["RelayState"].isstring())
114                 relayState = out["RelayState"].string(); 
115             recoverRelayState(request.getApplication(), request, relayState);
116     
117             // If it worked, we have a session key.
118             if (!out["key"].isstring())
119                 throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
120             
121             // Take care of cookie business and wrap it up.
122             return sendRedirect(request, out["key"].string(), out["entity_id"].string(), relayState.c_str());
123         }
124     }
125     catch (XMLToolingException& ex) {
126         // Try and preserve RelayState.
127         if (!relayState.empty())
128             ex.addProperty("RelayState", relayState.c_str());
129         throw;
130     }
131 }
132
133 void AssertionConsumerService::receive(DDF& in, ostream& out)
134 {
135     // Find application.
136     const char* aid=in["application_id"].string();
137     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
138     if (!app) {
139         // Something's horribly wrong.
140         m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
141         throw ConfigurationException("Unable to locate application for new session, deleted?");
142     }
143     
144     // Unpack the request.
145     auto_ptr<HTTPRequest> http(getRequest(in));
146     
147     // Do the work.
148     string relayState, entityID;
149     try {
150         string key = processMessage(*app, *http.get(), entityID, relayState);
151
152         // Repack for return to caller.
153         DDF ret=DDF(NULL).structure();
154         DDFJanitor jret(ret);
155         ret.addmember("key").string(key.c_str());
156         if (!entityID.empty())
157             ret.addmember("entity_id").string(entityID.c_str());
158         if (!relayState.empty())
159             ret.addmember("RelayState").string(relayState.c_str());
160         out << ret;
161     }
162     catch (XMLToolingException& ex) {
163         // Try and preserve RelayState if we can.
164         if (!relayState.empty())
165             ex.addProperty("RelayState", relayState.c_str());
166         throw;
167     }
168 }
169
170 string AssertionConsumerService::processMessage(
171     const Application& application, HTTPRequest& httpRequest, string& entityID, string& relayState
172     ) const
173 {
174 #ifndef SHIBSP_LITE
175     // Locate policy key.
176     pair<bool,const char*> policyId = getString("policyId", m_configNS.get());  // namespace-qualified if inside handler element
177     if (!policyId.first)
178         policyId = application.getString("policyId");   // unqualified in Application(s) element
179         
180     // Access policy properties.
181     const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
182     pair<bool,bool> validate = settings->getBool("validate");
183
184     // Lock metadata for use by policy.
185     Locker metadataLocker(application.getMetadataProvider());
186
187     // Create the policy.
188     shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
189     
190     // Decode the message and process it in a protocol-specific way.
191     auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
192     if (!msg.get())
193         throw BindingException("Failed to decode an SSO protocol response.");
194     recoverRelayState(application, httpRequest, relayState);
195     string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
196
197     auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
198     if (issuer.get())
199         entityID = issuer.get();
200     
201     return key;
202 #else
203     throw ConfigurationException("Cannot process message using lite version of shibsp library.");
204 #endif
205 }
206
207 pair<bool,long> AssertionConsumerService::sendRedirect(
208     SPRequest& request, const char* key, const char* entityID, const char* relayState
209     ) const
210 {
211     // We've got a good session, so set the session cookie.
212     pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
213     string k(key);
214     k += shib_cookie.second;
215     request.setCookie(shib_cookie.first.c_str(), k.c_str());
216
217     // History cookie.
218     maintainHistory(request, entityID, shib_cookie.second);
219
220     // Now redirect to the state value. By now, it should be set to *something* usable.
221     return make_pair(true, request.sendRedirect(relayState));
222 }
223
224 void AssertionConsumerService::checkAddress(
225     const Application& application, const HTTPRequest& httpRequest, const char* issuedTo
226     ) const
227 {
228     const PropertySet* props=application.getPropertySet("Sessions");
229     pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
230     if (!checkAddress.first)
231         checkAddress.second=true;
232
233     if (checkAddress.second) {
234         m_log.debug("checking client address");
235         if (httpRequest.getRemoteAddr() != issuedTo) {
236             throw FatalProfileException(
237                "Your client's current address ($client_addr) differs from the one used when you authenticated "
238                 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
239                 "Please contact your local support staff or help desk for assistance.",
240                 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
241                 );
242         }
243     }
244 }
245
246 #ifndef SHIBSP_LITE
247 ResolutionContext* AssertionConsumerService::resolveAttributes(
248     const Application& application,
249     const saml2md::EntityDescriptor* issuer,
250     const saml2::NameID* nameid,
251     const char* authncontext_class,
252     const char* authncontext_decl,
253     const vector<const Assertion*>* tokens,
254     const multimap<string,Attribute*>* attributes
255     ) const
256 {
257     try {
258         AttributeResolver* resolver = application.getAttributeResolver();
259         if (!resolver) {
260             m_log.info("no AttributeResolver available, skipping resolution");
261             return NULL;
262         }
263         
264         m_log.debug("resolving attributes...");
265
266         Locker locker(resolver);
267         auto_ptr<ResolutionContext> ctx(
268             resolver->createResolutionContext(application, issuer, nameid, authncontext_class, authncontext_decl, tokens, attributes)
269             );
270         resolver->resolveAttributes(*ctx.get());
271         return ctx.release();
272     }
273     catch (exception& ex) {
274         m_log.error("attribute resolution failed: %s", ex.what());
275     }
276     
277     return NULL;
278 }
279 #endif
280
281 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* entityID, const char* cookieProps) const
282 {
283     if (!entityID)
284         return;
285         
286     const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
287     pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
288     if (!idpHistory.first || idpHistory.second) {
289         // Set an IdP history cookie locally (essentially just a CDC).
290         CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
291
292         // Either leave in memory or set an expiration.
293         pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
294         if (!days.first || days.second==0) {
295             string c = string(cdc.set(entityID)) + cookieProps;
296             request.setCookie(CommonDomainCookie::CDCName, c.c_str());
297         }
298         else {
299             time_t now=time(NULL) + (days.second * 24 * 60 * 60);
300 #ifdef HAVE_GMTIME_R
301             struct tm res;
302             struct tm* ptime=gmtime_r(&now,&res);
303 #else
304             struct tm* ptime=gmtime(&now);
305 #endif
306             char timebuf[64];
307             strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
308             string c = string(cdc.set(entityID)) + cookieProps + "; expires=" + timebuf;
309             request.setCookie(CommonDomainCookie::CDCName, c.c_str());
310         }
311     }
312 }