Fix new sonar vulnerabilities
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / provisioning / ProxyServlet.java
1 /*******************************************************************************
2  * ============LICENSE_START==================================================
3  * * org.onap.dmaap
4  * * ===========================================================================
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * * ===========================================================================
7  * * Licensed under the Apache License, Version 2.0 (the "License");
8  * * you may not use this file except in compliance with the License.
9  * * You may obtain a copy of the License at
10  * *
11  *  *      http://www.apache.org/licenses/LICENSE-2.0
12  * *
13  *  * Unless required by applicable law or agreed to in writing, software
14  * * distributed under the License is distributed on an "AS IS" BASIS,
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * * See the License for the specific language governing permissions and
17  * * limitations under the License.
18  * * ============LICENSE_END====================================================
19  * *
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  * *
22  ******************************************************************************/
23
24
25 package org.onap.dmaap.datarouter.provisioning;
26
27 import java.io.File;
28 import java.io.FileInputStream;
29 import java.io.FileNotFoundException;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.net.URI;
33 import java.security.KeyStore;
34 import java.security.KeyStoreException;
35 import java.util.Collections;
36 import java.util.List;
37 import java.util.Properties;
38 import javax.servlet.ServletConfig;
39 import javax.servlet.ServletException;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
42 import org.apache.commons.io.IOUtils;
43 import org.apache.http.Header;
44 import org.apache.http.HttpEntity;
45 import org.apache.http.HttpResponse;
46 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
47 import org.apache.http.client.methods.HttpGet;
48 import org.apache.http.client.methods.HttpRequestBase;
49 import org.apache.http.conn.scheme.Scheme;
50 import org.apache.http.conn.ssl.SSLSocketFactory;
51 import org.apache.http.entity.BasicHttpEntity;
52 import org.apache.http.impl.client.AbstractHttpClient;
53 import org.apache.http.impl.client.DefaultHttpClient;
54 import org.onap.dmaap.datarouter.provisioning.utils.DB;
55 import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;
56
57 /**
58  * This class is the base class for those servlets that need to proxy their requests from the standby to active server.
59  * Its methods perform the proxy function to the active server. If the active server is not reachable, a 503
60  * (SC_SERVICE_UNAVAILABLE) is returned.  Only DELETE/GET/PUT/POST are supported.
61  *
62  * @author Robert Eby
63  * @version $Id: ProxyServlet.java,v 1.3 2014/03/24 18:47:10 eby Exp $
64  */
65 @SuppressWarnings("serial")
66 public class ProxyServlet extends BaseServlet {
67
68     private boolean inited = false;
69     private Scheme sch;
70
71     /**
72      * Initialize this servlet, by setting up SSL.
73      */
74     @SuppressWarnings("deprecation")
75     @Override
76     public void init(ServletConfig config) throws ServletException {
77         super.init(config);
78         try {
79             // Set up keystore
80             Properties props = (new DB()).getProperties();
81             String type = props.getProperty(Main.KEYSTORE_TYPE_PROPERTY, "jks");
82             String store = props.getProperty(Main.KEYSTORE_PATH_PROPERTY);
83             String pass = props.getProperty(Main.KEYSTORE_PASSWORD_PROPERTY);
84             KeyStore keyStore = readStore(store, pass, type);
85
86             store = props.getProperty(Main.TRUSTSTORE_PATH_PROPERTY);
87             pass = props.getProperty(Main.TRUSTSTORE_PASSWORD_PROPERTY);
88             if (store == null || store.length() == 0) {
89                 store = Main.DEFAULT_TRUSTSTORE;
90                 pass = "changeit";
91             }
92             KeyStore trustStore = readStore(store, pass, KeyStore.getDefaultType());
93
94             // We are connecting with the node name, but the certificate will have the CNAME
95             // So we need to accept a non-matching certificate name
96             SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore,
97                 props.getProperty(Main.KEYSTORE_PASSWORD_PROPERTY), trustStore);
98             socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
99             sch = new Scheme("https", 443, socketFactory);
100             inited = true;
101         } catch (Exception e) {
102             e.printStackTrace();
103         }
104         intlogger.info("ProxyServlet: inited = " + inited);
105     }
106
107     private KeyStore readStore(String store, String pass, String type) throws KeyStoreException {
108         KeyStore ks = KeyStore.getInstance(type);
109         try (FileInputStream instream = new FileInputStream(new File(store))) {
110             ks.load(instream, pass.toCharArray());
111         } catch (FileNotFoundException fileNotFoundException) {
112             intlogger.error("ProxyServlet: " + fileNotFoundException.getMessage());
113         } catch (Exception x) {
114             System.err.println("READING TRUSTSTORE: " + x);
115         }
116         return ks;
117     }
118
119     /**
120      * Return <i>true</i> if the requester has NOT set the <i>noproxy</i> CGI variable. If they have, this indicates
121      * they want to forcibly turn the proxy off.
122      *
123      * @param req the HTTP request
124      * @return true or false
125      */
126     protected boolean isProxyOK(final HttpServletRequest req) {
127         String t = req.getQueryString();
128         if (t != null) {
129             t = t.replaceAll("&amp;", "&");
130             for (String s : t.split("&")) {
131                 if (s.equals("noproxy") || s.startsWith("noproxy=")) {
132                     return false;
133                 }
134             }
135         }
136         return true;
137     }
138
139     /**
140      * Is this the standby server?  If it is, the proxy functions can be used. If not, the proxy functions should not be
141      * called, and will send a response of 500 (Internal Server Error).
142      *
143      * @return true if this server is the standby (and hence a proxy server).
144      */
145     public boolean isProxyServer() {
146         SynchronizerTask st = SynchronizerTask.getSynchronizer();
147         return st.getState() == SynchronizerTask.STANDBY;
148     }
149
150     /**
151      * Issue a proxy DELETE to the active provisioning server.
152      */
153     @Override
154     public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
155         doProxy(req, resp, "DELETE");
156     }
157
158     /**
159      * Issue a proxy GET to the active provisioning server.
160      */
161     @Override
162     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
163         doProxy(req, resp, "GET");
164     }
165
166     /**
167      * Issue a proxy PUT to the active provisioning server.
168      */
169     @Override
170     public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
171         doProxy(req, resp, "PUT");
172     }
173
174     /**
175      * Issue a proxy POST to the active provisioning server.
176      */
177     @Override
178     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
179         doProxy(req, resp, "POST");
180     }
181
182     /**
183      * Issue a proxy GET to the active provisioning server.  Unlike doGet() above, this method will allow the caller to
184      * fall back to other code if the remote server is unreachable.
185      *
186      * @return true if the proxy succeeded
187      */
188     public boolean doGetWithFallback(HttpServletRequest req, HttpServletResponse resp) throws IOException {
189         boolean rv = false;
190         if (inited) {
191             String url = buildUrl(req);
192             intlogger.info("ProxyServlet: proxying with fallback GET " + url);
193             try (AbstractHttpClient httpclient = new DefaultHttpClient()) {
194                 HttpRequestBase proxy = new HttpGet(url);
195                 try {
196                     httpclient.getConnectionManager().getSchemeRegistry().register(sch);
197
198                     // Copy request headers and request body
199                     copyRequestHeaders(req, proxy);
200
201                     // Execute the request
202                     HttpResponse pxy_response = httpclient.execute(proxy);
203
204                     // Get response headers and body
205                     int code = pxy_response.getStatusLine().getStatusCode();
206                     resp.setStatus(code);
207                     copyResponseHeaders(pxy_response, resp);
208
209                     HttpEntity entity = pxy_response.getEntity();
210                     if (entity != null) {
211                         InputStream in = entity.getContent();
212                         IOUtils.copy(in, resp.getOutputStream());
213                         in.close();
214                     }
215                     rv = true;
216
217                 } catch (IOException e) {
218                     System.err.println("ProxyServlet: " + e);
219                     e.printStackTrace();
220                 } finally {
221                     proxy.releaseConnection();
222                     httpclient.getConnectionManager().shutdown();
223                 }
224             }
225         } else {
226             intlogger.warn("ProxyServlet: proxy disabled");
227         }
228         return rv;
229     }
230
231     private void doProxy(HttpServletRequest req, HttpServletResponse resp, final String method) throws IOException {
232         if (inited && isProxyServer()) {
233             String url = buildUrl(req);
234             intlogger.info("ProxyServlet: proxying " + method + " " + url);
235             try (AbstractHttpClient httpclient = new DefaultHttpClient()) {
236                 ProxyHttpRequest proxy = new ProxyHttpRequest(method, url);
237                 try {
238                     httpclient.getConnectionManager().getSchemeRegistry().register(sch);
239
240                     // Copy request headers and request body
241                     copyRequestHeaders(req, proxy);
242                     if (method.equals("POST") || method.equals("PUT")) {
243                         BasicHttpEntity body = new BasicHttpEntity();
244                         body.setContent(req.getInputStream());
245                         body.setContentLength(-1);    // -1 = unknown
246                         proxy.setEntity(body);
247                     }
248
249                     // Execute the request
250                     HttpResponse pxy_response = httpclient.execute(proxy);
251
252                     // Get response headers and body
253                     int code = pxy_response.getStatusLine().getStatusCode();
254                     resp.setStatus(code);
255                     copyResponseHeaders(pxy_response, resp);
256
257                     HttpEntity entity = pxy_response.getEntity();
258                     if (entity != null) {
259                         InputStream in = entity.getContent();
260                         IOUtils.copy(in, resp.getOutputStream());
261                         in.close();
262                     }
263                 } catch (IOException e) {
264                     intlogger.warn("ProxyServlet: " + e);
265                     resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
266                     e.printStackTrace();
267                 } finally {
268                     proxy.releaseConnection();
269                     httpclient.getConnectionManager().shutdown();
270                 }
271             }
272         } else {
273             intlogger.warn("ProxyServlet: proxy disabled");
274             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
275         }
276     }
277
278     private String buildUrl(HttpServletRequest req) {
279         StringBuilder sb = new StringBuilder("https://");
280         sb.append(URLUtilities.getPeerPodName());
281         sb.append(req.getRequestURI());
282         String q = req.getQueryString();
283         if (q != null) {
284             sb.append("?").append(q);
285         }
286         return sb.toString();
287     }
288
289     private void copyRequestHeaders(HttpServletRequest from, HttpRequestBase to) {
290         @SuppressWarnings("unchecked")
291         List<String> list = Collections.list(from.getHeaderNames());
292         for (String name : list) {
293             // Proxy code will add this one
294             if (!name.equalsIgnoreCase("Content-Length")) {
295                 to.addHeader(name, from.getHeader(name));
296             }
297         }
298     }
299
300     private void copyResponseHeaders(HttpResponse from, HttpServletResponse to) {
301         for (Header hdr : from.getAllHeaders()) {
302             // Don't copy Date: our Jetty will add another Date header
303             if (!hdr.getName().equals("Date")) {
304                 to.addHeader(hdr.getName(), hdr.getValue());
305             }
306         }
307     }
308
309     public class ProxyHttpRequest extends HttpEntityEnclosingRequestBase {
310
311         private final String method;
312
313         public ProxyHttpRequest(final String method, final String uri) {
314             super();
315             this.method = method;
316             setURI(URI.create(uri));
317         }
318
319         @Override
320         public String getMethod() {
321             return method;
322         }
323     }
324 }