735196cfc38a7208c56471ff4ec5194a8149a228
[shibboleth/sp.git] / shibsp / handler / impl / SAML2Consumer.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  * SAML2Consumer.cpp
19  * 
20  * SAML 2.0 assertion consumer service 
21  */
22
23 #include "internal.h"
24 #include "handler/AssertionConsumerService.h"
25
26 #ifndef SHIBSP_LITE
27 # include "exceptions.h"
28 # include "Application.h"
29 # include "ServiceProvider.h"
30 # include "SessionCache.h"
31 # include "attribute/resolver/ResolutionContext.h"
32 # include <saml/saml2/core/Protocols.h>
33 # include <saml/saml2/profile/BrowserSSOProfileValidator.h>
34 # include <saml/saml2/metadata/Metadata.h>
35 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
36 using namespace opensaml::saml2;
37 using namespace opensaml::saml2p;
38 using namespace opensaml::saml2md;
39 using namespace opensaml;
40 # ifndef min
41 #  define min(a,b)            (((a) < (b)) ? (a) : (b))
42 # endif
43 #endif
44
45 using namespace shibsp;
46 using namespace xmltooling;
47 using namespace std;
48
49 namespace shibsp {
50
51 #if defined (_MSC_VER)
52     #pragma warning( push )
53     #pragma warning( disable : 4250 )
54 #endif
55     
56     class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
57     {
58     public:
59         SAML2Consumer(const DOMElement* e, const char* appId)
60             : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML2")) {
61         }
62         virtual ~SAML2Consumer() {}
63         
64 #ifndef SHIBSP_LITE
65         void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
66             AssertionConsumerService::generateMetadata(role, handlerURL);
67             role.addSupport(samlconstants::SAML20P_NS);
68         }
69
70     private:
71         void implementProtocol(
72             const Application& application,
73             const HTTPRequest& httpRequest,
74             HTTPResponse& httpResponse,
75             SecurityPolicy& policy,
76             const PropertySet* settings,
77             const XMLObject& xmlObject
78             ) const;
79 #endif
80     };
81
82 #if defined (_MSC_VER)
83     #pragma warning( pop )
84 #endif
85
86     Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
87     {
88         return new SAML2Consumer(p.first, p.second);
89     }
90     
91 };
92
93 #ifndef SHIBSP_LITE
94
95 void SAML2Consumer::implementProtocol(
96     const Application& application,
97     const HTTPRequest& httpRequest,
98     HTTPResponse& httpResponse,
99     SecurityPolicy& policy,
100     const PropertySet* settings,
101     const XMLObject& xmlObject
102     ) const
103 {
104     // Implementation of SAML 2.0 SSO profile(s).
105     m_log.debug("processing message against SAML 2.0 SSO profile");
106
107     // Remember whether we already established trust.
108     // None of the SAML 2 bindings require security at the protocol layer.
109     bool alreadySecured = policy.isAuthenticated();
110
111     // Check for errors...this will throw if it's not a successful message.
112     checkError(&xmlObject);
113
114     const Response* response = dynamic_cast<const Response*>(&xmlObject);
115     if (!response)
116         throw FatalProfileException("Incoming message was not a samlp:Response.");
117
118     const vector<saml2::Assertion*>& assertions = response->getAssertions();
119     const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
120     if (assertions.empty() && encassertions.empty())
121         throw FatalProfileException("Incoming message contained no SAML assertions.");
122
123     // Maintain list of "legit" tokens to feed to SP subsystems.
124     const Subject* ssoSubject=NULL;
125     const AuthnStatement* ssoStatement=NULL;
126     vector<const opensaml::Assertion*> tokens;
127
128     // Also track "bad" tokens that we'll cache but not use.
129     // This is necessary because there may be valid tokens not aimed at us.
130     vector<const opensaml::Assertion*> badtokens;
131
132     // And also track "owned" tokens that we decrypt here.
133     vector<saml2::Assertion*> ownedtokens;
134
135     // Profile validator.
136     time_t now = time(NULL);
137     string dest = httpRequest.getRequestURL();
138     BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str());
139
140     // With this flag on, we ignore any unsigned assertions.
141     const EntityDescriptor* entity = NULL;
142     pair<bool,bool> flag = make_pair(false,false);
143     if (alreadySecured && policy.getIssuerMetadata()) {
144         entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
145         flag = application.getRelyingParty(entity)->getBool("signedAssertions");
146     }
147
148     // authnskew allows rejection of SSO if AuthnInstant is too old.
149     const PropertySet* sessionProps = application.getPropertySet("Sessions");
150     pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
151
152     // Saves off error messages potentially helpful for users.
153     string contextualError;
154
155     for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
156         try {
157             // Skip unsigned assertion?
158             if (!(*a)->getSignature() && flag.first && flag.second)
159                 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
160
161             // We clear the security flag, so we can tell whether the token was secured on its own.
162             policy.setAuthenticated(false);
163             policy.reset(true);
164
165             // Extract message bits and re-verify Issuer information.
166             extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
167
168             // Run the policy over the assertion. Handles replay, freshness, and
169             // signature verification, assuming the relevant rules are configured.
170             policy.evaluate(*(*a));
171             
172             // If no security is in place now, we kick it.
173             if (!alreadySecured && !policy.isAuthenticated())
174                 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
175
176             // If we hadn't established Issuer yet, redo the signedAssertions check.
177             if (!entity && policy.getIssuerMetadata()) {
178                 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
179                 flag = application.getRelyingParty(entity)->getBool("signedAssertions");
180                 if (!(*a)->getSignature() && flag.first && flag.second)
181                     throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
182             }
183
184             // Now do profile and core semantic validation to ensure we can use it for SSO.
185             ssoValidator.validateAssertion(*(*a));
186
187             // Address checking.
188             checkAddress(application, httpRequest, ssoValidator.getAddress());
189
190             // Track it as a valid token.
191             tokens.push_back(*a);
192
193             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
194             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
195             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
196                 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
197                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
198                 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
199                     ssoStatement = *s;
200             }
201
202             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
203             if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
204                 ssoSubject = (*a)->getSubject();
205         }
206         catch (exception& ex) {
207             m_log.warn("detected a problem with assertion: %s", ex.what());
208             if (!ssoStatement)
209                 contextualError = ex.what();
210             badtokens.push_back(*a);
211         }
212     }
213
214     // In case we need decryption...
215     CredentialResolver* cr=application.getCredentialResolver();
216     if (!cr && !encassertions.empty())
217         m_log.warn("found encrypted assertions, but no CredentialResolver was available");
218
219     for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
220         // Attempt to decrypt it.
221         saml2::Assertion* decrypted=NULL;
222         try {
223             Locker credlocker(cr);
224             auto_ptr<MetadataCredentialCriteria> mcc(
225                 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
226                 );
227             auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, mcc.get()));
228             decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
229             if (decrypted) {
230                 wrapper.release();
231                 ownedtokens.push_back(decrypted);
232                 if (m_log.isDebugEnabled())
233                     m_log.debugStream() << "decrypted Assertion:" << logging::eol << *decrypted << logging::eol;
234             }
235         }
236         catch (exception& ex) {
237             m_log.error(ex.what());
238         }
239         if (!decrypted)
240             continue;
241
242         try {
243             // Skip unsigned assertion?
244             if (!decrypted->getSignature() && flag.first && flag.second)
245                 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
246
247             // We clear the security flag, so we can tell whether the token was secured on its own.
248             policy.setAuthenticated(false);
249             policy.reset(true);
250
251             // Extract message bits and re-verify Issuer information.
252             extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
253
254             // Run the policy over the assertion. Handles replay, freshness, and
255             // signature verification, assuming the relevant rules are configured.
256             // We have to marshall the object first to ensure signatures can be checked.
257             if (!decrypted->getDOM())
258                 decrypted->marshall();
259             policy.evaluate(*decrypted);
260             
261             // If no security is in place now, we kick it.
262             if (!alreadySecured && !policy.isAuthenticated())
263                 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
264
265             // Now do profile and core semantic validation to ensure we can use it for SSO.
266             ssoValidator.validateAssertion(*decrypted);
267
268             // Address checking.
269             checkAddress(application, httpRequest, ssoValidator.getAddress());
270
271             // Track it as a valid token.
272             tokens.push_back(decrypted);
273
274             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
275             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
276             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
277                 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
278                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
279                 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
280                     ssoStatement = *s;
281             }
282
283             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
284             if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
285                 ssoSubject = decrypted->getSubject();
286         }
287         catch (exception& ex) {
288             m_log.warn("detected a problem with assertion: %s", ex.what());
289             if (!ssoStatement)
290                 contextualError = ex.what();
291             badtokens.push_back(decrypted);
292         }
293     }
294
295     if (!ssoStatement) {
296         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
297         if (contextualError.empty())
298             throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
299         throw FatalProfileException(contextualError.c_str());
300     }
301
302     // May need to decrypt NameID.
303     bool ownedName = false;
304     NameID* ssoName = ssoSubject->getNameID();
305     if (!ssoName) {
306         EncryptedID* encname = ssoSubject->getEncryptedID();
307         if (encname) {
308             if (!cr)
309                 m_log.warn("found encrypted NameID, but no decryption credential was available");
310             else {
311                 Locker credlocker(cr);
312                 auto_ptr<MetadataCredentialCriteria> mcc(
313                     policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
314                     );
315                 try {
316                     auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
317                     ssoName = dynamic_cast<NameID*>(decryptedID.get());
318                     if (ssoName) {
319                         ownedName = true;
320                         decryptedID.release();
321                         if (m_log.isDebugEnabled())
322                             m_log.debugStream() << "decrypted NameID:" << logging::eol << *ssoName << logging::eol;
323                     }
324                 }
325                 catch (exception& ex) {
326                     m_log.error(ex.what());
327                 }
328             }
329         }
330     }
331
332     m_log.debug("SSO profile processing completed successfully");
333
334     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
335     // To complete processing, we need to extract and resolve attributes and then create the session.
336
337     // Now we have to extract the authentication details for session setup.
338
339     // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
340     time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
341     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
342     if (!lifetime.first || lifetime.second == 0)
343         lifetime.second = 28800;
344     if (sessionExp == 0)
345         sessionExp = now + lifetime.second;     // IdP says nothing, calulate based on SP.
346     else
347         sessionExp = min(sessionExp, now + lifetime.second);    // Use the lowest.
348
349     const AuthnContext* authnContext = ssoStatement->getAuthnContext();
350
351     try {
352         // The context will handle deleting attributes and new tokens.
353         auto_ptr<ResolutionContext> ctx(
354             resolveAttributes(
355                 application,
356                 policy.getIssuerMetadata(),
357                 samlconstants::SAML20P_NS,
358                 NULL,
359                 ssoName,
360                 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
361                 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
362                 &tokens
363                 )
364             );
365
366         if (ctx.get()) {
367             // Copy over any new tokens, but leave them in the context for cleanup.
368             tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
369         }
370
371         // Now merge in bad tokens for caching.
372         tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
373
374         application.getServiceProvider().getSessionCache()->insert(
375             application,
376             httpRequest,
377             httpResponse,
378             sessionExp,
379             entity,
380             samlconstants::SAML20P_NS,
381             ssoName,
382             ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
383             ssoStatement->getSessionIndex(),
384             (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
385             (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
386             &tokens,
387             ctx.get() ? &ctx->getResolvedAttributes() : NULL
388             );
389
390         if (ownedName)
391             delete ssoName;
392         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
393     }
394     catch (exception&) {
395         if (ownedName)
396             delete ssoName;
397         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
398         throw;
399     }
400 }
401
402 #endif