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