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 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
62 acceptNode(const DOMNode* node) const {
67 static SHIBSP_DLLLOCAL Blocker g_Blocker;
69 class SHIBSP_API MetadataGenerator : public AbstractHandler, public RemotedHandler
72 MetadataGenerator(const DOMElement* e, const char* appId);
73 virtual ~MetadataGenerator() {}
75 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
76 void receive(DDF& in, ostream& out);
79 pair<bool,long> processMessage(
80 const Application& application,
81 const char* handlerURL,
83 HTTPResponse& httpResponse
89 vector<string> m_bases;
93 #if defined (_MSC_VER)
94 #pragma warning( pop )
97 Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
99 return new MetadataGenerator(p.first, p.second);
104 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
105 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
107 ,m_http(0), m_https(0)
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");
116 string aclbuf=acl.second;
118 for (unsigned int i=0; i < aclbuf.length(); i++) {
119 if (aclbuf.at(i)==' ') {
120 m_acl.insert(aclbuf.substr(j, i-j));
124 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
129 static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
131 pair<bool,bool> flag = getBool("http");
133 m_http = flag.second ? 1 : -1;
134 flag = getBool("https");
136 m_https = flag.second ? 1 : -1;
138 e = XMLHelper::getFirstChildElement(e, EndpointBase);
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());
145 e = XMLHelper::getNextSiblingElement(e, EndpointBase);
150 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
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));
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);
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);
175 out=request.getServiceProvider().getListenerService()->send(in);
176 return unwrap(request, out);
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));
186 void MetadataGenerator::receive(DDF& in, ostream& out)
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;
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?");
198 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
201 // Wrap a response shim.
203 DDFJanitor jout(ret);
204 auto_ptr<HTTPResponse> resp(getResponse(ret));
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());
213 pair<bool,long> MetadataGenerator::processMessage(
214 const Application& application, const char* handlerURL, const char* entityID, HTTPResponse& httpResponse
218 m_log.debug("processing metadata request");
220 const PropertySet* relyingParty=NULL;
222 MetadataProvider* m=application.getMetadataProvider();
224 MetadataProviderCriteria mc(application, entityID);
225 relyingParty = application.getRelyingParty(m->getEntityDescriptor(mc).first);
228 relyingParty = &application;
231 EntityDescriptor* entity;
232 pair<bool,const char*> prop = getString("template");
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));
244 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
246 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, templ.c_str()));
250 entity = EntityDescriptorBuilder::buildEntityDescriptor();
253 auto_ptr<EntityDescriptor> wrapper(entity);
254 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
256 entity->setCacheDuration(cache.second);
259 cache = getUnsignedInt("validUntil");
261 entity->setValidUntil(time(NULL) + cache.second);
263 entity->setEntityID(relyingParty->getXMLString("entityID").second);
265 SPSSODescriptor* role;
266 if (entity->getSPSSODescriptors().empty()) {
267 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
268 entity->getSPSSODescriptors().push_back(role);
271 role = entity->getSPSSODescriptors().front();
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);
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) {
289 (*h)->generateMetadata(*role, handlerURL);
291 string temp(handlerURL);
293 (*h)->generateMetadata(*role, temp.c_str());
298 (*h)->generateMetadata(*role, handlerURL);
300 string temp(handlerURL);
301 temp.insert(temp.begin() + 4, 's');
302 (*h)->generateMetadata(*role, temp.c_str());
307 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
308 (*h)->generateMetadata(*role, b->c_str());
312 CredentialResolver* credResolver=application.getCredentialResolver();
314 Locker credLocker(credResolver);
315 CredentialCriteria cc;
316 prop = relyingParty->getString("keyName");
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();
325 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
326 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
327 kd->setKeyInfo(kinfo);
328 role->getKeyDescriptors().push_back(kd);
332 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
334 credResolver->resolve(creds,&cc);
335 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
336 KeyInfo* kinfo = (*c)->getKeyInfo();
338 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
339 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
340 kd->setKeyInfo(kinfo);
341 role->getKeyDescriptors().push_back(kd);
346 // Stream for response.
350 pair<bool,bool> flag = getBool("signing");
351 if (flag.first && flag.second) {
353 Locker credLocker(credResolver);
354 // Fill in criteria to use.
355 CredentialCriteria cc;
356 cc.setUsage(Credential::SIGNING_CREDENTIAL);
357 prop = getString("keyName");
359 cc.getKeyNames().insert(prop.second);
360 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
361 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
363 cc.setXMLAlgorithm(sigalg.second);
364 const Credential* cred = credResolver->resolve(&cc);
366 throw XMLSecurityException("Unable to obtain signing credential to use.");
368 // Pretty-print it first and then read it back in.
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));
374 Signature* sig = SignatureBuilder::buildSignature();
375 dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
377 sig->setSignatureAlgorithm(sigalg.second);
379 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
381 cr->setDigestAlgorithm(digalg.second);
384 // Sign while marshalling.
385 vector<Signature*> sigs(1,sig);
386 prettyentity->marshall(prettydoc,&sigs,cred);
390 throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
394 // Pretty-print it directly to client.
395 XMLHelper::serialize(entity->marshall(), s, true);
398 prop = getString("mimeType");
399 httpResponse.setContentType(prop.first ? prop.second : "application/samlmetadata+xml");
400 return make_pair(true, httpResponse.sendResponse(s));
402 return make_pair(false,0L);