2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * MetadataGenerator.cpp
24 * Handler for generating "approximate" metadata based on SP configuration.
28 #include "Application.h"
29 #include "exceptions.h"
30 #include "ServiceProvider.h"
31 #include "SPRequest.h"
32 #include "handler/AbstractHandler.h"
33 #include "handler/RemotedHandler.h"
34 #include "util/IPRange.h"
37 # include "attribute/resolver/AttributeExtractor.h"
38 # include "metadata/MetadataProviderCriteria.h"
39 # include <saml/exceptions.h>
40 # include <saml/SAMLConfig.h>
41 # include <saml/signature/ContentReference.h>
42 # include <saml/saml2/metadata/Metadata.h>
43 # include <saml/saml2/metadata/MetadataProvider.h>
44 # include <xmltooling/XMLToolingConfig.h>
45 # include <xmltooling/security/Credential.h>
46 # include <xmltooling/security/CredentialCriteria.h>
47 # include <xmltooling/security/SecurityHelper.h>
48 # include <xmltooling/signature/Signature.h>
49 # include <xmltooling/util/ParserPool.h>
50 # include <xmltooling/util/PathResolver.h>
51 # include <xercesc/framework/LocalFileInputSource.hpp>
52 # include <xercesc/framework/Wrapper4InputSource.hpp>
56 using namespace shibsp;
58 using namespace opensaml::saml2md;
59 using namespace opensaml;
60 using namespace xmlsignature;
62 using namespace xmltooling;
67 #if defined (_MSC_VER)
68 #pragma warning( push )
69 #pragma warning( disable : 4250 )
72 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
75 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
80 acceptNode(const DOMNode* node) const {
85 static SHIBSP_DLLLOCAL Blocker g_Blocker;
87 class SHIBSP_API MetadataGenerator : public AbstractHandler, public RemotedHandler
90 MetadataGenerator(const DOMElement* e, const char* appId);
91 virtual ~MetadataGenerator() {
96 for_each(m_contacts.begin(), m_contacts.end(), xmltooling::cleanup<ContactPerson>());
97 for_each(m_formats.begin(), m_formats.end(), xmltooling::cleanup<NameIDFormat>());
98 for_each(m_reqAttrs.begin(), m_reqAttrs.end(), xmltooling::cleanup<RequestedAttribute>());
99 for_each(m_attrConsumers.begin(), m_attrConsumers.end(), xmltooling::cleanup<AttributeConsumingService>());
103 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
104 void receive(DDF& in, ostream& out);
107 pair<bool,long> processMessage(
108 const Application& application,
109 const char* handlerURL,
110 const char* entityID,
111 HTTPResponse& httpResponse
114 vector<IPRange> m_acl;
117 short m_http,m_https;
118 vector<string> m_bases;
121 EntityAttributes* m_entityAttrs;
122 vector<ContactPerson*> m_contacts;
123 vector<NameIDFormat*> m_formats;
124 vector<RequestedAttribute*> m_reqAttrs;
125 vector<AttributeConsumingService*> m_attrConsumers;
129 #if defined (_MSC_VER)
130 #pragma warning( pop )
133 Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
135 return new MetadataGenerator(p.first, p.second);
140 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
141 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
143 ,m_http(0), m_https(0), m_uiinfo(nullptr), m_org(nullptr), m_entityAttrs(nullptr)
146 string address(appId);
147 address += getString("Location").second;
148 setAddress(address.c_str());
150 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
151 pair<bool,const char*> acl = getString("acl");
153 string aclbuf=acl.second;
155 for (unsigned int i=0; i < aclbuf.length(); ++i) {
156 if (aclbuf.at(i)==' ') {
158 m_acl.push_back(IPRange::parseCIDRBlock(aclbuf.substr(j, i-j).c_str()));
160 catch (exception& ex) {
161 m_log.error("invalid CIDR block (%s): %s", aclbuf.substr(j, i-j).c_str(), ex.what());
167 m_acl.push_back(IPRange::parseCIDRBlock(aclbuf.substr(j, aclbuf.length()-j).c_str()));
169 catch (exception& ex) {
170 m_log.error("invalid CIDR block (%s): %s", aclbuf.substr(j, aclbuf.length()-j).c_str(), ex.what());
174 m_log.warn("invalid CIDR range(s) in Metadata Generator acl property, allowing 127.0.0.1 as a fall back");
175 m_acl.push_back(IPRange::parseCIDRBlock("127.0.0.1"));
181 static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
183 pair<bool,const char*> salt = getString("salt");
185 m_salt = salt.second;
187 pair<bool,bool> flag = getBool("http");
189 m_http = flag.second ? 1 : -1;
190 flag = getBool("https");
192 m_https = flag.second ? 1 : -1;
194 e = XMLHelper::getFirstChildElement(e);
196 if (XMLString::equals(e->getLocalName(), EndpointBase) && e->hasChildNodes()) {
197 auto_ptr_char base(e->getFirstChild()->getNodeValue());
198 if (base.get() && *base.get())
199 m_bases.push_back(base.get());
202 // Try and parse the object.
203 auto_ptr<XMLObject> child(XMLObjectBuilder::buildOneFromElement(const_cast<DOMElement*>(e)));
204 ContactPerson* cp = dynamic_cast<ContactPerson*>(child.get());
207 m_contacts.push_back(cp);
210 NameIDFormat* nif = dynamic_cast<NameIDFormat*>(child.get());
213 m_formats.push_back(nif);
216 RequestedAttribute* req = dynamic_cast<RequestedAttribute*>(child.get());
219 m_reqAttrs.push_back(req);
222 AttributeConsumingService* acs = dynamic_cast<AttributeConsumingService*>(child.get());
225 m_attrConsumers.push_back(acs);
228 UIInfo* info = dynamic_cast<UIInfo*>(child.get());
235 m_log.warn("skipping duplicate UIInfo element");
239 Organization* org = dynamic_cast<Organization*>(child.get());
246 m_log.warn("skipping duplicate Organization element");
250 EntityAttributes* ea = dynamic_cast<EntityAttributes*>(child.get());
252 if (!m_entityAttrs) {
257 m_log.warn("skipping duplicate EntityAttributes element");
267 e = XMLHelper::getNextSiblingElement(e);
272 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
274 SPConfig& conf = SPConfig::getConfig();
275 if (conf.isEnabled(SPConfig::InProcess) && !m_acl.empty()) {
277 for (vector<IPRange>::const_iterator acl = m_acl.begin(); !found && acl != m_acl.end(); ++acl) {
278 found = acl->contains(request.getRemoteAddr().c_str());
281 m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
282 istringstream msg("Metadata Request Blocked");
283 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
288 if (conf.isEnabled(SPConfig::OutOfProcess)) {
289 // When out of process, we run natively and directly process the message.
290 return processMessage(request.getApplication(), request.getHandlerURL(), request.getParameter("entityID"), request);
293 // When not out of process, we remote all the message processing.
294 DDF out,in = DDF(m_address.c_str());
295 in.addmember("application_id").string(request.getApplication().getId());
296 in.addmember("handler_url").string(request.getHandlerURL());
297 if (request.getParameter("entityID"))
298 in.addmember("entity_id").string(request.getParameter("entityID"));
299 DDFJanitor jin(in), jout(out);
301 out=request.getServiceProvider().getListenerService()->send(in);
302 return unwrap(request, out);
305 catch (exception& ex) {
306 m_log.error("error while processing request: %s", ex.what());
307 istringstream msg("Metadata Request Failed");
308 return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
312 void MetadataGenerator::receive(DDF& in, ostream& out)
315 const char* aid=in["application_id"].string();
316 const char* hurl=in["handler_url"].string();
317 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
319 // Something's horribly wrong.
320 m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
321 throw ConfigurationException("Unable to locate application for metadata request, deleted?");
324 throw ConfigurationException("Missing handler_url parameter in remoted method call.");
327 // Wrap a response shim.
329 DDFJanitor jout(ret);
330 auto_ptr<HTTPResponse> resp(getResponse(ret));
332 // Since we're remoted, the result should either be a throw, a false/0 return,
333 // which we just return as an empty structure, or a response/redirect,
334 // which we capture in the facade and send back.
335 processMessage(*app, hurl, in["entity_id"].string(), *resp.get());
339 pair<bool,long> MetadataGenerator::processMessage(
340 const Application& application, const char* handlerURL, const char* entityID, HTTPResponse& httpResponse
344 m_log.debug("processing metadata request");
346 const PropertySet* relyingParty=nullptr;
348 MetadataProvider* m=application.getMetadataProvider();
350 MetadataProviderCriteria mc(application, entityID);
351 relyingParty = application.getRelyingParty(m->getEntityDescriptor(mc).first);
354 relyingParty = &application;
357 EntityDescriptor* entity;
358 pair<bool,const char*> prop = getString("template");
360 // Load a template to use for our metadata.
361 string templ(prop.second);
362 XMLToolingConfig::getConfig().getPathResolver()->resolve(templ, PathResolver::XMLTOOLING_CFG_FILE);
363 auto_ptr_XMLCh widenit(templ.c_str());
364 LocalFileInputSource src(widenit.get());
365 Wrapper4InputSource dsrc(&src,false);
366 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
367 XercesJanitor<DOMDocument> docjan(doc);
368 auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
370 entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
372 throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, templ.c_str()));
376 entity = EntityDescriptorBuilder::buildEntityDescriptor();
379 if (!entity->getID()) {
380 string hashinput = m_salt + relyingParty->getString("entityID").second;
381 string hashed = '_' + SecurityHelper::doHash("SHA1", hashinput.c_str(), hashinput.length());
382 auto_ptr_XMLCh widenit(hashed.c_str());
383 entity->setID(widenit.get());
386 auto_ptr<EntityDescriptor> wrapper(entity);
387 pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
389 entity->setCacheDuration(cache.second);
391 cache = getUnsignedInt("validUntil");
393 entity->setValidUntil(time(nullptr) + cache.second);
394 entity->setEntityID(relyingParty->getXMLString("entityID").second);
396 if (m_org && !entity->getOrganization())
397 entity->setOrganization(m_org->cloneOrganization());
399 for (vector<ContactPerson*>::const_iterator cp = m_contacts.begin(); cp != m_contacts.end(); ++cp)
400 entity->getContactPersons().push_back((*cp)->cloneContactPerson());
403 if (!entity->getExtensions())
404 entity->setExtensions(ExtensionsBuilder::buildExtensions());
405 entity->getExtensions()->getUnknownXMLObjects().push_back(m_entityAttrs->cloneEntityAttributes());
408 SPSSODescriptor* role;
409 if (entity->getSPSSODescriptors().empty()) {
410 role = SPSSODescriptorBuilder::buildSPSSODescriptor();
411 entity->getSPSSODescriptors().push_back(role);
414 role = entity->getSPSSODescriptors().front();
417 for (vector<NameIDFormat*>::const_iterator nif = m_formats.begin(); nif != m_formats.end(); ++nif)
418 role->getNameIDFormats().push_back((*nif)->cloneNameIDFormat());
421 if (!role->getExtensions())
422 role->setExtensions(ExtensionsBuilder::buildExtensions());
423 role->getExtensions()->getUnknownXMLObjects().push_back(m_uiinfo->cloneUIInfo());
426 for (vector<AttributeConsumingService*>::const_iterator acs = m_attrConsumers.begin(); acs != m_attrConsumers.end(); ++acs)
427 role->getAttributeConsumingServices().push_back((*acs)->cloneAttributeConsumingService());
429 if (!m_reqAttrs.empty()) {
431 const vector<AttributeConsumingService*>& svcs = const_cast<const SPSSODescriptor*>(role)->getAttributeConsumingServices();
432 for (vector<AttributeConsumingService*>::const_iterator s =svcs.begin(); s != svcs.end(); ++s) {
433 pair<bool,int> i = (*s)->getIndex();
434 if (i.first && index == i.second)
435 index = i.second + 1;
437 AttributeConsumingService* svc = AttributeConsumingServiceBuilder::buildAttributeConsumingService();
438 role->getAttributeConsumingServices().push_back(svc);
439 svc->setIndex(index);
440 ServiceName* sn = ServiceNameBuilder::buildServiceName();
441 svc->getServiceNames().push_back(sn);
442 sn->setName(entity->getEntityID());
443 static const XMLCh english[] = UNICODE_LITERAL_2(e,n);
444 sn->setLang(english);
445 for (vector<RequestedAttribute*>::const_iterator req = m_reqAttrs.begin(); req != m_reqAttrs.end(); ++req)
446 svc->getRequestedAttributes().push_back((*req)->cloneRequestedAttribute());
450 prop = relyingParty->getString("signing");
451 if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
452 role->AuthnRequestsSigned(true);
453 pair<bool,bool> flagprop = relyingParty->getBool("requireSignedAssertions");
454 if (flagprop.first && flagprop.second)
455 role->WantAssertionsSigned(true);
457 // Ask each handler to generate itself.
458 vector<const Handler*> handlers;
459 application.getHandlers(handlers);
460 for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
461 if (m_bases.empty()) {
462 if (strncmp(handlerURL, "https", 5) == 0) {
464 (*h)->generateMetadata(*role, handlerURL);
466 string temp(handlerURL);
468 (*h)->generateMetadata(*role, temp.c_str());
473 (*h)->generateMetadata(*role, handlerURL);
475 string temp(handlerURL);
476 temp.insert(temp.begin() + 4, 's');
477 (*h)->generateMetadata(*role, temp.c_str());
482 for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
483 (*h)->generateMetadata(*role, b->c_str());
487 AttributeExtractor* extractor = application.getAttributeExtractor();
489 Locker extlocker(extractor);
490 extractor->generateMetadata(*role);
493 CredentialResolver* credResolver=application.getCredentialResolver();
495 Locker credLocker(credResolver);
496 CredentialCriteria cc;
497 prop = relyingParty->getString("keyName");
499 cc.getKeyNames().insert(prop.second);
500 vector<const Credential*> signingcreds,enccreds;
501 cc.setUsage(Credential::SIGNING_CREDENTIAL);
502 credResolver->resolve(signingcreds, &cc);
503 cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
504 credResolver->resolve(enccreds, &cc);
506 for (vector<const Credential*>::const_iterator c = signingcreds.begin(); c != signingcreds.end(); ++c) {
507 KeyInfo* kinfo = (*c)->getKeyInfo();
509 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
510 kd->setKeyInfo(kinfo);
511 const XMLCh* use = KeyDescriptor::KEYTYPE_SIGNING;
512 for (vector<const Credential*>::iterator match = enccreds.begin(); match != enccreds.end(); ++match) {
515 enccreds.erase(match);
520 role->getKeyDescriptors().push_back(kd);
524 for (vector<const Credential*>::const_iterator c = enccreds.begin(); c != enccreds.end(); ++c) {
525 KeyInfo* kinfo = (*c)->getKeyInfo();
527 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
528 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
529 kd->setKeyInfo(kinfo);
530 role->getKeyDescriptors().push_back(kd);
535 // Stream for response.
539 pair<bool,bool> flag = getBool("signing");
540 if (flag.first && flag.second) {
542 Locker credLocker(credResolver);
543 // Fill in criteria to use.
544 CredentialCriteria cc;
545 cc.setUsage(Credential::SIGNING_CREDENTIAL);
546 prop = getString("keyName");
548 cc.getKeyNames().insert(prop.second);
549 pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
550 pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
552 cc.setXMLAlgorithm(sigalg.second);
553 const Credential* cred = credResolver->resolve(&cc);
555 throw XMLSecurityException("Unable to obtain signing credential to use.");
557 // Pretty-print it first and then read it back in.
559 XMLHelper::serialize(entity->marshall(), pretty, true);
560 DOMDocument* prettydoc = XMLToolingConfig::getConfig().getParser().parse(pretty);
561 auto_ptr<XMLObject> prettyentity(XMLObjectBuilder::buildOneFromElement(prettydoc->getDocumentElement(), true));
563 Signature* sig = SignatureBuilder::buildSignature();
564 dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
566 sig->setSignatureAlgorithm(sigalg.second);
568 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
570 cr->setDigestAlgorithm(digalg.second);
573 // Sign while marshalling.
574 vector<Signature*> sigs(1,sig);
575 prettyentity->marshall(prettydoc,&sigs,cred);
579 throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
583 // Pretty-print it directly to client.
584 XMLHelper::serialize(entity->marshall(), s, true);
587 prop = getString("mimeType");
588 httpResponse.setContentType(prop.first ? prop.second : "application/samlmetadata+xml");
589 return make_pair(true, httpResponse.sendResponse(s));
591 return make_pair(false,0L);