Attempt at a metadata generation handler.
[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         string implementProtocol(
72             const Application& application,
73             const HTTPRequest& httpRequest,
74             SecurityPolicy& policy,
75             const PropertySet* settings,
76             const XMLObject& xmlObject
77             ) const;
78 #endif
79     };
80
81 #if defined (_MSC_VER)
82     #pragma warning( pop )
83 #endif
84
85     Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
86     {
87         return new SAML2Consumer(p.first, p.second);
88     }
89     
90 };
91
92 #ifndef SHIBSP_LITE
93
94 string SAML2Consumer::implementProtocol(
95     const Application& application,
96     const HTTPRequest& httpRequest,
97     SecurityPolicy& policy,
98     const PropertySet* settings,
99     const XMLObject& xmlObject
100     ) const
101 {
102     // Implementation of SAML 2.0 SSO profile(s).
103     m_log.debug("processing message against SAML 2.0 SSO profile");
104
105     // Remember whether we already established trust.
106     // None of the SAML 2 bindings require security at the protocol layer.
107     bool alreadySecured = policy.isAuthenticated();
108
109     // Check for errors...this will throw if it's not a successful message.
110     checkError(&xmlObject);
111
112     const Response* response = dynamic_cast<const Response*>(&xmlObject);
113     if (!response)
114         throw FatalProfileException("Incoming message was not a samlp:Response.");
115
116     const vector<saml2::Assertion*>& assertions = response->getAssertions();
117     const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
118     if (assertions.empty() && encassertions.empty())
119         throw FatalProfileException("Incoming message contained no SAML assertions.");
120
121     // Maintain list of "legit" tokens to feed to SP subsystems.
122     const Subject* ssoSubject=NULL;
123     const AuthnStatement* ssoStatement=NULL;
124     vector<const opensaml::Assertion*> tokens;
125
126     // Also track "bad" tokens that we'll cache but not use.
127     // This is necessary because there may be valid tokens not aimed at us.
128     vector<const opensaml::Assertion*> badtokens;
129
130     // And also track "owned" tokens that we decrypt here.
131     vector<saml2::Assertion*> ownedtokens;
132
133     // Profile validator.
134     time_t now = time(NULL);
135     string dest = httpRequest.getRequestURL();
136     BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str());
137
138     // With this flag on, we ignore any unsigned assertions.
139     pair<bool,bool> flag = settings->getBool("signedAssertions");
140
141     // Saves off IP-mismatch error message because it's potentially helpful for users.
142     string addressMismatch;
143
144     for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
145         // Skip unsigned assertion?
146         if (!(*a)->getSignature() && flag.first && flag.second) {
147             m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
148             badtokens.push_back(*a);
149             continue;
150         }
151
152         try {
153             // We clear the security flag, so we can tell whether the token was secured on its own.
154             policy.setAuthenticated(false);
155             policy.reset(true);
156
157             // Extract message bits and re-verify Issuer information.
158             extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
159
160             // Run the policy over the assertion. Handles replay, freshness, and
161             // signature verification, assuming the relevant rules are configured.
162             policy.evaluate(*(*a));
163             
164             // If no security is in place now, we kick it.
165             if (!alreadySecured && !policy.isAuthenticated()) {
166                 m_log.warn("unable to establish security of assertion");
167                 badtokens.push_back(*a);
168                 continue;
169             }
170
171             // Now do profile and core semantic validation to ensure we can use it for SSO.
172             ssoValidator.validateAssertion(*(*a));
173
174             // Address checking.
175             try {
176                 if (ssoValidator.getAddress())
177                     checkAddress(application, httpRequest, ssoValidator.getAddress());
178             }
179             catch (exception& ex) {
180                 // We save off the message if there's no SSO statement yet.
181                 if (!ssoStatement)
182                     addressMismatch = ex.what();
183                 throw;
184             }
185
186             // Track it as a valid token.
187             tokens.push_back(*a);
188
189             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
190             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
191             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
192                 if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
193                     ssoStatement = *s;
194             }
195
196             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
197             if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
198                 ssoSubject = (*a)->getSubject();
199         }
200         catch (exception& ex) {
201             m_log.warn("detected a problem with assertion: %s", ex.what());
202             badtokens.push_back(*a);
203         }
204     }
205
206     // In case we need decryption...
207     CredentialResolver* cr=application.getCredentialResolver();
208     if (!cr && !encassertions.empty())
209         m_log.warn("found encrypted assertions, but no CredentialResolver was available");
210
211     for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
212         // Attempt to decrypt it.
213         saml2::Assertion* decrypted=NULL;
214         try {
215             Locker credlocker(cr);
216             auto_ptr<MetadataCredentialCriteria> mcc(
217                 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
218                 );
219             auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, mcc.get()));
220             decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
221             if (decrypted) {
222                 wrapper.release();
223                 ownedtokens.push_back(decrypted);
224             }
225         }
226         catch (exception& ex) {
227             m_log.error(ex.what());
228         }
229         if (!decrypted)
230             continue;
231
232         // Skip unsigned assertion?
233         if (!decrypted->getSignature() && flag.first && flag.second) {
234             m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
235             badtokens.push_back(decrypted);
236             continue;
237         }
238
239         try {
240             // We clear the security flag, so we can tell whether the token was secured on its own.
241             policy.setAuthenticated(false);
242             policy.reset(true);
243
244             // Extract message bits and re-verify Issuer information.
245             extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
246
247             // Run the policy over the assertion. Handles replay, freshness, and
248             // signature verification, assuming the relevant rules are configured.
249             // We have to marshall the object first to ensure signatures can be checked.
250             if (!decrypted->getDOM())
251                 decrypted->marshall();
252             policy.evaluate(*decrypted);
253             
254             // If no security is in place now, we kick it.
255             if (!alreadySecured && !policy.isAuthenticated()) {
256                 m_log.warn("unable to establish security of assertion");
257                 badtokens.push_back(decrypted);
258                 continue;
259             }
260
261             // Now do profile and core semantic validation to ensure we can use it for SSO.
262             ssoValidator.validateAssertion(*decrypted);
263
264             // Address checking.
265             try {
266                 if (ssoValidator.getAddress())
267                     checkAddress(application, httpRequest, ssoValidator.getAddress());
268             }
269             catch (exception& ex) {
270                 // We save off the message if there's no SSO statement yet.
271                 if (!ssoStatement)
272                     addressMismatch = ex.what();
273                 throw;
274             }
275
276             // Track it as a valid token.
277             tokens.push_back(decrypted);
278
279             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
280             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
281             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
282                 if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
283                     ssoStatement = *s;
284             }
285
286             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
287             if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
288                 ssoSubject = decrypted->getSubject();
289         }
290         catch (exception& ex) {
291             m_log.warn("detected a problem with assertion: %s", ex.what());
292             badtokens.push_back(decrypted);
293         }
294     }
295
296     if (!ssoStatement) {
297         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
298         if (addressMismatch.empty())
299             throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
300         throw FatalProfileException(addressMismatch.c_str());
301     }
302
303     // May need to decrypt NameID.
304     bool ownedName = false;
305     NameID* ssoName = ssoSubject->getNameID();
306     if (!ssoName) {
307         EncryptedID* encname = ssoSubject->getEncryptedID();
308         if (encname) {
309             if (!cr)
310                 m_log.warn("found encrypted NameID, but no decryption credential was available");
311             else {
312                 Locker credlocker(cr);
313                 auto_ptr<MetadataCredentialCriteria> mcc(
314                     policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
315                     );
316                 try {
317                     auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
318                     ssoName = dynamic_cast<NameID*>(decryptedID.get());
319                     if (ssoName) {
320                         ownedName = true;
321                         decryptedID.release();
322                     }
323                 }
324                 catch (exception& ex) {
325                     m_log.error(ex.what());
326                 }
327             }
328         }
329     }
330
331     m_log.debug("SSO profile processing completed successfully");
332
333     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
334     // To complete processing, we need to extract and resolve attributes and then create the session.
335
336     // Now we have to extract the authentication details for session setup.
337
338     // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
339     time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
340     const PropertySet* sessionProps = application.getPropertySet("Sessions");
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         string key = application.getServiceProvider().getSessionCache()->insert(
375             sessionExp,
376             application,
377             httpRequest.getRemoteAddr().c_str(),
378             policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
379             samlconstants::SAML20P_NS,
380             ssoName,
381             ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
382             ssoStatement->getSessionIndex(),
383             (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
384             (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
385             &tokens,
386             ctx.get() ? &ctx->getResolvedAttributes() : NULL
387             );
388
389         if (ownedName)
390             delete ssoName;
391         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
392         return key;
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