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 <saml/signature/ContentReference.h>
33 # include <xmltooling/XMLToolingConfig.h>
34 # include <xmltooling/security/Credential.h>
35 # include <xmltooling/security/CredentialCriteria.h>
36 # include <xmltooling/signature/Signature.h>
37 # include <xmltooling/util/PathResolver.h>
40 #include <xercesc/framework/LocalFileInputSource.hpp>
41 #include <xercesc/framework/Wrapper4InputSource.hpp>
43 using namespace shibsp;
45 using namespace opensaml::saml2md;
46 using namespace opensaml;
47 using namespace xmlsignature;
49 using namespace xmltooling;
54 #if defined (_MSC_VER)
55 #pragma warning( push )
56 #pragma warning( disable : 4250 )
59 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
62 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
67 acceptNode(const DOMNode* node) const {
72 static SHIBSP_DLLLOCAL Blocker g_Blocker;
74 class SHIBSP_API MetadataGenerator : public AbstractHandler, public RemotedHandler
77 MetadataGenerator(const DOMElement* e, const char* appId);
78 virtual ~MetadataGenerator() {}
80 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
81 void receive(DDF& in, ostream& out);
84 pair<bool,long> processMessage(
85 const Application& application,
86 const char* handlerURL,
88 HTTPResponse& httpResponse
94 vector<string> m_bases;
98 #if defined (_MSC_VER)
99 #pragma warning( pop )
102 Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
104 return new MetadataGenerator(p.first, p.second);
109 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
110 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
112 ,m_http(0), m_https(0)
115 string address(appId);
116 address += getString("Location").second;
117 setAddress(address.c_str());
118 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
119 pair<bool,const char*> acl = getString("acl");
121 string aclbuf=acl.second;
123 for (unsigned int i=0; i < aclbuf.length(); i++) {
124 if (aclbuf.at(i)==' ') {
125 m_acl.insert(aclbuf.substr(j, i-j));
129 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
134 static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
136 pair<bool,bool> flag = getBool("http");
138 m_http = flag.second ? 1 : -1;
139 flag = getBool("https");
141 m_https = flag.second ? 1 : -1;
143 e = XMLHelper::getFirstChildElement(e, EndpointBase);
145 if (e->hasChildNodes()) {
146 auto_ptr_char base(e->getFirstChild()->getNodeValue());
147 if (base.get() && *base.get())
148 m_bases.push_back(base.get());
150 e = XMLHelper::getNextSiblingElement(e, EndpointBase);
155 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
157 SPConfig& conf = SPConfig::getConfig();
158 if (conf.isEnabled(SPConfig::InProcess)) {
159 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
160 m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
161 istringstream msg("Metadata Request Blocked");
162 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
167 if (conf.isEnabled(SPConfig::OutOfProcess)) {
168 // When out of process, we run natively and directly process the message.
169 return processMessage(request.getApplication(), request.getHandlerURL(), request.getParameter("entityID"), request);
172 // When not out of process, we remote all the message processing.
173 DDF out,in = DDF(m_address.c_str());
174 in.addmember("application_id").string(request.getApplication().getId());
175 in.addmember("handler_url").string(request.getHandlerURL());
176 if (request.getParameter("entityID"))
177 in.addmember("entity_id").string(request.getParameter("entityID"));
178 DDFJanitor jin(in), jout(out);
180 out=request.getServiceProvider().getListenerService()->send(in);
181 return unwrap(request, out);
184 catch (exception& ex) {
185 m_log.error("error while processing request: %s", ex.what());
186 istringstream msg("Metadata Request Failed");
187 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
191 void MetadataGenerator::receive(DDF& in, ostream& out)
194 const char* aid=in["application_id"].string();
195 const char* hurl=in["handler_url"].string();
196 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
198 // Something's horribly wrong.
199 m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
200 throw ConfigurationException("Unable to locate application for metadata request, deleted?");
203 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
206 // Wrap a response shim.
208 DDFJanitor jout(ret);
209 auto_ptr<HTTPResponse> resp(getResponse(ret));
211 // Since we're remoted, the result should either be a throw, a false/0 return,
212 // which we just return as an empty structure, or a response/redirect,
213 // which we capture in the facade and send back.
214 processMessage(*app, hurl, in["entity_id"].string(), *resp.get());
218 pair<bool,long> MetadataGenerator::processMessage(
219 const Application& application, const char* handlerURL, const char* entityID, HTTPResponse& httpResponse
223 m_log.debug("processing metadata request");
225 const PropertySet* relyingParty=NULL;
227 MetadataProvider* m=application.getMetadataProvider();
229 MetadataProviderCriteria mc(application, entityID);
230 relyingParty = application.getRelyingParty(m->getEntityDescriptor(mc).first);
233 relyingParty = &application;
236 EntityDescriptor* entity;
237 pair<bool,const char*> prop = getString("template");
239 // Load a template to use for our metadata.
240 string templ(prop.second);
241 XMLToolingConfig::getConfig().getPathResolver()->resolve(templ, PathResolver::XMLTOOLING_CFG_FILE);
242 auto_ptr_XMLCh widenit(templ.c_str());
243 LocalFileInputSource src(widenit.get());
244 Wrapper4InputSource dsrc(&src,false);
245 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
246 XercesJanitor<DOMDocument> docjan(doc);
247 auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
249 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
251 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, templ.c_str()));
255 entity = EntityDescriptorBuilder::buildEntityDescriptor();
258 auto_ptr<EntityDescriptor> wrapper(entity);
259 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
261 entity->setCacheDuration(cache.second);
264 cache = getUnsignedInt("validUntil");
266 entity->setValidUntil(time(NULL) + cache.second);
268 entity->setEntityID(relyingParty->getXMLString("entityID").second);
270 SPSSODescriptor* role;
271 if (entity->getSPSSODescriptors().empty()) {
272 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
273 entity->getSPSSODescriptors().push_back(role);
276 role = entity->getSPSSODescriptors().front();
280 prop = relyingParty->getString("signing");
281 if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
282 role->AuthnRequestsSigned(true);
283 pair<bool,bool> flagprop = relyingParty->getBool("requireSignedAssertions");
284 if (flagprop.first && flagprop.second)
285 role->WantAssertionsSigned(true);
287 // Ask each handler to generate itself.
288 vector<const Handler*> handlers;
289 application.getHandlers(handlers);
290 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
291 if (m_bases.empty()) {
292 if (strncmp(handlerURL, "https", 5) == 0) {
294 (*h)->generateMetadata(*role, handlerURL);
296 string temp(handlerURL);
298 (*h)->generateMetadata(*role, temp.c_str());
303 (*h)->generateMetadata(*role, handlerURL);
305 string temp(handlerURL);
306 temp.insert(temp.begin() + 4, 's');
307 (*h)->generateMetadata(*role, temp.c_str());
312 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
313 (*h)->generateMetadata(*role, b->c_str());
317 CredentialResolver* credResolver=application.getCredentialResolver();
319 Locker credLocker(credResolver);
320 CredentialCriteria cc;
321 prop = relyingParty->getString("keyName");
323 cc.getKeyNames().insert(prop.second);
324 cc.setUsage(Credential::SIGNING_CREDENTIAL);
325 vector<const Credential*> creds;
326 credResolver->resolve(creds,&cc);
327 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
328 KeyInfo* kinfo = (*c)->getKeyInfo();
330 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
331 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
332 kd->setKeyInfo(kinfo);
333 role->getKeyDescriptors().push_back(kd);
337 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
339 credResolver->resolve(creds,&cc);
340 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
341 KeyInfo* kinfo = (*c)->getKeyInfo();
343 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
344 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
345 kd->setKeyInfo(kinfo);
346 role->getKeyDescriptors().push_back(kd);
351 // Stream for response.
355 pair<bool,bool> flag = getBool("signing");
356 if (flag.first && flag.second) {
358 Locker credLocker(credResolver);
359 // Fill in criteria to use.
360 CredentialCriteria cc;
361 cc.setUsage(Credential::SIGNING_CREDENTIAL);
362 prop = getString("keyName");
364 cc.getKeyNames().insert(prop.second);
365 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
366 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
368 cc.setXMLAlgorithm(sigalg.second);
369 const Credential* cred = credResolver->resolve(&cc);
371 throw XMLSecurityException("Unable to obtain signing credential to use.");
373 // Pretty-print it first and then read it back in.
375 XMLHelper::serialize(entity->marshall(), pretty, true);
376 DOMDocument* prettydoc = XMLToolingConfig::getConfig().getParser().parse(pretty);
377 auto_ptr<XMLObject> prettyentity(XMLObjectBuilder::buildOneFromElement(prettydoc->getDocumentElement(), true));
379 Signature* sig = SignatureBuilder::buildSignature();
380 dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
382 sig->setSignatureAlgorithm(sigalg.second);
384 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
386 cr->setDigestAlgorithm(digalg.second);
389 // Sign while marshalling.
390 vector<Signature*> sigs(1,sig);
391 prettyentity->marshall(prettydoc,&sigs,cred);
395 throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
399 // Pretty-print it directly to client.
400 XMLHelper::serialize(entity->marshall(), s, true);
403 prop = getString("mimeType");
404 httpResponse.setContentType(prop.first ? prop.second : "application/samlmetadata+xml");
405 return make_pair(true, httpResponse.sendResponse(s));
407 return make_pair(false,0L);