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
125 SPConfig& conf = SPConfig::getConfig();
126 if (conf.isEnabled(SPConfig::InProcess)) {
127 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
128 m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
129 istringstream msg("Metadata Request Blocked");
130 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED));
135 if (conf.isEnabled(SPConfig::OutOfProcess)) {
136 // When out of process, we run natively and directly process the message.
137 return processMessage(request.getApplication(), request.getHandlerURL(), request);
140 // When not out of process, we remote all the message processing.
141 DDF out,in = DDF(m_address.c_str());
142 in.addmember("application_id").string(request.getApplication().getId());
143 in.addmember("handler_url").string(request.getHandlerURL());
144 DDFJanitor jin(in), jout(out);
146 out=request.getServiceProvider().getListenerService()->send(in);
147 return unwrap(request, out);
150 catch (exception& ex) {
151 m_log.error("error while processing request: %s", ex.what());
152 istringstream msg("Metadata Request Failed");
153 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
157 void MetadataGenerator::receive(DDF& in, ostream& out)
160 const char* aid=in["application_id"].string();
161 const char* hurl=in["handler_url"].string();
162 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
164 // Something's horribly wrong.
165 m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
166 throw ConfigurationException("Unable to locate application for metadata request, deleted?");
169 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
172 // Wrap a response shim.
174 DDFJanitor jout(ret);
175 auto_ptr<HTTPResponse> resp(getResponse(ret));
177 // Since we're remoted, the result should either be a throw, a false/0 return,
178 // which we just return as an empty structure, or a response/redirect,
179 // which we capture in the facade and send back.
180 processMessage(*app, hurl, *resp.get());
184 pair<bool,long> MetadataGenerator::processMessage(const Application& application, const char* handlerURL, HTTPResponse& httpResponse) const
187 m_log.debug("processing metadata request");
189 EntityDescriptor* entity;
190 pair<bool,const char*> prop = getString("template");
192 // Load a template to use for our metadata.
193 LocalFileInputSource src(getXMLString("template").second);
194 Wrapper4InputSource dsrc(&src,false);
195 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
196 XercesJanitor<DOMDocument> docjan(doc);
197 auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
198 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
200 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, prop.second));
204 entity = EntityDescriptorBuilder::buildEntityDescriptor();
207 auto_ptr<EntityDescriptor> wrapper(entity);
208 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
210 entity->setValidUntil(time(NULL) + cache.second);
211 entity->setEntityID(application.getXMLString("entityID").second);
213 SPSSODescriptor* role;
214 if (entity->getSPSSODescriptors().empty()) {
215 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
216 entity->getSPSSODescriptors().push_back(role);
219 role = entity->getSPSSODescriptors().front();
223 prop = application.getRelyingParty(NULL)->getString("signing");
224 if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
225 role->AuthnRequestsSigned(true);
226 pair<bool,bool> flagprop =
227 application.getServiceProvider().getPolicySettings(application.getString("policyId").second)->getBool("signedAssertions");
228 if (flagprop.first && flagprop.second)
229 role->WantAssertionsSigned(true);
231 vector<const Handler*> handlers;
232 application.getHandlers(handlers);
233 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
234 if (m_bases.empty()) {
235 (*h)->generateMetadata(*role, handlerURL);
238 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
239 (*h)->generateMetadata(*role, b->c_str());
243 CredentialResolver* credResolver=application.getCredentialResolver();
245 Locker credLocker(credResolver);
246 CredentialCriteria cc;
247 cc.setUsage(Credential::SIGNING_CREDENTIAL);
248 vector<const Credential*> creds;
249 credResolver->resolve(creds,&cc);
250 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
251 KeyInfo* kinfo = (*c)->getKeyInfo();
253 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
254 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
255 kd->setKeyInfo(kinfo);
256 role->getKeyDescriptors().push_back(kd);
260 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
262 credResolver->resolve(creds,&cc);
263 for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
264 KeyInfo* kinfo = (*c)->getKeyInfo();
266 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
267 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
268 kd->setKeyInfo(kinfo);
269 role->getKeyDescriptors().push_back(kd);
275 pair<bool,bool> flag = getBool("signing");
276 if (flag.first && flag.second) {
278 Locker credLocker(credResolver);
279 // Fill in criteria to use.
280 CredentialCriteria cc;
281 cc.setUsage(Credential::SIGNING_CREDENTIAL);
282 prop = getString("keyName");
284 cc.getKeyNames().insert(prop.second);
285 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
286 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
288 cc.setXMLAlgorithm(sigalg.second);
289 const Credential* cred = credResolver->resolve(&cc);
291 throw XMLSecurityException("Unable to obtain signing credential to use.");
292 Signature* sig = SignatureBuilder::buildSignature();
293 entity->setSignature(sig);
295 sig->setSignatureAlgorithm(sigalg.second);
297 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
299 cr->setDigestAlgorithm(digalg.second);
302 // Sign response while marshalling.
303 vector<Signature*> sigs(1,sig);
304 entity->marshall((DOMDocument*)NULL,&sigs,cred);
310 httpResponse.setContentType("application/samlmetadata+xml");
311 return make_pair(true, httpResponse.sendResponse(s));
313 return make_pair(false,0);