<%@ page import="com.alibaba.fastjson.JSONObject,weaver.general.BaseBean,weaver.general.Util" %>

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page import="weaver.hrm.HrmUserVarify" %>
<%@ page import="weaver.hrm.User" %>
<%@ page import="weaver.general.GCONST" %>
<%@ page import="weaver.security.classLoader.ClassLoaderManager" %>
<%@ page import="java.util.List" %>
<%@ page import="weaver.filter.ServerDetector" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.io.FileOutputStream" %>
<%@ page import="java.lang.reflect.Method" %>
<%@ page import="bsh.Interpreter" %>
<%@ page import="java.lang.reflect.InvocationTargetException" %>
<jsp:useBean id="xssUtil" class="weaver.filter.XssUtil"></jsp:useBean>

<%

    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 serverId = ServerDetector.getServerId() == null? "": ServerDetector.getServerId().toLowerCase();
    // 版本号
    String ecVersion = xssUtil.getEcVersion() == null? "" : xssUtil.getEcVersion().toLowerCase();

    if (ecVersion.equalsIgnoreCase("e9")) {
        out.println("<span style=\"font-weight: bold\">SQL防护：</span>" + (checkSql()?"成功":"<span style='color:red;'>失败</span>") + "<br>");
        out.println("<span style=\"font-weight: bold\">SQL防护(tableName)：</span>" + (checkSqlAboutTableName()?"成功":"<span style='color:red;'>失败</span>") + "<br>");
        out.println("<span style=\"font-weight: bold\">SQL防护(tableField)：</span>" + (checkSqlAboutTableField()?"成功":"<span style='color:red;'>失败</span>") + "<br>");
        out.println("<span style=\"font-weight: bold\">Util防护：</span>" + (checkUtilFile()?"成功":"<span style='color:red;'>失败</span>") + "<br>");
        out.println("<span style=\"font-weight: bold\">DoMethod防护：</span>" + (checkDoMethod()?"成功":"<span style='color:red;'>失败</span>") + "<br>");
        out.println("<span style=\"font-weight: bold\">DoMethod-public防护：</span>" + (utilPublicProject()?"成功":"<span style='color:red;'>失败</span>") + "<br>");
    }

    boolean write = write();
    boolean writeSeparator = writeSeparator();
    boolean checkCmd = checkCmd();
    boolean checkCmdProtectThread = checkCmdProtectThread();
    boolean checkInvokeProtect = checkInvokeProtect();
    out.println("<span style=\"font-weight: bold\">WEBSHELL防护：</span>" + (write?"成功":"<span style='color:red;'>失败</span>") + "<br>");
    out.println("<span style=\"font-weight: bold\">WEBSHELL(Separator)：</span>" + (writeSeparator?"成功":"<span style='color:red;'>失败</span>") + "<br>");
    out.println("<span style=\"font-weight: bold\">命令防护：</span>" + (checkCmd?"成功":"<span style='color:red;'>失败</span>") + "<br>");
    out.println("<span style=\"font-weight: bold\">命令防护(thread)：</span>" + (checkCmdProtectThread?"成功":"<span style='color:red;'>失败</span>") + "<br>");
    out.println("<span style=\"font-weight: bold\">INVOKE防护：</span>" + (checkInvokeProtect?"成功":"<span style='color:red;'>失败</span>") + "<br>");
    out.println("<span style=\"font-weight: bold\">INTER防护：</span>" + (checkInvokeProtect?"成功":"<span style='color:red;'>失败</span>") + "<br>");


    out.println("------------------------------------<br>");

    // 关于tool
    if (!writeSeparator() && !checkSql() && getToolsJarLogInfo().contains("success")) {
        // 说明tools是第一次创建，这种情况需要重启一次，只需要重启一次即可
        out.println("<span style=\"font-weight: bold; color: red;\">检测失败的解决方案：</span>" + "见到此提示，麻烦再次重启下OA应用，只需要重启一次即可，如果重启之后未解决，麻烦提交到安全组" + "<br>");
        return;
    } else if (getToolsJarLogInfo().contains("error")) {
        out.println("<span style=\"font-weight: bold\">组件情况：</span>" + getToolsJarLogInfo() + "<br>");
    }

    if (ecVersion.contains("e9") && !write() && writeSeparator() && checkSql() && serverId.contains("resin3")) {
        out.println("<span style=\"font-weight: bold\">中间件版本：</span>" + "resin3" + "<br>");
        out.println("<span style=\"font-weight: bold; color: red;\">WEBSHELL防护失败的解决方案：</span>" + "需要升级Resin组件，提交流程到集群组升级Resin3到Resin4即可！" + "<br>");
    } else {
        out.println("<span style=\"font-weight: bold\">中间件版本：</span>" + serverId + "<br>");
        out.println("<span style=\"font-weight: bold\">OA版本：</span>" + ecVersion + "<br>");
    }

    if (!ecVersion.contains("e9") && !writeSeparator()) {
        out.println("<span style=\"font-weight: bold; color: red;\">检测失败尝试解决方案：</span>" + "使用管理员登录访问(访问后等待60s再次检测，只需访问一次此接口)：/security/monitor/updateClass.jsp" + "<br>");
    }

    if (write && writeSeparator && checkCmd && checkCmdProtectThread && !checkInvokeProtect) {
        out.println("<span style=\"font-weight: bold; color: red;\">invoke防护检测失败修复方案：</span>" + "如果客户是自动更新进行升级，麻烦重新打下官网的增量包，然后重启" + "<br>");
    }

    if (ecVersion.contains("e9")) {
        out.println("<span style=\"font-weight: bold;color: red; \">注意：</span>如果显示的是全部失败，可以尝试重启后检测；如果显示的是部分失败，由于有自动修复机制，可以等待2-3分钟再次检测查看（可重复刷新查看）<br>");
    }

%>

<%!

    public static boolean utilPublicProject() {
        try {
            com.cloudstore.dev.api.util.Util_public.doMethod("com.greenpineyu.fel.FelEngineImpl.eval", new Object[]{});
        } catch (Throwable e) {

            if (e instanceof InvocationTargetException) {
                e = ((InvocationTargetException) e).getTargetException();
            }
            if (e.getMessage() != null && e.getMessage().contains("[security reject]")) {
                return true;
            }
            if (e.toString().contains("[security reject]")) {
                return true;
            }
        }
        return false;
    }

    public static boolean bashProject() {
        try {
            Class aClass = Class.forName("bsh.Interpreter");
            Method method = aClass.getDeclaredMethod("eval", new Class[]{String.class});
            method.invoke(aClass.newInstance(), new Object[]{""});
        } catch (Throwable e) {

            if (e instanceof InvocationTargetException) {
                e = ((InvocationTargetException) e).getTargetException();
            }
            if (e.getMessage() != null && e.getMessage().contains("[security reject]")) {
                return true;
            }
            if (e.toString().contains("[security reject]")) {
                return true;
            }
        }
        return false;
    }

    public static boolean checkInvokeProtect() {

        try {
            FileOutputStream fos = new FileOutputStream(new java.io.FileDescriptor());
            Method[] methods = FileOutputStream.class.getDeclaredMethods();
            for (Method method : methods) {
                String name = method.getName();
                if (name.equals("open")) {
                    method.setAccessible(true);
                    method.invoke(fos,".jsp", false);
                }
            }
        } catch (Exception e) {
            if (e.getMessage() != null && e.getMessage().contains("security reject")) {
                return true;
            }
        }
        return false;
    }

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

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

    public String checkMemoryHorseExist() {
        try {
            ClassLoaderManager clm = ClassLoaderManager.getInstance();
            Class aClass = clm.loadClass("weaver.security.agentRules.utils.AgentCheckUtil");
            Map<String,String> mapResult = (Map<String,String>)aClass.getMethod("checkMemoryHorseExist").invoke(null);
            if (mapResult == null) {
                return "检测出现异常";
            }

            String code = mapResult.get("code");
            if (!code.equals("1")) {
                return "<span style='color:red;'>麻烦使用管理员登录访问查看详情：/security/checkHorse.jsp</span>";
            }

            return "不存在";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

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

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

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

    public String getToolsJarLogInfo() {
        try {
            ClassLoaderManager clm = ClassLoaderManager.getInstance();
            Class aClass = clm.loadClass("weaver.security.agentRules.utils.AgentCheckUtil");
            List<String> toolsInfo = (List<String>)aClass.getMethod("getToolsJarLogInfo").invoke(null);
            if (toolsInfo.isEmpty()) {
                return "systemRunInfo日志中未搜索到关于tools.jar的信息，可尝试稍等1分钟再次刷新此页面";
            }
            String info = toolsInfo.get(toolsInfo.size() - 1);
            return info.split(">>agent")[1];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public 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 boolean checkCmd() {
        try {
            ClassLoaderManager clm = ClassLoaderManager.getInstance();
            Class aClass = clm.loadClass("weaver.security.agentRules.utils.AgentCheckUtil");
            Object invoke = aClass.getMethod("checkCmdProtect").invoke(null);
            if (invoke instanceof Boolean) {
                return (Boolean) invoke;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

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

    public boolean writeSeparator() {
        try {
            ClassLoaderManager clm = ClassLoaderManager.getInstance();
            Class aClass = clm.loadClass("weaver.security.agentRules.utils.AgentCheckUtil");
            Object invoke = aClass.getMethod("checkWebShellProtect", new Class[]{String.class}).invoke(null,"../project.java");
            if (invoke instanceof Boolean) {
                return (Boolean) invoke;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        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;
    }
%>