Imported Upstream version 2.2.1+dfsg
[shibboleth/sp.git] / shibsp / handler / impl / AssertionLookup.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  * AssertionLookup.cpp
19  *
20  * Handler for looking assertions in SessionCache
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SessionCacheEx.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/RemotedHandler.h"
30 #include "util/SPConstants.h"
31
32 using namespace shibspconstants;
33 using namespace shibsp;
34 using namespace opensaml;
35 using namespace xmltooling;
36 using namespace std;
37
38 namespace shibsp {
39
40 #if defined (_MSC_VER)
41     #pragma warning( push )
42     #pragma warning( disable : 4250 )
43 #endif
44
45     class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
46     {
47     public:
48 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
49         short
50 #else
51         FilterAction
52 #endif
53         acceptNode(const DOMNode* node) const {
54             return FILTER_REJECT;
55         }
56     };
57
58     static SHIBSP_DLLLOCAL Blocker g_Blocker;
59
60     class SHIBSP_API AssertionLookup : public AbstractHandler, public RemotedHandler
61     {
62     public:
63         AssertionLookup(const DOMElement* e, const char* appId);
64         virtual ~AssertionLookup() {}
65
66         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
67         void receive(DDF& in, ostream& out);
68
69         const char* getType() const {
70             return "AssertionLookup";
71         }
72
73     private:
74         pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
75
76         set<string> m_acl;
77     };
78
79 #if defined (_MSC_VER)
80     #pragma warning( pop )
81 #endif
82
83     Handler* SHIBSP_DLLLOCAL AssertionLookupFactory(const pair<const DOMElement*,const char*>& p)
84     {
85         return new AssertionLookup(p.first, p.second);
86     }
87
88 };
89
90 AssertionLookup::AssertionLookup(const DOMElement* e, const char* appId)
91     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".AssertionLookup"), &g_Blocker)
92 {
93     setAddress("run::AssertionLookup");
94     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
95         pair<bool,const char*> acl = getString("exportACL");
96         if (!acl.first) {
97             m_acl.insert("127.0.0.1");
98             return;
99         }
100         string aclbuf=acl.second;
101         int j = 0;
102         for (unsigned int i=0;  i < aclbuf.length();  i++) {
103             if (aclbuf.at(i)==' ') {
104                 m_acl.insert(aclbuf.substr(j, i-j));
105                 j = i+1;
106             }
107         }
108         m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
109     }
110 }
111
112 pair<bool,long> AssertionLookup::run(SPRequest& request, bool isHandler) const
113 {
114     string relayState;
115     SPConfig& conf = SPConfig::getConfig();
116     if (conf.isEnabled(SPConfig::InProcess)) {
117         if (m_acl.count(request.getRemoteAddr()) == 0) {
118             m_log.error("request for assertion lookup blocked from invalid address (%s)", request.getRemoteAddr().c_str());
119             istringstream msg("Assertion Lookup Blocked");
120             return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
121         }
122     }
123
124     try {
125         if (conf.isEnabled(SPConfig::OutOfProcess)) {
126             // When out of process, we run natively and directly process the message.
127             return processMessage(request.getApplication(), request, request);
128         }
129         else {
130             // When not out of process, we remote all the message processing.
131             DDF out,in = wrap(request);
132             DDFJanitor jin(in), jout(out);
133
134             out=request.getServiceProvider().getListenerService()->send(in);
135             return unwrap(request, out);
136         }
137     }
138     catch (exception& ex) {
139         m_log.error("error while processing request: %s", ex.what());
140         istringstream msg("Assertion Lookup Failed");
141         return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
142     }
143 }
144
145 void AssertionLookup::receive(DDF& in, ostream& out)
146 {
147     // Find application.
148     const char* aid=in["application_id"].string();
149     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
150     if (!app) {
151         // Something's horribly wrong.
152         m_log.error("couldn't find application (%s) for assertion lookup", aid ? aid : "(missing)");
153         throw ConfigurationException("Unable to locate application for assertion lookup, deleted?");
154     }
155
156     // Unpack the request.
157     auto_ptr<HTTPRequest> req(getRequest(in));
158     //m_log.debug("found %d client certificates", req->getClientCertificates().size());
159
160     // Wrap a response shim.
161     DDF ret(NULL);
162     DDFJanitor jout(ret);
163     auto_ptr<HTTPResponse> resp(getResponse(ret));
164
165     // Since we're remoted, the result should either be a throw, a false/0 return,
166     // which we just return as an empty structure, or a response/redirect,
167     // which we capture in the facade and send back.
168     processMessage(*app, *req.get(), *resp.get());
169     out << ret;
170 }
171
172 pair<bool,long> AssertionLookup::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
173 {
174 #ifndef SHIBSP_LITE
175     const char* key = httpRequest.getParameter("key");
176     const char* ID = httpRequest.getParameter("ID");
177     if (!key || !*key || !ID || !*ID) {
178         m_log.error("assertion lookup request failed, missing required parameters");
179         throw FatalProfileException("Missing key or ID parameters.");
180     }
181
182     m_log.debug("processing assertion lookup request (session: %s, assertion: %s)", key, ID);
183
184     SessionCacheEx* cache = dynamic_cast<SessionCacheEx*>(application.getServiceProvider().getSessionCache());
185     if (!cache) {
186         m_log.error("session cache does not support extended API");
187         throw FatalProfileException("Session cache does not support assertion lookup.");
188     }
189
190     // The cache will either silently pass a session or NULL back, or throw an exception out.
191     Session* session = cache->find(application, key);
192     if (!session) {
193         m_log.error("valid session (%s) not found for assertion lookup", key);
194         throw FatalProfileException("Session key not found.");
195     }
196
197     Locker locker(session, false);
198
199     const Assertion* assertion = session->getAssertion(ID);
200     if (!assertion) {
201         m_log.error("assertion (%s) not found in session (%s)", ID, key);
202         throw FatalProfileException("Assertion not found.");
203     }
204
205     stringstream s;
206     s << *assertion;
207     httpResponse.setContentType("application/samlassertion+xml");
208     return make_pair(true, httpResponse.sendResponse(s));
209 #else
210     return make_pair(false,0L);
211 #endif
212 }