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 "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/signature/ContentReference.h>
35 # include <saml/saml2/metadata/Metadata.h>
36 # include <saml/saml2/metadata/MetadataProvider.h>
37 # include <xmltooling/XMLToolingConfig.h>
38 # include <xmltooling/security/Credential.h>
39 # include <xmltooling/security/CredentialCriteria.h>
40 # include <xmltooling/signature/Signature.h>
41 # include <xmltooling/util/PathResolver.h>
44 #include <xercesc/framework/LocalFileInputSource.hpp>
45 #include <xercesc/framework/Wrapper4InputSource.hpp>
47 using namespace shibsp;
49 using namespace opensaml::saml2md;
50 using namespace opensaml;
51 using namespace xmlsignature;
53 using namespace xmltooling;
58 #if defined (_MSC_VER)
59 #pragma warning( push )
60 #pragma warning( disable : 4250 )
63 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
66 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
71 acceptNode(const DOMNode* node) const {
76 static SHIBSP_DLLLOCAL Blocker g_Blocker;
78 class SHIBSP_API MetadataGenerator : public AbstractHandler, public RemotedHandler
81 MetadataGenerator(const DOMElement* e, const char* appId);
82 virtual ~MetadataGenerator() {}
84 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
85 void receive(DDF& in, ostream& out);
88 pair<bool,long> processMessage(
89 const Application& application,
90 const char* handlerURL,
92 HTTPResponse& httpResponse
98 vector<string> m_bases;
102 #if defined (_MSC_VER)
103 #pragma warning( pop )
106 Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
108 return new MetadataGenerator(p.first, p.second);
113 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
114 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
116 ,m_http(0), m_https(0)
119 string address(appId);
120 address += getString("Location").second;
121 setAddress(address.c_str());
122 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
123 pair<bool,const char*> acl = getString("acl");
125 string aclbuf=acl.second;
127 for (unsigned int i=0; i < aclbuf.length(); i++) {
128 if (aclbuf.at(i)==' ') {
129 m_acl.insert(aclbuf.substr(j, i-j));
133 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
138 static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
140 pair<bool,bool> flag = getBool("http");
142 m_http = flag.second ? 1 : -1;
143 flag = getBool("https");
145 m_https = flag.second ? 1 : -1;
147 e = XMLHelper::getFirstChildElement(e, EndpointBase);
149 if (e->hasChildNodes()) {
150 auto_ptr_char base(e->getFirstChild()->getNodeValue());
151 if (base.get() && *base.get())
152 m_bases.push_back(base.get());
154 e = XMLHelper::getNextSiblingElement(e, EndpointBase);
159 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
161 SPConfig& conf = SPConfig::getConfig();
162 if (conf.isEnabled(SPConfig::InProcess)) {
163 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
164 m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
165 istringstream msg("Metadata Request Blocked");
166 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
171 if (conf.isEnabled(SPConfig::OutOfProcess)) {
172 // When out of process, we run natively and directly process the message.
173 return processMessage(request.getApplication(), request.getHandlerURL(), request.getParameter("entityID"), request);
176 // When not out of process, we remote all the message processing.
177 DDF out,in = DDF(m_address.c_str());
178 in.addmember("application_id").string(request.getApplication().getId());
179 in.addmember("handler_url").string(request.getHandlerURL());
180 if (request.getParameter("entityID"))
181 in.addmember("entity_id").string(request.getParameter("entityID"));
182 DDFJanitor jin(in), jout(out);
184 out=request.getServiceProvider().getListenerService()->send(in);
185 return unwrap(request, out);
188 catch (exception& ex) {
189 m_log.error("error while processing request: %s", ex.what());
190 istringstream msg("Metadata Request Failed");
191 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
195 void MetadataGenerator::receive(DDF& in, ostream& out)
198 const char* aid=in["application_id"].string();
199 const char* hurl=in["handler_url"].string();
200 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
202 // Something's horribly wrong.
203 m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
204 throw ConfigurationException("Unable to locate application for metadata request, deleted?");
207 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
210 // Wrap a response shim.
212 DDFJanitor jout(ret);
213 auto_ptr<HTTPResponse> resp(getResponse(ret));
215 // Since we're remoted, the result should either be a throw, a false/0 return,
216 // which we just return as an empty structure, or a response/redirect,
217 // which we capture in the facade and send back.
218 processMessage(*app, hurl, in["entity_id"].string(), *resp.get());
222 pair<bool,long> MetadataGenerator::processMessage(
223 const Application& application, const char* handlerURL, const char* entityID, HTTPResponse& httpResponse
227 m_log.debug("processing metadata request");
229 const PropertySet* relyingParty=NULL;
231 MetadataProvider* m=application.getMetadataProvider();
233 MetadataProviderCriteria mc(application, entityID);
234 relyingParty = application.getRelyingParty(m->getEntityDescriptor(mc).first);
237 relyingParty = &application;
240 EntityDescriptor* entity;
241 pair<bool,const char*> prop = getString("template");
243 // Load a template to use for our metadata.
244 string templ(prop.second);
245 XMLToolingConfig::getConfig().getPathResolver()->resolve(templ, PathResolver::XMLTOOLING_CFG_FILE);
246 auto_ptr_XMLCh widenit(templ.c_str());
247 LocalFileInputSource src(widenit.get());
248 Wrapper4InputSource dsrc(&src,false);
249 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
250 XercesJanitor<DOMDocument> docjan(doc);
251 auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
253 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
255 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, templ.c_str()));
259 entity = EntityDescriptorBuilder::buildEntityDescriptor();
262 auto_ptr<EntityDescriptor> wrapper(entity);
263 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
265 entity->setCacheDuration(cache.second);
268 cache = getUnsignedInt("validUntil");
270 entity->setValidUntil(time(NULL) + cache.second);
272 entity->setEntityID(relyingParty->getXMLString("entityID").second);
274 SPSSODescriptor* role;
275 if (entity->getSPSSODescriptors().empty()) {
276 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
277 entity->getSPSSODescriptors().push_back(role);
280 role = entity->getSPSSODescriptors().front();
284 prop = relyingParty->getString("signing");
285 if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
286 role->AuthnRequestsSigned(true);
287 pair<bool,bool> flagprop = relyingParty->getBool("requireSignedAssertions");
288 if (flagprop.first && flagprop.second)
289 role->WantAssertionsSigned(true);
291 // Ask each handler to generate itself.
292 vector<const Handler*> handlers;
293 application.getHandlers(handlers);
294 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
295 if (m_bases.empty()) {
296 if (strncmp(handlerURL, "https", 5) == 0) {
298 (*h)->generateMetadata(*role, handlerURL);
300 string temp(handlerURL);
302 (*h)->generateMetadata(*role, temp.c_str());
307 (*h)->generateMetadata(*role, handlerURL);
309 string temp(handlerURL);
310 temp.insert(temp.begin() + 4, 's');
311 (*h)->generateMetadata(*role, temp.c_str());
316 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
317 (*h)->generateMetadata(*role, b->c_str());
321 CredentialResolver* credResolver=application.getCredentialResolver();
323 Locker credLocker(credResolver);
324 CredentialCriteria cc;
325 prop = relyingParty->getString("keyName");
327 cc.getKeyNames().insert(prop.second);
328 cc.setUsage(Credential::SIGNING_CREDENTIAL);
329 vector<const Credential*> creds;
330 credResolver->resolve(creds,&cc);
331 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
332 KeyInfo* kinfo = (*c)->getKeyInfo();
334 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
335 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
336 kd->setKeyInfo(kinfo);
337 role->getKeyDescriptors().push_back(kd);
341 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
343 credResolver->resolve(creds,&cc);
344 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
345 KeyInfo* kinfo = (*c)->getKeyInfo();
347 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
348 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
349 kd->setKeyInfo(kinfo);
350 role->getKeyDescriptors().push_back(kd);
355 // Stream for response.
359 pair<bool,bool> flag = getBool("signing");
360 if (flag.first && flag.second) {
362 Locker credLocker(credResolver);
363 // Fill in criteria to use.
364 CredentialCriteria cc;
365 cc.setUsage(Credential::SIGNING_CREDENTIAL);
366 prop = getString("keyName");
368 cc.getKeyNames().insert(prop.second);
369 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
370 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
372 cc.setXMLAlgorithm(sigalg.second);
373 const Credential* cred = credResolver->resolve(&cc);
375 throw XMLSecurityException("Unable to obtain signing credential to use.");
377 // Pretty-print it first and then read it back in.
379 XMLHelper::serialize(entity->marshall(), pretty, true);
380 DOMDocument* prettydoc = XMLToolingConfig::getConfig().getParser().parse(pretty);
381 auto_ptr<XMLObject> prettyentity(XMLObjectBuilder::buildOneFromElement(prettydoc->getDocumentElement(), true));
383 Signature* sig = SignatureBuilder::buildSignature();
384 dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
386 sig->setSignatureAlgorithm(sigalg.second);
388 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
390 cr->setDigestAlgorithm(digalg.second);
393 // Sign while marshalling.
394 vector<Signature*> sigs(1,sig);
395 prettyentity->marshall(prettydoc,&sigs,cred);
399 throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
403 // Pretty-print it directly to client.
404 XMLHelper::serialize(entity->marshall(), s, true);
407 prop = getString("mimeType");
408 httpResponse.setContentType(prop.first ? prop.second : "application/samlmetadata+xml");
409 return make_pair(true, httpResponse.sendResponse(s));
411 return make_pair(false,0L);