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"
34 #include <xercesc/framework/LocalFileInputSource.hpp>
35 #include <xercesc/framework/Wrapper4InputSource.hpp>
37 using namespace shibsp;
39 using namespace opensaml::saml2md;
40 using namespace opensaml;
41 using namespace xmlsignature;
43 using namespace xmltooling;
48 #if defined (_MSC_VER)
49 #pragma warning( push )
50 #pragma warning( disable : 4250 )
53 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
56 short acceptNode(const DOMNode* node) const {
61 static SHIBSP_DLLLOCAL Blocker g_Blocker;
63 class SHIBSP_API MetadataGenerator : public AbstractHandler, public RemotedHandler
66 MetadataGenerator(const DOMElement* e, const char* appId);
67 virtual ~MetadataGenerator() {}
69 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
70 void receive(DDF& in, ostream& out);
73 pair<bool,long> processMessage(
74 const Application& application,
75 const char* handlerURL,
77 HTTPResponse& httpResponse
83 vector<string> m_bases;
87 #if defined (_MSC_VER)
88 #pragma warning( pop )
91 Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
93 return new MetadataGenerator(p.first, p.second);
98 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
99 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
101 ,m_http(0), m_https(0)
104 string address(appId);
105 address += getString("Location").second;
106 setAddress(address.c_str());
107 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
108 pair<bool,const char*> acl = getString("acl");
110 string aclbuf=acl.second;
112 for (unsigned int i=0; i < aclbuf.length(); i++) {
113 if (aclbuf.at(i)==' ') {
114 m_acl.insert(aclbuf.substr(j, i-j));
118 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
123 static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
125 pair<bool,bool> flag = getBool("http");
127 m_http = flag.second ? 1 : -1;
128 flag = getBool("https");
130 m_https = flag.second ? 1 : -1;
132 e = XMLHelper::getFirstChildElement(e, EndpointBase);
134 if (e->hasChildNodes()) {
135 auto_ptr_char base(e->getFirstChild()->getNodeValue());
136 if (base.get() && *base.get())
137 m_bases.push_back(base.get());
139 e = XMLHelper::getNextSiblingElement(e, EndpointBase);
144 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
146 SPConfig& conf = SPConfig::getConfig();
147 if (conf.isEnabled(SPConfig::InProcess)) {
148 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
149 m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
150 istringstream msg("Metadata Request Blocked");
151 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED));
156 if (conf.isEnabled(SPConfig::OutOfProcess)) {
157 // When out of process, we run natively and directly process the message.
158 return processMessage(request.getApplication(), request.getHandlerURL(), request.getParameter("entityID"), request);
161 // When not out of process, we remote all the message processing.
162 DDF out,in = DDF(m_address.c_str());
163 in.addmember("application_id").string(request.getApplication().getId());
164 in.addmember("handler_url").string(request.getHandlerURL());
165 if (request.getParameter("entityID"))
166 in.addmember("entity_id").string(request.getParameter("entityID"));
167 DDFJanitor jin(in), jout(out);
169 out=request.getServiceProvider().getListenerService()->send(in);
170 return unwrap(request, out);
173 catch (exception& ex) {
174 m_log.error("error while processing request: %s", ex.what());
175 istringstream msg("Metadata Request Failed");
176 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
180 void MetadataGenerator::receive(DDF& in, ostream& out)
183 const char* aid=in["application_id"].string();
184 const char* hurl=in["handler_url"].string();
185 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
187 // Something's horribly wrong.
188 m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
189 throw ConfigurationException("Unable to locate application for metadata request, deleted?");
192 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
195 // Wrap a response shim.
197 DDFJanitor jout(ret);
198 auto_ptr<HTTPResponse> resp(getResponse(ret));
200 // Since we're remoted, the result should either be a throw, a false/0 return,
201 // which we just return as an empty structure, or a response/redirect,
202 // which we capture in the facade and send back.
203 processMessage(*app, hurl, in["entity_id"].string(), *resp.get());
207 pair<bool,long> MetadataGenerator::processMessage(
208 const Application& application, const char* handlerURL, const char* entityID, HTTPResponse& httpResponse
212 m_log.debug("processing metadata request");
214 const PropertySet* relyingParty=NULL;
216 MetadataProvider* m=application.getMetadataProvider();
218 MetadataProviderCriteria mc(application, entityID);
219 relyingParty = application.getRelyingParty(m->getEntityDescriptor(mc).first);
222 relyingParty = &application;
225 EntityDescriptor* entity;
226 pair<bool,const char*> prop = getString("template");
228 // Load a template to use for our metadata.
229 LocalFileInputSource src(getXMLString("template").second);
230 Wrapper4InputSource dsrc(&src,false);
231 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
232 XercesJanitor<DOMDocument> docjan(doc);
233 auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
235 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
237 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, prop.second));
241 entity = EntityDescriptorBuilder::buildEntityDescriptor();
244 auto_ptr<EntityDescriptor> wrapper(entity);
245 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
247 entity->setCacheDuration(cache.second);
250 cache = getUnsignedInt("validUntil");
252 entity->setValidUntil(time(NULL) + cache.second);
254 entity->setEntityID(relyingParty->getXMLString("entityID").second);
256 SPSSODescriptor* role;
257 if (entity->getSPSSODescriptors().empty()) {
258 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
259 entity->getSPSSODescriptors().push_back(role);
262 role = entity->getSPSSODescriptors().front();
266 prop = relyingParty->getString("signing");
267 if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
268 role->AuthnRequestsSigned(true);
269 pair<bool,bool> flagprop = relyingParty->getBool("requireSignedAssertions");
270 if (flagprop.first && flagprop.second)
271 role->WantAssertionsSigned(true);
273 // Ask each handler to generate itself.
274 vector<const Handler*> handlers;
275 application.getHandlers(handlers);
276 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
277 if (m_bases.empty()) {
278 if (strncmp(handlerURL, "https", 5) == 0) {
280 (*h)->generateMetadata(*role, handlerURL);
282 string temp(handlerURL);
284 (*h)->generateMetadata(*role, temp.c_str());
289 (*h)->generateMetadata(*role, handlerURL);
291 string temp(handlerURL);
292 temp.insert(temp.begin() + 4, 's');
293 (*h)->generateMetadata(*role, temp.c_str());
298 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
299 (*h)->generateMetadata(*role, b->c_str());
303 CredentialResolver* credResolver=application.getCredentialResolver();
305 Locker credLocker(credResolver);
306 CredentialCriteria cc;
307 prop = relyingParty->getString("keyName");
309 cc.getKeyNames().insert(prop.second);
310 cc.setUsage(Credential::SIGNING_CREDENTIAL);
311 vector<const Credential*> creds;
312 credResolver->resolve(creds,&cc);
313 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
314 KeyInfo* kinfo = (*c)->getKeyInfo();
316 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
317 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
318 kd->setKeyInfo(kinfo);
319 role->getKeyDescriptors().push_back(kd);
323 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
325 credResolver->resolve(creds,&cc);
326 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
327 KeyInfo* kinfo = (*c)->getKeyInfo();
329 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
330 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
331 kd->setKeyInfo(kinfo);
332 role->getKeyDescriptors().push_back(kd);
337 // Stream for response.
341 pair<bool,bool> flag = getBool("signing");
342 if (flag.first && flag.second) {
344 Locker credLocker(credResolver);
345 // Fill in criteria to use.
346 CredentialCriteria cc;
347 cc.setUsage(Credential::SIGNING_CREDENTIAL);
348 prop = getString("keyName");
350 cc.getKeyNames().insert(prop.second);
351 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
352 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
354 cc.setXMLAlgorithm(sigalg.second);
355 const Credential* cred = credResolver->resolve(&cc);
357 throw XMLSecurityException("Unable to obtain signing credential to use.");
359 // Pretty-print it first and then read it back in.
361 XMLHelper::serialize(entity->marshall(), pretty, true);
362 DOMDocument* prettydoc = XMLToolingConfig::getConfig().getParser().parse(pretty);
363 auto_ptr<XMLObject> prettyentity(XMLObjectBuilder::buildOneFromElement(prettydoc->getDocumentElement(), true));
365 Signature* sig = SignatureBuilder::buildSignature();
366 dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
368 sig->setSignatureAlgorithm(sigalg.second);
370 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
372 cr->setDigestAlgorithm(digalg.second);
375 // Sign while marshalling.
376 vector<Signature*> sigs(1,sig);
377 prettyentity->marshall(prettydoc,&sigs,cred);
381 throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
385 // Pretty-print it directly to client.
386 XMLHelper::serialize(entity->marshall(), s, true);
389 prop = getString("mimeType");
390 httpResponse.setContentType(prop.first ? prop.second : "application/samlmetadata+xml");
391 return make_pair(true, httpResponse.sendResponse(s));
393 return make_pair(false,0L);