Fix LogServlet Vulnerabilities
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / provisioning / LogServlet.java
1 /*******************************************************************************\r
2  * ============LICENSE_START==================================================\r
3  * * org.onap.dmaap\r
4  * * ===========================================================================\r
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
6  * * ===========================================================================\r
7  * * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * * you may not use this file except in compliance with the License.\r
9  * * You may obtain a copy of the License at\r
10  * *\r
11  *  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * *\r
13  *  * Unless required by applicable law or agreed to in writing, software\r
14  * * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * * See the License for the specific language governing permissions and\r
17  * * limitations under the License.\r
18  * * ============LICENSE_END====================================================\r
19  * *\r
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
21  * *\r
22  ******************************************************************************/\r
23 \r
24 \r
25 package org.onap.dmaap.datarouter.provisioning;\r
26 \r
27 import java.io.IOException;\r
28 import java.sql.Connection;\r
29 import java.sql.ResultSet;\r
30 import java.sql.SQLException;\r
31 import java.sql.Statement;\r
32 import java.text.ParseException;\r
33 import java.text.SimpleDateFormat;\r
34 import java.util.Date;\r
35 import java.util.HashMap;\r
36 import java.util.Map;\r
37 \r
38 import javax.servlet.ServletOutputStream;\r
39 import javax.servlet.http.HttpServletRequest;\r
40 import javax.servlet.http.HttpServletResponse;\r
41 \r
42 import org.onap.dmaap.datarouter.provisioning.beans.DeliveryRecord;\r
43 import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;\r
44 import org.onap.dmaap.datarouter.provisioning.beans.ExpiryRecord;\r
45 import org.onap.dmaap.datarouter.provisioning.beans.LOGJSONable;\r
46 import org.onap.dmaap.datarouter.provisioning.beans.PublishRecord;\r
47 import org.onap.dmaap.datarouter.provisioning.beans.Subscription;\r
48 import org.onap.dmaap.datarouter.provisioning.eelf.EelfMsgs;\r
49 import org.onap.dmaap.datarouter.provisioning.utils.DB;\r
50 import org.onap.dmaap.datarouter.provisioning.utils.LOGJSONObject;\r
51 \r
52 import com.att.eelf.configuration.EELFLogger;\r
53 import com.att.eelf.configuration.EELFManager;\r
54 \r
55 import static org.onap.dmaap.datarouter.provisioning.utils.HttpServletUtils.sendResponseError;\r
56 \r
57 /**\r
58  * This servlet handles requests to the <feedLogURL> and  <subLogURL>,\r
59  * which are generated by the provisioning server to handle the log query API.\r
60  *\r
61  * @author Robert Eby\r
62  * @version $Id: LogServlet.java,v 1.11 2014/03/28 17:27:02 eby Exp $\r
63  */\r
64 @SuppressWarnings("serial")\r
65 public class LogServlet extends BaseServlet {\r
66     //Adding EELF Logger Rally:US664892\r
67     private static EELFLogger eelflogger = EELFManager.getInstance().getLogger("org.onap.dmaap.datarouter.provisioning.LogServlet");\r
68     private static final long TWENTYFOUR_HOURS = (24 * 60 * 60 * 1000L);\r
69     private static final String FMT_1 = "yyyy-MM-dd'T'HH:mm:ss'Z'";\r
70     private static final String FMT_2 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";\r
71 \r
72     private static  boolean isfeedlog;\r
73 \r
74     public abstract class RowHandler {\r
75         private final ServletOutputStream out;\r
76         private final String[] fields;\r
77         private boolean firstrow;\r
78 \r
79         public RowHandler(ServletOutputStream out, String fieldparam, boolean b) {\r
80             this.out = out;\r
81             this.firstrow = b;\r
82             this.fields = (fieldparam != null) ? fieldparam.split(":") : null;\r
83         }\r
84         public void handleRow(ResultSet rs) {\r
85             try {\r
86                 LOGJSONable js = buildJSONable(rs);\r
87                 LOGJSONObject jo = js.asJSONObject();\r
88                 if (fields != null) {\r
89                     // filter out unwanted fields\r
90                     LOGJSONObject j2 = new LOGJSONObject();\r
91                     for (String key : fields) {\r
92                         Object v = jo.opt(key);\r
93                         if (v != null)\r
94                             j2.put(key, v);\r
95                     }\r
96                     jo = j2;\r
97                 }\r
98                 String t = firstrow ? "\n" : ",\n";\r
99                 t += jo.toString();\r
100                 out.print(t);\r
101                 firstrow = false;\r
102             } catch (Exception exception) {\r
103                 intlogger.info("Failed to handle row. Exception = " + exception.getMessage(),exception);\r
104             }\r
105         }\r
106         public abstract LOGJSONable buildJSONable(ResultSet rs) throws SQLException;\r
107     }\r
108     public class PublishRecordRowHandler extends RowHandler {\r
109         public PublishRecordRowHandler(ServletOutputStream out, String fields, boolean b) {\r
110             super(out, fields, b);\r
111         }\r
112         @Override\r
113         public LOGJSONable buildJSONable(ResultSet rs) throws SQLException {\r
114             return new PublishRecord(rs);\r
115         }\r
116     }\r
117     public class DeliveryRecordRowHandler extends RowHandler {\r
118         public DeliveryRecordRowHandler(ServletOutputStream out, String fields, boolean b) {\r
119             super(out, fields, b);\r
120         }\r
121         @Override\r
122         public LOGJSONable buildJSONable(ResultSet rs) throws SQLException {\r
123             return new DeliveryRecord(rs);\r
124         }\r
125     }\r
126     public class ExpiryRecordRowHandler extends RowHandler {\r
127         public ExpiryRecordRowHandler(ServletOutputStream out, String fields, boolean b) {\r
128             super(out, fields, b);\r
129         }\r
130         @Override\r
131         public LOGJSONable buildJSONable(ResultSet rs) throws SQLException {\r
132             return new ExpiryRecord(rs);\r
133         }\r
134     }\r
135 \r
136     /**\r
137      * This class must be created from either a {@link FeedLogServlet} or a {@link SubLogServlet}.\r
138      * @param isFeedLog boolean to handle those places where a feedlog request is different from\r
139      * a sublog request\r
140      */\r
141     protected LogServlet(boolean isFeedLog) {\r
142         this.isfeedlog = isFeedLog;\r
143     }\r
144 \r
145     /**\r
146      * DELETE a logging URL -- not supported.\r
147      */\r
148     @Override\r
149     public void doDelete(HttpServletRequest req, HttpServletResponse resp) {\r
150         setIpAndFqdnForEelf("doDelete");\r
151         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");\r
152         String message = "DELETE not allowed for the logURL.";\r
153         EventLogRecord elr = new EventLogRecord(req);\r
154         elr.setMessage(message);\r
155         elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r
156         eventlogger.info(elr);\r
157         sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);\r
158     }\r
159     /**\r
160      * GET a logging URL -- retrieve logging data for a feed or subscription.\r
161      * See the <b>Logging API</b> document for details on how this method should be invoked.\r
162      */\r
163     @Override\r
164     public void doGet(HttpServletRequest req, HttpServletResponse resp) {\r
165         setIpAndFqdnForEelf("doGet");\r
166         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");\r
167         int id = getIdFromPath(req);\r
168         if (id < 0) {\r
169             sendResponseError(resp, HttpServletResponse.SC_BAD_REQUEST, "Missing or bad feed/subscription number.", eventlogger);\r
170             return;\r
171         }\r
172         Map<String, String> map = buildMapFromRequest(req);\r
173         if (map.get("err") != null) {\r
174             sendResponseError(resp, HttpServletResponse.SC_BAD_REQUEST, "Invalid arguments: "+map.get("err"), eventlogger);\r
175             return;\r
176         }\r
177         // check Accept: header??\r
178 \r
179         resp.setStatus(HttpServletResponse.SC_OK);\r
180         resp.setContentType(LOGLIST_CONTENT_TYPE);\r
181 \r
182         try (ServletOutputStream out = resp.getOutputStream()) {\r
183             final String fields = req.getParameter("fields");\r
184 \r
185             out.print("[");\r
186             if (isfeedlog) {\r
187                 // Handle /feedlog/feedid request\r
188                 boolean firstrow = true;\r
189 \r
190                 // 1. Collect publish records for this feed\r
191                 RowHandler rh = new PublishRecordRowHandler(out, fields, firstrow);\r
192                 getPublishRecordsForFeed(id, rh, map);\r
193                 firstrow = rh.firstrow;\r
194 \r
195                 // 2. Collect delivery records for subscriptions to this feed\r
196                 rh = new DeliveryRecordRowHandler(out, fields, firstrow);\r
197                 getDeliveryRecordsForFeed(id, rh, map);\r
198                 firstrow = rh.firstrow;\r
199 \r
200                 // 3. Collect expiry records for subscriptions to this feed\r
201                 rh = new ExpiryRecordRowHandler(out, fields, firstrow);\r
202                 getExpiryRecordsForFeed(id, rh, map);\r
203             } else {\r
204                 // Handle /sublog/subid request\r
205                 Subscription sub = Subscription.getSubscriptionById(id);\r
206                 if (sub != null) {\r
207                     // 1. Collect publish records for the feed this subscription feeds\r
208                     RowHandler rh = new PublishRecordRowHandler(out, fields, true);\r
209                     getPublishRecordsForFeed(sub.getFeedid(), rh, map);\r
210 \r
211                     // 2. Collect delivery records for this subscription\r
212                     rh = new DeliveryRecordRowHandler(out, fields, rh.firstrow);\r
213                     getDeliveryRecordsForSubscription(id, rh, map);\r
214 \r
215                     // 3. Collect expiry records for this subscription\r
216                     rh = new ExpiryRecordRowHandler(out, fields, rh.firstrow);\r
217                     getExpiryRecordsForSubscription(id, rh, map);\r
218                 }\r
219             }\r
220             out.print("]");\r
221         } catch (IOException ioe) {\r
222             eventlogger.error("IOException: " + ioe.getMessage());\r
223         }\r
224     }\r
225     /**\r
226      * PUT a logging URL -- not supported.\r
227      */\r
228     @Override\r
229     public void doPut(HttpServletRequest req, HttpServletResponse resp) {\r
230         setIpAndFqdnForEelf("doPut");\r
231         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");\r
232         String message = "PUT not allowed for the logURL.";\r
233         EventLogRecord elr = new EventLogRecord(req);\r
234         elr.setMessage(message);\r
235         elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r
236         eventlogger.info(elr);\r
237         sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);\r
238     }\r
239     /**\r
240      * POST a logging URL -- not supported.\r
241      */\r
242     @Override\r
243     public void doPost(HttpServletRequest req, HttpServletResponse resp) {\r
244         setIpAndFqdnForEelf("doPost");\r
245         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));\r
246         String message = "POST not allowed for the logURL.";\r
247         EventLogRecord elr = new EventLogRecord(req);\r
248         elr.setMessage(message);\r
249         elr.setResult(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\r
250         eventlogger.info(elr);\r
251         sendResponseError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, message, eventlogger);\r
252     }\r
253 \r
254     private Map<String, String> buildMapFromRequest(HttpServletRequest req) {\r
255         Map<String, String> map = new HashMap<>();\r
256         String s = req.getParameter("type");\r
257         if (s != null) {\r
258             if (s.equals("pub") || s.equals("del") || s.equals("exp")) {\r
259                 map.put("type", s);\r
260             } else {\r
261                 map.put("err", "bad type");\r
262                 return map;\r
263             }\r
264         } else\r
265             map.put("type", "all");\r
266         map.put("publishSQL", "");\r
267         map.put("statusSQL", "");\r
268         map.put("resultSQL", "");\r
269         map.put("reasonSQL", "");\r
270 \r
271         s = req.getParameter("publishId");\r
272         if (s != null) {\r
273             if (s.indexOf("'") >= 0) {\r
274                 map.put("err", "bad publishId");\r
275                 return map;\r
276             }\r
277             map.put("publishSQL", " AND PUBLISH_ID = '"+s+"'");\r
278         }\r
279 \r
280         s = req.getParameter("statusCode");\r
281         if (s != null) {\r
282             String sql = null;\r
283             if (s.equals("success")) {\r
284                 sql = " AND STATUS >= 200 AND STATUS < 300";\r
285             } else if (s.equals("redirect")) {\r
286                 sql = " AND STATUS >= 300 AND STATUS < 400";\r
287             } else if (s.equals("failure")) {\r
288                 sql = " AND STATUS >= 400";\r
289             } else {\r
290                 try {\r
291                     Integer n = Integer.parseInt(s);\r
292                     if ((n >= 100 && n < 600) || (n == -1))\r
293                         sql = " AND STATUS = " + n;\r
294                 } catch (NumberFormatException e) {\r
295                 }\r
296             }\r
297             if (sql == null) {\r
298                 map.put("err", "bad statusCode");\r
299                 return map;\r
300             }\r
301             map.put("statusSQL", sql);\r
302             map.put("resultSQL", sql.replaceAll("STATUS", "RESULT"));\r
303         }\r
304 \r
305         s = req.getParameter("expiryReason");\r
306         if (s != null) {\r
307             map.put("type", "exp");\r
308             if (s.equals("notRetryable")) {\r
309                 map.put("reasonSQL", " AND REASON = 'notRetryable'");\r
310             } else if (s.equals("retriesExhausted")) {\r
311                 map.put("reasonSQL", " AND REASON = 'retriesExhausted'");\r
312             } else if (s.equals("diskFull")) {\r
313                 map.put("reasonSQL", " AND REASON = 'diskFull'");\r
314             } else if (s.equals("other")) {\r
315                 map.put("reasonSQL", " AND REASON = 'other'");\r
316             } else {\r
317                 map.put("err", "bad expiryReason");\r
318                 return map;\r
319             }\r
320         }\r
321 \r
322         long stime = getTimeFromParam(req.getParameter("start"));\r
323         if (stime < 0) {\r
324             map.put("err", "bad start");\r
325             return map;\r
326         }\r
327         long etime = getTimeFromParam(req.getParameter("end"));\r
328         if (etime < 0) {\r
329             map.put("err", "bad end");\r
330             return map;\r
331         }\r
332         if (stime == 0 && etime == 0) {\r
333             etime = System.currentTimeMillis();\r
334             stime = etime - TWENTYFOUR_HOURS;\r
335         } else if (stime == 0) {\r
336             stime = etime - TWENTYFOUR_HOURS;\r
337         } else if (etime == 0) {\r
338             etime = stime + TWENTYFOUR_HOURS;\r
339         }\r
340         map.put("timeSQL", String.format(" AND EVENT_TIME >= %d AND EVENT_TIME <= %d", stime, etime));\r
341         return map;\r
342     }\r
343     private long getTimeFromParam(final String s) {\r
344         if (s == null)\r
345             return 0;\r
346         try {\r
347             // First, look for an RFC 3339 date\r
348             String fmt = (s.indexOf('.') > 0) ? FMT_2 : FMT_1;\r
349             SimpleDateFormat sdf = new SimpleDateFormat(fmt);\r
350             Date d = sdf.parse(s);\r
351             return d.getTime();\r
352         } catch (ParseException parseException) {\r
353             intlogger.error("Exception in getting Time :- "+parseException.getMessage(),parseException);\r
354         }\r
355         try {\r
356             // Also allow a long (in ms); useful for testing\r
357             long n = Long.parseLong(s);\r
358             return n;\r
359         } catch (NumberFormatException numberFormatException) {\r
360             intlogger.error("Exception in getting Time :- "+numberFormatException.getMessage(),numberFormatException);\r
361         }\r
362         intlogger.info("Error parsing time="+s);\r
363         return -1;\r
364     }\r
365 \r
366     private void getPublishRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
367         String type = map.get("type");\r
368         if (type.equals("all") || type.equals("pub")) {\r
369             String sql = "select * from LOG_RECORDS where FEEDID = "+feedid\r
370                 + " AND TYPE = 'pub'"\r
371                 + map.get("timeSQL") + map.get("publishSQL") + map.get("statusSQL");\r
372             getRecordsForSQL(sql, rh);\r
373         }\r
374     }\r
375     private void getDeliveryRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
376         String type = map.get("type");\r
377         if (type.equals("all") || type.equals("del")) {\r
378             String sql = "select * from LOG_RECORDS where FEEDID = "+feedid\r
379                 + " AND TYPE = 'del'"\r
380                 + map.get("timeSQL") + map.get("publishSQL") + map.get("resultSQL");\r
381             getRecordsForSQL(sql, rh);\r
382         }\r
383     }\r
384     private void getDeliveryRecordsForSubscription(int subid, RowHandler rh, Map<String, String> map) {\r
385         String type = map.get("type");\r
386         if (type.equals("all") || type.equals("del")) {\r
387             String sql = "select * from LOG_RECORDS where DELIVERY_SUBID = "+subid\r
388                 + " AND TYPE = 'del'"\r
389                 + map.get("timeSQL") + map.get("publishSQL") + map.get("resultSQL");\r
390             getRecordsForSQL(sql, rh);\r
391         }\r
392     }\r
393     private void getExpiryRecordsForFeed(int feedid, RowHandler rh, Map<String, String> map) {\r
394         String type = map.get("type");\r
395         if (type.equals("all") || type.equals("exp")) {\r
396             String st = map.get("statusSQL");\r
397             if (st == null || st.length() == 0) {\r
398                 String sql = "select * from LOG_RECORDS where FEEDID = "+feedid\r
399                     + " AND TYPE = 'exp'"\r
400                     + map.get("timeSQL") + map.get("publishSQL") + map.get("reasonSQL");\r
401                 getRecordsForSQL(sql, rh);\r
402             }\r
403         }\r
404     }\r
405     private void getExpiryRecordsForSubscription(int subid, RowHandler rh, Map<String, String> map) {\r
406         String type = map.get("type");\r
407         if (type.equals("all") || type.equals("exp")) {\r
408             String st = map.get("statusSQL");\r
409             if (st == null || st.length() == 0) {\r
410                 String sql = "select * from LOG_RECORDS where DELIVERY_SUBID = "+subid\r
411                     + " AND TYPE = 'exp'"\r
412                     + map.get("timeSQL") + map.get("publishSQL") + map.get("reasonSQL");\r
413                 getRecordsForSQL(sql, rh);\r
414             }\r
415         }\r
416     }\r
417     private void getRecordsForSQL(String sql, RowHandler rh) {\r
418         intlogger.debug(sql);\r
419         long start = System.currentTimeMillis();\r
420         DB db = new DB();\r
421         Connection conn = null;\r
422         try {\r
423             conn = db.getConnection();\r
424            try( Statement  stmt = conn.createStatement()){\r
425              try(ResultSet rs = stmt.executeQuery(sql)){\r
426                  while (rs.next()) {\r
427                      rh.handleRow(rs);\r
428                  }\r
429              }\r
430            }\r
431         } catch (SQLException sqlException) {\r
432             intlogger.info("Failed to get Records. Exception = " +sqlException.getMessage(),sqlException);\r
433         } finally {\r
434             if (conn != null)\r
435                 db.release(conn);\r
436         }\r
437         intlogger.debug("Time: " + (System.currentTimeMillis()-start) + " ms");\r
438     }\r
439 }\r