Change license header.
[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 "attribute/resolver/ResolutionContext.h"
35 # include <saml/exceptions.h>
36 # include <saml/SAMLConfig.h>
37 # include <saml/binding/SecurityPolicy.h>
38 # include <saml/binding/SecurityPolicyRule.h>
39 # include <saml/saml1/core/Assertions.h>
40 # include <saml/saml1/core/Protocols.h>
41 # include <saml/saml2/metadata/Metadata.h>
42 # include <xmltooling/io/HTTPRequest.h>
43 # include <xmltooling/util/DateTime.h>
44 using namespace opensaml::saml1;
45 using namespace opensaml::saml1p;
46 using namespace opensaml;
47 using saml2::NameID;
48 using saml2::NameIDBuilder;
49 using saml2md::EntityDescriptor;
50 using saml2md::SPSSODescriptor;
51 using saml2md::MetadataException;
52 #else
53 # include "lite/SAMLConstants.h"
54 #endif
55
56 using namespace shibsp;
57 using namespace xmltooling;
58 using namespace std;
59
60 namespace shibsp {
61
62 #if defined (_MSC_VER)
63     #pragma warning( push )
64     #pragma warning( disable : 4250 )
65 #endif
66
67     class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
68     {
69     public:
70         SAML1Consumer(const DOMElement* e, const char* appId)
71             : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
72 #ifndef SHIBSP_LITE
73             m_ssoRule = nullptr;
74             m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
75             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
76                 m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(SAML1BROWSERSSO_POLICY_RULE, e);
77 #endif
78         }
79         virtual ~SAML1Consumer() {
80 #ifndef SHIBSP_LITE
81             delete m_ssoRule;
82 #endif
83         }
84
85 #ifndef SHIBSP_LITE
86         void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
87             AssertionConsumerService::generateMetadata(role, handlerURL);
88             role.addSupport(samlconstants::SAML11_PROTOCOL_ENUM);
89             role.addSupport(samlconstants::SAML10_PROTOCOL_ENUM);
90         }
91
92     private:
93         void implementProtocol(
94             const Application& application,
95             const HTTPRequest& httpRequest,
96             HTTPResponse& httpResponse,
97             SecurityPolicy& policy,
98             const PropertySet*,
99             const XMLObject& xmlObject
100             ) const;
101
102         bool m_post;
103         SecurityPolicyRule* m_ssoRule;
104 #else
105         const XMLCh* getProtocolFamily() const {
106             return samlconstants::SAML11_PROTOCOL_ENUM;
107         }
108 #endif
109     };
110
111 #if defined (_MSC_VER)
112     #pragma warning( pop )
113 #endif
114
115     Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
116     {
117         return new SAML1Consumer(p.first, p.second);
118     }
119
120 #ifndef SHIBSP_LITE
121     class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
122     {
123     public:
124         _rulenamed(const char* name) : m_name(name) {}
125         bool operator()(const SecurityPolicyRule* rule) const {
126             return rule ? !strcmp(m_name, rule->getType()) : false;
127         }
128     private:
129         const char* m_name;
130     };
131 #endif
132 };
133
134 #ifndef SHIBSP_LITE
135
136 void SAML1Consumer::implementProtocol(
137     const Application& application,
138     const HTTPRequest& httpRequest,
139     HTTPResponse& httpResponse,
140     SecurityPolicy& policy,
141     const PropertySet*,
142     const XMLObject& xmlObject
143     ) const
144 {
145     // Implementation of SAML 1.x SSO profile(s).
146     m_log.debug("processing message against SAML 1.x SSO profile");
147
148     // Check for errors...this will throw if it's not a successful message.
149     checkError(&xmlObject);
150
151     // With the binding aspects now moved out to the MessageDecoder,
152     // the focus here is on the assertion content. For SAML 1.x POST,
153     // all the security comes from the protocol layer, and signing
154     // the assertion isn't sufficient. So we can check the policy
155     // object now and bail if it's not a secured message.
156     if (m_post && !policy.isAuthenticated()) {
157         if (policy.getIssuer() && !policy.getIssuerMetadata())
158             throw MetadataException("Security of SAML 1.x SSO POST response not established.");
159         throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
160     }
161
162     // Remember whether we already established trust.
163     bool alreadySecured = policy.isAuthenticated();
164
165     const Response* response = dynamic_cast<const Response*>(&xmlObject);
166     if (!response)
167         throw FatalProfileException("Incoming message was not a samlp:Response.");
168
169     const vector<saml1::Assertion*>& assertions = response->getAssertions();
170     if (assertions.empty())
171         throw FatalProfileException("Incoming message contained no SAML assertions.");
172
173     pair<bool,int> minor = response->getMinorVersion();
174
175     // Maintain list of "legit" tokens to feed to SP subsystems.
176     const AuthenticationStatement* ssoStatement=nullptr;
177     vector<const opensaml::Assertion*> tokens;
178
179     // Also track "bad" tokens that we'll cache but not use.
180     // This is necessary because there may be valid tokens not aimed at us.
181     vector<const opensaml::Assertion*> badtokens;
182
183     // With this flag on, we ignore any unsigned assertions.
184     const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
185     pair<bool,bool> flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
186
187     // authnskew allows rejection of SSO if AuthnInstant is too old.
188     const PropertySet* sessionProps = application.getPropertySet("Sessions");
189     pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
190
191     // Saves off error messages potentially helpful for users.
192     string contextualError;
193
194     // Ensure the BrowserSSO rule is in the policy set.
195     if (find_if(policy.getRules(), _rulenamed(SAML1BROWSERSSO_POLICY_RULE)) == nullptr)
196         policy.getRules().push_back(m_ssoRule);
197
198     // Populate recipient as audience.
199     policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
200
201     time_t now = time(nullptr);
202     for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=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 = const_cast<const saml1::Assertion*>(*a)->getAuthenticationStatements();
231             for (vector<AuthenticationStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
232                 if (authnskew.first && authnskew.second &&
233                     (*s)->getAuthenticationInstant() && (now - (*s)->getAuthenticationInstantEpoch() > authnskew.second))
234                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
235                 else if (!ssoStatement) {
236                     ssoStatement = *s;
237                     break;
238                 }
239             }
240         }
241         catch (exception& ex) {
242             m_log.warn("detected a problem with assertion: %s", ex.what());
243             if (!ssoStatement)
244                 contextualError = ex.what();
245             badtokens.push_back(*a);
246         }
247     }
248
249     if (!ssoStatement) {
250         if (contextualError.empty())
251             throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
252         throw FatalProfileException(contextualError.c_str());
253     }
254
255     // Address checking.
256     SubjectLocality* locality = ssoStatement->getSubjectLocality();
257     if (locality && locality->getIPAddress()) {
258         auto_ptr_char ip(locality->getIPAddress());
259         checkAddress(application, httpRequest, ip.get());
260     }
261
262     m_log.debug("SSO profile processing completed successfully");
263
264     NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
265
266     // Now we have to extract the authentication details for attribute and session setup.
267
268     // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
269     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
270     if (!lifetime.first || lifetime.second == 0)
271         lifetime.second = 28800;
272
273     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
274     // To complete processing, we need to extract and resolve attributes and then create the session.
275
276     // Normalize the SAML 1.x NameIdentifier...
277     auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : nullptr);
278     if (n) {
279         nameid->setName(n->getName());
280         nameid->setFormat(n->getFormat());
281         nameid->setNameQualifier(n->getNameQualifier());
282     }
283
284     // The context will handle deleting attributes and new tokens.
285     auto_ptr<ResolutionContext> ctx(
286         resolveAttributes(
287             application,
288             policy.getIssuerMetadata(),
289             (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
290                 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
291             n,
292             nameid.get(),
293             ssoStatement->getAuthenticationMethod(),
294             nullptr,
295             &tokens
296             )
297         );
298
299     if (ctx.get()) {
300         // Copy over any new tokens, but leave them in the context for cleanup.
301         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
302     }
303
304     // Now merge in bad tokens for caching.
305     tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
306
307     application.getServiceProvider().getSessionCache()->insert(
308         application,
309         httpRequest,
310         httpResponse,
311         now + lifetime.second,
312         entity,
313         (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
314             samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
315         nameid.get(),
316         ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : nullptr,
317         nullptr,
318         ssoStatement->getAuthenticationMethod(),
319         nullptr,
320         &tokens,
321         ctx.get() ? &ctx->getResolvedAttributes() : nullptr
322         );
323 }
324
325 #endif