Upgrade Vulnerable Direct Dependencies [log4j]
[sdc.git] / utils / webseal-simulator / src / main / java / org / openecomp / sdc / webseal / simulator / SdcProxy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 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
21 package org.openecomp.sdc.webseal.simulator;
22
23 import org.apache.http.Header;
24 import org.apache.http.client.methods.*;
25 import org.apache.http.config.Registry;
26 import org.apache.http.config.RegistryBuilder;
27 import org.apache.http.conn.socket.ConnectionSocketFactory;
28 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
29 import org.apache.http.conn.ssl.NoopHostnameVerifier;
30 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
31 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
32 import org.apache.http.entity.ContentType;
33 import org.apache.http.entity.InputStreamEntity;
34 import org.apache.http.impl.client.CloseableHttpClient;
35 import org.apache.http.impl.client.HttpClients;
36 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
37 import org.apache.http.ssl.SSLContextBuilder;
38 import org.apache.logging.log4j.LogManager;
39 import org.apache.logging.log4j.Logger;
40 import org.openecomp.sdc.webseal.simulator.conf.Conf;
41
42 import javax.net.ssl.SSLContext;
43 import javax.servlet.RequestDispatcher;
44 import javax.servlet.ServletConfig;
45 import javax.servlet.ServletException;
46 import javax.servlet.ServletInputStream;
47 import javax.servlet.http.Cookie;
48 import javax.servlet.http.HttpServlet;
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
51 import java.io.IOException;
52 import java.io.InputStream;
53 import java.io.OutputStream;
54 import java.io.UnsupportedEncodingException;
55 import java.net.MalformedURLException;
56 import java.net.URL;
57 import java.net.URLEncoder;
58 import java.security.KeyStoreException;
59 import java.security.NoSuchAlgorithmException;
60 import java.util.*;
61 import java.util.stream.Collectors;
62 import java.util.zip.GZIPInputStream;
63
64 public class SdcProxy extends HttpServlet {
65
66     private static final long serialVersionUID = 1L;
67     private static URL url;
68     private CloseableHttpClient httpClient;
69     private Conf conf;
70     private final String SDC1 = "/sdc1";
71     private final String ONBOARDING = "/onboarding/";
72     private final String SCRIPTS = "/scripts";
73     private final String STYLES = "/styles";
74     private final String LANGUAGES = "/languages";
75     private final String CONFIGURATIONS = "/configurations";
76     private static final Set<String> RESERVED_HEADERS = Arrays.stream(ReservedHeaders.values()).map(h -> h.getValue()).collect(Collectors.toSet());
77
78
79     private final static Logger logger = LogManager.getLogger(SdcProxy.class);
80
81     public void init(ServletConfig config) throws ServletException {
82         super.init(config);
83         conf = Conf.getInstance();
84         try {
85             String feHost = conf.getFeHost();
86             url = new URL(feHost);
87         } catch (MalformedURLException me) {
88             throw new ServletException("Proxy URL is invalid", me);
89         }
90
91         try {
92             httpClient = buildRestClient();
93         } catch (Exception e) {
94             throw new ServletException("Build rest client failed", e);
95         }
96     }
97
98     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
99         proxy(request, response, MethodEnum.GET);
100     }
101
102     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
103
104         String userId = request.getParameter("userId");
105         String password = request.getParameter("password");
106
107         // Already sign-in
108         if (userId == null) {
109             userId = request.getHeader("USER_ID");
110         }
111
112         System.out.println("SdcProxy -> doPost userId=" + userId);
113         request.setAttribute("message", "OK");
114         if (password != null && getUser(userId, password) == null) {
115             MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);
116             RequestDispatcher view = request.getRequestDispatcher("login");
117             request.setAttribute("message", "ERROR: userid or password incorect");
118             view.forward(mutableRequest, response);
119         } else {
120             System.out.println("SdcProxy -> doPost going to doGet");
121             request.setAttribute("HTTP_IV_USER", userId);
122             proxy(request, response, MethodEnum.POST);
123         }
124     }
125
126     public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
127         proxy(request, response, MethodEnum.PUT);
128     }
129
130     public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
131         proxy(request, response, MethodEnum.DELETE);
132     }
133
134     private synchronized void proxy(HttpServletRequest request, HttpServletResponse response, MethodEnum methodEnum) throws IOException, UnsupportedEncodingException {
135
136         Map<String, String[]> requestParameters = request.getParameterMap();
137         String userIdHeader = getUseridFromRequest(request);
138         User user = getUser(userIdHeader);
139
140         // new request - forward to login page
141         if (userIdHeader == null) {
142             System.out.print("Going to login");
143             response.sendRedirect("/login");
144             return;
145         }
146
147         String uri = getUri(request, requestParameters);
148         HttpRequestBase httpMethod = createHttpMethod(request, methodEnum, uri);
149         addHeadersToMethod(httpMethod, user, request);
150
151         try (CloseableHttpResponse closeableHttpResponse =  httpClient.execute(httpMethod)){;
152             response.setStatus(closeableHttpResponse.getStatusLine().getStatusCode());
153             if (request.getRequestURI().indexOf(".svg") > -1) {
154                 response.setContentType("image/svg+xml");
155             }
156
157             if(closeableHttpResponse.getEntity() != null) {
158                 InputStream responseBodyStream = closeableHttpResponse.getEntity().getContent();
159                 Header contentEncodingHeader = closeableHttpResponse.getLastHeader("Content-Encoding");
160                 if (contentEncodingHeader != null && contentEncodingHeader.getValue().equalsIgnoreCase("gzip")) {
161                     responseBodyStream = new GZIPInputStream(responseBodyStream);
162                 }
163                 write(responseBodyStream, response.getOutputStream());
164             }
165         }
166     }
167
168     private User getUser(String userId, String password) {
169         User user = getUser(userId);
170         if (user.getPassword().equals(password)) {
171             return user;
172         }
173         return null;
174     }
175
176     private User getUser(String userId) {
177         return conf.getUsers().get(userId);
178
179     }
180
181     private List<String> getContextPaths() {
182         List<String> contextPaths = new ArrayList<>();
183         contextPaths.add(SDC1);
184         contextPaths.add(ONBOARDING);
185         contextPaths.add(STYLES);
186         contextPaths.add(SCRIPTS);
187         contextPaths.add(LANGUAGES);
188         contextPaths.add(CONFIGURATIONS);
189         return contextPaths;
190     }
191
192     private String getUri(HttpServletRequest request, Map<String, String[]> requestParameters) throws UnsupportedEncodingException {
193         String suffix = request.getRequestURI();
194         if (getContextPaths().stream().anyMatch(request.getRequestURI()::contains)) {
195             suffix = alignUrlProxy(suffix);
196         }
197         StringBuilder query = alignUrlParameters(requestParameters);
198         String uri = String.format("%s%s", new Object[]{this.url.toString() + suffix, query.toString()});
199         return uri;
200     }
201
202     private HttpRequestBase createHttpMethod(HttpServletRequest request, MethodEnum methodEnum, String uri) throws IOException {
203         HttpRequestBase proxyMethod = null;
204         ServletInputStream inputStream = null;
205         InputStreamEntity entity = null;
206
207         switch (methodEnum) {
208             case GET:
209                 proxyMethod = new HttpGet(uri);
210                 break;
211             case POST:
212                 proxyMethod = new HttpPost(uri);
213                 inputStream = request.getInputStream();
214                 entity = new InputStreamEntity(inputStream, getContentType(request));
215                 ((HttpPost) proxyMethod).setEntity(entity);
216                 break;
217             case PUT:
218                 proxyMethod = new HttpPut(uri);
219                 inputStream = request.getInputStream();
220                 entity = new InputStreamEntity(inputStream, getContentType(request));
221                 ((HttpPut) proxyMethod).setEntity(entity);
222                 break;
223             case DELETE:
224                 proxyMethod = new HttpDelete(uri);
225                 break;
226         }
227         return proxyMethod;
228     }
229
230     private ContentType getContentType(HttpServletRequest request) {
231         String contentTypeStr = request.getContentType();
232             if (contentTypeStr == null ){
233                 contentTypeStr = request.getHeader("contentType");
234             }
235         ContentType contentType = ContentType.parse(contentTypeStr);
236         return ContentType.create(contentType.getMimeType());
237     }
238
239     private String getUseridFromRequest(HttpServletRequest request) {
240
241         String userIdHeader = request.getHeader("USER_ID");
242         if (userIdHeader != null) {
243             return userIdHeader;
244         }
245         Object o = request.getAttribute("HTTP_IV_USER");
246         if (o != null) {
247             return o.toString();
248         }
249         Cookie[] cookies = request.getCookies();
250
251         if (cookies != null) {
252             for (int i = 0; i < cookies.length; ++i) {
253                 if (cookies[i].getName().equals("USER_ID")) {
254                     userIdHeader = cookies[i].getValue();
255                 }
256             }
257         }
258         return userIdHeader;
259     }
260
261     private static void addHeadersToMethod(HttpUriRequest proxyMethod, User user, HttpServletRequest request) {
262
263         proxyMethod.setHeader(ReservedHeaders.HTTP_IV_USER.name(), user.getUserId());
264         proxyMethod.setHeader(ReservedHeaders.USER_ID.name(), user.getUserId());
265         proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_FIRSTNAME.name(), user.getFirstName());
266         proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_EMAIL.name(), user.getEmail());
267         proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_LASTNAME.name(), user.getLastName());
268         proxyMethod.setHeader(ReservedHeaders.HTTP_IV_REMOTE_ADDRESS.name(), "0.0.0.0");
269         proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_WSTYPE.name(), "Intranet");
270                 proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_EMAIL.name(), "me@mail.com");
271
272                 Enumeration<String> headerNames = request.getHeaderNames();
273                 while (headerNames.hasMoreElements()) {
274                         String headerName = headerNames.nextElement();
275                         if (!RESERVED_HEADERS.contains(headerName)) {
276                                 Enumeration<String> headers = request.getHeaders(headerName);
277                                 while (headers.hasMoreElements()) {
278                                         String headerValue = headers.nextElement();
279                                         proxyMethod.setHeader(headerName, headerValue);
280                                 }
281                         }
282                 }
283     }
284
285     private String alignUrlProxy(String requestURI) {
286
287         int i = requestURI.indexOf(ONBOARDING);
288         if (-1 != i) {
289             return requestURI.substring(i);
290         }
291
292         i = requestURI.indexOf(SDC1 + SDC1);
293         if (-1 != i) {
294             return requestURI.substring(SDC1.length());
295         }
296
297         i = requestURI.indexOf(SDC1);
298         if (-1 != i) {
299             return requestURI;
300         }
301
302         return SDC1 + requestURI;
303     }
304
305     private static StringBuilder alignUrlParameters(Map<String, String[]> requestParameters) throws UnsupportedEncodingException {
306         StringBuilder query = new StringBuilder();
307         for (String name : requestParameters.keySet()) {
308             for (String value : (String[]) requestParameters.get(name)) {
309                 if (query.length() == 0) {
310                     query.append("?");
311                 } else {
312                     query.append("&");
313                 }
314                 name = URLEncoder.encode(name, "UTF-8");
315                 value = URLEncoder.encode(value, "UTF-8");
316
317                 query.append(String.format("&%s=%s", new Object[]{name, value}));
318             }
319         }
320         return query;
321     }
322
323     private void write(InputStream inputStream, OutputStream outputStream) throws IOException {
324         int b;
325         while (inputStream != null && (b = inputStream.read()) != -1) {
326             outputStream.write(b);
327         }
328         outputStream.flush();
329     }
330
331     public String getServletInfo() {
332         return "Http Proxy Servlet";
333     }
334
335     enum ReservedHeaders {
336         HTTP_IV_USER("HTTP_IV_USER"), USER_ID("USER_ID"), HTTP_CSP_FIRSTNAME("HTTP_CSP_FIRSTNAME"), HTTP_CSP_EMAIL("HTTP_CSP_EMAIL"), HTTP_CSP_LASTNAME("HTTP_CSP_LASTNAME"), HTTP_IV_REMOTE_ADDRESS("HTTP_IV_REMOTE_ADDRESS"), HTTP_CSP_WSTYPE("HTTP_CSP_WSTYPE"), HOST("Host"), CONTENTLENGTH("Content-Length");
337
338         private String value;
339
340         ReservedHeaders(String value) {
341             this.value = value;
342         }
343
344         public String getValue() {
345             return value;
346         }
347     }
348
349
350     private static CloseableHttpClient buildRestClient() throws NoSuchAlgorithmException, KeyStoreException {
351         SSLContextBuilder builder = new SSLContextBuilder();
352         builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
353         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault(),
354                 NoopHostnameVerifier.INSTANCE);
355         Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
356                 .register("http", new PlainConnectionSocketFactory())
357                 .register("https", sslsf)
358                 .build();
359         PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
360         return HttpClients.custom()
361                 .setSSLSocketFactory(sslsf)
362                 .setConnectionManager(cm)
363                 .build();
364     }
365 }