08e73e0ba34f55c9b55044480cc71963e7b4019c
[shibboleth/sp.git] / shibsp / handler / impl / MetadataGenerator.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * MetadataGenerator.cpp
19  * 
20  * Handler for generating "approximate" metadata based on SP configuration.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "handler/AbstractHandler.h"
28 #include "handler/RemotedHandler.h"
29
30 #ifndef SHIBSP_LITE
31 # include "metadata/MetadataProviderCriteria.h"
32 #endif
33
34 #include <xercesc/framework/LocalFileInputSource.hpp>
35 #include <xercesc/framework/Wrapper4InputSource.hpp>
36
37 using namespace shibsp;
38 #ifndef SHIBSP_LITE
39 using namespace opensaml::saml2md;
40 using namespace opensaml;
41 using namespace xmlsignature;
42 #endif
43 using namespace xmltooling;
44 using namespace std;
45
46 namespace shibsp {
47
48 #if defined (_MSC_VER)
49     #pragma warning( push )
50     #pragma warning( disable : 4250 )
51 #endif
52
53     class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
54     {
55     public:
56         short acceptNode(const DOMNode* node) const {
57             return FILTER_REJECT;
58         }
59     };
60
61     static SHIBSP_DLLLOCAL Blocker g_Blocker;
62
63     class SHIBSP_API MetadataGenerator : public AbstractHandler, public RemotedHandler
64     {
65     public:
66         MetadataGenerator(const DOMElement* e, const char* appId);
67         virtual ~MetadataGenerator() {}
68
69         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
70         void receive(DDF& in, ostream& out);
71
72     private:
73         pair<bool,long> processMessage(
74             const Application& application,
75             const char* handlerURL,
76             const char* entityID,
77             HTTPResponse& httpResponse
78             ) const;
79
80         set<string> m_acl;
81 #ifndef SHIBSP_LITE
82         short m_http,m_https;
83         vector<string> m_bases;
84 #endif
85     };
86
87 #if defined (_MSC_VER)
88     #pragma warning( pop )
89 #endif
90
91     Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
92     {
93         return new MetadataGenerator(p.first, p.second);
94     }
95
96 };
97
98 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
99     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
100 #ifndef SHIBSP_LITE
101         ,m_http(0), m_https(0)
102 #endif
103 {
104     string address(appId);
105     address += getString("Location").second;
106     setAddress(address.c_str());
107     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
108         pair<bool,const char*> acl = getString("acl");
109         if (acl.first) {
110             string aclbuf=acl.second;
111             int j = 0;
112             for (unsigned int i=0;  i < aclbuf.length();  i++) {
113                 if (aclbuf.at(i)==' ') {
114                     m_acl.insert(aclbuf.substr(j, i-j));
115                     j = i+1;
116                 }
117             }
118             m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
119         }
120     }
121
122 #ifndef SHIBSP_LITE
123     static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
124     
125     pair<bool,bool> flag = getBool("http");
126     if (flag.first)
127         m_http = flag.second ? 1 : -1;
128     flag = getBool("https");
129     if (flag.first)
130         m_https = flag.second ? 1 : -1;
131     
132     e = XMLHelper::getFirstChildElement(e, EndpointBase);
133     while (e) {
134         if (e->hasChildNodes()) {
135             auto_ptr_char base(e->getFirstChild()->getNodeValue());
136             if (base.get() && *base.get())
137                 m_bases.push_back(base.get());
138         }
139         e = XMLHelper::getNextSiblingElement(e, EndpointBase);
140     }
141 #endif
142 }
143
144 pair<bool,long> MetadataGenerator::run(SPRequest& request, bool isHandler) const
145 {
146     SPConfig& conf = SPConfig::getConfig();
147     if (conf.isEnabled(SPConfig::InProcess)) {
148         if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
149             m_log.error("request for metadata blocked from invalid address (%s)", request.getRemoteAddr().c_str());
150             istringstream msg("Metadata Request Blocked");
151             return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED));
152         }
153     }
154     
155     try {
156         if (conf.isEnabled(SPConfig::OutOfProcess)) {
157             // When out of process, we run natively and directly process the message.
158             return processMessage(request.getApplication(), request.getHandlerURL(), request.getParameter("entityID"), request);
159         }
160         else {
161             // When not out of process, we remote all the message processing.
162             DDF out,in = DDF(m_address.c_str());
163             in.addmember("application_id").string(request.getApplication().getId());
164             in.addmember("handler_url").string(request.getHandlerURL());
165             if (request.getParameter("entityID"))
166                 in.addmember("entity_id").string(request.getParameter("entityID"));
167             DDFJanitor jin(in), jout(out);
168             
169             out=request.getServiceProvider().getListenerService()->send(in);
170             return unwrap(request, out);
171         }
172     }
173     catch (exception& ex) {
174         m_log.error("error while processing request: %s", ex.what());
175         istringstream msg("Metadata Request Failed");
176         return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
177     }
178 }
179
180 void MetadataGenerator::receive(DDF& in, ostream& out)
181 {
182     // Find application.
183     const char* aid=in["application_id"].string();
184     const char* hurl=in["handler_url"].string();
185     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
186     if (!app) {
187         // Something's horribly wrong.
188         m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
189         throw ConfigurationException("Unable to locate application for metadata request, deleted?");
190     }
191     else if (!hurl) {
192         throw ConfigurationException("Missing handler_url parameter in remoted method call.");
193     }
194     
195     // Wrap a response shim.
196     DDF ret(NULL);
197     DDFJanitor jout(ret);
198     auto_ptr<HTTPResponse> resp(getResponse(ret));
199         
200     // Since we're remoted, the result should either be a throw, a false/0 return,
201     // which we just return as an empty structure, or a response/redirect,
202     // which we capture in the facade and send back.
203     processMessage(*app, hurl, in["entity_id"].string(), *resp.get());
204     out << ret;
205 }
206
207 pair<bool,long> MetadataGenerator::processMessage(
208     const Application& application, const char* handlerURL, const char* entityID, HTTPResponse& httpResponse
209     ) const
210 {
211 #ifndef SHIBSP_LITE
212     m_log.debug("processing metadata request");
213
214     const PropertySet* relyingParty=NULL;
215     if (entityID) {
216         MetadataProvider* m=application.getMetadataProvider();
217         Locker locker(m);
218         MetadataProviderCriteria mc(application, entityID);
219         relyingParty = application.getRelyingParty(m->getEntityDescriptor(mc).first);
220     }
221     else {
222         relyingParty = &application;
223     }
224
225     EntityDescriptor* entity;
226     pair<bool,const char*> prop = getString("template");
227     if (prop.first) {
228         // Load a template to use for our metadata.
229         LocalFileInputSource src(getXMLString("template").second);
230         Wrapper4InputSource dsrc(&src,false);
231         DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
232         XercesJanitor<DOMDocument> docjan(doc);
233         auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
234         docjan.release();
235         entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
236         if (!entity)
237             throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, prop.second));
238         xmlobj.release();
239     }
240     else {
241         entity = EntityDescriptorBuilder::buildEntityDescriptor();
242     }
243
244     auto_ptr<EntityDescriptor> wrapper(entity);
245     pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
246     if (cache.first)
247         entity->setValidUntil(time(NULL) + cache.second);
248     entity->setEntityID(relyingParty->getXMLString("entityID").second);
249
250     SPSSODescriptor* role;
251     if (entity->getSPSSODescriptors().empty()) {
252         role = SPSSODescriptorBuilder::buildSPSSODescriptor();
253         entity->getSPSSODescriptors().push_back(role);
254     }
255     else {
256         role = entity->getSPSSODescriptors().front();
257     }
258
259     // Policy flags.
260     prop = relyingParty->getString("signing");
261     if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
262         role->AuthnRequestsSigned(true);
263     pair<bool,bool> flagprop = relyingParty->getBool("requireSignedAssertions");
264     if (flagprop.first && flagprop.second)
265         role->WantAssertionsSigned(true);
266
267     // Ask each handler to generate itself.
268     vector<const Handler*> handlers;
269     application.getHandlers(handlers);
270     for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
271         if (m_bases.empty()) {
272             if (strncmp(handlerURL, "https", 5) == 0) {
273                 if (m_https >= 0)
274                     (*h)->generateMetadata(*role, handlerURL);
275                 if (m_http == 1) {
276                     string temp(handlerURL);
277                     temp.erase(4, 1);
278                     (*h)->generateMetadata(*role, temp.c_str());
279                 }
280             }
281             else {
282                 if (m_http >= 0)
283                     (*h)->generateMetadata(*role, handlerURL);
284                 if (m_https == 1) {
285                     string temp(handlerURL);
286                     temp.insert(temp.begin() + 4, 's');
287                     (*h)->generateMetadata(*role, temp.c_str());
288                 }
289             }
290         }
291         else {
292             for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
293                 (*h)->generateMetadata(*role, b->c_str());
294         }
295     }
296
297     CredentialResolver* credResolver=application.getCredentialResolver();
298     if (credResolver) {
299         Locker credLocker(credResolver);
300         CredentialCriteria cc;
301         prop = relyingParty->getString("keyName");
302         if (prop.first)
303             cc.getKeyNames().insert(prop.second);
304         cc.setUsage(Credential::SIGNING_CREDENTIAL);
305         vector<const Credential*> creds;
306         credResolver->resolve(creds,&cc);
307         for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
308             KeyInfo* kinfo = (*c)->getKeyInfo();
309             if (kinfo) {
310                 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
311                 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
312                 kd->setKeyInfo(kinfo);
313                 role->getKeyDescriptors().push_back(kd);
314             }
315         }
316
317         cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
318         creds.clear();
319         credResolver->resolve(creds,&cc);
320         for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
321             KeyInfo* kinfo = (*c)->getKeyInfo();
322             if (kinfo) {
323                 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
324                 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
325                 kd->setKeyInfo(kinfo);
326                 role->getKeyDescriptors().push_back(kd);
327             }
328         }
329     }
330
331     // Stream for response.
332     stringstream s;
333
334     // Self-sign it?
335     pair<bool,bool> flag = getBool("signing");
336     if (flag.first && flag.second) {
337         if (credResolver) {
338             Locker credLocker(credResolver);
339             // Fill in criteria to use.
340             CredentialCriteria cc;
341             cc.setUsage(Credential::SIGNING_CREDENTIAL);
342             prop = getString("keyName");
343             if (prop.first)
344                 cc.getKeyNames().insert(prop.second);
345             pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
346             pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
347             if (sigalg.first)
348                 cc.setXMLAlgorithm(sigalg.second);
349             const Credential* cred = credResolver->resolve(&cc);
350             if (!cred)
351                 throw XMLSecurityException("Unable to obtain signing credential to use.");
352
353             // Pretty-print it first and then read it back in.
354             stringstream pretty;
355             XMLHelper::serialize(entity->marshall(), pretty, true);
356             DOMDocument* prettydoc = XMLToolingConfig::getConfig().getParser().parse(pretty);
357             auto_ptr<XMLObject> prettyentity(XMLObjectBuilder::buildOneFromElement(prettydoc->getDocumentElement(), true));
358     
359             Signature* sig = SignatureBuilder::buildSignature();
360             dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
361             if (sigalg.first)
362                 sig->setSignatureAlgorithm(sigalg.second);
363             if (digalg.first) {
364                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
365                 if (cr)
366                     cr->setDigestAlgorithm(digalg.second);
367             }
368
369             // Sign while marshalling.
370             vector<Signature*> sigs(1,sig);
371             prettyentity->marshall(prettydoc,&sigs,cred);
372             s << *prettyentity;
373         }
374         else {
375             throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
376         }
377     }
378     else {
379         // Pretty-print it directly to client.
380         XMLHelper::serialize(entity->marshall(), s, true);
381     }
382
383     prop = getString("mimeType");
384     httpResponse.setContentType(prop.first ? prop.second : "application/samlmetadata+xml");
385     return make_pair(true, httpResponse.sendResponse(s));
386 #else
387     return make_pair(false,0L);
388 #endif
389 }