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