Remove extra lf from decryption logging.
[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     // With this flag on, we ignore any unsigned assertions.
136     const EntityDescriptor* entity = NULL;
137     pair<bool,bool> flag = make_pair(false,false);
138     if (alreadySecured && policy.getIssuerMetadata()) {
139         entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
140         flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
141     }
142
143     time_t now = time(NULL);
144     string dest = httpRequest.getRequestURL();
145
146     // authnskew allows rejection of SSO if AuthnInstant is too old.
147     const PropertySet* sessionProps = application.getPropertySet("Sessions");
148     pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
149
150     // Saves off error messages potentially helpful for users.
151     string contextualError;
152
153     for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
154         try {
155             // Skip unsigned assertion?
156             if (!(*a)->getSignature() && flag.first && flag.second)
157                 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
158
159             // We clear the security flag, so we can tell whether the token was secured on its own.
160             policy.setAuthenticated(false);
161             policy.reset(true);
162
163             // Extract message bits and re-verify Issuer information.
164             extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
165
166             // Run the policy over the assertion. Handles replay, freshness, and
167             // signature verification, assuming the relevant rules are configured.
168             policy.evaluate(*(*a));
169             
170             // If no security is in place now, we kick it.
171             if (!alreadySecured && !policy.isAuthenticated())
172                 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
173
174             // If we hadn't established Issuer yet, redo the signedAssertions check.
175             if (!entity && policy.getIssuerMetadata()) {
176                 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
177                 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
178                 if (!(*a)->getSignature() && flag.first && flag.second)
179                     throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
180             }
181
182             // Now do profile and core semantic validation to ensure we can use it for SSO.
183             BrowserSSOProfileValidator ssoValidator(
184                 application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str()
185                 );
186             ssoValidator.validateAssertion(*(*a));
187
188             // Address checking.
189             checkAddress(application, httpRequest, ssoValidator.getAddress());
190
191             // Track it as a valid token.
192             tokens.push_back(*a);
193
194             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
195             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
196             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
197                 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
198                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
199                 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
200                     ssoStatement = *s;
201             }
202
203             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
204             if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
205                 ssoSubject = (*a)->getSubject();
206         }
207         catch (exception& ex) {
208             m_log.warn("detected a problem with assertion: %s", ex.what());
209             if (!ssoStatement)
210                 contextualError = ex.what();
211             badtokens.push_back(*a);
212         }
213     }
214
215     // In case we need decryption...
216     CredentialResolver* cr=application.getCredentialResolver();
217     if (!cr && !encassertions.empty())
218         m_log.warn("found encrypted assertions, but no CredentialResolver was available");
219
220     for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
221         // Attempt to decrypt it.
222         saml2::Assertion* decrypted=NULL;
223         try {
224             Locker credlocker(cr);
225             auto_ptr<MetadataCredentialCriteria> mcc(
226                 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
227                 );
228             auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
229             decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
230             if (decrypted) {
231                 wrapper.release();
232                 ownedtokens.push_back(decrypted);
233                 if (m_log.isDebugEnabled())
234                     m_log.debugStream() << "decrypted Assertion: " << *decrypted << logging::eol;
235             }
236         }
237         catch (exception& ex) {
238             m_log.error(ex.what());
239         }
240         if (!decrypted)
241             continue;
242
243         try {
244             // Skip unsigned assertion?
245             if (!decrypted->getSignature() && flag.first && flag.second)
246                 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
247
248             // We clear the security flag, so we can tell whether the token was secured on its own.
249             policy.setAuthenticated(false);
250             policy.reset(true);
251
252             // Extract message bits and re-verify Issuer information.
253             extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
254
255             // Run the policy over the assertion. Handles replay, freshness, and
256             // signature verification, assuming the relevant rules are configured.
257             // We have to marshall the object first to ensure signatures can be checked.
258             if (!decrypted->getDOM())
259                 decrypted->marshall();
260             policy.evaluate(*decrypted);
261             
262             // If no security is in place now, we kick it.
263             if (!alreadySecured && !policy.isAuthenticated())
264                 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
265
266             // Now do profile and core semantic validation to ensure we can use it for SSO.
267             BrowserSSOProfileValidator ssoValidator(
268                 application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str()
269                 );
270             ssoValidator.validateAssertion(*decrypted);
271
272             // Address checking.
273             checkAddress(application, httpRequest, ssoValidator.getAddress());
274
275             // Track it as a valid token.
276             tokens.push_back(decrypted);
277
278             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
279             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
280             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
281                 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
282                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
283                 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
284                     ssoStatement = *s;
285             }
286
287             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
288             if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
289                 ssoSubject = decrypted->getSubject();
290         }
291         catch (exception& ex) {
292             m_log.warn("detected a problem with assertion: %s", ex.what());
293             if (!ssoStatement)
294                 contextualError = ex.what();
295             badtokens.push_back(decrypted);
296         }
297     }
298
299     if (!ssoStatement) {
300         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
301         if (contextualError.empty())
302             throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
303         throw FatalProfileException(contextualError.c_str());
304     }
305
306     // May need to decrypt NameID.
307     bool ownedName = false;
308     NameID* ssoName = ssoSubject->getNameID();
309     if (!ssoName) {
310         EncryptedID* encname = ssoSubject->getEncryptedID();
311         if (encname) {
312             if (!cr)
313                 m_log.warn("found encrypted NameID, but no decryption credential was available");
314             else {
315                 Locker credlocker(cr);
316                 auto_ptr<MetadataCredentialCriteria> mcc(
317                     policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
318                     );
319                 try {
320                     auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get()));
321                     ssoName = dynamic_cast<NameID*>(decryptedID.get());
322                     if (ssoName) {
323                         ownedName = true;
324                         decryptedID.release();
325                         if (m_log.isDebugEnabled())
326                             m_log.debugStream() << "decrypted NameID: " << *ssoName << logging::eol;
327                     }
328                 }
329                 catch (exception& ex) {
330                     m_log.error(ex.what());
331                 }
332             }
333         }
334     }
335
336     m_log.debug("SSO profile processing completed successfully");
337
338     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
339     // To complete processing, we need to extract and resolve attributes and then create the session.
340
341     // Now we have to extract the authentication details for session setup.
342
343     // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
344     time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
345     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
346     if (!lifetime.first || lifetime.second == 0)
347         lifetime.second = 28800;
348     if (sessionExp == 0)
349         sessionExp = now + lifetime.second;     // IdP says nothing, calulate based on SP.
350     else
351         sessionExp = min(sessionExp, now + lifetime.second);    // Use the lowest.
352
353     const AuthnContext* authnContext = ssoStatement->getAuthnContext();
354
355     try {
356         // The context will handle deleting attributes and new tokens.
357         auto_ptr<ResolutionContext> ctx(
358             resolveAttributes(
359                 application,
360                 policy.getIssuerMetadata(),
361                 samlconstants::SAML20P_NS,
362                 NULL,
363                 ssoName,
364                 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
365                 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
366                 &tokens
367                 )
368             );
369
370         if (ctx.get()) {
371             // Copy over any new tokens, but leave them in the context for cleanup.
372             tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
373         }
374
375         // Now merge in bad tokens for caching.
376         tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
377
378         application.getServiceProvider().getSessionCache()->insert(
379             application,
380             httpRequest,
381             httpResponse,
382             sessionExp,
383             entity,
384             samlconstants::SAML20P_NS,
385             ssoName,
386             ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
387             ssoStatement->getSessionIndex(),
388             (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
389             (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
390             &tokens,
391             ctx.get() ? &ctx->getResolvedAttributes() : NULL
392             );
393
394         if (ownedName)
395             delete ssoName;
396         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
397     }
398     catch (exception&) {
399         if (ownedName)
400             delete ssoName;
401         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
402         throw;
403     }
404 }
405
406 #endif