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