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