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