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(const Application& application, const char* handlerURL, HTTPResponse& httpResponse) const;
74 vector<string> m_bases;
79 #if defined (_MSC_VER)
80 #pragma warning( pop )
83 Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
85 return new MetadataGenerator(p.first, p.second);
90 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
91 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
93 ,m_https(0), m_http(0), m_mime(NULL)
96 string address(appId);
97 address += getString("Location").second;
98 setAddress(address.c_str());
99 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
100 pair<bool,const char*> acl = getString("acl");
102 string aclbuf=acl.second;
104 for (unsigned int i=0; i < aclbuf.length(); i++) {
105 if (aclbuf.at(i)==' ') {
106 m_acl.insert(aclbuf.substr(j, i-j));
110 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
115 static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
117 pair<bool,bool> flag = getBool("http");
119 m_http = flag.second ? 1 : -1;
120 flag = getBool("https");
122 m_https = flag.second ? 1 : -1;
124 pair<bool,const char*> mime = getString("mimeType");
126 m_mime = mime.second;
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);
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 DDFJanitor jin(in), jout(out);
163 out=request.getServiceProvider().getListenerService()->send(in);
164 return unwrap(request, out);
167 catch (exception& ex) {
168 m_log.error("error while processing request: %s", ex.what());
169 istringstream msg("Metadata Request Failed");
170 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
174 void MetadataGenerator::receive(DDF& in, ostream& out)
177 const char* aid=in["application_id"].string();
178 const char* hurl=in["handler_url"].string();
179 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
181 // Something's horribly wrong.
182 m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
183 throw ConfigurationException("Unable to locate application for metadata request, deleted?");
186 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
189 // Wrap a response shim.
191 DDFJanitor jout(ret);
192 auto_ptr<HTTPResponse> resp(getResponse(ret));
194 // Since we're remoted, the result should either be a throw, a false/0 return,
195 // which we just return as an empty structure, or a response/redirect,
196 // which we capture in the facade and send back.
197 processMessage(*app, hurl, *resp.get());
201 pair<bool,long> MetadataGenerator::processMessage(const Application& application, const char* handlerURL, HTTPResponse& httpResponse) const
204 m_log.debug("processing metadata request");
206 EntityDescriptor* entity;
207 pair<bool,const char*> prop = getString("template");
209 // Load a template to use for our metadata.
210 LocalFileInputSource src(getXMLString("template").second);
211 Wrapper4InputSource dsrc(&src,false);
212 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
213 XercesJanitor<DOMDocument> docjan(doc);
214 auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
215 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
217 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, prop.second));
221 entity = EntityDescriptorBuilder::buildEntityDescriptor();
224 auto_ptr<EntityDescriptor> wrapper(entity);
225 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
227 entity->setValidUntil(time(NULL) + cache.second);
228 entity->setEntityID(application.getXMLString("entityID").second);
230 SPSSODescriptor* role;
231 if (entity->getSPSSODescriptors().empty()) {
232 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
233 entity->getSPSSODescriptors().push_back(role);
236 role = entity->getSPSSODescriptors().front();
240 prop = application.getRelyingParty(NULL)->getString("signing");
241 if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
242 role->AuthnRequestsSigned(true);
243 pair<bool,bool> flagprop = application.getRelyingParty(NULL)->getBool("signedAssertions");
244 if (flagprop.first && flagprop.second)
245 role->WantAssertionsSigned(true);
247 // Ask each handler to generate itself.
248 vector<const Handler*> handlers;
249 application.getHandlers(handlers);
250 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
251 if (m_bases.empty()) {
252 if (strncmp(handlerURL, "https", 5) == 0) {
254 (*h)->generateMetadata(*role, handlerURL);
256 string temp(handlerURL);
258 (*h)->generateMetadata(*role, temp.c_str());
263 (*h)->generateMetadata(*role, handlerURL);
265 string temp(handlerURL);
266 temp.insert(temp.begin() + 4, 's');
267 (*h)->generateMetadata(*role, temp.c_str());
272 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
273 (*h)->generateMetadata(*role, b->c_str());
277 CredentialResolver* credResolver=application.getCredentialResolver();
279 Locker credLocker(credResolver);
280 CredentialCriteria cc;
281 cc.setUsage(Credential::SIGNING_CREDENTIAL);
282 vector<const Credential*> creds;
283 credResolver->resolve(creds,&cc);
284 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
285 KeyInfo* kinfo = (*c)->getKeyInfo();
287 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
288 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
289 kd->setKeyInfo(kinfo);
290 role->getKeyDescriptors().push_back(kd);
294 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
296 credResolver->resolve(creds,&cc);
297 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
298 KeyInfo* kinfo = (*c)->getKeyInfo();
300 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
301 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
302 kd->setKeyInfo(kinfo);
303 role->getKeyDescriptors().push_back(kd);
308 // Stream for response.
312 pair<bool,bool> flag = getBool("signing");
313 if (flag.first && flag.second) {
315 Locker credLocker(credResolver);
316 // Fill in criteria to use.
317 CredentialCriteria cc;
318 cc.setUsage(Credential::SIGNING_CREDENTIAL);
319 prop = getString("keyName");
321 cc.getKeyNames().insert(prop.second);
322 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
323 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
325 cc.setXMLAlgorithm(sigalg.second);
326 const Credential* cred = credResolver->resolve(&cc);
328 throw XMLSecurityException("Unable to obtain signing credential to use.");
330 // Pretty-print it first and then read it back in.
332 XMLHelper::serialize(entity->marshall(), pretty, true);
333 DOMDocument* prettydoc = XMLToolingConfig::getConfig().getParser().parse(pretty);
334 auto_ptr<XMLObject> prettyentity(XMLObjectBuilder::buildOneFromElement(prettydoc->getDocumentElement(), true));
336 Signature* sig = SignatureBuilder::buildSignature();
337 dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
339 sig->setSignatureAlgorithm(sigalg.second);
341 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
343 cr->setDigestAlgorithm(digalg.second);
346 // Sign while marshalling.
347 vector<Signature*> sigs(1,sig);
348 prettyentity->marshall(prettydoc,&sigs,cred);
352 throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
356 // Pretty-print it directly to client.
357 XMLHelper::serialize(entity->marshall(), s, true);
360 httpResponse.setContentType(m_mime ? m_mime : "application/samlmetadata+xml");
361 return make_pair(true, httpResponse.sendResponse(s));
363 return make_pair(false,0L);