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