48a077b3eb0de1636e3ac051ec3a306ffdb6bb91
[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(const Application& application, const char* handlerURL, HTTPResponse& httpResponse) const;
70
71         set<string> m_acl;
72 #ifndef SHIBSP_LITE
73         short m_http,m_https;
74         vector<string> m_bases;
75         const char* m_mime;
76 #endif
77     };
78
79 #if defined (_MSC_VER)
80     #pragma warning( pop )
81 #endif
82
83     Handler* SHIBSP_DLLLOCAL MetadataGeneratorFactory(const pair<const DOMElement*,const char*>& p)
84     {
85         return new MetadataGenerator(p.first, p.second);
86     }
87
88 };
89
90 MetadataGenerator::MetadataGenerator(const DOMElement* e, const char* appId)
91     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".MetadataGenerator"), &g_Blocker)
92 #ifndef SHIBSP_LITE
93         ,m_https(0), m_http(0), m_mime(NULL)
94 #endif
95 {
96     string address(appId);
97     address += getString("Location").second;
98     setAddress(address.c_str());
99     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
100         pair<bool,const char*> acl = getString("acl");
101         if (acl.first) {
102             string aclbuf=acl.second;
103             int j = 0;
104             for (unsigned int i=0;  i < aclbuf.length();  i++) {
105                 if (aclbuf.at(i)==' ') {
106                     m_acl.insert(aclbuf.substr(j, i-j));
107                     j = i+1;
108                 }
109             }
110             m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
111         }
112     }
113
114 #ifndef SHIBSP_LITE
115     static XMLCh EndpointBase[] = UNICODE_LITERAL_12(E,n,d,p,o,i,n,t,B,a,s,e);
116     
117     pair<bool,bool> flag = getBool("http");
118     if (flag.first)
119         m_http = flag.second ? 1 : -1;
120     flag = getBool("https");
121     if (flag.first)
122         m_https = flag.second ? 1 : -1;
123     
124     pair<bool,const char*> mime = getString("mimeType");
125     if (mime.first)
126         m_mime = mime.second;
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);
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             DDFJanitor jin(in), jout(out);
162             
163             out=request.getServiceProvider().getListenerService()->send(in);
164             return unwrap(request, out);
165         }
166     }
167     catch (exception& ex) {
168         m_log.error("error while processing request: %s", ex.what());
169         istringstream msg("Metadata Request Failed");
170         return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
171     }
172 }
173
174 void MetadataGenerator::receive(DDF& in, ostream& out)
175 {
176     // Find application.
177     const char* aid=in["application_id"].string();
178     const char* hurl=in["handler_url"].string();
179     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
180     if (!app) {
181         // Something's horribly wrong.
182         m_log.error("couldn't find application (%s) for metadata request", aid ? aid : "(missing)");
183         throw ConfigurationException("Unable to locate application for metadata request, deleted?");
184     }
185     else if (!hurl) {
186         throw ConfigurationException("Missing handler_url parameter in remoted method call.");
187     }
188     
189     // Wrap a response shim.
190     DDF ret(NULL);
191     DDFJanitor jout(ret);
192     auto_ptr<HTTPResponse> resp(getResponse(ret));
193         
194     // Since we're remoted, the result should either be a throw, a false/0 return,
195     // which we just return as an empty structure, or a response/redirect,
196     // which we capture in the facade and send back.
197     processMessage(*app, hurl, *resp.get());
198     out << ret;
199 }
200
201 pair<bool,long> MetadataGenerator::processMessage(const Application& application, const char* handlerURL, HTTPResponse& httpResponse) const
202 {
203 #ifndef SHIBSP_LITE
204     m_log.debug("processing metadata request");
205
206     EntityDescriptor* entity;
207     pair<bool,const char*> prop = getString("template");
208     if (prop.first) {
209         // Load a template to use for our metadata.
210         LocalFileInputSource src(getXMLString("template").second);
211         Wrapper4InputSource dsrc(&src,false);
212         DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
213         XercesJanitor<DOMDocument> docjan(doc);
214         auto_ptr<XMLObject> xmlobj(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
215         entity = dynamic_cast<EntityDescriptor*>(xmlobj.get());
216         if (!entity)
217             throw ConfigurationException("Template file ($1) did not contain an EntityDescriptor", params(1, prop.second));
218         xmlobj.release();
219     }
220     else {
221         entity = EntityDescriptorBuilder::buildEntityDescriptor();
222     }
223
224     auto_ptr<EntityDescriptor> wrapper(entity);
225     pair<bool,unsigned int> cache = getUnsignedInt("cacheDuration");
226     if (cache.first)
227         entity->setValidUntil(time(NULL) + cache.second);
228     entity->setEntityID(application.getXMLString("entityID").second);
229
230     SPSSODescriptor* role;
231     if (entity->getSPSSODescriptors().empty()) {
232         role = SPSSODescriptorBuilder::buildSPSSODescriptor();
233         entity->getSPSSODescriptors().push_back(role);
234     }
235     else {
236         role = entity->getSPSSODescriptors().front();
237     }
238
239     // Policy flags.
240     prop = application.getRelyingParty(NULL)->getString("signing");
241     if (prop.first && (!strcmp(prop.second,"true") || !strcmp(prop.second,"front")))
242         role->AuthnRequestsSigned(true);
243     pair<bool,bool> flagprop = application.getRelyingParty(NULL)->getBool("signedAssertions");
244     if (flagprop.first && flagprop.second)
245         role->WantAssertionsSigned(true);
246
247     // Ask each handler to generate itself.
248     vector<const Handler*> handlers;
249     application.getHandlers(handlers);
250     for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
251         if (m_bases.empty()) {
252             if (strncmp(handlerURL, "https", 5) == 0) {
253                 if (m_https >= 0)
254                     (*h)->generateMetadata(*role, handlerURL);
255                 if (m_http == 1) {
256                     string temp(handlerURL);
257                     temp.erase(4, 1);
258                     (*h)->generateMetadata(*role, temp.c_str());
259                 }
260             }
261             else {
262                 if (m_http >= 0)
263                     (*h)->generateMetadata(*role, handlerURL);
264                 if (m_https == 1) {
265                     string temp(handlerURL);
266                     temp.insert(temp.begin() + 4, 's');
267                     (*h)->generateMetadata(*role, temp.c_str());
268                 }
269             }
270         }
271         else {
272             for (vector<string>::const_iterator b = m_bases.begin(); b != m_bases.end(); ++b)
273                 (*h)->generateMetadata(*role, b->c_str());
274         }
275     }
276
277     CredentialResolver* credResolver=application.getCredentialResolver();
278     if (credResolver) {
279         Locker credLocker(credResolver);
280         CredentialCriteria cc;
281         cc.setUsage(Credential::SIGNING_CREDENTIAL);
282         vector<const Credential*> creds;
283         credResolver->resolve(creds,&cc);
284         for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
285             KeyInfo* kinfo = (*c)->getKeyInfo();
286             if (kinfo) {
287                 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
288                 kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
289                 kd->setKeyInfo(kinfo);
290                 role->getKeyDescriptors().push_back(kd);
291             }
292         }
293
294         cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
295         creds.clear();
296         credResolver->resolve(creds,&cc);
297         for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
298             KeyInfo* kinfo = (*c)->getKeyInfo();
299             if (kinfo) {
300                 KeyDescriptor* kd = KeyDescriptorBuilder::buildKeyDescriptor();
301                 kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
302                 kd->setKeyInfo(kinfo);
303                 role->getKeyDescriptors().push_back(kd);
304             }
305         }
306     }
307
308     // Stream for response.
309     stringstream s;
310
311     // Self-sign it?
312     pair<bool,bool> flag = getBool("signing");
313     if (flag.first && flag.second) {
314         if (credResolver) {
315             Locker credLocker(credResolver);
316             // Fill in criteria to use.
317             CredentialCriteria cc;
318             cc.setUsage(Credential::SIGNING_CREDENTIAL);
319             prop = getString("keyName");
320             if (prop.first)
321                 cc.getKeyNames().insert(prop.second);
322             pair<bool,const XMLCh*> sigalg = getXMLString("signingAlg");
323             pair<bool,const XMLCh*> digalg = getXMLString("digestAlg");
324             if (sigalg.first)
325                 cc.setXMLAlgorithm(sigalg.second);
326             const Credential* cred = credResolver->resolve(&cc);
327             if (!cred)
328                 throw XMLSecurityException("Unable to obtain signing credential to use.");
329
330             // Pretty-print it first and then read it back in.
331             stringstream pretty;
332             XMLHelper::serialize(entity->marshall(), pretty, true);
333             DOMDocument* prettydoc = XMLToolingConfig::getConfig().getParser().parse(pretty);
334             auto_ptr<XMLObject> prettyentity(XMLObjectBuilder::buildOneFromElement(prettydoc->getDocumentElement(), true));
335     
336             Signature* sig = SignatureBuilder::buildSignature();
337             dynamic_cast<EntityDescriptor*>(prettyentity.get())->setSignature(sig);
338             if (sigalg.first)
339                 sig->setSignatureAlgorithm(sigalg.second);
340             if (digalg.first) {
341                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
342                 if (cr)
343                     cr->setDigestAlgorithm(digalg.second);
344             }
345
346             // Sign while marshalling.
347             vector<Signature*> sigs(1,sig);
348             prettyentity->marshall(prettydoc,&sigs,cred);
349             s << *prettyentity;
350         }
351         else {
352             throw FatalProfileException("Can't self-sign metadata, no credential resolver found.");
353         }
354     }
355     else {
356         // Pretty-print it directly to client.
357         XMLHelper::serialize(entity->marshall(), s, true);
358     }
359
360     httpResponse.setContentType(m_mime ? m_mime : "application/samlmetadata+xml");
361     return make_pair(true, httpResponse.sendResponse(s));
362 #else
363     return make_pair(false,0L);
364 #endif
365 }