2 * Copyright 2001-2010 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 "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/RemotedHandler.h"
32 # include "attribute/resolver/AttributeExtractor.h"
33 # include "metadata/MetadataProviderCriteria.h"
34 # include <saml/exceptions.h>
35 # include <saml/SAMLConfig.h>
36 # include <saml/signature/ContentReference.h>
37 # include <saml/saml2/metadata/Metadata.h>
38 # include <saml/saml2/metadata/MetadataProvider.h>
39 # include <xmltooling/XMLToolingConfig.h>
40 # include <xmltooling/security/Credential.h>
41 # include <xmltooling/security/CredentialCriteria.h>
42 # include <xmltooling/security/SecurityHelper.h>
43 # include <xmltooling/signature/Signature.h>
44 # include <xmltooling/util/ParserPool.h>
45 # include <xmltooling/util/PathResolver.h>
46 # include <xercesc/framework/LocalFileInputSource.hpp>
47 # include <xercesc/framework/Wrapper4InputSource.hpp>
51 using namespace shibsp;
53 using namespace opensaml::saml2md;
54 using namespace opensaml;
55 using namespace xmlsignature;
57 using namespace xmltooling;
62 #if defined (_MSC_VER)
63 #pragma warning( push )
64 #pragma warning( disable : 4250 )
67 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
70 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
75 acceptNode(const DOMNode* node) const {
80 static SHIBSP_DLLLOCAL Blocker g_Blocker;
82 class SHIBSP_API MetadataGenerator : public AbstractHandler, public RemotedHandler
85 MetadataGenerator(const DOMElement* e, const char* appId);
86 virtual ~MetadataGenerator() {
91 for_each(m_contacts.begin(), m_contacts.end(), xmltooling::cleanup<ContactPerson>());
92 for_each(m_formats.begin(), m_formats.end(), xmltooling::cleanup<NameIDFormat>());
93 for_each(m_reqAttrs.begin(), m_reqAttrs.end(), xmltooling::cleanup<RequestedAttribute>());
94 for_each(m_attrConsumers.begin(), m_attrConsumers.end(), xmltooling::cleanup<AttributeConsumingService>());
98 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
99 void receive(DDF& in, ostream& out);
102 pair<bool,long> processMessage(
103 const Application& application,
104 const char* handlerURL,
105 const char* entityID,
106 HTTPResponse& httpResponse
112 short m_http,m_https;
113 vector<string> m_bases;
116 EntityAttributes* m_entityAttrs;
117 vector<ContactPerson*> m_contacts;
118 vector<NameIDFormat*> m_formats;
119 vector<RequestedAttribute*> m_reqAttrs;
120 vector<AttributeConsumingService*> m_attrConsumers;
124 #if defined (_MSC_VER)
125 #pragma warning( pop )
128 Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
130 return new MetadataGenerator(p.first, p.second);
135 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
136 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
138 ,m_http(0), m_https(0), m_uiinfo(nullptr), m_org(nullptr), m_entityAttrs(nullptr)
141 string address(appId);
142 address += getString("Location").second;
143 setAddress(address.c_str());
144 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
145 pair<bool,const char*> acl = getString("acl");
147 string aclbuf=acl.second;
149 for (unsigned int i=0; i < aclbuf.length(); i++) {
150 if (aclbuf.at(i)==' ') {
151 m_acl.insert(aclbuf.substr(j, i-j));
155 m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
160 static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
162 pair<bool,const char*> salt = getString("salt");
164 m_salt = salt.second;
166 pair<bool,bool> flag = getBool("http");
168 m_http = flag.second ? 1 : -1;
169 flag = getBool("https");
171 m_https = flag.second ? 1 : -1;
173 e = XMLHelper::getFirstChildElement(e);
175 if (XMLString::equals(e->getLocalName(), EndpointBase) && e->hasChildNodes()) {
176 auto_ptr_char base(e->getFirstChild()->getNodeValue());
177 if (base.get() && *base.get())
178 m_bases.push_back(base.get());
181 // Try and parse the object.
182 auto_ptr<XMLObject> child(XMLObjectBuilder::buildOneFromElement(const_cast<DOMElement*>(e)));
183 ContactPerson* cp = dynamic_cast<ContactPerson*>(child.get());
186 m_contacts.push_back(cp);
189 NameIDFormat* nif = dynamic_cast<NameIDFormat*>(child.get());
192 m_formats.push_back(nif);
195 RequestedAttribute* req = dynamic_cast<RequestedAttribute*>(child.get());
198 m_reqAttrs.push_back(req);
201 AttributeConsumingService* acs = dynamic_cast<AttributeConsumingService*>(child.get());
204 m_attrConsumers.push_back(acs);
207 UIInfo* info = dynamic_cast<UIInfo*>(child.get());
214 m_log.warn("skipping duplicate UIInfo element");
218 Organization* org = dynamic_cast<Organization*>(child.get());
225 m_log.warn("skipping duplicate Organization element");
229 EntityAttributes* ea = dynamic_cast<EntityAttributes*>(child.get());
231 if (!m_entityAttrs) {
236 m_log.warn("skipping duplicate EntityAttributes element");
246 e = XMLHelper::getNextSiblingElement(e);
251 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
253 SPConfig& conf = SPConfig::getConfig();
254 if (conf.isEnabled(SPConfig::InProcess)) {
255 if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
256 m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
257 istringstream msg("Metadata Request Blocked");
258 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
263 if (conf.isEnabled(SPConfig::OutOfProcess)) {
264 // When out of process, we run natively and directly process the message.
265 return processMessage(request.getApplication(), request.getHandlerURL(), request.getParameter("entityID"), request);
268 // When not out of process, we remote all the message processing.
269 DDF out,in = DDF(m_address.c_str());
270 in.addmember("application_id").string(request.getApplication().getId());
271 in.addmember("handler_url").string(request.getHandlerURL());
272 if (request.getParameter("entityID"))
273 in.addmember("entity_id").string(request.getParameter("entityID"));
274 DDFJanitor jin(in), jout(out);
276 out=request.getServiceProvider().getListenerService()->send(in);
277 return unwrap(request, out);
280 catch (exception& ex) {
281 m_log.error("error while processing request: %s", ex.what());
282 istringstream msg("Metadata Request Failed");
283 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
287 void MetadataGenerator::receive(DDF& in, ostream& out)
290 const char* aid=in["application_id"].string();
291 const char* hurl=in["handler_url"].string();
292 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
294 // Something's horribly wrong.
295 m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
296 throw ConfigurationException("Unable to locate application for metadata request, deleted?");
299 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
302 // Wrap a response shim.
304 DDFJanitor jout(ret);
305 auto_ptr<HTTPResponse> resp(getResponse(ret));
307 // Since we're remoted, the result should either be a throw, a false/0 return,
308 // which we just return as an empty structure, or a response/redirect,
309 // which we capture in the facade and send back.
310 processMessage(*app, hurl, in["entity_id"].string(), *resp.get());
314 pair<bool,long> MetadataGenerator::processMessage(
315 const Application& application, const char* handlerURL, const char* entityID, HTTPResponse& httpResponse
319 m_log.debug("processing metadata request");
321 const PropertySet* relyingParty=nullptr;
323 MetadataProvider* m=application.getMetadataProvider();
325 MetadataProviderCriteria mc(application, entityID);
326 relyingParty = application.getRelyingParty(m->getEntityDescriptor(mc).first);
329 relyingParty = &application;
332 EntityDescriptor* entity;
333 pair<bool,const char*> prop = getString("template");
335 // Load a template to use for our metadata.
336 string templ(prop.second);
337 XMLToolingConfig::getConfig().getPathResolver()->resolve(templ, PathResolver::XMLTOOLING_CFG_FILE);
338 auto_ptr_XMLCh widenit(templ.c_str());
339 LocalFileInputSource src(widenit.get());
340 Wrapper4InputSource dsrc(&src,false);
341 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
342 XercesJanitor<DOMDocument> docjan(doc);
343 auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
345 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
347 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, templ.c_str()));
351 entity = EntityDescriptorBuilder::buildEntityDescriptor();
354 if (!entity->getID()) {
355 string hashinput = m_salt + relyingParty->getString("entityID").second;
356 string hashed = '_' + SecurityHelper::doHash("SHA1", hashinput.c_str(), hashinput.length());
357 auto_ptr_XMLCh widenit(hashed.c_str());
358 entity->setID(widenit.get());
361 auto_ptr<EntityDescriptor> wrapper(entity);
362 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
364 entity->setCacheDuration(cache.second);
366 cache = getUnsignedInt("validUntil");
368 entity->setValidUntil(time(nullptr) + cache.second);
369 entity->setEntityID(relyingParty->getXMLString("entityID").second);
371 if (m_org && !entity->getOrganization())
372 entity->setOrganization(m_org->cloneOrganization());
374 for (vector<ContactPerson*>::const_iterator cp = m_contacts.begin(); cp != m_contacts.end(); ++cp)
375 entity->getContactPersons().push_back((*cp)->cloneContactPerson());
378 if (!entity->getExtensions())
379 entity->setExtensions(ExtensionsBuilder::buildExtensions());
380 entity->getExtensions()->getUnknownXMLObjects().push_back(m_entityAttrs->cloneEntityAttributes());
383 SPSSODescriptor* role;
384 if (entity->getSPSSODescriptors().empty()) {
385 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
386 entity->getSPSSODescriptors().push_back(role);
389 role = entity->getSPSSODescriptors().front();
392 for (vector<NameIDFormat*>::const_iterator nif = m_formats.begin(); nif != m_formats.end(); ++nif)
393 role->getNameIDFormats().push_back((*nif)->cloneNameIDFormat());
396 if (!role->getExtensions())
397 role->setExtensions(ExtensionsBuilder::buildExtensions());
398 role->getExtensions()->getUnknownXMLObjects().push_back(m_uiinfo->cloneUIInfo());
401 for (vector<AttributeConsumingService*>::const_iterator acs = m_attrConsumers.begin(); acs != m_attrConsumers.end(); ++acs)
402 role->getAttributeConsumingServices().push_back((*acs)->cloneAttributeConsumingService());
404 if (!m_reqAttrs.empty()) {
406 const vector<AttributeConsumingService*>& svcs = const_cast<const SPSSODescriptor*>(role)->getAttributeConsumingServices();
407 for (vector<AttributeConsumingService*>::const_iterator s =svcs.begin(); s != svcs.end(); ++s) {
408 pair<bool,int> i = (*s)->getIndex();
409 if (i.first && index == i.second)
410 index = i.second + 1;
412 AttributeConsumingService* svc = AttributeConsumingServiceBuilder::buildAttributeConsumingService();
413 role->getAttributeConsumingServices().push_back(svc);
414 svc->setIndex(index);
415 ServiceName* sn = ServiceNameBuilder::buildServiceName();
416 svc->getServiceNames().push_back(sn);
417 sn->setName(entity->getEntityID());
418 static const XMLCh english[] = UNICODE_LITERAL_2(e,n);
419 sn->setLang(english);
420 for (vector<RequestedAttribute*>::const_iterator req = m_reqAttrs.begin(); req != m_reqAttrs.end(); ++req)
421 svc->getRequestedAttributes().push_back((*req)->cloneRequestedAttribute());
425 prop = relyingParty->getString("signing");
426 if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
427 role->AuthnRequestsSigned(true);
428 pair<bool,bool> flagprop = relyingParty->getBool("requireSignedAssertions");
429 if (flagprop.first && flagprop.second)
430 role->WantAssertionsSigned(true);
432 // Ask each handler to generate itself.
433 vector<const Handler*> handlers;
434 application.getHandlers(handlers);
435 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
436 if (m_bases.empty()) {
437 if (strncmp(handlerURL, "https", 5) == 0) {
439 (*h)->generateMetadata(*role, handlerURL);
441 string temp(handlerURL);
443 (*h)->generateMetadata(*role, temp.c_str());
448 (*h)->generateMetadata(*role, handlerURL);
450 string temp(handlerURL);
451 temp.insert(temp.begin() + 4, 's');
452 (*h)->generateMetadata(*role, temp.c_str());
457 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
458 (*h)->generateMetadata(*role, b->c_str());
462 AttributeExtractor* extractor = application.getAttributeExtractor();
464 Locker extlocker(extractor);
465 extractor->generateMetadata(*role);
468 CredentialResolver* credResolver=application.getCredentialResolver();
470 Locker credLocker(credResolver);
471 CredentialCriteria cc;
472 prop = relyingParty->getString("keyName");
474 cc.getKeyNames().insert(prop.second);
475 vector<const Credential*> signingcreds,enccreds;
476 cc.setUsage(Credential::SIGNING_CREDENTIAL);
477 credResolver->resolve(signingcreds, &cc);
478 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
479 credResolver->resolve(enccreds, &cc);
481 for (vector<const Credential*>::const_iterator c = signingcreds.begin(); c != signingcreds.end(); ++c) {
482 KeyInfo* kinfo = (*c)->getKeyInfo();
484 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
485 kd->setKeyInfo(kinfo);
486 const XMLCh* use = KeyDescriptor::KEYTYPE_SIGNING;
487 for (vector<const Credential*>::iterator match = enccreds.begin(); match != enccreds.end(); ++match) {
490 enccreds.erase(match);
495 role->getKeyDescriptors().push_back(kd);
499 for (vector<const Credential*>::const_iterator c = enccreds.begin(); c != enccreds.end(); ++c) {
500 KeyInfo* kinfo = (*c)->getKeyInfo();
502 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
503 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
504 kd->setKeyInfo(kinfo);
505 role->getKeyDescriptors().push_back(kd);
510 // Stream for response.
514 pair<bool,bool> flag = getBool("signing");
515 if (flag.first && flag.second) {
517 Locker credLocker(credResolver);
518 // Fill in criteria to use.
519 CredentialCriteria cc;
520 cc.setUsage(Credential::SIGNING_CREDENTIAL);
521 prop = getString("keyName");
523 cc.getKeyNames().insert(prop.second);
524 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
525 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
527 cc.setXMLAlgorithm(sigalg.second);
528 const Credential* cred = credResolver->resolve(&cc);
530 throw XMLSecurityException("Unable to obtain signing credential to use.");
532 // Pretty-print it first and then read it back in.
534 XMLHelper::serialize(entity->marshall(), pretty, true);
535 DOMDocument* prettydoc = XMLToolingConfig::getConfig().getParser().parse(pretty);
536 auto_ptr<XMLObject> prettyentity(XMLObjectBuilder::buildOneFromElement(prettydoc->getDocumentElement(), true));
538 Signature* sig = SignatureBuilder::buildSignature();
539 dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
541 sig->setSignatureAlgorithm(sigalg.second);
543 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
545 cr->setDigestAlgorithm(digalg.second);
548 // Sign while marshalling.
549 vector<Signature*> sigs(1,sig);
550 prettyentity->marshall(prettydoc,&sigs,cred);
554 throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
558 // Pretty-print it directly to client.
559 XMLHelper::serialize(entity->marshall(), s, true);
562 prop = getString("mimeType");
563 httpResponse.setContentType(prop.first ? prop.second : "application/samlmetadata+xml");
564 return make_pair(true, httpResponse.sendResponse(s));
566 return make_pair(false,0L);