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;
73 vector<string> m_bases;
77 #if defined (_MSC_VER)
78 #pragma warning( pop )
81 Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
83 return new MetadataGenerator(p.first, p.second);
88 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
89 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
91 string address(appId);
92 address += getString("Location").second;
93 setAddress(address.c_str());
94 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
95 pair<bool,const char*> acl = getString("acl");
97 string aclbuf=acl.second;
99 for (unsigned int i=0; i < aclbuf.length(); i++) {
100 if (aclbuf.at(i)==' ') {
101 m_acl.insert(aclbuf.substr(j, i-j));
105 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
110 static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
111 e = XMLHelper::getFirstChildElement(e, EndpointBase);
113 if (e->hasChildNodes()) {
114 auto_ptr_char base(e->getFirstChild()->getNodeValue());
115 if (base.get() && *base.get())
116 m_bases.push_back(base.get());
118 e = XMLHelper::getNextSiblingElement(e, EndpointBase);
123 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
126 SPConfig& conf = SPConfig::getConfig();
127 if (conf.isEnabled(SPConfig::InProcess)) {
128 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
129 m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
130 istringstream msg("Metadata Request Blocked");
131 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
136 if (conf.isEnabled(SPConfig::OutOfProcess)) {
137 // When out of process, we run natively and directly process the message.
138 return processMessage(request.getApplication(), request.getHandlerURL(), request);
141 // When not out of process, we remote all the message processing.
142 DDF out,in = DDF(m_address.c_str());
143 in.addmember("application_id").string(request.getApplication().getId());
144 in.addmember("handler_url").string(request.getHandlerURL());
145 DDFJanitor jin(in), jout(out);
147 out=request.getServiceProvider().getListenerService()->send(in);
148 return unwrap(request, out);
151 catch (exception& ex) {
152 m_log.error("error while processing request: %s", ex.what());
153 istringstream msg("Metadata Request Failed");
154 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
158 void MetadataGenerator::receive(DDF& in, ostream& out)
161 const char* aid=in["application_id"].string();
162 const char* hurl=in["handler_url"].string();
163 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
165 // Something's horribly wrong.
166 m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
167 throw ConfigurationException("Unable to locate application for metadata request, deleted?");
170 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
173 // Wrap a response shim.
175 DDFJanitor jout(ret);
176 auto_ptr<HTTPResponse> resp(getResponse(ret));
178 // Since we're remoted, the result should either be a throw, a false/0 return,
179 // which we just return as an empty structure, or a response/redirect,
180 // which we capture in the facade and send back.
181 processMessage(*app, hurl, *resp.get());
185 pair<bool,long> MetadataGenerator::processMessage(const Application& application, const char* handlerURL, HTTPResponse& httpResponse) const
188 m_log.debug("processing metadata request");
190 EntityDescriptor* entity;
191 pair<bool,const char*> prop = getString("template");
193 // Load a template to use for our metadata.
194 LocalFileInputSource src(getXMLString("template").second);
195 Wrapper4InputSource dsrc(&src,false);
196 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
197 XercesJanitor<DOMDocument> docjan(doc);
198 auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
199 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
201 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, prop.second));
205 entity = EntityDescriptorBuilder::buildEntityDescriptor();
208 auto_ptr<EntityDescriptor> wrapper(entity);
209 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
211 entity->setValidUntil(time(NULL) + cache.second);
212 entity->setEntityID(application.getXMLString("entityID").second);
214 SPSSODescriptor* role;
215 if (entity->getSPSSODescriptors().empty()) {
216 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
217 entity->getSPSSODescriptors().push_back(role);
220 role = entity->getSPSSODescriptors().front();
223 vector<const Handler*> handlers;
224 application.getHandlers(handlers);
225 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
226 (*h)->generateMetadata(*role, handlerURL);
227 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
228 (*h)->generateMetadata(*role, b->c_str());
231 CredentialResolver* credResolver=application.getCredentialResolver();
233 Locker credLocker(credResolver);
234 CredentialCriteria cc;
235 cc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
236 vector<const Credential*> creds;
237 credResolver->resolve(creds,&cc);
238 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
239 KeyInfo* kinfo = (*c)->getKeyInfo();
241 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
242 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
243 kd->setKeyInfo(kinfo);
244 role->getKeyDescriptors().push_back(kd);
248 cc.setUsage(CredentialCriteria::ENCRYPTION_CREDENTIAL);
250 credResolver->resolve(creds,&cc);
251 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
252 KeyInfo* kinfo = (*c)->getKeyInfo();
254 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
255 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
256 kd->setKeyInfo(kinfo);
257 role->getKeyDescriptors().push_back(kd);
263 pair<bool,bool> flag = getBool("signing");
264 if (flag.first && flag.second) {
266 Locker credLocker(credResolver);
267 // Fill in criteria to use.
268 CredentialCriteria cc;
269 cc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
270 prop = getString("keyName");
272 cc.getKeyNames().insert(prop.second);
273 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
274 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
276 cc.setXMLAlgorithm(sigalg.second);
277 const Credential* cred = credResolver->resolve(&cc);
279 throw XMLSecurityException("Unable to obtain signing credential to use.");
280 Signature* sig = SignatureBuilder::buildSignature();
281 entity->setSignature(sig);
283 sig->setSignatureAlgorithm(sigalg.second);
285 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
287 cr->setDigestAlgorithm(digalg.second);
290 // Sign response while marshalling.
291 vector<Signature*> sigs(1,sig);
292 entity->marshall((DOMDocument*)NULL,&sigs,cred);
298 httpResponse.setContentType("application/samlmetadata+xml");
299 return make_pair(true, httpResponse.sendResponse(s));
301 return make_pair(false,0);