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