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