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