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