Move token validation into SAML library, first draft SAML 1 SSO handler.
[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/resolver/ResolutionContext.h"
29 #include "handler/AssertionConsumerService.h"
30
31 #include <saml/saml1/core/Assertions.h>
32 #include <saml/saml1/core/Protocols.h>
33 #include <saml/saml1/profile/BrowserSSOProfileValidator.h>
34 #include <saml/saml2/metadata/Metadata.h>
35
36 using namespace shibsp;
37 using namespace opensaml::saml1;
38 using namespace opensaml::saml1p;
39 using namespace opensaml;
40 using namespace xmltooling;
41 using namespace log4cpp;
42 using namespace std;
43 using saml2::NameID;
44 using saml2::NameIDBuilder;
45 using saml2md::EntityDescriptor;
46
47 namespace shibsp {
48
49 #if defined (_MSC_VER)
50     #pragma warning( push )
51     #pragma warning( disable : 4250 )
52 #endif
53     
54     class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
55     {
56     public:
57         SAML1Consumer(const DOMElement* e) : AssertionConsumerService(e, Category::getInstance(SHIBSP_LOGCAT".SAML1")) {}
58         virtual ~SAML1Consumer() {}
59         
60     private:
61         string implementProtocol(
62             const Application& application,
63             const HTTPRequest& httpRequest,
64             SecurityPolicy& policy,
65             const PropertySet* settings,
66             const XMLObject& xmlObject
67             ) const;
68     };
69
70 #if defined (_MSC_VER)
71     #pragma warning( pop )
72 #endif
73
74     Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const DOMElement* const & e)
75     {
76         return new SAML1Consumer(e);
77     }
78     
79 };
80
81 string SAML1Consumer::implementProtocol(
82     const Application& application,
83     const HTTPRequest& httpRequest,
84     SecurityPolicy& policy,
85     const PropertySet* settings,
86     const XMLObject& xmlObject
87     ) const
88 {
89     // Implementation of SAML 1.x SSO profile(s).
90     m_log.debug("processing message against SAML 1.x SSO profile");
91
92     // With the binding aspects now moved out to the MessageDecoder,
93     // the focus here is on the assertion content. For SAML 1.x,
94     // all the security comes from the protocol layer, and signing
95     // the assertion isn't sufficient. So we can check the policy
96     // object now and bail if it's not a secure message.
97     if (!policy.isSecure())
98         throw SecurityPolicyException("Security of SAML 1.x SSO response not established.");
99
100     // Check for errors...this will throw if it's not a successful message.
101     checkError(&xmlObject);
102
103     const Response* response = dynamic_cast<const Response*>(&xmlObject);
104     if (!response)
105         throw FatalProfileException("Incoming message was not a samlp:Response.");
106
107     const vector<saml1::Assertion*>& assertions = response->getAssertions();
108     if (assertions.empty())
109         throw FatalProfileException("Incoming message contained no SAML assertions.");
110
111     // Maintain list of "legit" tokens to feed to SP subsystems.
112     const AuthenticationStatement* ssoStatement=NULL;
113     vector<const opensaml::Assertion*> tokens;
114
115     // Profile validator.
116     time_t now = time(NULL);
117     BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now);
118
119     // With this flag on, we ignore any unsigned assertions.
120     pair<bool,bool> flag = settings->getBool("signedAssertions");
121     for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
122         // Skip unsigned assertion?
123         if (!(*a)->getSignature() && flag.first && flag.second) {
124             m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
125             continue;
126         }
127
128         try {
129             // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
130             // and signature verification, assuming the relevant rules are configured.
131             policy.evaluate(*(*a));
132
133             // Now do profile and core semantic validation to ensure we can use it for SSO.
134             ssoValidator.validateAssertion(*(*a));
135
136             // Track it as a valid token.
137             tokens.push_back(*a);
138
139             // Save off the first valid SSO statement.
140             if (!ssoStatement && !(*a)->getAuthenticationStatements().empty())
141                 ssoStatement = (*a)->getAuthenticationStatements().front();
142         }
143         catch (exception& ex) {
144             m_log.warn("profile validation error in assertion: %s", ex.what());
145         }
146     }
147
148     if (!ssoStatement)
149         throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
150
151     // Address checking.
152     SubjectLocality* locality = ssoStatement->getSubjectLocality();
153     if (locality && locality->getIPAddress()) {
154         auto_ptr_char ip(locality->getIPAddress());
155         checkAddress(application, httpRequest, ip.get());
156     }
157
158     m_log.debug("SSO profile processing completed successfully");
159
160     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
161     // To complete processing, we need to resolve attributes and then create the session.
162
163     // First, normalize the SAML 1.x NameIdentifier...
164     auto_ptr<NameID> nameid(NameIDBuilder::buildNameID());
165     NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
166     if (n) {
167         nameid->setName(n->getName());
168         nameid->setFormat(n->getFormat());
169         nameid->setNameQualifier(n->getNameQualifier());
170     }
171
172     const EntityDescriptor* issuerMetadata = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
173     auto_ptr<ResolutionContext> ctx(
174         resolveAttributes(application, httpRequest, issuerMetadata, *nameid.get(), &tokens)
175         );
176
177     // Copy over any new tokens, but leave them in the context for cleanup.
178     tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
179
180     // Now we have to extract the authentication details for session setup.
181
182     // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
183     const PropertySet* sessionProps = application.getPropertySet("Sessions");
184     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : make_pair(true,28800);
185     if (!lifetime.first)
186         lifetime.second = 28800;
187     auto_ptr_char authnInstant(
188         ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL
189         );
190     auto_ptr_char authnMethod(ssoStatement->getAuthenticationMethod());
191
192     vector<shibsp::Attribute*>& attrs = ctx->getResolvedAttributes();
193     string key = application.getServiceProvider().getSessionCache()->insert(
194         lifetime.second ? now + lifetime.second : 0,
195         application,
196         httpRequest.getRemoteAddr().c_str(),
197         issuerMetadata,
198         *nameid.get(),
199         authnInstant.get(),
200         NULL,
201         authnMethod.get(),
202         NULL,
203         &tokens,
204         &attrs
205         );
206     attrs.clear();  // Attributes are owned by cache now.
207     return key;
208 }