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