Fix NodeServlet Vulnerabilities
[dmaap/datarouter.git] / datarouter-node / src / main / java / org / onap / dmaap / datarouter / node / NodeServlet.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.node;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import java.io.File;
30 import java.io.FileOutputStream;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.OutputStream;
35 import java.io.Writer;
36 import java.nio.file.Files;
37 import java.nio.file.Path;
38 import java.nio.file.Paths;
39 import java.util.Enumeration;
40 import java.util.regex.Pattern;
41 import javax.servlet.ServletException;
42 import javax.servlet.http.HttpServlet;
43 import javax.servlet.http.HttpServletRequest;
44 import javax.servlet.http.HttpServletResponse;
45
46 import org.apache.log4j.Logger;
47 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
48
49 import static org.onap.dmaap.datarouter.node.NodeUtils.sendResponseError;
50
51 /**
52  * Servlet for handling all http and https requests to the data router node
53  * <p>
54  * Handled requests are:
55  * <br>
56  * GET http://<i>node</i>/internal/fetchProv - fetch the provisioning data
57  * <br>
58  * PUT/DELETE https://<i>node</i>/internal/publish/<i>fileid</i> - n2n transfer
59  * <br>
60  * PUT/DELETE https://<i>node</i>/publish/<i>feedid</i>/<i>fileid</i> - publsh request
61  */
62 public class NodeServlet extends HttpServlet {
63     private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.node.NodeServlet");
64     private static NodeConfigManager config;
65     private static Pattern MetaDataPattern;
66     //Adding EELF Logger Rally:US664892
67     private static EELFLogger eelflogger = EELFManager.getInstance()
68         .getLogger("org.onap.dmaap.datarouter.node.NodeServlet");
69
70     static {
71         final String ws = "\\s*";
72         // assume that \\ and \" have been replaced by X
73         final String string = "\"[^\"]*\"";
74         //String string = "\"(?:[^\"\\\\]|\\\\.)*\"";
75         final String number = "[+-]?(?:\\.\\d+|(?:0|[1-9]\\d*)(?:\\.\\d*)?)(?:[eE][+-]?\\d+)?";
76         final String value = "(?:" + string + "|" + number + "|null|true|false)";
77         final String item = string + ws + ":" + ws + value + ws;
78         final String object = ws + "\\{" + ws + "(?:" + item + "(?:" + "," + ws + item + ")*)?\\}" + ws;
79         MetaDataPattern = Pattern.compile(object, Pattern.DOTALL);
80     }
81
82     /**
83      * Get the NodeConfigurationManager
84      */
85     public void init() {
86         config = NodeConfigManager.getInstance();
87         logger.info("NODE0101 Node Servlet Configured");
88     }
89
90     private boolean down(HttpServletResponse resp) throws IOException {
91         if (config.isShutdown() || !config.isConfigured()) {
92             sendResponseError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE, logger);
93             logger.info("NODE0102 Rejecting request: Service is being quiesced");
94             return (true);
95         }
96         return (false);
97     }
98
99     /**
100      * Handle a GET for /internal/fetchProv
101      */
102     protected void doGet(HttpServletRequest req, HttpServletResponse resp){
103         NodeUtils.setIpAndFqdnForEelf("doGet");
104         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
105             getIdFromPath(req) + "");
106         try{
107             if (down(resp)) {
108                 return;
109             }
110
111         } catch (IOException ioe) {
112             logger.error("IOException" + ioe.getMessage());
113         }
114         String path = req.getPathInfo();
115         String qs = req.getQueryString();
116         String ip = req.getRemoteAddr();
117         if (qs != null) {
118             path = path + "?" + qs;
119         }
120         if ("/internal/fetchProv".equals(path)) {
121             config.gofetch(ip);
122             resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
123             return;
124         } else if (path.startsWith("/internal/resetSubscription/")) {
125             String subid = path.substring(28);
126             if (subid.length() != 0 && subid.indexOf('/') == -1) {
127                 NodeMain.resetQueue(subid, ip);
128                 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
129                 return;
130             }
131         }
132
133         logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
134         sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, logger);
135     }
136
137     /**
138      * Handle all PUT requests
139      */
140     protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
141         NodeUtils.setIpAndFqdnForEelf("doPut");
142         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
143             getIdFromPath(req) + "");
144         try {
145             common(req, resp, true);
146         } catch(IOException ioe){
147             logger.error("IOException" + ioe.getMessage());
148         } catch(ServletException se){
149             logger.error("ServletException" + se.getMessage());
150         }
151     }
152
153     /**
154      * Handle all DELETE requests
155      */
156     protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
157         NodeUtils.setIpAndFqdnForEelf("doDelete");
158         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
159             getIdFromPath(req) + "");
160         try {
161             common(req, resp, false);
162         } catch(IOException ioe){
163             logger.error("IOException" + ioe.getMessage());
164         } catch(ServletException se){
165             logger.error("ServletException" + se.getMessage());
166         }
167     }
168
169     private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput)
170         throws ServletException, IOException {
171         if (down(resp)) {
172             return;
173         }
174         if (!req.isSecure()) {
175             logger.info(
176                 "NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr());
177             resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests");
178             return;
179         }
180         String fileid = req.getPathInfo();
181         if (fileid == null) {
182             logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
183                 .getRemoteAddr());
184             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
185                 "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
186             return;
187         }
188         String feedid = null;
189         String user = null;
190         String credentials = req.getHeader("Authorization");
191         if (credentials == null) {
192             logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + " from " + req
193                 .getRemoteAddr());
194             resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required");
195             return;
196         }
197         String ip = req.getRemoteAddr();
198         String lip = req.getLocalAddr();
199         String pubid = null;
200         String xpubid = null;
201         String rcvd = NodeUtils.logts(System.currentTimeMillis()) + ";from=" + ip + ";by=" + lip;
202         Target[] targets = null;
203         if (fileid.startsWith("/publish/")) {
204             fileid = fileid.substring(9);
205             int i = fileid.indexOf('/');
206             if (i == -1 || i == fileid.length() - 1) {
207                 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
208                     .getRemoteAddr());
209                 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
210                     "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.  Possible missing fileid.");
211                 return;
212             }
213             feedid = fileid.substring(0, i);
214             fileid = fileid.substring(i + 1);
215             pubid = config.getPublishId();
216             xpubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
217             targets = config.getTargets(feedid);
218         } else if (fileid.startsWith("/internal/publish/")) {
219             if (!config.isAnotherNode(credentials, ip)) {
220                 logger.info("NODE0107 Rejecting unauthorized node-to-node transfer attempt from " + ip);
221                 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
222                 return;
223             }
224             fileid = fileid.substring(18);
225             pubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
226             targets = config.parseRouting(req.getHeader("X-ATT-DR-ROUTING"));
227         } else {
228             logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
229                 .getRemoteAddr());
230             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
231                 "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
232             return;
233         }
234         if (fileid.indexOf('/') != -1) {
235             logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
236                 .getRemoteAddr());
237             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
238                 "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
239             return;
240         }
241         String qs = req.getQueryString();
242         if (qs != null) {
243             fileid = fileid + "?" + qs;
244         }
245         String hp = config.getMyName();
246         int xp = config.getExtHttpsPort();
247         if (xp != 443) {
248             hp = hp + ":" + xp;
249         }
250         String logurl = "https://" + hp + "/internal/publish/" + fileid;
251         if (feedid != null) {
252             logurl = "https://" + hp + "/publish/" + feedid + "/" + fileid;
253             String reason = config.isPublishPermitted(feedid, credentials, ip);
254             if (reason != null) {
255                 logger.info(
256                     "NODE0111 Rejecting unauthorized publish attempt to feed " + feedid + " fileid " + fileid + " from "
257                         + ip + " reason " + reason);
258                 resp.sendError(HttpServletResponse.SC_FORBIDDEN, reason);
259                 return;
260             }
261             user = config.getAuthUser(feedid, credentials);
262             String newnode = config.getIngressNode(feedid, user, ip);
263             if (newnode != null) {
264                 String port = "";
265                 int iport = config.getExtHttpsPort();
266                 if (iport != 443) {
267                     port = ":" + iport;
268                 }
269                 String redirto = "https://" + newnode + port + "/publish/" + feedid + "/" + fileid;
270                 logger.info(
271                     "NODE0108 Redirecting publish attempt for feed " + feedid + " user " + user + " ip " + ip + " to "
272                         + redirto);
273                 resp.sendRedirect(redirto);
274                 return;
275             }
276             resp.setHeader("X-ATT-DR-PUBLISH-ID", pubid);
277         }
278         String fbase = config.getSpoolDir() + "/" + pubid;
279         File data = new File(fbase);
280         File meta = new File(fbase + ".M");
281         OutputStream dos = null;
282         InputStream is = null;
283         try (Writer mw = new FileWriter(meta)){
284             StringBuffer mx = new StringBuffer();
285             mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
286             Enumeration hnames = req.getHeaderNames();
287             String ctype = null;
288             while (hnames.hasMoreElements()) {
289                 String hn = (String) hnames.nextElement();
290                 String hnlc = hn.toLowerCase();
291                 if ((isput && ("content-type".equals(hnlc) ||
292                     "content-language".equals(hnlc) ||
293                     "content-md5".equals(hnlc) ||
294                     "content-range".equals(hnlc))) ||
295                     "x-att-dr-meta".equals(hnlc) ||
296                     (feedid == null && "x-att-dr-received".equals(hnlc)) ||
297                     (hnlc.startsWith("x-") && !hnlc.startsWith("x-att-dr-"))) {
298                     Enumeration hvals = req.getHeaders(hn);
299                     while (hvals.hasMoreElements()) {
300                         String hv = (String) hvals.nextElement();
301                         if ("content-type".equals(hnlc)) {
302                             ctype = hv;
303                         }
304                         if ("x-att-dr-meta".equals(hnlc)) {
305                             if (hv.length() > 4096) {
306                                 logger.info(
307                                     "NODE0109 Rejecting publish attempt with metadata too long for feed " + feedid
308                                         + " user " + user + " ip " + ip);
309                                 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Metadata too long");
310                                 return;
311                             }
312                             if (!MetaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) {
313                                 logger.info(
314                                     "NODE0109 Rejecting publish attempt with malformed metadata for feed " + feedid
315                                         + " user " + user + " ip " + ip);
316                                 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed metadata");
317                                 return;
318                             }
319                         }
320                         mx.append(hn).append('\t').append(hv).append('\n');
321                     }
322                 }
323             }
324             mx.append("X-ATT-DR-RECEIVED\t").append(rcvd).append('\n');
325             String metadata = mx.toString();
326             byte[] buf = new byte[1024 * 1024];
327             int i;
328             try {
329                 is = req.getInputStream();
330                 dos = new FileOutputStream(data);
331                 while ((i = is.read(buf)) > 0) {
332                     dos.write(buf, 0, i);
333                 }
334                 is.close();
335                 is = null;
336                 dos.close();
337                 dos = null;
338             } catch (IOException ioe) {
339                 long exlen = -1;
340                 try {
341                     exlen = Long.parseLong(req.getHeader("Content-Length"));
342                 } catch (Exception e) {
343                 }
344                 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user,
345                     ioe.getMessage());
346                 throw ioe;
347             }
348             Path dpath = Paths.get(fbase);
349             for (Target t : targets) {
350                 DestInfo di = t.getDestInfo();
351                 if (di == null) {
352                     // TODO: unknown destination
353                     continue;
354                 }
355                 String dbase = di.getSpool() + "/" + pubid;
356                 Files.createLink(Paths.get(dbase), dpath);
357                 mw.write(metadata);
358                 if (di.getSubId() == null) {
359                     mw.write("X-ATT-DR-ROUTING\t" + t.getRouting() + "\n");
360                 }
361                 meta.renameTo(new File(dbase + ".M"));
362             }
363             resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
364             resp.getOutputStream().close();
365             StatusLog.logPub(pubid, feedid, logurl, req.getMethod(), ctype, data.length(), ip, user,
366                 HttpServletResponse.SC_NO_CONTENT);
367         } catch (IOException ioe) {
368             logger.info(
369                 "NODE0110 IO Exception receiving publish attempt for feed " + feedid + " user " + user + " ip " + ip
370                     + " " + ioe.toString(), ioe);
371             throw ioe;
372         } finally {
373             if (is != null) {
374                 try {
375                     is.close();
376                 } catch (Exception e) {
377                 }
378             }
379             if (dos != null) {
380                 try {
381                     dos.close();
382                 } catch (Exception e) {
383                 }
384             }
385             try {
386                 data.delete();
387             } catch (Exception e) {
388             }
389             try {
390                 meta.delete();
391             } catch (Exception e) {
392             }
393         }
394     }
395
396     private int getIdFromPath(HttpServletRequest req) {
397         String path = req.getPathInfo();
398         if (path == null || path.length() < 2) {
399             return -1;
400         }
401         try {
402             return Integer.parseInt(path.substring(1));
403         } catch (NumberFormatException e) {
404             return -1;
405         }
406     }
407 }