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/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/signature/Signature.h>
42 # include <xmltooling/util/ParserPool.h>
43 # include <xmltooling/util/PathResolver.h>
44 # include <xercesc/framework/LocalFileInputSource.hpp>
45 # include <xercesc/framework/Wrapper4InputSource.hpp>
49 using namespace shibsp;
51 using namespace opensaml::saml2md;
52 using namespace opensaml;
53 using namespace xmlsignature;
55 using namespace xmltooling;
60 #if defined (_MSC_VER)
61 #pragma warning( push )
62 #pragma warning( disable : 4250 )
65 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
68 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
73 acceptNode(const DOMNode* node) const {
78 static SHIBSP_DLLLOCAL Blocker g_Blocker;
80 class SHIBSP_API MetadataGenerator : public AbstractHandler, public RemotedHandler
83 MetadataGenerator(const DOMElement* e, const char* appId);
84 virtual ~MetadataGenerator() {}
86 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
87 void receive(DDF& in, ostream& out);
90 pair<bool,long> processMessage(
91 const Application& application,
92 const char* handlerURL,
94 HTTPResponse& httpResponse
100 vector<string> m_bases;
104 #if defined (_MSC_VER)
105 #pragma warning( pop )
108 Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
110 return new MetadataGenerator(p.first, p.second);
115 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
116 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
118 ,m_http(0), m_https(0)
121 string address(appId);
122 address += getString("Location").second;
123 setAddress(address.c_str());
124 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
125 pair<bool,const char*> acl = getString("acl");
127 string aclbuf=acl.second;
129 for (unsigned int i=0; i < aclbuf.length(); i++) {
130 if (aclbuf.at(i)==' ') {
131 m_acl.insert(aclbuf.substr(j, i-j));
135 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
140 static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
142 pair<bool,bool> flag = getBool("http");
144 m_http = flag.second ? 1 : -1;
145 flag = getBool("https");
147 m_https = flag.second ? 1 : -1;
149 e = XMLHelper::getFirstChildElement(e, EndpointBase);
151 if (e->hasChildNodes()) {
152 auto_ptr_char base(e->getFirstChild()->getNodeValue());
153 if (base.get() && *base.get())
154 m_bases.push_back(base.get());
156 e = XMLHelper::getNextSiblingElement(e, EndpointBase);
161 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
163 SPConfig& conf = SPConfig::getConfig();
164 if (conf.isEnabled(SPConfig::InProcess)) {
165 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
166 m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
167 istringstream msg("Metadata Request Blocked");
168 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
173 if (conf.isEnabled(SPConfig::OutOfProcess)) {
174 // When out of process, we run natively and directly process the message.
175 return processMessage(request.getApplication(), request.getHandlerURL(), request.getParameter("entityID"), request);
178 // When not out of process, we remote all the message processing.
179 DDF out,in = DDF(m_address.c_str());
180 in.addmember("application_id").string(request.getApplication().getId());
181 in.addmember("handler_url").string(request.getHandlerURL());
182 if (request.getParameter("entityID"))
183 in.addmember("entity_id").string(request.getParameter("entityID"));
184 DDFJanitor jin(in), jout(out);
186 out=request.getServiceProvider().getListenerService()->send(in);
187 return unwrap(request, out);
190 catch (exception& ex) {
191 m_log.error("error while processing request: %s", ex.what());
192 istringstream msg("Metadata Request Failed");
193 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
197 void MetadataGenerator::receive(DDF& in, ostream& out)
200 const char* aid=in["application_id"].string();
201 const char* hurl=in["handler_url"].string();
202 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
204 // Something's horribly wrong.
205 m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
206 throw ConfigurationException("Unable to locate application for metadata request, deleted?");
209 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
212 // Wrap a response shim.
214 DDFJanitor jout(ret);
215 auto_ptr<HTTPResponse> resp(getResponse(ret));
217 // Since we're remoted, the result should either be a throw, a false/0 return,
218 // which we just return as an empty structure, or a response/redirect,
219 // which we capture in the facade and send back.
220 processMessage(*app, hurl, in["entity_id"].string(), *resp.get());
224 pair<bool,long> MetadataGenerator::processMessage(
225 const Application& application, const char* handlerURL, const char* entityID, HTTPResponse& httpResponse
229 m_log.debug("processing metadata request");
231 const PropertySet* relyingParty=NULL;
233 MetadataProvider* m=application.getMetadataProvider();
235 MetadataProviderCriteria mc(application, entityID);
236 relyingParty = application.getRelyingParty(m->getEntityDescriptor(mc).first);
239 relyingParty = &application;
242 EntityDescriptor* entity;
243 pair<bool,const char*> prop = getString("template");
245 // Load a template to use for our metadata.
246 string templ(prop.second);
247 XMLToolingConfig::getConfig().getPathResolver()->resolve(templ, PathResolver::XMLTOOLING_CFG_FILE);
248 auto_ptr_XMLCh widenit(templ.c_str());
249 LocalFileInputSource src(widenit.get());
250 Wrapper4InputSource dsrc(&src,false);
251 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
252 XercesJanitor<DOMDocument> docjan(doc);
253 auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
255 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
257 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, templ.c_str()));
261 entity = EntityDescriptorBuilder::buildEntityDescriptor();
264 if (!entity->getID())
265 entity->setID(SAMLConfig::getConfig().generateIdentifier());
267 auto_ptr<EntityDescriptor> wrapper(entity);
268 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
270 entity->setCacheDuration(cache.second);
273 cache = getUnsignedInt("validUntil");
275 entity->setValidUntil(time(NULL) + cache.second);
277 entity->setEntityID(relyingParty->getXMLString("entityID").second);
279 SPSSODescriptor* role;
280 if (entity->getSPSSODescriptors().empty()) {
281 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
282 entity->getSPSSODescriptors().push_back(role);
285 role = entity->getSPSSODescriptors().front();
289 prop = relyingParty->getString("signing");
290 if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
291 role->AuthnRequestsSigned(true);
292 pair<bool,bool> flagprop = relyingParty->getBool("requireSignedAssertions");
293 if (flagprop.first && flagprop.second)
294 role->WantAssertionsSigned(true);
296 // Ask each handler to generate itself.
297 vector<const Handler*> handlers;
298 application.getHandlers(handlers);
299 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
300 if (m_bases.empty()) {
301 if (strncmp(handlerURL, "https", 5) == 0) {
303 (*h)->generateMetadata(*role, handlerURL);
305 string temp(handlerURL);
307 (*h)->generateMetadata(*role, temp.c_str());
312 (*h)->generateMetadata(*role, handlerURL);
314 string temp(handlerURL);
315 temp.insert(temp.begin() + 4, 's');
316 (*h)->generateMetadata(*role, temp.c_str());
321 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
322 (*h)->generateMetadata(*role, b->c_str());
326 CredentialResolver* credResolver=application.getCredentialResolver();
328 Locker credLocker(credResolver);
329 CredentialCriteria cc;
330 prop = relyingParty->getString("keyName");
332 cc.getKeyNames().insert(prop.second);
333 cc.setUsage(Credential::SIGNING_CREDENTIAL);
334 vector<const Credential*> creds;
335 credResolver->resolve(creds,&cc);
336 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
337 KeyInfo* kinfo = (*c)->getKeyInfo();
339 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
340 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
341 kd->setKeyInfo(kinfo);
342 role->getKeyDescriptors().push_back(kd);
346 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
348 credResolver->resolve(creds,&cc);
349 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
350 KeyInfo* kinfo = (*c)->getKeyInfo();
352 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
353 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
354 kd->setKeyInfo(kinfo);
355 role->getKeyDescriptors().push_back(kd);
360 // Stream for response.
364 pair<bool,bool> flag = getBool("signing");
365 if (flag.first && flag.second) {
367 Locker credLocker(credResolver);
368 // Fill in criteria to use.
369 CredentialCriteria cc;
370 cc.setUsage(Credential::SIGNING_CREDENTIAL);
371 prop = getString("keyName");
373 cc.getKeyNames().insert(prop.second);
374 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
375 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
377 cc.setXMLAlgorithm(sigalg.second);
378 const Credential* cred = credResolver->resolve(&cc);
380 throw XMLSecurityException("Unable to obtain signing credential to use.");
382 // Pretty-print it first and then read it back in.
384 XMLHelper::serialize(entity->marshall(), pretty, true);
385 DOMDocument* prettydoc = XMLToolingConfig::getConfig().getParser().parse(pretty);
386 auto_ptr<XMLObject> prettyentity(XMLObjectBuilder::buildOneFromElement(prettydoc->getDocumentElement(), true));
388 Signature* sig = SignatureBuilder::buildSignature();
389 dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
391 sig->setSignatureAlgorithm(sigalg.second);
393 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
395 cr->setDigestAlgorithm(digalg.second);
398 // Sign while marshalling.
399 vector<Signature*> sigs(1,sig);
400 prettyentity->marshall(prettydoc,&sigs,cred);
404 throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
408 // Pretty-print it directly to client.
409 XMLHelper::serialize(entity->marshall(), s, true);
412 prop = getString("mimeType");
413 httpResponse.setContentType(prop.first ? prop.second : "application/samlmetadata+xml");
414 return make_pair(true, httpResponse.sendResponse(s));
416 return make_pair(false,0L);