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"
30 #include <xercesc/framework/LocalFileInputSource.hpp>
31 #include <xercesc/framework/Wrapper4InputSource.hpp>
33 using namespace shibsp;
35 using namespace opensaml::saml2md;
36 using namespace opensaml;
37 using namespace xmlsignature;
39 using namespace xmltooling;
44 #if defined (_MSC_VER)
45 #pragma warning( push )
46 #pragma warning( disable : 4250 )
49 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
52 short acceptNode(const DOMNode* node) const {
57 static SHIBSP_DLLLOCAL Blocker g_Blocker;
59 class SHIBSP_API MetadataGenerator : public AbstractHandler, public RemotedHandler
62 MetadataGenerator(const DOMElement* e, const char* appId);
63 virtual ~MetadataGenerator() {}
65 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
66 void receive(DDF& in, ostream& out);
69 pair<bool,long> processMessage(
70 const Application& application,
71 const char* handlerURL,
73 HTTPResponse& httpResponse
79 vector<string> m_bases;
83 #if defined (_MSC_VER)
84 #pragma warning( pop )
87 Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
89 return new MetadataGenerator(p.first, p.second);
94 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
95 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
97 ,m_https(0), m_http(0)
100 string address(appId);
101 address += getString("Location").second;
102 setAddress(address.c_str());
103 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
104 pair<bool,const char*> acl = getString("acl");
106 string aclbuf=acl.second;
108 for (unsigned int i=0; i < aclbuf.length(); i++) {
109 if (aclbuf.at(i)==' ') {
110 m_acl.insert(aclbuf.substr(j, i-j));
114 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
119 static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
121 pair<bool,bool> flag = getBool("http");
123 m_http = flag.second ? 1 : -1;
124 flag = getBool("https");
126 m_https = flag.second ? 1 : -1;
128 e = XMLHelper::getFirstChildElement(e, EndpointBase);
130 if (e->hasChildNodes()) {
131 auto_ptr_char base(e->getFirstChild()->getNodeValue());
132 if (base.get() && *base.get())
133 m_bases.push_back(base.get());
135 e = XMLHelper::getNextSiblingElement(e, EndpointBase);
140 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
142 SPConfig& conf = SPConfig::getConfig();
143 if (conf.isEnabled(SPConfig::InProcess)) {
144 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
145 m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
146 istringstream msg("Metadata Request Blocked");
147 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED));
152 if (conf.isEnabled(SPConfig::OutOfProcess)) {
153 // When out of process, we run natively and directly process the message.
154 return processMessage(request.getApplication(), request.getHandlerURL(), request.getParameter("entityID"), request);
157 // When not out of process, we remote all the message processing.
158 DDF out,in = DDF(m_address.c_str());
159 in.addmember("application_id").string(request.getApplication().getId());
160 in.addmember("handler_url").string(request.getHandlerURL());
161 if (request.getParameter("entityID"))
162 in.addmember("entity_id").string(request.getParameter("entityID"));
163 DDFJanitor jin(in), jout(out);
165 out=request.getServiceProvider().getListenerService()->send(in);
166 return unwrap(request, out);
169 catch (exception& ex) {
170 m_log.error("error while processing request: %s", ex.what());
171 istringstream msg("Metadata Request Failed");
172 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
176 void MetadataGenerator::receive(DDF& in, ostream& out)
179 const char* aid=in["application_id"].string();
180 const char* hurl=in["handler_url"].string();
181 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
183 // Something's horribly wrong.
184 m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
185 throw ConfigurationException("Unable to locate application for metadata request, deleted?");
188 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
191 // Wrap a response shim.
193 DDFJanitor jout(ret);
194 auto_ptr<HTTPResponse> resp(getResponse(ret));
196 // Since we're remoted, the result should either be a throw, a false/0 return,
197 // which we just return as an empty structure, or a response/redirect,
198 // which we capture in the facade and send back.
199 processMessage(*app, hurl, in["entity_id"].string(), *resp.get());
203 pair<bool,long> MetadataGenerator::processMessage(
204 const Application& application, const char* handlerURL, const char* entityID, HTTPResponse& httpResponse
208 m_log.debug("processing metadata request");
210 const PropertySet* relyingParty=NULL;
212 MetadataProvider* m=application.getMetadataProvider();
214 MetadataProvider::Criteria mc(entityID);
215 relyingParty = application.getRelyingParty(m->getEntityDescriptor(mc).first);
218 relyingParty = application.getRelyingParty(NULL);
221 EntityDescriptor* entity;
222 pair<bool,const char*> prop = getString("template");
224 // Load a template to use for our metadata.
225 LocalFileInputSource src(getXMLString("template").second);
226 Wrapper4InputSource dsrc(&src,false);
227 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
228 XercesJanitor<DOMDocument> docjan(doc);
229 auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
231 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
233 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, prop.second));
237 entity = EntityDescriptorBuilder::buildEntityDescriptor();
240 auto_ptr<EntityDescriptor> wrapper(entity);
241 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
243 entity->setValidUntil(time(NULL) + cache.second);
244 entity->setEntityID(relyingParty->getXMLString("entityID").second);
246 SPSSODescriptor* role;
247 if (entity->getSPSSODescriptors().empty()) {
248 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
249 entity->getSPSSODescriptors().push_back(role);
252 role = entity->getSPSSODescriptors().front();
256 prop = relyingParty->getString("signing");
257 if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
258 role->AuthnRequestsSigned(true);
259 pair<bool,bool> flagprop = relyingParty->getBool("signedAssertions");
260 if (flagprop.first && flagprop.second)
261 role->WantAssertionsSigned(true);
263 // Ask each handler to generate itself.
264 vector<const Handler*> handlers;
265 application.getHandlers(handlers);
266 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
267 if (m_bases.empty()) {
268 if (strncmp(handlerURL, "https", 5) == 0) {
270 (*h)->generateMetadata(*role, handlerURL);
272 string temp(handlerURL);
274 (*h)->generateMetadata(*role, temp.c_str());
279 (*h)->generateMetadata(*role, handlerURL);
281 string temp(handlerURL);
282 temp.insert(temp.begin() + 4, 's');
283 (*h)->generateMetadata(*role, temp.c_str());
288 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
289 (*h)->generateMetadata(*role, b->c_str());
293 CredentialResolver* credResolver=application.getCredentialResolver();
295 Locker credLocker(credResolver);
296 CredentialCriteria cc;
297 prop = relyingParty->getString("keyName");
299 cc.getKeyNames().insert(prop.second);
300 cc.setUsage(Credential::SIGNING_CREDENTIAL);
301 vector<const Credential*> creds;
302 credResolver->resolve(creds,&cc);
303 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
304 KeyInfo* kinfo = (*c)->getKeyInfo();
306 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
307 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
308 kd->setKeyInfo(kinfo);
309 role->getKeyDescriptors().push_back(kd);
313 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
315 credResolver->resolve(creds,&cc);
316 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
317 KeyInfo* kinfo = (*c)->getKeyInfo();
319 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
320 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
321 kd->setKeyInfo(kinfo);
322 role->getKeyDescriptors().push_back(kd);
327 // Stream for response.
331 pair<bool,bool> flag = getBool("signing");
332 if (flag.first && flag.second) {
334 Locker credLocker(credResolver);
335 // Fill in criteria to use.
336 CredentialCriteria cc;
337 cc.setUsage(Credential::SIGNING_CREDENTIAL);
338 prop = getString("keyName");
340 cc.getKeyNames().insert(prop.second);
341 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
342 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
344 cc.setXMLAlgorithm(sigalg.second);
345 const Credential* cred = credResolver->resolve(&cc);
347 throw XMLSecurityException("Unable to obtain signing credential to use.");
349 // Pretty-print it first and then read it back in.
351 XMLHelper::serialize(entity->marshall(), pretty, true);
352 DOMDocument* prettydoc = XMLToolingConfig::getConfig().getParser().parse(pretty);
353 auto_ptr<XMLObject> prettyentity(XMLObjectBuilder::buildOneFromElement(prettydoc->getDocumentElement(), true));
355 Signature* sig = SignatureBuilder::buildSignature();
356 dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
358 sig->setSignatureAlgorithm(sigalg.second);
360 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
362 cr->setDigestAlgorithm(digalg.second);
365 // Sign while marshalling.
366 vector<Signature*> sigs(1,sig);
367 prettyentity->marshall(prettydoc,&sigs,cred);
371 throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
375 // Pretty-print it directly to client.
376 XMLHelper::serialize(entity->marshall(), s, true);
379 prop = getString("mimeType");
380 httpResponse.setContentType(prop.first ? prop.second : "application/samlmetadata+xml");
381 return make_pair(true, httpResponse.sendResponse(s));
383 return make_pair(false,0L);