2 * Copyright 2001-2009 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/XMLToolingConfig.h>
33 # include <xmltooling/security/Credential.h>
34 # include <xmltooling/util/PathResolver.h>
37 #include <xercesc/framework/LocalFileInputSource.hpp>
38 #include <xercesc/framework/Wrapper4InputSource.hpp>
40 using namespace shibsp;
42 using namespace opensaml::saml2md;
43 using namespace opensaml;
44 using namespace xmlsignature;
46 using namespace xmltooling;
51 #if defined (_MSC_VER)
52 #pragma warning( push )
53 #pragma warning( disable : 4250 )
56 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
59 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
64 acceptNode(const DOMNode* node) const {
69 static SHIBSP_DLLLOCAL Blocker g_Blocker;
71 class SHIBSP_API MetadataGenerator : public AbstractHandler, public RemotedHandler
74 MetadataGenerator(const DOMElement* e, const char* appId);
75 virtual ~MetadataGenerator() {}
77 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
78 void receive(DDF& in, ostream& out);
81 pair<bool,long> processMessage(
82 const Application& application,
83 const char* handlerURL,
85 HTTPResponse& httpResponse
91 vector<string> m_bases;
95 #if defined (_MSC_VER)
96 #pragma warning( pop )
99 Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
101 return new MetadataGenerator(p.first, p.second);
106 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
107 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
109 ,m_http(0), m_https(0)
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");
118 string aclbuf=acl.second;
120 for (unsigned int i=0; i < aclbuf.length(); i++) {
121 if (aclbuf.at(i)==' ') {
122 m_acl.insert(aclbuf.substr(j, i-j));
126 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
131 static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
133 pair<bool,bool> flag = getBool("http");
135 m_http = flag.second ? 1 : -1;
136 flag = getBool("https");
138 m_https = flag.second ? 1 : -1;
140 e = XMLHelper::getFirstChildElement(e, EndpointBase);
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());
147 e = XMLHelper::getNextSiblingElement(e, EndpointBase);
152 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
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));
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);
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);
177 out=request.getServiceProvider().getListenerService()->send(in);
178 return unwrap(request, out);
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));
188 void MetadataGenerator::receive(DDF& in, ostream& out)
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;
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?");
200 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
203 // Wrap a response shim.
205 DDFJanitor jout(ret);
206 auto_ptr<HTTPResponse> resp(getResponse(ret));
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());
215 pair<bool,long> MetadataGenerator::processMessage(
216 const Application& application, const char* handlerURL, const char* entityID, HTTPResponse& httpResponse
220 m_log.debug("processing metadata request");
222 const PropertySet* relyingParty=NULL;
224 MetadataProvider* m=application.getMetadataProvider();
226 MetadataProviderCriteria mc(application, entityID);
227 relyingParty = application.getRelyingParty(m->getEntityDescriptor(mc).first);
230 relyingParty = &application;
233 EntityDescriptor* entity;
234 pair<bool,const char*> prop = getString("template");
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));
246 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
248 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, templ.c_str()));
252 entity = EntityDescriptorBuilder::buildEntityDescriptor();
255 auto_ptr<EntityDescriptor> wrapper(entity);
256 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
258 entity->setCacheDuration(cache.second);
261 cache = getUnsignedInt("validUntil");
263 entity->setValidUntil(time(NULL) + cache.second);
265 entity->setEntityID(relyingParty->getXMLString("entityID").second);
267 SPSSODescriptor* role;
268 if (entity->getSPSSODescriptors().empty()) {
269 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
270 entity->getSPSSODescriptors().push_back(role);
273 role = entity->getSPSSODescriptors().front();
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);
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) {
291 (*h)->generateMetadata(*role, handlerURL);
293 string temp(handlerURL);
295 (*h)->generateMetadata(*role, temp.c_str());
300 (*h)->generateMetadata(*role, handlerURL);
302 string temp(handlerURL);
303 temp.insert(temp.begin() + 4, 's');
304 (*h)->generateMetadata(*role, temp.c_str());
309 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
310 (*h)->generateMetadata(*role, b->c_str());
314 CredentialResolver* credResolver=application.getCredentialResolver();
316 Locker credLocker(credResolver);
317 CredentialCriteria cc;
318 prop = relyingParty->getString("keyName");
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();
327 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
328 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
329 kd->setKeyInfo(kinfo);
330 role->getKeyDescriptors().push_back(kd);
334 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
336 credResolver->resolve(creds,&cc);
337 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
338 KeyInfo* kinfo = (*c)->getKeyInfo();
340 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
341 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
342 kd->setKeyInfo(kinfo);
343 role->getKeyDescriptors().push_back(kd);
348 // Stream for response.
352 pair<bool,bool> flag = getBool("signing");
353 if (flag.first && flag.second) {
355 Locker credLocker(credResolver);
356 // Fill in criteria to use.
357 CredentialCriteria cc;
358 cc.setUsage(Credential::SIGNING_CREDENTIAL);
359 prop = getString("keyName");
361 cc.getKeyNames().insert(prop.second);
362 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
363 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
365 cc.setXMLAlgorithm(sigalg.second);
366 const Credential* cred = credResolver->resolve(&cc);
368 throw XMLSecurityException("Unable to obtain signing credential to use.");
370 // Pretty-print it first and then read it back in.
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));
376 Signature* sig = SignatureBuilder::buildSignature();
377 dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
379 sig->setSignatureAlgorithm(sigalg.second);
381 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
383 cr->setDigestAlgorithm(digalg.second);
386 // Sign while marshalling.
387 vector<Signature*> sigs(1,sig);
388 prettyentity->marshall(prettydoc,&sigs,cred);
392 throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
396 // Pretty-print it directly to client.
397 XMLHelper::serialize(entity->marshall(), s, true);
400 prop = getString("mimeType");
401 httpResponse.setContentType(prop.first ? prop.second : "application/samlmetadata+xml");
402 return make_pair(true, httpResponse.sendResponse(s));
404 return make_pair(false,0L);