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;
78 #if defined (_MSC_VER)
79 #pragma warning( pop )
82 Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
84 return new MetadataGenerator(p.first, p.second);
89 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
90 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
92 ,m_https(0), m_http(0)
95 string address(appId);
96 address += getString("Location").second;
97 setAddress(address.c_str());
98 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
99 pair<bool,const char*> acl = getString("acl");
101 string aclbuf=acl.second;
103 for (unsigned int i=0; i < aclbuf.length(); i++) {
104 if (aclbuf.at(i)==' ') {
105 m_acl.insert(aclbuf.substr(j, i-j));
109 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
114 static XMLCh _http[] = UNICODE_LITERAL_4(h,t,t,p);
115 static XMLCh _https[] = UNICODE_LITERAL_5(h,t,t,p,s);
116 static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
118 pair<bool,bool> flag = getBool("http");
120 m_http = flag.second ? 1 : -1;
121 flag = getBool("https");
123 m_https = flag.second ? 1 : -1;
125 e = XMLHelper::getFirstChildElement(e, EndpointBase);
127 if (e->hasChildNodes()) {
128 auto_ptr_char base(e->getFirstChild()->getNodeValue());
129 if (base.get() && *base.get())
130 m_bases.push_back(base.get());
132 e = XMLHelper::getNextSiblingElement(e, EndpointBase);
137 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
139 SPConfig& conf = SPConfig::getConfig();
140 if (conf.isEnabled(SPConfig::InProcess)) {
141 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
142 m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
143 istringstream msg("Metadata Request Blocked");
144 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED));
149 if (conf.isEnabled(SPConfig::OutOfProcess)) {
150 // When out of process, we run natively and directly process the message.
151 return processMessage(request.getApplication(), request.getHandlerURL(), request);
154 // When not out of process, we remote all the message processing.
155 DDF out,in = DDF(m_address.c_str());
156 in.addmember("application_id").string(request.getApplication().getId());
157 in.addmember("handler_url").string(request.getHandlerURL());
158 DDFJanitor jin(in), jout(out);
160 out=request.getServiceProvider().getListenerService()->send(in);
161 return unwrap(request, out);
164 catch (exception& ex) {
165 m_log.error("error while processing request: %s", ex.what());
166 istringstream msg("Metadata Request Failed");
167 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
171 void MetadataGenerator::receive(DDF& in, ostream& out)
174 const char* aid=in["application_id"].string();
175 const char* hurl=in["handler_url"].string();
176 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
178 // Something's horribly wrong.
179 m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
180 throw ConfigurationException("Unable to locate application for metadata request, deleted?");
183 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
186 // Wrap a response shim.
188 DDFJanitor jout(ret);
189 auto_ptr<HTTPResponse> resp(getResponse(ret));
191 // Since we're remoted, the result should either be a throw, a false/0 return,
192 // which we just return as an empty structure, or a response/redirect,
193 // which we capture in the facade and send back.
194 processMessage(*app, hurl, *resp.get());
198 pair<bool,long> MetadataGenerator::processMessage(const Application& application, const char* handlerURL, HTTPResponse& httpResponse) const
201 m_log.debug("processing metadata request");
203 EntityDescriptor* entity;
204 pair<bool,const char*> prop = getString("template");
206 // Load a template to use for our metadata.
207 LocalFileInputSource src(getXMLString("template").second);
208 Wrapper4InputSource dsrc(&src,false);
209 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
210 XercesJanitor<DOMDocument> docjan(doc);
211 auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
212 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
214 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, prop.second));
218 entity = EntityDescriptorBuilder::buildEntityDescriptor();
221 auto_ptr<EntityDescriptor> wrapper(entity);
222 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
224 entity->setValidUntil(time(NULL) + cache.second);
225 entity->setEntityID(application.getXMLString("entityID").second);
227 SPSSODescriptor* role;
228 if (entity->getSPSSODescriptors().empty()) {
229 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
230 entity->getSPSSODescriptors().push_back(role);
233 role = entity->getSPSSODescriptors().front();
237 prop = application.getRelyingParty(NULL)->getString("signing");
238 if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
239 role->AuthnRequestsSigned(true);
240 pair<bool,bool> flagprop = application.getRelyingParty(NULL)->getBool("signedAssertions");
241 if (flagprop.first && flagprop.second)
242 role->WantAssertionsSigned(true);
244 // Ask each handler to generate itself.
245 vector<const Handler*> handlers;
246 application.getHandlers(handlers);
247 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
248 if (m_bases.empty()) {
249 if (strncmp(handlerURL, "https", 5) == 0) {
251 (*h)->generateMetadata(*role, handlerURL);
253 string temp(handlerURL);
255 (*h)->generateMetadata(*role, temp.c_str());
260 (*h)->generateMetadata(*role, handlerURL);
262 string temp(handlerURL);
263 temp.insert(temp.begin() + 4, 's');
264 (*h)->generateMetadata(*role, temp.c_str());
269 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
270 (*h)->generateMetadata(*role, b->c_str());
274 CredentialResolver* credResolver=application.getCredentialResolver();
276 Locker credLocker(credResolver);
277 CredentialCriteria cc;
278 cc.setUsage(Credential::SIGNING_CREDENTIAL);
279 vector<const Credential*> creds;
280 credResolver->resolve(creds,&cc);
281 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
282 KeyInfo* kinfo = (*c)->getKeyInfo();
284 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
285 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
286 kd->setKeyInfo(kinfo);
287 role->getKeyDescriptors().push_back(kd);
291 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
293 credResolver->resolve(creds,&cc);
294 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
295 KeyInfo* kinfo = (*c)->getKeyInfo();
297 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
298 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
299 kd->setKeyInfo(kinfo);
300 role->getKeyDescriptors().push_back(kd);
306 pair<bool,bool> flag = getBool("signing");
307 if (flag.first && flag.second) {
309 Locker credLocker(credResolver);
310 // Fill in criteria to use.
311 CredentialCriteria cc;
312 cc.setUsage(Credential::SIGNING_CREDENTIAL);
313 prop = getString("keyName");
315 cc.getKeyNames().insert(prop.second);
316 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
317 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
319 cc.setXMLAlgorithm(sigalg.second);
320 const Credential* cred = credResolver->resolve(&cc);
322 throw XMLSecurityException("Unable to obtain signing credential to use.");
323 Signature* sig = SignatureBuilder::buildSignature();
324 entity->setSignature(sig);
326 sig->setSignatureAlgorithm(sigalg.second);
328 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
330 cr->setDigestAlgorithm(digalg.second);
333 // Sign response while marshalling.
334 vector<Signature*> sigs(1,sig);
335 entity->marshall((DOMDocument*)NULL,&sigs,cred);
341 httpResponse.setContentType("application/samlmetadata+xml");
342 return make_pair(true, httpResponse.sendResponse(s));
344 return make_pair(false,0L);