Change ownership of attributes input to cache.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML1Consumer.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  * SAML1Consumer.cpp
19  * 
20  * SAML 1.x 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/Attribute.h"
32 # include "attribute/filtering/AttributeFilter.h"
33 # include "attribute/filtering/BasicFilteringContext.h"
34 # include "attribute/resolver/AttributeExtractor.h"
35 # include "attribute/resolver/ResolutionContext.h"
36 # include <saml/saml1/core/Assertions.h>
37 # include <saml/saml1/core/Protocols.h>
38 # include <saml/saml1/profile/BrowserSSOProfileValidator.h>
39 # include <saml/saml2/metadata/Metadata.h>
40 using namespace opensaml::saml1;
41 using namespace opensaml::saml1p;
42 using namespace opensaml;
43 using saml2::NameID;
44 using saml2::NameIDBuilder;
45 using saml2md::EntityDescriptor;
46 #else
47 # include "lite/SAMLConstants.h"
48 #endif
49
50 using namespace shibsp;
51 using namespace xmltooling;
52 using namespace log4cpp;
53 using namespace std;
54
55 namespace shibsp {
56
57 #if defined (_MSC_VER)
58     #pragma warning( push )
59     #pragma warning( disable : 4250 )
60 #endif
61     
62     class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
63     {
64     public:
65         SAML1Consumer(const DOMElement* e, const char* appId)
66                 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SAML1SSO")) {
67 #ifndef SHIBSP_LITE
68             m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
69 #endif
70         }
71         virtual ~SAML1Consumer() {}
72         
73     private:
74 #ifndef SHIBSP_LITE
75         string implementProtocol(
76             const Application& application,
77             const HTTPRequest& httpRequest,
78             SecurityPolicy& policy,
79             const PropertySet* settings,
80             const XMLObject& xmlObject
81             ) const;
82         bool m_post;
83 #endif
84     };
85
86 #if defined (_MSC_VER)
87     #pragma warning( pop )
88 #endif
89
90     Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
91     {
92         return new SAML1Consumer(p.first, p.second);
93     }
94     
95 };
96
97 #ifndef SHIBSP_LITE
98
99 string SAML1Consumer::implementProtocol(
100     const Application& application,
101     const HTTPRequest& httpRequest,
102     SecurityPolicy& policy,
103     const PropertySet* settings,
104     const XMLObject& xmlObject
105     ) const
106 {
107     // Implementation of SAML 1.x SSO profile(s).
108     m_log.debug("processing message against SAML 1.x SSO profile");
109
110     // With the binding aspects now moved out to the MessageDecoder,
111     // the focus here is on the assertion content. For SAML 1.x POST,
112     // all the security comes from the protocol layer, and signing
113     // the assertion isn't sufficient. So we can check the policy
114     // object now and bail if it's not a secure message.
115     if (m_post && !policy.isSecure())
116         throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
117         
118     // Remember whether we already established trust.
119     bool alreadySecured = policy.isSecure();
120
121     // Check for errors...this will throw if it's not a successful message.
122     checkError(&xmlObject);
123
124     const Response* response = dynamic_cast<const Response*>(&xmlObject);
125     if (!response)
126         throw FatalProfileException("Incoming message was not a samlp:Response.");
127
128     const vector<saml1::Assertion*>& assertions = response->getAssertions();
129     if (assertions.empty())
130         throw FatalProfileException("Incoming message contained no SAML assertions.");
131
132     // Maintain list of "legit" tokens to feed to SP subsystems.
133     const AuthenticationStatement* ssoStatement=NULL;
134     vector<const opensaml::Assertion*> tokens;
135
136     // Also track "bad" tokens that we'll cache but not use.
137     // This is necessary because there may be valid tokens not aimed at us.
138     vector<const opensaml::Assertion*> badtokens;
139
140     // Profile validator.
141     time_t now = time(NULL);
142     BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now);
143
144     // With this flag on, we ignore any unsigned assertions.
145     pair<bool,bool> flag = settings->getBool("signedAssertions");
146
147     for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
148         // Skip unsigned assertion?
149         if (!(*a)->getSignature() && flag.first && flag.second) {
150             m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
151             badtokens.push_back(*a);
152             continue;
153         }
154
155         try {
156             // We clear the security flag, so we can tell whether the token was secured on its own.
157             policy.setSecure(false);
158             
159             // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
160             // and signature verification, assuming the relevant rules are configured.
161             policy.evaluate(*(*a));
162             
163             // If no security is in place now, we kick it.
164             if (!alreadySecured && !policy.isSecure()) {
165                 m_log.warn("unable to establish security of assertion");
166                 badtokens.push_back(*a);
167                 continue;
168             }
169
170             // Now do profile and core semantic validation to ensure we can use it for SSO.
171             ssoValidator.validateAssertion(*(*a));
172
173             // Track it as a valid token.
174             tokens.push_back(*a);
175
176             // Save off the first valid SSO statement.
177             if (!ssoStatement && !(*a)->getAuthenticationStatements().empty())
178                 ssoStatement = (*a)->getAuthenticationStatements().front();
179         }
180         catch (exception& ex) {
181             m_log.warn("detected a problem with assertion: %s", ex.what());
182             badtokens.push_back(*a);
183         }
184     }
185
186     if (!ssoStatement)
187         throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
188
189     // Address checking.
190     SubjectLocality* locality = ssoStatement->getSubjectLocality();
191     if (locality && locality->getIPAddress()) {
192         auto_ptr_char ip(locality->getIPAddress());
193         checkAddress(application, httpRequest, ip.get());
194     }
195
196     m_log.debug("SSO profile processing completed successfully");
197
198     NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
199
200     // Now we have to extract the authentication details for attribute and session setup.
201
202     // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
203     const PropertySet* sessionProps = application.getPropertySet("Sessions");
204     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
205     if (!lifetime.first)
206         lifetime.second = 28800;
207     auto_ptr_char authnInstant(
208         ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL
209         );
210     auto_ptr_char authnMethod(ssoStatement->getAuthenticationMethod());
211
212     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
213     // To complete processing, we need to extract and resolve attributes and then create the session.
214     multimap<string,Attribute*> resolvedAttributes;
215     AttributeExtractor* extractor = application.getAttributeExtractor();
216     if (extractor) {
217         m_log.debug("extracting pushed attributes...");
218         Locker extlocker(extractor);
219         if (n) {
220             try {
221                 extractor->extractAttributes(application, policy.getIssuerMetadata(), *n, resolvedAttributes);
222             }
223             catch (exception& ex) {
224                 m_log.error("caught exception extracting attributes: %s", ex.what());
225             }
226         }
227         for (vector<const opensaml::Assertion*>::const_iterator t = tokens.begin(); t!=tokens.end(); ++t) {
228             try {
229                 extractor->extractAttributes(application, policy.getIssuerMetadata(), *(*t), resolvedAttributes);
230             }
231             catch (exception& ex) {
232                 m_log.error("caught exception extracting attributes: %s", ex.what());
233             }
234         }
235
236         AttributeFilter* filter = application.getAttributeFilter();
237         if (filter && !resolvedAttributes.empty()) {
238             BasicFilteringContext fc(application, resolvedAttributes, policy.getIssuerMetadata(), authnMethod.get());
239             Locker filtlocker(filter);
240             try {
241                 filter->filterAttributes(fc, resolvedAttributes);
242             }
243             catch (exception& ex) {
244                 m_log.error("caught exception filtering attributes: %s", ex.what());
245                 m_log.error("dumping extracted attributes due to filtering exception");
246                 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,shibsp::Attribute>());
247                 resolvedAttributes.clear();
248             }
249         }
250     }
251
252     // Normalize the SAML 1.x NameIdentifier...
253     auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : NULL);
254     if (n) {
255         nameid->setName(n->getName());
256         nameid->setFormat(n->getFormat());
257         nameid->setNameQualifier(n->getNameQualifier());
258     }
259
260     const EntityDescriptor* issuerMetadata =
261         policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
262     auto_ptr<ResolutionContext> ctx(
263         resolveAttributes(application, issuerMetadata, nameid.get(), authnMethod.get(), NULL, &tokens, &resolvedAttributes)
264         );
265
266     if (ctx.get()) {
267         // Copy over any new tokens, but leave them in the context for cleanup.
268         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
269
270         // Copy over new attributes, and transfer ownership.
271         resolvedAttributes.insert(ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
272         ctx->getResolvedAttributes().clear();
273     }
274
275     // Now merge in bad tokens for caching.
276     tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
277
278     try {
279         string key = application.getServiceProvider().getSessionCache()->insert(
280             lifetime.second ? now + lifetime.second : 0,
281             application,
282             httpRequest.getRemoteAddr().c_str(),
283             issuerMetadata,
284             nameid.get(),
285             authnInstant.get(),
286             NULL,
287             authnMethod.get(),
288             NULL,
289             &tokens,
290             &resolvedAttributes
291             );
292         for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());
293         return key;
294     }
295     catch (exception&) {
296         for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());
297         throw;
298     }
299 }
300
301 #endif