0b663a2fdf200fea7b3b9575700459232197d8fd
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML1Consumer.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * SAML1Consumer.cpp
23  *
24  * SAML 1.x assertion consumer service.
25  */
26
27 #include "internal.h"
28 #include "handler/AssertionConsumerService.h"
29
30 #ifndef SHIBSP_LITE
31 # include "Application.h"
32 # include "ServiceProvider.h"
33 # include "SessionCache.h"
34 # include "TransactionLog.h"
35 # include "attribute/resolver/ResolutionContext.h"
36 # include <boost/iterator/indirect_iterator.hpp>
37 # include <saml/exceptions.h>
38 # include <saml/SAMLConfig.h>
39 # include <saml/binding/SecurityPolicy.h>
40 # include <saml/binding/SecurityPolicyRule.h>
41 # include <saml/saml1/core/Assertions.h>
42 # include <saml/saml1/core/Protocols.h>
43 # include <saml/saml2/metadata/Metadata.h>
44 # include <xmltooling/XMLToolingConfig.h>
45 # include <xmltooling/io/HTTPRequest.h>
46 # include <xmltooling/util/DateTime.h>
47 using namespace opensaml::saml1;
48 using namespace opensaml::saml1p;
49 using namespace opensaml;
50 using namespace boost;
51 using saml2::NameID;
52 using saml2::NameIDBuilder;
53 using saml2md::EntityDescriptor;
54 using saml2md::SPSSODescriptor;
55 using saml2md::MetadataException;
56 #else
57 # include "lite/SAMLConstants.h"
58 #endif
59
60 using namespace shibsp;
61 using namespace xmltooling;
62 using namespace std;
63
64 namespace shibsp {
65
66 #if defined (_MSC_VER)
67     #pragma warning( push )
68     #pragma warning( disable : 4250 )
69 #endif
70
71     class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
72     {
73     public:
74         SAML1Consumer(const DOMElement* e, const char* appId)
75             : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
76 #ifndef SHIBSP_LITE
77             m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
78             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
79                 m_ssoRule.reset(SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(SAML1BROWSERSSO_POLICY_RULE, e));
80 #endif
81         }
82         virtual ~SAML1Consumer() {}
83
84 #ifndef SHIBSP_LITE
85         void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
86             AssertionConsumerService::generateMetadata(role, handlerURL);
87             role.addSupport(samlconstants::SAML11_PROTOCOL_ENUM);
88             role.addSupport(samlconstants::SAML10_PROTOCOL_ENUM);
89         }
90
91     private:
92         void implementProtocol(
93             const Application& application,
94             const HTTPRequest& httpRequest,
95             HTTPResponse& httpResponse,
96             SecurityPolicy& policy,
97             const PropertySet*,
98             const XMLObject& xmlObject
99             ) const;
100
101         bool m_post;
102         scoped_ptr<SecurityPolicyRule> m_ssoRule;
103 #else
104         const XMLCh* getProtocolFamily() const {
105             return samlconstants::SAML11_PROTOCOL_ENUM;
106         }
107 #endif
108     };
109
110 #if defined (_MSC_VER)
111     #pragma warning( pop )
112 #endif
113
114     Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
115     {
116         return new SAML1Consumer(p.first, p.second);
117     }
118
119 #ifndef SHIBSP_LITE
120     class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
121     {
122     public:
123         _rulenamed(const char* name) : m_name(name) {}
124         bool operator()(const SecurityPolicyRule* rule) const {
125             return rule ? !strcmp(m_name, rule->getType()) : false;
126         }
127     private:
128         const char* m_name;
129     };
130 #endif
131 };
132
133 #ifndef SHIBSP_LITE
134
135 void SAML1Consumer::implementProtocol(
136     const Application& application,
137     const HTTPRequest& httpRequest,
138     HTTPResponse& httpResponse,
139     SecurityPolicy& policy,
140     const PropertySet*,
141     const XMLObject& xmlObject
142     ) const
143 {
144     // Implementation of SAML 1.x SSO profile(s).
145     m_log.debug("processing message against SAML 1.x SSO profile");
146
147     // Check for errors...this will throw if it's not a successful message.
148     checkError(&xmlObject, policy.getIssuerMetadata());
149
150     // With the binding aspects now moved out to the MessageDecoder,
151     // the focus here is on the assertion content. For SAML 1.x POST,
152     // all the security comes from the protocol layer, and signing
153     // the assertion isn't sufficient. So we can check the policy
154     // object now and bail if it's not a secured message.
155     if (m_post && !policy.isAuthenticated()) {
156         if (policy.getIssuer() && !policy.getIssuerMetadata())
157             throw MetadataException("Security of SAML 1.x SSO POST response not established.");
158         throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
159     }
160
161     // Remember whether we already established trust.
162     bool alreadySecured = policy.isAuthenticated();
163
164     const Response* response = dynamic_cast<const Response*>(&xmlObject);
165     if (!response)
166         throw FatalProfileException("Incoming message was not a samlp:Response.");
167
168     const vector<saml1::Assertion*>& assertions = response->getAssertions();
169     if (assertions.empty())
170         throw FatalProfileException("Incoming message contained no SAML assertions.");
171
172     pair<bool,int> minor = response->getMinorVersion();
173
174     // Maintain list of "legit" tokens to feed to SP subsystems.
175     const AuthenticationStatement* ssoStatement=nullptr;
176     vector<const opensaml::Assertion*> tokens;
177
178     // Also track "bad" tokens that we'll cache but not use.
179     // This is necessary because there may be valid tokens not aimed at us.
180     vector<const opensaml::Assertion*> badtokens;
181
182     // With this flag on, we ignore any unsigned assertions.
183     const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
184     pair<bool,bool> flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
185
186     // authnskew allows rejection of SSO if AuthnInstant is too old.
187     const PropertySet* sessionProps = application.getPropertySet("Sessions");
188     pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
189
190     // Saves off error messages potentially helpful for users.
191     string contextualError;
192
193     // Ensure the BrowserSSO rule is in the policy set.
194     if (find_if(policy.getRules(), _rulenamed(SAML1BROWSERSSO_POLICY_RULE)) == nullptr)
195         policy.getRules().push_back(m_ssoRule.get());
196
197     // Populate recipient as audience.
198     policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
199
200     time_t now = time(nullptr);
201     for (indirect_iterator<vector<saml1::Assertion*>::const_iterator> a = make_indirect_iterator(assertions.begin());
202             a != make_indirect_iterator(assertions.end()); ++a) {
203         try {
204             // Skip unsigned assertion?
205             if (!a->getSignature() && flag.first && flag.second)
206                 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
207
208             // We clear the security flag, so we can tell whether the token was secured on its own.
209             policy.setAuthenticated(false);
210             policy.reset(true);
211
212             // Extract message bits and re-verify Issuer information.
213             extractMessageDetails(
214                 *a, (minor.first && minor.second==0) ? samlconstants::SAML10_PROTOCOL_ENUM : samlconstants::SAML11_PROTOCOL_ENUM, policy
215                 );
216
217             // Run the policy over the assertion. Handles replay, freshness, and
218             // signature verification, assuming the relevant rules are configured,
219             // along with condition and profile enforcement.
220             policy.evaluate(*a, &httpRequest);
221
222             // If no security is in place now, we kick it.
223             if (!alreadySecured && !policy.isAuthenticated())
224                 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
225
226             // Track it as a valid token.
227             tokens.push_back(&(*a));
228
229             // Save off the first valid SSO statement.
230             const vector<AuthenticationStatement*>& statements =
231                     const_cast<const saml1::Assertion&>(*a).getAuthenticationStatements();
232             for (indirect_iterator<vector<AuthenticationStatement*>::const_iterator> s = make_indirect_iterator(statements.begin());
233                     s != make_indirect_iterator(statements.end()); ++s) {
234                 if (s->getAuthenticationInstant() &&
235                         s->getAuthenticationInstantEpoch() - XMLToolingConfig::getConfig().clock_skew_secs > now) {
236                     contextualError = "The login time at your identity provider was future-dated.";
237                 }
238                 else if (authnskew.first && authnskew.second && s->getAuthenticationInstant() &&
239                         s->getAuthenticationInstantEpoch() <= now && (now - s->getAuthenticationInstantEpoch() > authnskew.second)) {
240                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the allowed limit.";
241                 }
242                 else if (authnskew.first && authnskew.second && s->getAuthenticationInstant() == nullptr) {
243                     contextualError = "Your identity provider did not supply a time of login, violating local policy.";
244                 }
245                 else if (!ssoStatement) {
246                     ssoStatement = &(*s);
247                     break;
248                 }
249             }
250         }
251         catch (std::exception& ex) {
252             m_log.warn("detected a problem with assertion: %s", ex.what());
253             if (!ssoStatement)
254                 contextualError = ex.what();
255             badtokens.push_back(&(*a));
256         }
257     }
258
259     if (!ssoStatement) {
260         if (contextualError.empty())
261             throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
262         throw FatalProfileException(contextualError.c_str());
263     }
264
265     // Address checking.
266     SubjectLocality* locality = ssoStatement->getSubjectLocality();
267     if (locality && locality->getIPAddress()) {
268         auto_ptr_char ip(locality->getIPAddress());
269         checkAddress(application, httpRequest, ip.get());
270     }
271
272     m_log.debug("SSO profile processing completed successfully");
273
274     NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
275
276     // Now we have to extract the authentication details for attribute and session setup.
277
278     // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
279     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
280     if (!lifetime.first || lifetime.second == 0)
281         lifetime.second = 28800;
282
283     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
284     // To complete processing, we need to extract and resolve attributes and then create the session.
285
286     // Normalize the SAML 1.x NameIdentifier...
287     scoped_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : nullptr);
288     if (n) {
289         nameid->setName(n->getName());
290         nameid->setFormat(n->getFormat());
291         nameid->setNameQualifier(n->getNameQualifier());
292     }
293
294     // The context will handle deleting attributes and new tokens.
295     scoped_ptr<ResolutionContext> ctx(
296         resolveAttributes(
297             application,
298             &httpRequest,
299             policy.getIssuerMetadata(),
300             (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
301                 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
302             response,
303             n,
304             ssoStatement,
305             nameid.get(),
306             nullptr,
307             ssoStatement->getAuthenticationMethod(),
308             nullptr,
309             &tokens
310             )
311         );
312
313     if (ctx) {
314         // Copy over any new tokens, but leave them in the context for cleanup.
315         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
316     }
317
318     // Now merge in bad tokens for caching.
319     tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
320
321     string session_id;
322     application.getServiceProvider().getSessionCache()->insert(
323         session_id,
324         application,
325         httpRequest,
326         httpResponse,
327         now + lifetime.second,
328         entity,
329         (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
330             samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
331         nameid.get(),
332         ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : nullptr,
333         nullptr,
334         ssoStatement->getAuthenticationMethod(),
335         nullptr,
336         &tokens,
337         ctx ? &ctx->getResolvedAttributes() : nullptr
338         );
339
340     scoped_ptr<LoginEvent> login_event(newLoginEvent(application, httpRequest));
341     if (login_event) {
342         login_event->m_sessionID = session_id.c_str();
343         login_event->m_peer = entity;
344         auto_ptr_char prot(
345             (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
346                 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM
347             );
348         login_event->m_protocol = prot.get();
349         login_event->m_nameID = nameid.get();
350         login_event->m_saml1AuthnStatement = ssoStatement;
351         login_event->m_saml1Response = response;
352         if (ctx)
353             login_event->m_attributes = &ctx->getResolvedAttributes();
354         application.getServiceProvider().getTransactionLog()->write(*login_event);
355     }
356 }
357
358 #endif