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