2 * Copyright 2001-2010 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * MetadataGenerator.cpp
20 * Handler for generating "approximate" metadata based on SP configuration.
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"
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>
50 using namespace shibsp;
52 using namespace opensaml::saml2md;
53 using namespace opensaml;
54 using namespace xmlsignature;
56 using namespace xmltooling;
61 #if defined (_MSC_VER)
62 #pragma warning( push )
63 #pragma warning( disable : 4250 )
66 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
69 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
74 acceptNode(const DOMNode* node) const {
79 static SHIBSP_DLLLOCAL Blocker g_Blocker;
81 class SHIBSP_API MetadataGenerator : public AbstractHandler, public RemotedHandler
84 MetadataGenerator(const DOMElement* e, const char* appId);
85 virtual ~MetadataGenerator() {}
87 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
88 void receive(DDF& in, ostream& out);
91 pair<bool,long> processMessage(
92 const Application& application,
93 const char* handlerURL,
95 HTTPResponse& httpResponse
101 short m_http,m_https;
102 vector<string> m_bases;
106 #if defined (_MSC_VER)
107 #pragma warning( pop )
110 Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
112 return new MetadataGenerator(p.first, p.second);
117 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
118 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
120 ,m_http(0), m_https(0)
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");
129 string aclbuf=acl.second;
131 for (unsigned int i=0; i < aclbuf.length(); i++) {
132 if (aclbuf.at(i)==' ') {
133 m_acl.insert(aclbuf.substr(j, i-j));
137 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
142 static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
144 pair<bool,const char*> salt = getString("salt");
146 m_salt = salt.second;
148 pair<bool,bool> flag = getBool("http");
150 m_http = flag.second ? 1 : -1;
151 flag = getBool("https");
153 m_https = flag.second ? 1 : -1;
155 e = XMLHelper::getFirstChildElement(e, EndpointBase);
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());
162 e = XMLHelper::getNextSiblingElement(e, EndpointBase);
167 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
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));
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);
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);
192 out=request.getServiceProvider().getListenerService()->send(in);
193 return unwrap(request, out);
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));
203 void MetadataGenerator::receive(DDF& in, ostream& out)
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;
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?");
215 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
218 // Wrap a response shim.
220 DDFJanitor jout(ret);
221 auto_ptr<HTTPResponse> resp(getResponse(ret));
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());
230 pair<bool,long> MetadataGenerator::processMessage(
231 const Application& application, const char* handlerURL, const char* entityID, HTTPResponse& httpResponse
235 m_log.debug("processing metadata request");
237 const PropertySet* relyingParty=nullptr;
239 MetadataProvider* m=application.getMetadataProvider();
241 MetadataProviderCriteria mc(application, entityID);
242 relyingParty = application.getRelyingParty(m->getEntityDescriptor(mc).first);
245 relyingParty = &application;
248 EntityDescriptor* entity;
249 pair<bool,const char*> prop = getString("template");
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));
261 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
263 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, templ.c_str()));
267 entity = EntityDescriptorBuilder::buildEntityDescriptor();
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());
277 auto_ptr<EntityDescriptor> wrapper(entity);
278 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
280 entity->setCacheDuration(cache.second);
282 cache = getUnsignedInt("validUntil");
284 entity->setValidUntil(time(nullptr) + cache.second);
285 entity->setEntityID(relyingParty->getXMLString("entityID").second);
287 SPSSODescriptor* role;
288 if (entity->getSPSSODescriptors().empty()) {
289 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
290 entity->getSPSSODescriptors().push_back(role);
293 role = entity->getSPSSODescriptors().front();
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);
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) {
311 (*h)->generateMetadata(*role, handlerURL);
313 string temp(handlerURL);
315 (*h)->generateMetadata(*role, temp.c_str());
320 (*h)->generateMetadata(*role, handlerURL);
322 string temp(handlerURL);
323 temp.insert(temp.begin() + 4, 's');
324 (*h)->generateMetadata(*role, temp.c_str());
329 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
330 (*h)->generateMetadata(*role, b->c_str());
334 CredentialResolver* credResolver=application.getCredentialResolver();
336 Locker credLocker(credResolver);
337 CredentialCriteria cc;
338 prop = relyingParty->getString("keyName");
340 cc.getKeyNames().insert(prop.second);
341 vector<const Credential*> signingcreds,enccreds;
342 cc.setUsage(Credential::SIGNING_CREDENTIAL);
343 credResolver->resolve(signingcreds, &cc);
344 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
345 credResolver->resolve(enccreds, &cc);
347 for (vector<const Credential*>::const_iterator c = signingcreds.begin(); c != signingcreds.end(); ++c) {
348 KeyInfo* kinfo = (*c)->getKeyInfo();
350 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
351 kd->setKeyInfo(kinfo);
352 const XMLCh* use = KeyDescriptor::KEYTYPE_SIGNING;
353 for (vector<const Credential*>::iterator match = enccreds.begin(); match != enccreds.end(); ++match) {
356 enccreds.erase(match);
361 role->getKeyDescriptors().push_back(kd);
365 for (vector<const Credential*>::const_iterator c = enccreds.begin(); c != enccreds.end(); ++c) {
366 KeyInfo* kinfo = (*c)->getKeyInfo();
368 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
369 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
370 kd->setKeyInfo(kinfo);
371 role->getKeyDescriptors().push_back(kd);
376 // Stream for response.
380 pair<bool,bool> flag = getBool("signing");
381 if (flag.first && flag.second) {
383 Locker credLocker(credResolver);
384 // Fill in criteria to use.
385 CredentialCriteria cc;
386 cc.setUsage(Credential::SIGNING_CREDENTIAL);
387 prop = getString("keyName");
389 cc.getKeyNames().insert(prop.second);
390 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
391 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
393 cc.setXMLAlgorithm(sigalg.second);
394 const Credential* cred = credResolver->resolve(&cc);
396 throw XMLSecurityException("Unable to obtain signing credential to use.");
398 // Pretty-print it first and then read it back in.
400 XMLHelper::serialize(entity->marshall(), pretty, true);
401 DOMDocument* prettydoc = XMLToolingConfig::getConfig().getParser().parse(pretty);
402 auto_ptr<XMLObject> prettyentity(XMLObjectBuilder::buildOneFromElement(prettydoc->getDocumentElement(), true));
404 Signature* sig = SignatureBuilder::buildSignature();
405 dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
407 sig->setSignatureAlgorithm(sigalg.second);
409 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
411 cr->setDigestAlgorithm(digalg.second);
414 // Sign while marshalling.
415 vector<Signature*> sigs(1,sig);
416 prettyentity->marshall(prettydoc,&sigs,cred);
420 throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
424 // Pretty-print it directly to client.
425 XMLHelper::serialize(entity->marshall(), s, true);
428 prop = getString("mimeType");
429 httpResponse.setContentType(prop.first ? prop.second : "application/samlmetadata+xml");
430 return make_pair(true, httpResponse.sendResponse(s));
432 return make_pair(false,0L);