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