2 * Copyright 2001-2007 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 "handler/AbstractHandler.h"
28 #include "handler/RemotedHandler.h"
31 # include "metadata/MetadataProviderCriteria.h"
32 # include <xmltooling/util/PathResolver.h>
35 #include <xercesc/framework/LocalFileInputSource.hpp>
36 #include <xercesc/framework/Wrapper4InputSource.hpp>
38 using namespace shibsp;
40 using namespace opensaml::saml2md;
41 using namespace opensaml;
42 using namespace xmlsignature;
44 using namespace xmltooling;
49 #if defined (_MSC_VER)
50 #pragma warning( push )
51 #pragma warning( disable : 4250 )
54 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
57 short acceptNode(const DOMNode* node) const {
62 static SHIBSP_DLLLOCAL Blocker g_Blocker;
64 class SHIBSP_API MetadataGenerator : public AbstractHandler, public RemotedHandler
67 MetadataGenerator(const DOMElement* e, const char* appId);
68 virtual ~MetadataGenerator() {}
70 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
71 void receive(DDF& in, ostream& out);
74 pair<bool,long> processMessage(
75 const Application& application,
76 const char* handlerURL,
78 HTTPResponse& httpResponse
84 vector<string> m_bases;
88 #if defined (_MSC_VER)
89 #pragma warning( pop )
92 Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
94 return new MetadataGenerator(p.first, p.second);
99 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
100 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
102 ,m_http(0), m_https(0)
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");
111 string aclbuf=acl.second;
113 for (unsigned int i=0; i < aclbuf.length(); i++) {
114 if (aclbuf.at(i)==' ') {
115 m_acl.insert(aclbuf.substr(j, i-j));
119 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
124 static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
126 pair<bool,bool> flag = getBool("http");
128 m_http = flag.second ? 1 : -1;
129 flag = getBool("https");
131 m_https = flag.second ? 1 : -1;
133 e = XMLHelper::getFirstChildElement(e, EndpointBase);
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());
140 e = XMLHelper::getNextSiblingElement(e, EndpointBase);
145 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
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));
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);
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);
170 out=request.getServiceProvider().getListenerService()->send(in);
171 return unwrap(request, out);
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));
181 void MetadataGenerator::receive(DDF& in, ostream& out)
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;
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?");
193 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
196 // Wrap a response shim.
198 DDFJanitor jout(ret);
199 auto_ptr<HTTPResponse> resp(getResponse(ret));
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());
208 pair<bool,long> MetadataGenerator::processMessage(
209 const Application& application, const char* handlerURL, const char* entityID, HTTPResponse& httpResponse
213 m_log.debug("processing metadata request");
215 const PropertySet* relyingParty=NULL;
217 MetadataProvider* m=application.getMetadataProvider();
219 MetadataProviderCriteria mc(application, entityID);
220 relyingParty = application.getRelyingParty(m->getEntityDescriptor(mc).first);
223 relyingParty = &application;
226 EntityDescriptor* entity;
227 pair<bool,const char*> prop = getString("template");
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));
239 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
241 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, templ.c_str()));
245 entity = EntityDescriptorBuilder::buildEntityDescriptor();
248 auto_ptr<EntityDescriptor> wrapper(entity);
249 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
251 entity->setCacheDuration(cache.second);
254 cache = getUnsignedInt("validUntil");
256 entity->setValidUntil(time(NULL) + cache.second);
258 entity->setEntityID(relyingParty->getXMLString("entityID").second);
260 SPSSODescriptor* role;
261 if (entity->getSPSSODescriptors().empty()) {
262 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
263 entity->getSPSSODescriptors().push_back(role);
266 role = entity->getSPSSODescriptors().front();
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);
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) {
284 (*h)->generateMetadata(*role, handlerURL);
286 string temp(handlerURL);
288 (*h)->generateMetadata(*role, temp.c_str());
293 (*h)->generateMetadata(*role, handlerURL);
295 string temp(handlerURL);
296 temp.insert(temp.begin() + 4, 's');
297 (*h)->generateMetadata(*role, temp.c_str());
302 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
303 (*h)->generateMetadata(*role, b->c_str());
307 CredentialResolver* credResolver=application.getCredentialResolver();
309 Locker credLocker(credResolver);
310 CredentialCriteria cc;
311 prop = relyingParty->getString("keyName");
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();
320 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
321 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
322 kd->setKeyInfo(kinfo);
323 role->getKeyDescriptors().push_back(kd);
327 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
329 credResolver->resolve(creds,&cc);
330 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
331 KeyInfo* kinfo = (*c)->getKeyInfo();
333 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
334 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
335 kd->setKeyInfo(kinfo);
336 role->getKeyDescriptors().push_back(kd);
341 // Stream for response.
345 pair<bool,bool> flag = getBool("signing");
346 if (flag.first && flag.second) {
348 Locker credLocker(credResolver);
349 // Fill in criteria to use.
350 CredentialCriteria cc;
351 cc.setUsage(Credential::SIGNING_CREDENTIAL);
352 prop = getString("keyName");
354 cc.getKeyNames().insert(prop.second);
355 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
356 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
358 cc.setXMLAlgorithm(sigalg.second);
359 const Credential* cred = credResolver->resolve(&cc);
361 throw XMLSecurityException("Unable to obtain signing credential to use.");
363 // Pretty-print it first and then read it back in.
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));
369 Signature* sig = SignatureBuilder::buildSignature();
370 dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
372 sig->setSignatureAlgorithm(sigalg.second);
374 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
376 cr->setDigestAlgorithm(digalg.second);
379 // Sign while marshalling.
380 vector<Signature*> sigs(1,sig);
381 prettyentity->marshall(prettydoc,&sigs,cred);
385 throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
389 // Pretty-print it directly to client.
390 XMLHelper::serialize(entity->marshall(), s, true);
393 prop = getString("mimeType");
394 httpResponse.setContentType(prop.first ? prop.second : "application/samlmetadata+xml");
395 return make_pair(true, httpResponse.sendResponse(s));
397 return make_pair(false,0L);