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:
acceptNode(const DOMNode * node) const64         FilterAction acceptNode(const DOMNode* node) const {
65             return FILTER_REJECT;
66         }
67     };
68 
69     static SHIBSP_DLLLOCAL TransformSINodeFilter g_TSINFilter;
70 
71 #ifndef SHIBSP_LITE
72     static const XMLCh force[] =        UNICODE_LITERAL_5(f,o,r,c,e);
73     static const XMLCh match[] =        UNICODE_LITERAL_5(m,a,t,c,h);
74     static const XMLCh Regex[] =        UNICODE_LITERAL_5(R,e,g,e,x);
75     static const XMLCh Subst[] =        UNICODE_LITERAL_5(S,u,b,s,t);
76 #endif
77 
78     class SHIBSP_DLLLOCAL TransformSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
79     {
80     public:
TransformSessionInitiator(const DOMElement * e,const char * appId)81         TransformSessionInitiator(const DOMElement* e, const char* appId)
82                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".SessionInitiator.Transform"), &g_TSINFilter), m_appId(appId) {
83             // If Location isn't set, defer address registration until the setParent call.
84             pair<bool,const char*> loc = getString("Location");
85             if (loc.first) {
86                 string address = m_appId + loc.second + "::run::TransformSI";
87                 setAddress(address.c_str());
88             }
89             m_supportedOptions.insert("isPassive");
90 
91 #ifndef SHIBSP_LITE
92             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
93                 m_alwaysRun = getBool("alwaysRun").second;
94                 e = XMLHelper::getFirstChildElement(e);
95                 while (e) {
96                     if (e->hasChildNodes()) {
97                         bool flag = XMLHelper::getAttrBool(e, false, force);
98                         if (XMLString::equals(e->getLocalName(), Subst)) {
99                             auto_ptr_char temp(XMLHelper::getTextContent(e));
100                             if (temp.get() && *temp.get())
101                                 m_subst.push_back(pair<bool,string>(flag, temp.get()));
102                         }
103                         else if (XMLString::equals(e->getLocalName(), Regex) && e->hasAttributeNS(nullptr, match)) {
104                             auto_ptr_char m(e->getAttributeNS(nullptr, match));
105                             auto_ptr_char repl(XMLHelper::getTextContent(e));
106                             if (m.get() && *m.get() && repl.get() && *repl.get())
107                                 m_regex.push_back(boost::tuple<bool,string,string>(flag, m.get(), repl.get()));
108                         }
109                         else {
110                             m_log.warn("Unknown element found in Transform SessionInitiator configuration, check for errors.");
111                         }
112                     }
113                     e = XMLHelper::getNextSiblingElement(e);
114                 }
115             }
116 #endif
117             SPConfig::getConfig().deprecation().warn(TRANSFORM_SESSION_INITIATOR" SessionInitiator is slated for removal");
118         }
119 
~TransformSessionInitiator()120         virtual ~TransformSessionInitiator() {}
121 
122         void setParent(const PropertySet* parent);
123         void receive(DDF& in, ostream& out);
124         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
125 
126     private:
127         void doRequest(const Application& application, string& entityID) const;
128         string m_appId;
129 #ifndef SHIBSP_LITE
130         bool m_alwaysRun;
131         vector< pair<bool, string> > m_subst;
132         vector< boost::tuple<bool,string,string> > m_regex;
133 #endif
134     };
135 
136 #if defined (_MSC_VER)
137     #pragma warning( pop )
138 #endif
139 
TransformSessionInitiatorFactory(const pair<const DOMElement *,const char * > & p,bool)140     SessionInitiator* SHIBSP_DLLLOCAL TransformSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p, bool)
141     {
142         return new TransformSessionInitiator(p.first, p.second);
143     }
144 
145 };
146 
setParent(const PropertySet * parent)147 void TransformSessionInitiator::setParent(const PropertySet* parent)
148 {
149     DOMPropertySet::setParent(parent);
150     pair<bool,const char*> loc = getString("Location");
151     if (loc.first) {
152         string address = m_appId + loc.second + "::run::TransformSI";
153         setAddress(address.c_str());
154     }
155     else {
156         m_log.warn("no Location property in Transform SessionInitiator (or parent), can't register as remoted handler");
157     }
158 }
159 
run(SPRequest & request,string & entityID,bool isHandler) const160 pair<bool,long> TransformSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
161 {
162     // We have to have a candidate name to function.
163     if (entityID.empty() || !checkCompatibility(request, isHandler))
164         return make_pair(false, 0L);
165 
166     const Application& app = request.getApplication();
167 
168     m_log.debug("attempting to transform input (%s) into a valid entityID", entityID.c_str());
169 
170     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
171         doRequest(app, entityID);
172     else {
173         // Remote the call.
174         DDF out,in = DDF(m_address.c_str()).structure();
175         DDFJanitor jin(in), jout(out);
176         in.addmember("application_id").string(app.getId());
177         in.addmember("entity_id").string(entityID.c_str());
178 
179         // Remote the processing.
180         out = send(request, in);
181         if (out.isstring())
182             entityID = out.string();
183     }
184 
185     return make_pair(false, 0L);
186 }
187 
receive(DDF & in,ostream & out)188 void TransformSessionInitiator::receive(DDF& in, ostream& out)
189 {
190     // Find application.
191     const char* aid = in["application_id"].string();
192     const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
193     if (!app) {
194         // Something's horribly wrong.
195         m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
196         throw ConfigurationException("Unable to locate application for new session, deleted?");
197     }
198 
199     const char* entityID = in["entity_id"].string();
200     if (!entityID)
201         throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
202 
203     string copy(entityID);
204     doRequest(*app, copy);
205     DDF ret = DDF(nullptr).string(copy.c_str());
206     DDFJanitor jout(ret);
207     out << ret;
208 }
209 
doRequest(const Application & application,string & entityID) const210 void TransformSessionInitiator::doRequest(const Application& application, string& entityID) const
211 {
212 #ifndef SHIBSP_LITE
213     MetadataProvider* m = application.getMetadataProvider();
214     Locker locker(m);
215 
216     MetadataProviderCriteria mc(application, entityID.c_str(), &IDPSSODescriptor::ELEMENT_QNAME);
217     pair<const EntityDescriptor*,const RoleDescriptor*> entity;
218     if (!m_alwaysRun) {
219         // First check the original value, it might be valid already.
220         entity = m->getEntityDescriptor(mc);
221         if (entity.first)
222             return;
223     }
224 
225     m_log.debug("attempting transform of (%s)", entityID.c_str());
226 
227     // Guess not, try each subst.
228     string transform;
229     for (vector< pair<bool,string> >::const_iterator t = m_subst.begin(); t != m_subst.end(); ++t) {
230         string::size_type pos = t->second.find("$entityID");
231         if (pos == string::npos)
232             continue;
233         transform = t->second;
234         transform.replace(pos, 9, entityID);
235         if (t->first) {
236             m_log.info("forcibly transformed entityID from (%s) to (%s)", entityID.c_str(), transform.c_str());
237             entityID = transform;
238         }
239 
240         m_log.debug("attempting lookup with entityID (%s)", transform.c_str());
241 
242         mc.entityID_ascii = transform.c_str();
243         entity = m->getEntityDescriptor(mc);
244         if (entity.first) {
245             m_log.info("transformed entityID from (%s) to (%s)", entityID.c_str(), transform.c_str());
246             if (!t->first)
247                 entityID = transform;
248             return;
249         }
250     }
251 
252     // Now try regexs.
253     for (vector< boost::tuple<bool,string,string> >::const_iterator r = m_regex.begin(); r != m_regex.end(); ++r) {
254         try {
255             RegularExpression exp(r->get<1>().c_str());
256             XMLCh* temp = exp.replace(entityID.c_str(), r->get<2>().c_str());
257             if (temp) {
258                 auto_ptr_char narrow(temp);
259                 XMLString::release(&temp);
260 
261                 // For some reason it returns the match string if it doesn't match the expression.
262                 if (entityID == narrow.get())
263                     continue;
264 
265                 if (r->get<0>()) {
266                     m_log.info("forcibly transformed entityID from (%s) to (%s)", entityID.c_str(), narrow.get());
267                     entityID = narrow.get();
268                 }
269 
270                 m_log.debug("attempting lookup with entityID (%s)", narrow.get());
271 
272                 mc.entityID_ascii = narrow.get();
273                 entity = m->getEntityDescriptor(mc);
274                 if (entity.first) {
275                     m_log.info("transformed entityID from (%s) to (%s)", entityID.c_str(), narrow.get());
276                     if (!r->get<0>())
277                         entityID = narrow.get();
278                     return;
279                 }
280             }
281         }
282         catch (XMLException& ex) {
283             auto_ptr_char msg(ex.getMessage());
284             m_log.error("caught error applying regular expression: %s", msg.get());
285         }
286     }
287 
288     m_log.warn("unable to find a valid entityID based on the supplied input");
289 #endif
290 }
291