New -lite library and elimination of SAML libraries from modules.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / Shib1SessionInitiator.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  * Shib1SessionInitiator.cpp
19  * 
20  * Shibboleth 1.x AuthnRequest support.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/RemotedHandler.h"
30 #include "handler/SessionInitiator.h"
31 #include "util/SPConstants.h"
32
33 #ifndef SHIBSP_LITE
34 # include <saml/saml2/metadata/Metadata.h>
35 # include <saml/saml2/metadata/EndpointManager.h>
36 #endif
37 #include <xmltooling/XMLToolingConfig.h>
38 #include <xmltooling/util/URLEncoder.h>
39
40 using namespace shibsp;
41 using namespace opensaml::saml2md;
42 using namespace opensaml;
43 using namespace xmltooling;
44 using namespace log4cpp;
45 using namespace std;
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 Shib1SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
55     {
56     public:
57         Shib1SessionInitiator(const DOMElement* e, const char* appId)
58                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator")), m_appId(appId) {
59             // If Location isn't set, defer address registration until the setParent call.
60             pair<bool,const char*> loc = getString("Location");
61             if (loc.first) {
62                 string address = m_appId + loc.second + "::run::Shib1SI";
63                 setAddress(address.c_str());
64             }
65         }
66         virtual ~Shib1SessionInitiator() {}
67         
68         void setParent(const PropertySet* parent);
69         void receive(DDF& in, ostream& out);
70         pair<bool,long> run(SPRequest& request, const char* entityID=NULL, bool isHandler=true) const;
71
72     private:
73         pair<bool,long> doRequest(
74             const Application& application,
75             HTTPResponse& httpResponse,
76             const char* entityID,
77             const char* acsLocation,
78             string& relayState
79             ) const;
80         string m_appId;
81     };
82
83 #if defined (_MSC_VER)
84     #pragma warning( pop )
85 #endif
86
87     SessionInitiator* SHIBSP_DLLLOCAL Shib1SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
88     {
89         return new Shib1SessionInitiator(p.first, p.second);
90     }
91
92 };
93
94 void Shib1SessionInitiator::setParent(const PropertySet* parent)
95 {
96     DOMPropertySet::setParent(parent);
97     pair<bool,const char*> loc = getString("Location");
98     if (loc.first) {
99         string address = m_appId + loc.second + "::run::Shib1SI";
100         setAddress(address.c_str());
101     }
102     else {
103         m_log.warn("no Location property in Shib1 SessionInitiator (or parent), can't register as remoted handler");
104     }
105 }
106
107 pair<bool,long> Shib1SessionInitiator::run(SPRequest& request, const char* entityID, bool isHandler) const
108 {
109     // We have to know the IdP to function.
110     if (!entityID || !*entityID)
111         return make_pair(false,0);
112
113     string target;
114     const Handler* ACS=NULL;
115     const char* option;
116     const Application& app=request.getApplication();
117
118     if (isHandler) {
119         option=request.getParameter("acsIndex");
120         if (option)
121             ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
122
123         option = request.getParameter("target");
124         if (option)
125             target = option;
126
127         // Since we're passing the ACS by value, we need to compute the return URL,
128         // so we'll need the target resource for real.
129         recoverRelayState(request.getApplication(), request, target, false);
130     }
131     else {
132         // We're running as a "virtual handler" from within the filter.
133         // The target resource is the current one and everything else is defaulted.
134         target=request.getRequestURL();
135     }
136
137     // Since we're not passing by index, we need to fully compute the return URL and binding.
138     if (!ACS)
139         ACS = app.getDefaultAssertionConsumerService();
140
141     // Compute the ACS URL. We add the ACS location to the base handlerURL.
142     string ACSloc=request.getHandlerURL(target.c_str());
143     pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
144     if (loc.first) ACSloc+=loc.second;
145
146     if (isHandler) {
147         // We may already have RelayState set if we looped back here,
148         // but just in case target is a resource, we reset it back.
149         target.erase();
150         option = request.getParameter("target");
151         if (option)
152             target = option;
153     }
154
155     m_log.debug("attempting to initiate session using Shibboleth with provider (%s)", entityID);
156
157     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
158         return doRequest(app, request, entityID, ACSloc.c_str(), target);
159
160     // Remote the call.
161     DDF out,in = DDF(m_address.c_str()).structure();
162     DDFJanitor jin(in), jout(out);
163     in.addmember("application_id").string(app.getId());
164     in.addmember("entity_id").string(entityID);
165     in.addmember("acsLocation").string(ACSloc.c_str());
166     if (!target.empty())
167         in.addmember("RelayState").string(target.c_str());
168
169     // Remote the processing.
170     out = request.getServiceProvider().getListenerService()->send(in);
171     return unwrap(request, out);
172 }
173
174 void Shib1SessionInitiator::receive(DDF& in, ostream& out)
175 {
176     // Find application.
177     const char* aid=in["application_id"].string();
178     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
179     if (!app) {
180         // Something's horribly wrong.
181         m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
182         throw ConfigurationException("Unable to locate application for new session, deleted?");
183     }
184
185     const char* entityID = in["entity_id"].string();
186     const char* acsLocation = in["acsLocation"].string();
187     if (!entityID || !acsLocation)
188         throw ConfigurationException("No entityID or acsLocation parameter supplied to remoted SessionInitiator.");
189
190     DDF ret(NULL);
191     DDFJanitor jout(ret);
192
193     // Wrap the outgoing object with a Response facade.
194     auto_ptr<HTTPResponse> http(getResponse(ret));
195
196     string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
197
198     // Since we're remoted, the result should either be a throw, which we pass on,
199     // a false/0 return, which we just return as an empty structure, or a response/redirect,
200     // which we capture in the facade and send back.
201     doRequest(*app, *http.get(), entityID, acsLocation, relayState);
202     out << ret;
203 }
204
205 pair<bool,long> Shib1SessionInitiator::doRequest(
206     const Application& app,
207     HTTPResponse& httpResponse,
208     const char* entityID,
209     const char* acsLocation,
210     string& relayState
211     ) const
212 {
213 #ifndef SHIBSP_LITE
214     // Use metadata to invoke the SSO service directly.
215     MetadataProvider* m=app.getMetadataProvider();
216     Locker locker(m);
217     const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
218     if (!entity) {
219         m_log.error("unable to locate metadata for provider (%s)", entityID);
220         throw MetadataException("Unable to locate metadata for identity provider ($entityID)",
221             namedparams(1, "entityID", entityID));
222     }
223     const IDPSSODescriptor* role=entity->getIDPSSODescriptor(shibspconstants::SHIB1_PROTOCOL_ENUM);
224     if (!role) {
225         m_log.error("unable to locate Shibboleth-aware identity provider role for provider (%s)", entityID);
226         return make_pair(false,0);
227     }
228     const EndpointType* ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(
229         shibspconstants::SHIB1_AUTHNREQUEST_PROFILE_URI
230         );
231     if (!ep) {
232         m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
233         return make_pair(false,0);
234     }
235
236     preserveRelayState(app, httpResponse, relayState);
237
238     // Shib 1.x requires a target value.
239     if (relayState.empty())
240         relayState = "default";
241
242     char timebuf[16];
243     sprintf(timebuf,"%u",time(NULL));
244     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
245     auto_ptr_char dest(ep->getLocation());
246     string req=string(dest.get()) + (strchr(dest.get(),'?') ? '&' : '?') + "shire=" + urlenc->encode(acsLocation) +
247         "&time=" + timebuf + "&target=" + urlenc->encode(relayState.c_str()) +
248         "&providerId=" + urlenc->encode(app.getString("entityID").second);
249
250     return make_pair(true, httpResponse.sendRedirect(req.c_str()));
251 #else
252     return make_pair(false,0);
253 #endif
254 }