https://issues.shibboleth.net/jira/browse/SSPCPP-160
[shibboleth/cpp-sp.git] / shibsp / handler / impl / MetadataGenerator.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  * MetadataGenerator.cpp
19  *
20  * Handler for generating "approximate" metadata based on SP configuration.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "handler/AbstractHandler.h"
28 #include "handler/RemotedHandler.h"
29
30 #ifndef SHIBSP_LITE
31 # include "metadata/MetadataProviderCriteria.h"
32 #endif
33
34 #include <xercesc/framework/LocalFileInputSource.hpp>
35 #include <xercesc/framework/Wrapper4InputSource.hpp>
36
37 using namespace shibsp;
38 #ifndef SHIBSP_LITE
39 using namespace opensaml::saml2md;
40 using namespace opensaml;
41 using namespace xmlsignature;
42 #endif
43 using namespace xmltooling;
44 using namespace std;
45
46 namespace shibsp {
47
48 #if defined (_MSC_VER)
49     #pragma warning( push )
50     #pragma warning( disable : 4250 )
51 #endif
52
53     class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
54     {
55     public:
56         short acceptNode(const DOMNode* node) const {
57             return FILTER_REJECT;
58         }
59     };
60
61     static SHIBSP_DLLLOCAL Blocker g_Blocker;
62
63     class SHIBSP_API MetadataGenerator : public AbstractHandler, public RemotedHandler
64     {
65     public:
66         MetadataGenerator(const DOMElement* e, const char* appId);
67         virtual ~MetadataGenerator() {}
68
69         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
70         void receive(DDF& in, ostream& out);
71
72     private:
73         pair<bool,long> processMessage(
74             const Application& application,
75             const char* handlerURL,
76             const char* entityID,
77             HTTPResponse& httpResponse
78             ) const;
79
80         set<string> m_acl;
81 #ifndef SHIBSP_LITE
82         short m_http,m_https;
83         vector<string> m_bases;
84 #endif
85     };
86
87 #if defined (_MSC_VER)
88     #pragma warning( pop )
89 #endif
90
91     Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
92     {
93         return new MetadataGenerator(p.first, p.second);
94     }
95
96 };
97
98 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
99     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
100 #ifndef SHIBSP_LITE
101         ,m_http(0), m_https(0)
102 #endif
103 {
104     string address(appId);
105     address += getString("Location").second;
106     setAddress(address.c_str());
107     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
108         pair<bool,const char*> acl = getString("acl");
109         if (acl.first) {
110             string aclbuf=acl.second;
111             int j = 0;
112             for (unsigned int i=0;  i < aclbuf.length();  i++) {
113                 if (aclbuf.at(i)==' ') {
114                     m_acl.insert(aclbuf.substr(j, i-j));
115                     j = i+1;
116                 }
117             }
118             m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
119         }
120     }
121
122 #ifndef SHIBSP_LITE
123     static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
124
125     pair<bool,bool> flag = getBool("http");
126     if (flag.first)
127         m_http = flag.second ? 1 : -1;
128     flag = getBool("https");
129     if (flag.first)
130         m_https = flag.second ? 1 : -1;
131
132     e = XMLHelper::getFirstChildElement(e, EndpointBase);
133     while (e) {
134         if (e->hasChildNodes()) {
135             auto_ptr_char base(e->getFirstChild()->getNodeValue());
136             if (base.get() && *base.get())
137                 m_bases.push_back(base.get());
138         }
139         e = XMLHelper::getNextSiblingElement(e, EndpointBase);
140     }
141 #endif
142 }
143
144 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
145 {
146     SPConfig& conf = SPConfig::getConfig();
147     if (conf.isEnabled(SPConfig::InProcess)) {
148         if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
149             m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
150             istringstream msg("Metadata Request Blocked");
151             return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED));
152         }
153     }
154
155     try {
156         if (conf.isEnabled(SPConfig::OutOfProcess)) {
157             // When out of process, we run natively and directly process the message.
158             return processMessage(request.getApplication(), request.getHandlerURL(), request.getParameter("entityID"), request);
159         }
160         else {
161             // When not out of process, we remote all the message processing.
162             DDF out,in = DDF(m_address.c_str());
163             in.addmember("application_id").string(request.getApplication().getId());
164             in.addmember("handler_url").string(request.getHandlerURL());
165             if (request.getParameter("entityID"))
166                 in.addmember("entity_id").string(request.getParameter("entityID"));
167             DDFJanitor jin(in), jout(out);
168
169             out=request.getServiceProvider().getListenerService()->send(in);
170             return unwrap(request, out);
171         }
172     }
173     catch (exception& ex) {
174         m_log.error("error while processing request: %s", ex.what());
175         istringstream msg("Metadata Request Failed");
176         return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
177     }
178 }
179
180 void MetadataGenerator::receive(DDF& in, ostream& out)
181 {
182     // Find application.
183     const char* aid=in["application_id"].string();
184     const char* hurl=in["handler_url"].string();
185     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
186     if (!app) {
187         // Something's horribly wrong.
188         m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
189         throw ConfigurationException("Unable to locate application for metadata request, deleted?");
190     }
191     else if (!hurl) {
192         throw ConfigurationException("Missing handler_url parameter in remoted method call.");
193     }
194
195     // Wrap a response shim.
196     DDF ret(NULL);
197     DDFJanitor jout(ret);
198     auto_ptr<HTTPResponse> resp(getResponse(ret));
199
200     // Since we're remoted, the result should either be a throw, a false/0 return,
201     // which we just return as an empty structure, or a response/redirect,
202     // which we capture in the facade and send back.
203     processMessage(*app, hurl, in["entity_id"].string(), *resp.get());
204     out << ret;
205 }
206
207 pair<bool,long> MetadataGenerator::processMessage(
208     const Application& application, const char* handlerURL, const char* entityID, HTTPResponse& httpResponse
209     ) const
210 {
211 #ifndef SHIBSP_LITE
212     m_log.debug("processing metadata request");
213
214     const PropertySet* relyingParty=NULL;
215     if (entityID) {
216         MetadataProvider* m=application.getMetadataProvider();
217         Locker locker(m);
218         MetadataProviderCriteria mc(application, entityID);
219         relyingParty = application.getRelyingParty(m->getEntityDescriptor(mc).first);
220     }
221     else {
222         relyingParty = &application;
223     }
224
225     EntityDescriptor* entity;
226     pair<bool,const char*> prop = getString("template");
227     if (prop.first) {
228         // Load a template to use for our metadata.
229         LocalFileInputSource src(getXMLString("template").second);
230         Wrapper4InputSource dsrc(&src,false);
231         DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
232         XercesJanitor<DOMDocument> docjan(doc);
233         auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
234         docjan.release();
235         entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
236         if (!entity)
237             throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, prop.second));
238         xmlobj.release();
239     }
240     else {
241         entity = EntityDescriptorBuilder::buildEntityDescriptor();
242     }
243
244     auto_ptr<EntityDescriptor> wrapper(entity);
245     pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
246     if (cache.first) {
247         entity->setCacheDuration(cache.second);
248     }
249     else {
250         cache = getUnsignedInt("validUntil");
251         if (cache.first)
252             entity->setValidUntil(time(NULL) + cache.second);
253     }
254     entity->setEntityID(relyingParty->getXMLString("entityID").second);
255
256     SPSSODescriptor* role;
257     if (entity->getSPSSODescriptors().empty()) {
258         role = SPSSODescriptorBuilder::buildSPSSODescriptor();
259         entity->getSPSSODescriptors().push_back(role);
260     }
261     else {
262         role = entity->getSPSSODescriptors().front();
263     }
264
265     // Policy flags.
266     prop = relyingParty->getString("signing");
267     if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
268         role->AuthnRequestsSigned(true);
269     pair<bool,bool> flagprop = relyingParty->getBool("requireSignedAssertions");
270     if (flagprop.first && flagprop.second)
271         role->WantAssertionsSigned(true);
272
273     // Ask each handler to generate itself.
274     vector<const Handler*> handlers;
275     application.getHandlers(handlers);
276     for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
277         if (m_bases.empty()) {
278             if (strncmp(handlerURL, "https", 5) == 0) {
279                 if (m_https >= 0)
280                     (*h)->generateMetadata(*role, handlerURL);
281                 if (m_http == 1) {
282                     string temp(handlerURL);
283                     temp.erase(4, 1);
284                     (*h)->generateMetadata(*role, temp.c_str());
285                 }
286             }
287             else {
288                 if (m_http >= 0)
289                     (*h)->generateMetadata(*role, handlerURL);
290                 if (m_https == 1) {
291                     string temp(handlerURL);
292                     temp.insert(temp.begin() + 4, 's');
293                     (*h)->generateMetadata(*role, temp.c_str());
294                 }
295             }
296         }
297         else {
298             for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
299                 (*h)->generateMetadata(*role, b->c_str());
300         }
301     }
302
303     CredentialResolver* credResolver=application.getCredentialResolver();
304     if (credResolver) {
305         Locker credLocker(credResolver);
306         CredentialCriteria cc;
307         prop = relyingParty->getString("keyName");
308         if (prop.first)
309             cc.getKeyNames().insert(prop.second);
310         cc.setUsage(Credential::SIGNING_CREDENTIAL);
311         vector<const Credential*> creds;
312         credResolver->resolve(creds,&cc);
313         for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
314             KeyInfo* kinfo = (*c)->getKeyInfo();
315             if (kinfo) {
316                 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
317                 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
318                 kd->setKeyInfo(kinfo);
319                 role->getKeyDescriptors().push_back(kd);
320             }
321         }
322
323         cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
324         creds.clear();
325         credResolver->resolve(creds,&cc);
326         for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
327             KeyInfo* kinfo = (*c)->getKeyInfo();
328             if (kinfo) {
329                 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
330                 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
331                 kd->setKeyInfo(kinfo);
332                 role->getKeyDescriptors().push_back(kd);
333             }
334         }
335     }
336
337     // Stream for response.
338     stringstream s;
339
340     // Self-sign it?
341     pair<bool,bool> flag = getBool("signing");
342     if (flag.first && flag.second) {
343         if (credResolver) {
344             Locker credLocker(credResolver);
345             // Fill in criteria to use.
346             CredentialCriteria cc;
347             cc.setUsage(Credential::SIGNING_CREDENTIAL);
348             prop = getString("keyName");
349             if (prop.first)
350                 cc.getKeyNames().insert(prop.second);
351             pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
352             pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
353             if (sigalg.first)
354                 cc.setXMLAlgorithm(sigalg.second);
355             const Credential* cred = credResolver->resolve(&cc);
356             if (!cred)
357                 throw XMLSecurityException("Unable to obtain signing credential to use.");
358
359             // Pretty-print it first and then read it back in.
360             stringstream pretty;
361             XMLHelper::serialize(entity->marshall(), pretty, true);
362             DOMDocument* prettydoc = XMLToolingConfig::getConfig().getParser().parse(pretty);
363             auto_ptr<XMLObject> prettyentity(XMLObjectBuilder::buildOneFromElement(prettydoc->getDocumentElement(), true));
364
365             Signature* sig = SignatureBuilder::buildSignature();
366             dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
367             if (sigalg.first)
368                 sig->setSignatureAlgorithm(sigalg.second);
369             if (digalg.first) {
370                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
371                 if (cr)
372                     cr->setDigestAlgorithm(digalg.second);
373             }
374
375             // Sign while marshalling.
376             vector<Signature*> sigs(1,sig);
377             prettyentity->marshall(prettydoc,&sigs,cred);
378             s << *prettyentity;
379         }
380         else {
381             throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
382         }
383     }
384     else {
385         // Pretty-print it directly to client.
386         XMLHelper::serialize(entity->marshall(), s, true);
387     }
388
389     prop = getString("mimeType");
390     httpResponse.setContentType(prop.first ? prop.second : "application/samlmetadata+xml");
391     return make_pair(true, httpResponse.sendResponse(s));
392 #else
393     return make_pair(false,0L);
394 #endif
395 }