<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ page import="java.util.*,java.io.*,weaver.filter.XssUtil" %>
<%@ page import="weaver.security.classLoader.ReflectMethodCall,weaver.hrm.*,java.util.regex.*" %>
<jsp:useBean id="xssUtil" class="weaver.filter.XssUtil" scope="page"></jsp:useBean>
<%String secondPrefixPath = xssUtil.null2String(xssUtil.getRule().get("second-prefix-path"));%>
<%

User userr = HrmUserVarify.getUser(request, response);
if(userr == null){
	return;
}
 XssUtil sc = new XssUtil();
int uid = sc.getIntValue(sc.null2String(sc.getRule().get("userID")),1);
if(userr.getUID()!=uid){
	//response.sendRedirect("/notice/noright.jsp");
	out.println("please login with admin.");
	return;
}

	if(userr!=null && !"".equals(request.getParameter("ip"))){
		if("allow".equals(request.getParameter("src"))){
			try{
				//xssUtil.getTmpForbiddenIpMap().remove(request.getParameter("ip"));
				Map forbiddenIp = (Map)xssUtil.getTmpForbiddenIpMap().get(request.getParameter("ip"));
				forbiddenIp.put("status","false");
				forbiddenIp.put("type","Manager manual allow");
			}catch(Exception e){}
		}else if("forbidden".equals(request.getParameter("src"))){
			try{
				Map forbiddenIp = (Map)xssUtil.getTmpForbiddenIpMap().get(request.getParameter("ip"));
				if(forbiddenIp == null) {
					xssUtil.putToTmpForbiddenIpMap(request.getParameter("ip"), request.getRequestURI(), "Manager manual join");
					forbiddenIp = (Map)xssUtil.getTmpForbiddenIpMap().get(request.getParameter("ip"));
				}
				forbiddenIp.put("status","true");
				forbiddenIp.put("type","Manager manual join");
			}catch(Exception e){}
		}
	}
	
%>
<!DOCTYPE html>
<html lang="zh-CN">
<head lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>参数拦截信息</title>

    <link href="<%=secondPrefixPath%>/security/monitor/logparser/static/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
    <link href="<%=secondPrefixPath%>/security/monitor/logparser/static/bootstrap-3.3.5/css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"/>
	<script type="text/javascript">
		function allow(ip){
			if(confirm("该IP由于存在疑似可疑系统的行为而被禁止访问系统. 你确定要解封吗？")){
				document.getElementById("ip").value=ip;
				document.getElementById("src").value="allow";
				document.getElementById("updateRulesForm").submit();
			}
		}

		function forbidden(ip,path,desc){
			if(confirm("禁止后，该IP将无法访问系统。你确定要加入禁止该IP吗？")){
				document.getElementById("ip").value=ip;
				document.getElementById("src").value="forbidden";
				document.getElementById("url").value= path;
				document.getElementById("desc").value= desc;
				document.getElementById("updateRulesForm").submit();
			}
		}
	</script>
</head>
<body>
<div class="container">
    <h2 class="text-center">参数拦截信息</h2>
</div>
<br>
<form action="<%=secondPrefixPath%>/security/monitor/logparser/xss.jsp" id="updateRulesForm" name="updateRulesForm" style="display:none;" method="post">
	<input type="hidden" name = "ip" id="ip"/>
	<input type="hidden" name = "src" id="src" value="allow"/>
	<input type="hidden" name = "url" id="url" value=""/>
	<input type="hidden" name = "desc" id="desc" value=""/>
</form>
<!--
<div class="container">
    <form class="form-inline" method="GET" action="/listXssLog">
        <input type="hidden" name="filename" value="${filename}"/>
        <input type="hidden" name="uuid" value="${uuid}"/>
        <c:choose>
            <c:when test="${isShrink==0}">
                <button type="submit" class="btn btn-success" id="foldBtn">&nbsp;收&nbsp;&nbsp;&nbsp;缩&nbsp;</button>&nbsp;&nbsp;
                <input type="hidden" name="isShrink" value="1" id="isShrink"/>
            </c:when>
            <c:when test="${isShrink==1}">
                <button type="submit" class="btn btn-info" id="foldBtn">&nbsp;展&nbsp;&nbsp;&nbsp;开&nbsp;</button>&nbsp;&nbsp;
                <input type="hidden" name="isShrink" value="0" id="isShrink"/>
            </c:when>
            <c:otherwise>
                <button type="submit" class="btn btn-success" id="foldBtn">&nbsp;收&nbsp;&nbsp;&nbsp;缩&nbsp;</button>&nbsp;&nbsp;
                <input type="hidden" name="isShrink" value="1" id="isShrink"/>
            </c:otherwise>
        </c:choose>
    </form>
</div>
-->
<br>

<div class="bs-example" data-example-id="hoverable-table">
    <table class="table table-hover table-responsive  table-condensed table-striped">
      <thead>
        <tr>
            <th style="width:10%">日期</th>
            <th style="width:15%">路径</th>
            <th style="width:10%">参数</th>
            <th style="width:15%">值</th>
			<th style="width:15%">触发规则</th>
            <th style="width:10%">操作者</th>
            <th style="width:10%">源IP</th>
			<th style="width:10%">来源城市</th>
			<th style="width:5%">操作</th>
        </tr>
      </thead>
      <tbody>
	   <%!
	  
	          //返回正则的方法
				public String returnNeedStr(String reg,String str){
					try{
						Pattern pattern = Pattern.compile(reg);
						Matcher matcher = pattern.matcher(str);
						while(matcher.find()){
							return htmlEncode(matcher.group(1));
						}
					}catch(Exception e){
					   // e.printStackTrace();
					}
					return  null;
				}

				//返回正则的方法
				public String returnNeedStr2(String reg,String str){
					try{
						Pattern pattern = Pattern.compile(reg);
						Matcher matcher = pattern.matcher(str);
						while(matcher.find()){
							return htmlEncode(matcher.group(0));
						}
					}catch(Exception e){
						// e.printStackTrace();
					}
					return  null;
				}

				public  String htmlEncode(String source) {
						if(source == null) {
						   return "";
						}
					   String html = "";
					   StringBuffer buffer = new StringBuffer();
						for(int i = 0; i < source.length(); i++) {
						   char c = source.charAt(i);
						   switch (c) {
						   case '<':
							   buffer.append("&lt;");
							   break;
						   case '>':
							   buffer.append("&gt;");
							   break;
						   case '&':
							   buffer.append("&amp;");
							   break;
						   case '"':
							   buffer.append("&quot;");
							   break;
						   case 10:
						   case 13:
							   break;
						   default:
							   buffer.append(c);
						   }
						}
					   html = buffer.toString();
					   return html;
		 }
	     %>
		<%   
			InputStreamReader inputStreamReader = null;
			BufferedReader reader = null;
			Map map = xssUtil.getTmpForbiddenIpMap();
			try{
			
				String securityLogPath = sc.getXssLogFilePath()+ File.separatorChar+"systemSecurity"+sc.getCurrentDateString()+".log";
				File logFile = new File(securityLogPath);
				if(!logFile.exists()){
					 out.println("<tr><td>暂无当天日志<td></tr>");
					 return;
				}
				inputStreamReader = new InputStreamReader( new FileInputStream(logFile),"GBK");
				reader = new BufferedReader(inputStreamReader);
				String line = null;
				int i = 0;
				while((line = reader.readLine()) != null){
				if(line.indexOf("Xss(NoPass)") > 0){
					// 级别
					String levelReg = "level:([\\S]+)";
					String level = returnNeedStr(levelReg,line);
					if(level == null || "".equals(level)){
					   out.println("<tr style='color:red !important;'>");
					}else{
					   out.println("<tr>");
					}
					//日期
					String dateReg =  "[0-9]{4}[-][0-9]{1,2}[-][0-9]{1,2}[ ][0-9]{1,2}[:][0-9]{1,2}[:][0-9]{1,2}";
					String date = returnNeedStr2(dateReg,line);
					out.println(" <td data-toggle=\"modal\">"+date+"</td>");

					

					// referer
					/*
					String refererReg = "referer:([\\S]+)";
					String referer = returnNeedStr(refererReg,line);
					out.println(" <td data-toggle=\"modal\" data-target=\"#myModal\">"+referer+"</td>");

					String ruleReg = "rule=([\\S]+) p";
					String rule = returnNeedStr(ruleReg,line);
					out.println(" <td data-toggle=\"modal\" data-target=\"#myModal\">"+rule+"</td>");
					*/


					String pathReg = "path:([\\S]+)";
					String path = returnNeedStr(pathReg,line);
				   out.println(" <td data-toggle=\"modal\">"+path+"</td>");

					String paramReg = "param:([\\S]+)";
					String param = returnNeedStr(paramReg,line);
					out.println(" <td data-toggle=\"modal\" >"+param+"</td>");


					String paramValueReg = "paramValue:([\\S\\s]+)";
					String s = returnNeedStr(paramValueReg, line);
					if(s != null){
					   String paramValue = s.split(":::")[0];
					   if(paramValue.length()>100){
						  out.println(" <td data-toggle=\"modal\" title=\""+htmlEncode(paramValue.substring(0,100))+"\"> "+htmlEncode(paramValue.substring(0,50))+"...</td>");
					   }else{
						  out.println(" <td data-toggle=\"modal\">"+htmlEncode(paramValue)+"</td>");
					   }
					   
					}else{
						out.println(" <td data-toggle=\"modal\">无</td>");
					}
					
					String ruleReg = "rule=([\\S]+)";
					String rule = returnNeedStr(ruleReg,line);
					out.println(" <td data-toggle=\"modal\" title=\""+rule+"\">"+rule+"</td>");

					String userReg = "user:([\\S]+)";
					String user = returnNeedStr(userReg,line);
					out.println(" <td data-toggle=\"modal\">"+user+"</td>");

					String SourceIPReg = "Source IP:([\\S]+)";
					String sourceIP = returnNeedStr(SourceIPReg,line);
					out.println(" <td data-toggle=\"modal\">"+sourceIP+"</td>");

					ReflectMethodCall rmc = new ReflectMethodCall();	
					String city = (String)rmc.call("weaver.security.util.IPUtil",null,"getCityInfo",
								new Class[]{String.class}, sourceIP);
					out.println(" <td data-toggle=\"modal\">"+city+"</td>");
					String opStr = "";
					if(sourceIP != null && map!=null) {
						Map ipMap = (Map) map.get(sourceIP);
						if(ipMap!=null) {
							if ("true".equals("" + ipMap.get("status"))) {
								opStr = "<div style=\"margin-left:auto;margin-right:auto;text-align:center;cursor:pointer;color:#f25f1e;width:54px;height:26px;line-height:26px;border:1px solid #d6d6d6;\" onclick=\"allow('"+htmlEncode(sourceIP)+"');\">解封</div>";
							}else{
								opStr = "<div style=\"margin-left:auto;margin-right:auto;text-align:center;cursor:pointer;color:#f25f1e;width:54px;height:26px;line-height:26px;border:1px solid #d6d6d6;\" onclick=\"forbidden('"+htmlEncode(sourceIP)+"','"+path+"','');\">禁止</div>";
							}
						}else{
							opStr = "<div style=\"margin-left:auto;margin-right:auto;text-align:center;cursor:pointer;color:#f25f1e;width:54px;height:26px;line-height:26px;border:1px solid #d6d6d6;\" onclick=\"forbidden('"+htmlEncode(sourceIP)+"','"+path+"','');\">禁止</div>";

						}
					}
					out.println(" <td data-toggle=\"modal\">"+opStr+"</td>");
					out.println("</tr>");
				}
        }
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(inputStreamReader != null){
				inputStreamReader.close();
			}
			if(reader != null){
				reader.close();
			}
		}
     %>
      </tbody>
    </table>
	<!--
    <div style="margin-left: 1300px">
        <a href="/downloadFile?uuid=${uuid}_xss" target="_blank" class="btn btn-danger" id="downloadFile">添加完白名单后，点此下载白名单文件</a>
    </div>
	-->
</div>


</body>
</html>