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