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