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