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