https://bugs.internet2.edu/jira/browse/SSPCPP-288
[shibboleth/sp.git] / shibsp / handler / impl / MetadataGenerator.cpp
index 48a077b..322b7e3 100644 (file)
@@ -1,6 +1,6 @@
 /*
- *  Copyright 2001-2007 Internet2
- * 
+ *  Copyright 2001-2010 Internet2
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
@@ -16,7 +16,7 @@
 
 /**
  * MetadataGenerator.cpp
- * 
+ *
  * Handler for generating "approximate" metadata based on SP configuration.
  */
 
 #include "Application.h"
 #include "exceptions.h"
 #include "ServiceProvider.h"
+#include "SPRequest.h"
 #include "handler/AbstractHandler.h"
 #include "handler/RemotedHandler.h"
 
-#include <xercesc/framework/LocalFileInputSource.hpp>
-#include <xercesc/framework/Wrapper4InputSource.hpp>
+#ifndef SHIBSP_LITE
+# include "metadata/MetadataProviderCriteria.h"
+# include <saml/exceptions.h>
+# include <saml/SAMLConfig.h>
+# include <saml/signature/ContentReference.h>
+# include <saml/saml2/metadata/Metadata.h>
+# include <saml/saml2/metadata/MetadataProvider.h>
+# include <xmltooling/XMLToolingConfig.h>
+# include <xmltooling/security/Credential.h>
+# include <xmltooling/security/CredentialCriteria.h>
+# include <xmltooling/security/SecurityHelper.h>
+# include <xmltooling/signature/Signature.h>
+# include <xmltooling/util/ParserPool.h>
+# include <xmltooling/util/PathResolver.h>
+# include <xercesc/framework/LocalFileInputSource.hpp>
+# include <xercesc/framework/Wrapper4InputSource.hpp>
+#endif
+
 
 using namespace shibsp;
 #ifndef SHIBSP_LITE
@@ -49,7 +66,12 @@ namespace shibsp {
     class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
     {
     public:
-        short acceptNode(const DOMNode* node) const {
+#ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
+        short
+#else
+        FilterAction
+#endif
+        acceptNode(const DOMNode* node) const {
             return FILTER_REJECT;
         }
     };
@@ -66,13 +88,18 @@ namespace shibsp {
         void receive(DDF& in, ostream& out);
 
     private:
-        pair<bool,long> processMessage(const Application& application, const char* handlerURL, HTTPResponse& httpResponse) const;
+        pair<bool,long> processMessage(
+            const Application& application,
+            const char* handlerURL,
+            const char* entityID,
+            HTTPResponse& httpResponse
+            ) const;
 
         set<string> m_acl;
 #ifndef SHIBSP_LITE
+        string m_salt;
         short m_http,m_https;
         vector<string> m_bases;
-        const char* m_mime;
 #endif
     };
 
@@ -90,7 +117,7 @@ namespace shibsp {
 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
 #ifndef SHIBSP_LITE
-        ,m_https(0), m_http(0), m_mime(NULL)
+        ,m_http(0), m_https(0)
 #endif
 {
     string address(appId);
@@ -113,17 +140,17 @@ MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
 
 #ifndef SHIBSP_LITE
     static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
-    
+
+    pair<bool,const char*> salt = getString("salt");
+    if (salt.first)
+        m_salt = salt.second;
+
     pair<bool,bool> flag = getBool("http");
     if (flag.first)
         m_http = flag.second ? 1 : -1;
     flag = getBool("https");
     if (flag.first)
         m_https = flag.second ? 1 : -1;
-    
-    pair<bool,const char*> mime = getString("mimeType");
-    if (mime.first)
-        m_mime = mime.second;
 
     e = XMLHelper::getFirstChildElement(e, EndpointBase);
     while (e) {
@@ -144,22 +171,24 @@ pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
         if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
             m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
             istringstream msg("Metadata Request Blocked");
-            return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED));
+            return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
         }
     }
-    
+
     try {
         if (conf.isEnabled(SPConfig::OutOfProcess)) {
             // When out of process, we run natively and directly process the message.
-            return processMessage(request.getApplication(), request.getHandlerURL(), request);
+            return processMessage(request.getApplication(), request.getHandlerURL(), request.getParameter("entityID"), request);
         }
         else {
             // When not out of process, we remote all the message processing.
             DDF out,in = DDF(m_address.c_str());
             in.addmember("application_id").string(request.getApplication().getId());
             in.addmember("handler_url").string(request.getHandlerURL());
+            if (request.getParameter("entityID"))
+                in.addmember("entity_id").string(request.getParameter("entityID"));
             DDFJanitor jin(in), jout(out);
-            
+
             out=request.getServiceProvider().getListenerService()->send(in);
             return unwrap(request, out);
         }
@@ -185,47 +214,75 @@ void MetadataGenerator::receive(DDF& in, ostream& out)
     else if (!hurl) {
         throw ConfigurationException("Missing handler_url parameter in remoted method call.");
     }
-    
+
     // Wrap a response shim.
     DDF ret(NULL);
     DDFJanitor jout(ret);
     auto_ptr<HTTPResponse> resp(getResponse(ret));
-        
+
     // Since we're remoted, the result should either be a throw, a false/0 return,
     // which we just return as an empty structure, or a response/redirect,
     // which we capture in the facade and send back.
-    processMessage(*app, hurl, *resp.get());
+    processMessage(*app, hurl, in["entity_id"].string(), *resp.get());
     out << ret;
 }
 
-pair<bool,long> MetadataGenerator::processMessage(const Application& application, const char* handlerURL, HTTPResponse& httpResponse) const
+pair<bool,long> MetadataGenerator::processMessage(
+    const Application& application, const char* handlerURL, const char* entityID, HTTPResponse& httpResponse
+    ) const
 {
 #ifndef SHIBSP_LITE
     m_log.debug("processing metadata request");
 
+    const PropertySet* relyingParty=NULL;
+    if (entityID) {
+        MetadataProvider* m=application.getMetadataProvider();
+        Locker locker(m);
+        MetadataProviderCriteria mc(application, entityID);
+        relyingParty = application.getRelyingParty(m->getEntityDescriptor(mc).first);
+    }
+    else {
+        relyingParty = &application;
+    }
+
     EntityDescriptor* entity;
     pair<bool,const char*> prop = getString("template");
     if (prop.first) {
         // Load a template to use for our metadata.
-        LocalFileInputSource src(getXMLString("template").second);
+        string templ(prop.second);
+        XMLToolingConfig::getConfig().getPathResolver()->resolve(templ, PathResolver::XMLTOOLING_CFG_FILE);
+        auto_ptr_XMLCh widenit(templ.c_str());
+        LocalFileInputSource src(widenit.get());
         Wrapper4InputSource dsrc(&src,false);
         DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
         XercesJanitor<DOMDocument> docjan(doc);
         auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
+        docjan.release();
         entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
         if (!entity)
-            throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, prop.second));
+            throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, templ.c_str()));
         xmlobj.release();
     }
     else {
         entity = EntityDescriptorBuilder::buildEntityDescriptor();
     }
 
+    if (!entity->getID()) {
+        string hashinput = m_salt + relyingParty->getString("entityID").second;
+        string hashed = '_' + SecurityHelper::doHash("SHA1", hashinput.c_str(), hashinput.length());
+        auto_ptr_XMLCh widenit(hashed.c_str());
+        entity->setID(widenit.get());
+    }
+
     auto_ptr<EntityDescriptor> wrapper(entity);
     pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
+    if (cache.first) {
+        entity->setCacheDuration(cache.second);
+    }
+    cache = getUnsignedInt("validUntil");
     if (cache.first)
         entity->setValidUntil(time(NULL) + cache.second);
-    entity->setEntityID(application.getXMLString("entityID").second);
+    entity->setEntityID(relyingParty->getXMLString("entityID").second);
 
     SPSSODescriptor* role;
     if (entity->getSPSSODescriptors().empty()) {
@@ -237,10 +294,10 @@ pair<bool,long> MetadataGenerator::processMessage(const Application& application
     }
 
     // Policy flags.
-    prop = application.getRelyingParty(NULL)->getString("signing");
+    prop = relyingParty->getString("signing");
     if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
         role->AuthnRequestsSigned(true);
-    pair<bool,bool> flagprop = application.getRelyingParty(NULL)->getBool("signedAssertions");
+    pair<bool,bool> flagprop = relyingParty->getBool("requireSignedAssertions");
     if (flagprop.first && flagprop.second)
         role->WantAssertionsSigned(true);
 
@@ -278,6 +335,9 @@ pair<bool,long> MetadataGenerator::processMessage(const Application& application
     if (credResolver) {
         Locker credLocker(credResolver);
         CredentialCriteria cc;
+        prop = relyingParty->getString("keyName");
+        if (prop.first)
+            cc.getKeyNames().insert(prop.second);
         cc.setUsage(Credential::SIGNING_CREDENTIAL);
         vector<const Credential*> creds;
         credResolver->resolve(creds,&cc);
@@ -332,7 +392,7 @@ pair<bool,long> MetadataGenerator::processMessage(const Application& application
             XMLHelper::serialize(entity->marshall(), pretty, true);
             DOMDocument* prettydoc = XMLToolingConfig::getConfig().getParser().parse(pretty);
             auto_ptr<XMLObject> prettyentity(XMLObjectBuilder::buildOneFromElement(prettydoc->getDocumentElement(), true));
-    
+
             Signature* sig = SignatureBuilder::buildSignature();
             dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
             if (sigalg.first)
@@ -357,7 +417,8 @@ pair<bool,long> MetadataGenerator::processMessage(const Application& application
         XMLHelper::serialize(entity->marshall(), s, true);
     }
 
-    httpResponse.setContentType(m_mime ? m_mime : "application/samlmetadata+xml");
+    prop = getString("mimeType");
+    httpResponse.setContentType(prop.first ? prop.second : "application/samlmetadata+xml");
     return make_pair(true, httpResponse.sendResponse(s));
 #else
     return make_pair(false,0L);