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