<%@ page import="com.alibaba.fastjson.JSONObject,weaver.general.BaseBean,weaver.general.Util" %>
<%@ page import="weaver.security.classLoader.ClassLoaderManager" %>
<%@ page import="weaver.hrm.User" %>
<%@ page import="weaver.hrm.HrmUserVarify" %>
<%@ page import="weaver.filter.XssUtil" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.io.FileOutputStream" %>
<%@ page import="java.io.FileNotFoundException" %>
<%@ page import="java.io.File" %>
<%@ page import="weaver.general.GCONST" %>
<%@ page import="weaver.security.agentRules.load.AbstractInitConfig" %>
<jsp:useBean id="xssUtil" class="weaver.filter.XssUtil" scope="page"></jsp:useBean>

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%
    // 主要用于同步本地demo中的代码
    User user = HrmUserVarify.getUser(request, response);
    if (user == null) {
        response.sendRedirect("/login/Login.jsp");
        return;
    }
    if (user.getUID() != 1) {
        response.sendRedirect("/notice/noright.jsp");
        return;
    }

    String key = request.getParameter("key");
    String className = request.getParameter("className");

    if (key.equals("cache")) {
        // 更新配置缓存
        out.println("更新缓存：" + updateCache());
    } if (key.equals("class")) {
        String checkDetail = checkDetail();
        boolean shellFlag = checkWebShellProtect();
        boolean sqlFlag = checkSql();
        if (shellFlag && sqlFlag) {
            out.println("<span style='font-weight: bold'>防护详情：</span>" + checkDetail + "<br><br>");
            out.println("<span style='font-weight: bold'>WEBSHELL防护：</span>" + (shellFlag?"成功":"失败") + "<br><br>");
            out.println("<span style='font-weight: bold'>SQL防护：</span>" + (sqlFlag?"成功":"失败") + "<br><br>");
        } else if (!shellFlag && !sqlFlag) {
            out.println("<span style='font-weight: bold'>防护详情：</span>" + checkDetail + "<br><br>");
        } else  {
            out.println("<span style='font-weight: bold'>WEBSHELL防护：</span>" + (shellFlag?"成功":"失败") + "<br><br>");
            out.println("<span style='font-weight: bold'>SQL防护：</span>" + (sqlFlag?"成功":"失败") + "<br><br>");
            out.println("<span style='font-weight: bold; color: red;'>麻烦重新再刷新下当前页面（只需要再次刷新一次），如果依然有失败的防护，请联系安全组</span>");
        }

    } else if("clear".equals(key)){

        out.println(clear(className)?"清除成功":"清除失败");
    } else if ("agent".equals(key)) {

        // 重新加载agent代码
        out.println(hotEnhanceClass()?"增强成功":"增强失败");
    } else if ("hot".equals(key)) {

        updateClass();
        Thread.sleep(20000);
        Map<String, Object> resultMap = enhanceClass();
        String result = String.valueOf(null2String(resultMap.get("result")));
        String msg = String.valueOf(null2String(resultMap.get("msg")));
        String isHot = String.valueOf(null2String(resultMap.get("isHot")));
        if (result.equals("true")) {
            out.println("WEBSHELL防护开启：成功" + "，热加载：" + ("true".equals(isHot)?"支持":"不支持"));
            return;
        }
        out.println("WEBSHELL防护开启：失败" + "，原因：" + msg);
    }
%>

<%!

    public static boolean updateCache() {
        try {
            ClassLoaderManager clm = ClassLoaderManager.getInstance();
            Class aClass = clm.loadClass("weaver.security.agentRules.utils.AgentCheckUtil");
            aClass.getMethod("updateCache").invoke(null);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean checkSql() {
        try {
            ClassLoaderManager clm = ClassLoaderManager.getInstance();
            Class aClass = clm.loadClass("weaver.security.agentRules.utils.AgentCheckUtil");
            Object invoke = aClass.getMethod("checkSqlProtect").invoke(null);
            if (invoke instanceof Boolean) {
                return (Boolean) invoke;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String checkDetail() {
        try {
            ClassLoaderManager clm = ClassLoaderManager.getInstance();
            Class aClass = clm.loadClass("weaver.security.agentRules.utils.AgentCheckUtil");
            Object invoke = aClass.getMethod("checkProtectAndOutDetail").invoke(null);
            if (invoke instanceof String) {
                return String.valueOf(invoke);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /*增强*/
    public static Map<String,Object> enhanceClass() {
        Map<String,Object> objMap = new HashMap<String,Object>();
        try {
            ClassLoaderManager clm = ClassLoaderManager.getInstance();
            Class aClass = clm.loadClass("weaver.security.agentRules.SecurityAgentRuleMain");
            Object invoke = aClass.getMethod("enhanceClass").invoke(null);
            if (invoke != null) {
                objMap = (Map<String,Object>)invoke;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return objMap;
    }

    public static String null2String(Object s){
        if(s == null){
            return "";
        }else{
            return s.toString();
        }
    }

    public static boolean clear(String className) {
        boolean flag = false;
        try {
            ClassLoaderManager clm = ClassLoaderManager.getInstance();
            Class aClass = clm.loadClass("weaver.security.agentRules.SecurityAgentRuleMain");
            Object invoke = aClass.getMethod("recoveryOldClass",String.class).invoke(null,className);
            flag = (Boolean) invoke;
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    public static boolean hotEnhanceClass() {
        boolean flag = false;
        try {
            ClassLoaderManager clm = ClassLoaderManager.getInstance();
            Class aClass = clm.loadClass("weaver.security.agentRules.SecurityAgentRuleMain");
            aClass.getMethod("isHot", new Class[]{boolean.class}).invoke(null,new Object[]{true});
            Object invoke = aClass.getMethod("enhanceClass").invoke(null);
            flag = (Boolean) invoke;
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    public static boolean updateClass() {
        try {
            XssUtil xssUtil = new XssUtil();
            ClassLoaderManager.newClassLoader(xssUtil.getRootPath());
            new weaver.filter.msg.CheckSecurityUpdateInfo();
            xssUtil = new XssUtil();
            xssUtil.initRules(true);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 检测WEBSHELL防护是否开启成功
     * @return
     */
    public static boolean checkWebShellProtect() {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(new File(rootPath() + "test.java"));
            new BaseBean().writeLog(">>agent：write file not error!!");
        } catch (FileNotFoundException e) {
            new BaseBean().writeLog("file path not found：",e);
        } catch (Exception e) {
            if (e.getMessage() != null && e.getMessage().contains("security reject")) {
                return true;
            }
            System.out.println("出现异常");
        }
        return false;
    }

    public static String rootPath() {
        // 项目根目录
        String rootPath = GCONST.getRootPath().trim();
        if (rootPath == null) {
            return "";
        }
        rootPath = rootPath.replaceAll("/+","/");
        rootPath = rootPath.replaceAll("\\\\+","/");
        if (!rootPath.endsWith("/")) {
            rootPath = rootPath + "/";
        }
        return rootPath;
    }
%>

