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 using saml2md::MetadataException;
43 #else
44 # include "lite/SAMLConstants.h"
45 #endif
46
47 using namespace shibsp;
48 using namespace xmltooling;
49 using namespace std;
50
51 namespace shibsp {
52
53 #if defined (_MSC_VER)
54     #pragma warning( push )
55     #pragma warning( disable : 4250 )
56 #endif
57     
58     class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
59     {
60     public:
61         SAML1Consumer(const DOMElement* e, const char* appId)
62                 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
63 #ifndef SHIBSP_LITE
64             m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
65 #endif
66         }
67         virtual ~SAML1Consumer() {}
68         
69     private:
70 #ifndef SHIBSP_LITE
71         string implementProtocol(
72             const Application& application,
73             const HTTPRequest& httpRequest,
74             SecurityPolicy& policy,
75             const PropertySet* settings,
76             const XMLObject& xmlObject
77             ) const;
78         bool m_post;
79 #endif
80     };
81
82 #if defined (_MSC_VER)
83     #pragma warning( pop )
84 #endif
85
86     Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
87     {
88         return new SAML1Consumer(p.first, p.second);
89     }
90     
91 };
92
93 #ifndef SHIBSP_LITE
94
95 string SAML1Consumer::implementProtocol(
96     const Application& application,
97     const HTTPRequest& httpRequest,
98     SecurityPolicy& policy,
99     const PropertySet* settings,
100     const XMLObject& xmlObject
101     ) const
102 {
103     // Implementation of SAML 1.x SSO profile(s).
104     m_log.debug("processing message against SAML 1.x SSO profile");
105
106     // Check for errors...this will throw if it's not a successful message.
107     checkError(&xmlObject);
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         if (policy.getIssuer() && !policy.getIssuerMetadata())
116             throw MetadataException("Security of SAML 1.x SSO POST response not established.");
117         throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
118     }
119         
120     // Remember whether we already established trust.
121     bool alreadySecured = policy.isSecure();
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
210     // Normalize the SAML 1.x NameIdentifier...
211     auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : NULL);
212     if (n) {
213         nameid->setName(n->getName());
214         nameid->setFormat(n->getFormat());
215         nameid->setNameQualifier(n->getNameQualifier());
216     }
217
218     // The context will handle deleting attributes and new tokens.
219     auto_ptr<ResolutionContext> ctx(
220         resolveAttributes(
221             application,
222             policy.getIssuerMetadata(),
223             (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
224                 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
225             n,
226             nameid.get(),
227             ssoStatement->getAuthenticationMethod(),
228             NULL,
229             &tokens
230             )
231         );
232
233     if (ctx.get()) {
234         // Copy over any new tokens, but leave them in the context for cleanup.
235         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
236     }
237
238     // Now merge in bad tokens for caching.
239     tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
240
241     return application.getServiceProvider().getSessionCache()->insert(
242         now + lifetime.second,
243         application,
244         httpRequest.getRemoteAddr().c_str(),
245         policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
246         (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
247             samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
248         nameid.get(),
249         ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
250         NULL,
251         ssoStatement->getAuthenticationMethod(),
252         NULL,
253         &tokens,
254         ctx.get() ? &ctx->getResolvedAttributes() : NULL
255         );
256 }
257
258 #endif