baaf4b0a808c09c108eb0d4b9e22cb53e932fcd8
[shibboleth/cpp-sp.git] / shibsp / handler / impl / TransformSessionInitiator.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * TransformSessionInitiator.cpp
23  * 
24  * Support for mapping input into an entityID using a transform.
25  */
26
27 #include "internal.h"
28 #include "Application.h"
29 #include "exceptions.h"
30 #include "ServiceProvider.h"
31 #include "SPRequest.h"
32 #include "handler/AbstractHandler.h"
33 #include "handler/RemotedHandler.h"
34 #include "handler/SessionInitiator.h"
35 #include "util/SPConstants.h"
36
37 #ifndef SHIBSP_LITE
38 # include "metadata/MetadataProviderCriteria.h"
39 # include <saml/saml2/metadata/Metadata.h>
40 #endif
41 #include <boost/tuple/tuple.hpp>
42 #include <xmltooling/XMLToolingConfig.h>
43 #include <xmltooling/util/URLEncoder.h>
44 #include <xercesc/util/XMLUniDefs.hpp>
45 #include <xercesc/util/regx/RegularExpression.hpp>
46
47 using namespace shibsp;
48 using namespace opensaml::saml2md;
49 using namespace opensaml;
50 using namespace xmltooling;
51 using namespace boost;
52 using namespace std;
53
54 namespace shibsp {
55
56 #if defined (_MSC_VER)
57     #pragma warning( push )
58     #pragma warning( disable : 4250 )
59 #endif
60
61     class SHIBSP_DLLLOCAL TransformSINodeFilter : public DOMNodeFilter
62     {
63     public:
64 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
65         short
66 #else
67         FilterAction
68 #endif
69         acceptNode(const DOMNode* node) const {
70             return FILTER_REJECT;
71         }
72     };
73
74     static SHIBSP_DLLLOCAL TransformSINodeFilter g_TSINFilter;
75
76 #ifndef SHIBSP_LITE
77     static const XMLCh force[] =        UNICODE_LITERAL_5(f,o,r,c,e);
78     static const XMLCh match[] =        UNICODE_LITERAL_5(m,a,t,c,h);
79     static const XMLCh Regex[] =        UNICODE_LITERAL_5(R,e,g,e,x);
80     static const XMLCh Subst[] =        UNICODE_LITERAL_5(S,u,b,s,t);
81 #endif
82
83     class SHIBSP_DLLLOCAL TransformSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
84     {
85     public:
86         TransformSessionInitiator(const DOMElement* e, const char* appId)
87                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.Transform"), &g_TSINFilter), m_appId(appId) {
88             // If Location isn't set, defer address registration until the setParent call.
89             pair<bool,const char*> loc = getString("Location");
90             if (loc.first) {
91                 string address = m_appId + loc.second + "::run::TransformSI";
92                 setAddress(address.c_str());
93             }
94             m_supportedOptions.insert("isPassive");
95
96 #ifndef SHIBSP_LITE
97             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
98                 m_alwaysRun = getBool("alwaysRun").second;
99                 e = XMLHelper::getFirstChildElement(e);
100                 while (e) {
101                     if (e->hasChildNodes()) {
102                         bool flag = XMLHelper::getAttrBool(e, false, force);
103                         if (XMLString::equals(e->getLocalName(), Subst)) {
104                             auto_ptr_char temp(e->getTextContent());
105                             if (temp.get() && *temp.get())
106                                 m_subst.push_back(pair<bool,string>(flag, temp.get()));
107                         }
108                         else if (XMLString::equals(e->getLocalName(), Regex) && e->hasAttributeNS(nullptr, match)) {
109                             auto_ptr_char m(e->getAttributeNS(nullptr, match));
110                             auto_ptr_char repl(e->getTextContent());
111                             if (m.get() && *m.get() && repl.get() && *repl.get())
112                                 m_regex.push_back(tuple<bool,string,string>(flag, m.get(), repl.get()));
113                         }
114                         else {
115                             m_log.warn("Unknown element found in Transform SessionInitiator configuration, check for errors.");
116                         }
117                     }
118                     e = XMLHelper::getNextSiblingElement(e);
119                 }
120             }
121 #endif
122         }
123
124         virtual ~TransformSessionInitiator() {}
125         
126         void setParent(const PropertySet* parent);
127         void receive(DDF& in, ostream& out);
128         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
129
130     private:
131         void doRequest(const Application& application, string& entityID) const;
132         string m_appId;
133 #ifndef SHIBSP_LITE
134         bool m_alwaysRun;
135         vector< pair<bool, string> > m_subst;
136         vector< tuple<bool,string,string> > m_regex;
137 #endif
138     };
139
140 #if defined (_MSC_VER)
141     #pragma warning( pop )
142 #endif
143
144     SessionInitiator* SHIBSP_DLLLOCAL TransformSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
145     {
146         return new TransformSessionInitiator(p.first, p.second);
147     }
148
149 };
150
151 void TransformSessionInitiator::setParent(const PropertySet* parent)
152 {
153     DOMPropertySet::setParent(parent);
154     pair<bool,const char*> loc = getString("Location");
155     if (loc.first) {
156         string address = m_appId + loc.second + "::run::TransformSI";
157         setAddress(address.c_str());
158     }
159     else {
160         m_log.warn("no Location property in Transform SessionInitiator (or parent), can't register as remoted handler");
161     }
162 }
163
164 pair<bool,long> TransformSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
165 {
166     // We have to have a candidate name to function.
167     if (entityID.empty() || !checkCompatibility(request, isHandler))
168         return make_pair(false, 0L);
169
170     const Application& app = request.getApplication();
171
172     m_log.debug("attempting to transform input (%s) into a valid entityID", entityID.c_str());
173
174     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
175         doRequest(app, entityID);
176     else {
177         // Remote the call.
178         DDF out,in = DDF(m_address.c_str()).structure();
179         DDFJanitor jin(in), jout(out);
180         in.addmember("application_id").string(app.getId());
181         in.addmember("entity_id").string(entityID.c_str());
182     
183         // Remote the processing.
184         out = request.getServiceProvider().getListenerService()->send(in);
185         if (out.isstring())
186             entityID = out.string();
187     }
188     
189     return make_pair(false, 0L);
190 }
191
192 void TransformSessionInitiator::receive(DDF& in, ostream& out)
193 {
194     // Find application.
195     const char* aid = in["application_id"].string();
196     const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
197     if (!app) {
198         // Something's horribly wrong.
199         m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
200         throw ConfigurationException("Unable to locate application for new session, deleted?");
201     }
202
203     const char* entityID = in["entity_id"].string();
204     if (!entityID)
205         throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
206
207     string copy(entityID);
208     doRequest(*app, copy);
209     DDF ret = DDF(nullptr).string(copy.c_str());
210     DDFJanitor jout(ret);
211     out << ret;
212 }
213
214 void TransformSessionInitiator::doRequest(const Application& application, string& entityID) const
215 {
216 #ifndef SHIBSP_LITE
217     MetadataProvider* m = application.getMetadataProvider();
218     Locker locker(m);
219
220     MetadataProviderCriteria mc(application, entityID.c_str(), &IDPSSODescriptor::ELEMENT_QNAME);
221     pair<const EntityDescriptor*,const RoleDescriptor*> entity;
222     if (!m_alwaysRun) {
223         // First check the original value, it might be valid already.
224         entity = m->getEntityDescriptor(mc);
225         if (entity.first)
226             return;
227     }
228
229     m_log.debug("attempting transform of (%s)", entityID.c_str());
230
231     // Guess not, try each subst.
232     string transform;
233     for (vector< pair<bool,string> >::const_iterator t = m_subst.begin(); t != m_subst.end(); ++t) {
234         string::size_type pos = t->second.find("$entityID");
235         if (pos == string::npos)
236             continue;
237         transform = t->second;
238         transform.replace(pos, 9, entityID);
239         if (t->first) {
240             m_log.info("forcibly transformed entityID from (%s) to (%s)", entityID.c_str(), transform.c_str());
241             entityID = transform;
242         }
243
244         m_log.debug("attempting lookup with entityID (%s)", transform.c_str());
245     
246         mc.entityID_ascii = transform.c_str();
247         entity = m->getEntityDescriptor(mc);
248         if (entity.first) {
249             m_log.info("transformed entityID from (%s) to (%s)", entityID.c_str(), transform.c_str());
250             if (!t->first)
251                 entityID = transform;
252             return;
253         }
254     }
255
256     // Now try regexs.
257     for (vector< tuple<bool,string,string> >::const_iterator r = m_regex.begin(); r != m_regex.end(); ++r) {
258         try {
259             RegularExpression exp(r->get<1>().c_str());
260             XMLCh* temp = exp.replace(entityID.c_str(), r->get<2>().c_str());
261             if (temp) {
262                 auto_ptr_char narrow(temp);
263                 XMLString::release(&temp);
264
265                 // For some reason it returns the match string if it doesn't match the expression.
266                 if (entityID == narrow.get())
267                     continue;
268
269                 if (r->get<0>()) {
270                     m_log.info("forcibly transformed entityID from (%s) to (%s)", entityID.c_str(), narrow.get());
271                     entityID = narrow.get();
272                 }
273
274                 m_log.debug("attempting lookup with entityID (%s)", narrow.get());
275
276                 mc.entityID_ascii = narrow.get();
277                 entity = m->getEntityDescriptor(mc);
278                 if (entity.first) {
279                     m_log.info("transformed entityID from (%s) to (%s)", entityID.c_str(), narrow.get());
280                     if (!r->get<0>())
281                         entityID = narrow.get();
282                     return;
283                 }
284             }
285         }
286         catch (XMLException& ex) {
287             auto_ptr_char msg(ex.getMessage());
288             m_log.error("caught error applying regular expression: %s", msg.get());
289         }
290     }
291
292     m_log.warn("unable to find a valid entityID based on the supplied input");
293 #endif
294 }