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