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