Merge "Fix sql injection vulnerability"
[portal.git] / ecomp-portal-BE-os / src / main / java / org / onap / portalapp / filter / SecurityXssFilter.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (c) 2019 Samsung
7  * ===================================================================
8  *
9  * Unless otherwise specified, all software contained herein is licensed
10  * under the Apache License, Version 2.0 (the "License");
11  * you may not use this software except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  *             http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  *
22  * Unless otherwise specified, all documentation contained herein is licensed
23  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
24  * you may not use this documentation except in compliance with the License.
25  * You may obtain a copy of the License at
26  *
27  *             https://creativecommons.org/licenses/by/4.0/
28  *
29  * Unless required by applicable law or agreed to in writing, documentation
30  * distributed under the License is distributed on an "AS IS" BASIS,
31  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
32  * See the License for the specific language governing permissions and
33  * limitations under the License.
34  *
35  * ============LICENSE_END============================================
36  *
37  * 
38  */
39
40 package org.onap.portalapp.filter;
41
42 import java.io.BufferedReader;
43 import java.io.ByteArrayInputStream;
44 import java.io.ByteArrayOutputStream;
45 import java.io.IOException;
46 import java.io.InputStreamReader;
47 import java.nio.charset.StandardCharsets;
48 import java.util.Enumeration;
49
50 import javax.servlet.FilterChain;
51 import javax.servlet.ReadListener;
52 import javax.servlet.ServletInputStream;
53 import javax.servlet.http.HttpServletRequest;
54 import javax.servlet.http.HttpServletRequestWrapper;
55 import javax.servlet.http.HttpServletResponse;
56
57 import org.apache.commons.io.IOUtils;
58 import org.apache.commons.lang.StringUtils;
59 import org.apache.http.HttpStatus;
60 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
61 import org.springframework.web.filter.OncePerRequestFilter;
62
63 public class SecurityXssFilter extends OncePerRequestFilter {
64
65         private EELFLoggerDelegate sxLogger = EELFLoggerDelegate.getLogger(SecurityXssFilter.class);
66
67         private static final String APPLICATION_JSON = "application/json";
68
69         private static final String ERROR_BAD_REQUEST = "{\"error\":\"BAD_REQUEST\"}";
70
71         private SecurityXssValidator validator = SecurityXssValidator.getInstance();
72
73         public class RequestWrapper extends HttpServletRequestWrapper {
74
75                 private ByteArrayOutputStream cachedBytes;
76
77                 public RequestWrapper(HttpServletRequest request) {
78                         super(request);
79                 }
80
81                 @Override
82                 public ServletInputStream getInputStream() throws IOException {
83                         if (cachedBytes == null)
84                                 cacheInputStream();
85
86                         return new CachedServletInputStream();
87                 }
88
89                 @Override
90                 public BufferedReader getReader() throws IOException {
91                         return new BufferedReader(new InputStreamReader(getInputStream()));
92                 }
93
94                 private void cacheInputStream() throws IOException {
95                         cachedBytes = new ByteArrayOutputStream();
96                         IOUtils.copy(super.getInputStream(), cachedBytes);
97                 }
98
99                 public class CachedServletInputStream extends ServletInputStream {
100                         private ByteArrayInputStream input;
101
102                         public CachedServletInputStream() {
103                                 input = new ByteArrayInputStream(cachedBytes.toByteArray());
104                         }
105
106                         @Override
107                         public int read() throws IOException {
108                                 return input.read();
109                         }
110
111                         @Override
112                         public boolean isFinished() {
113                                 return false;
114                         }
115
116                         @Override
117                         public boolean isReady() {
118                                 return false;
119                         }
120
121                         @Override
122                         public void setReadListener(ReadListener readListener) {
123                                 // do nothing
124                         }
125                 }
126         }
127
128         @Override
129         protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
130                         throws IOException {
131                 StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString());
132                 String queryString = request.getQueryString();
133                 String requestUrl;
134
135                 if (queryString == null) {
136                         requestUrl = requestURL.toString();
137                 } else {
138                         requestUrl = requestURL.append('?').append(queryString).toString();
139                 }
140
141                 validateRequest(requestUrl, response);
142                 StringBuilder headerValues = new StringBuilder();
143                 Enumeration<String> headerNames = request.getHeaderNames();
144
145                 while (headerNames.hasMoreElements()) {
146                         String key = headerNames.nextElement();
147                         String value = request.getHeader(key);
148                         headerValues.append(value);
149                 }
150
151                 validateRequest(headerValues.toString(), response);
152
153                 if (validateRequestType(request)) {
154                         request = new RequestWrapper(request);
155                         String requestData = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8.toString());
156                         validateRequest(requestData, response);
157                 }
158
159                 try {
160                         filterChain.doFilter(request, response);
161                 } catch (Exception e) {
162                         sxLogger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e);
163                         response.sendError(org.springframework.http.HttpStatus.BAD_REQUEST.value(), "Handling bad request");
164                 }
165         }
166
167         private boolean validateRequestType(HttpServletRequest request) {
168                 return (request.getMethod().equalsIgnoreCase("POST") || request.getMethod().equalsIgnoreCase("PUT")
169                                 || request.getMethod().equalsIgnoreCase("DELETE"));
170         }
171         
172         private void validateRequest(String text, HttpServletResponse response) throws IOException {
173                 try {
174                         if (StringUtils.isNotBlank(text) && validator.denyXSS(text)) {
175                                 response.setContentType(APPLICATION_JSON);
176                                 response.setStatus(HttpStatus.SC_BAD_REQUEST);
177                                 response.getWriter().write(ERROR_BAD_REQUEST);
178                                 throw new SecurityException(ERROR_BAD_REQUEST);
179                         }
180                 } catch (Exception e) {
181                         sxLogger.error(EELFLoggerDelegate.errorLogger, "doFilterInternal() failed due to BAD_REQUEST", e);
182                         response.getWriter().close();
183                 }
184         }
185 }