Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Tomcat 虛擬路徑配置與定時掃描刪除惡意 WAR 檔案的 Java 實作方案

編輯:系統常見問題解答

背景動機

伺服器屢遭入侵,webapps 目錄頻繁出現不明惡意 .war 檔案。對策:

  1. 修改 Tomcat 虛擬路徑,將應用部署目錄移出預設 webapps。
  2. 部署監聽器定時掃描 webapps 與 work 目錄,自動刪除非白名單檔案。

一、修改 server.xml 虛擬主機路徑

在 C 槽建立 C:/webApp、C:/webWork 兩目錄,修改 <Host> 節點:

<Host appBase="C:/webApp/" autoDeploy="true" name="localhost" unpackWARs="true" workDir="C:/webWork/"></Host>

二、實作定時掃描刪除監聽器

1. ProtectTaskListener.java(ServletContextListener)

package com.px.listener;
import com.px.util.Config;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ProtectTaskListener implements ServletContextListener {
    private Timer timer;
    public void contextInitialized(ServletContextEvent event) {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                ProtectUtil.deleteOtherFile();
            }
        }, Config.CHECK_TIME);
    }
    public void contextDestroyed(ServletContextEvent event) {
        timer.cancel();
    }
}

2. ProtectUtil.java(核心刪除邏輯)

package com.px.listener;
import java.io.File;

public class ProtectUtil {
    public static final String WEBAPPS_PATH = "C:/webApp";
    public static final String WORK_PATH = "C:/webWork";
    public static final String[] WORK_WHITELIST = {"hospital1", "installer", "jswork", "reports"};

    public static void deleteOtherFile() {
        deleteWebAppsOtherFile();
        deleteWorkOtherFile();
    }

    public static void deleteWebAppsOtherFile() {
        File file = new File(WEBAPPS_PATH);
        if (file.exists()) {
            for (File f : file.listFiles()) {
                if (!f.getName().equals("hospital1")) {
                    delFileOrDirectory(f);
                }
            }
        }
    }

    public static void deleteWorkOtherFile() {
        File file = new File(WORK_PATH);
        if (file.exists()) {
            for (File f : file.listFiles()) {
                boolean delete = true;
                for (String w : WORK_WHITELIST) {
                    if (f.getName().equals(w)) { delete = false; break; }
                }
                if (delete) delFileOrDirectory(f);
            }
        }
    }

    private static void delFileOrDirectory(File file) {
        if (file.exists()) {
            if (file.isDirectory()) {
                for (File sub : file.listFiles()) delFileOrDirectory(sub);
            }
            file.delete();
        }
    }
}

部署說明

  1. 將編譯後的類別打包至專案 WEB-INF/classes 或獨立 JAR 放入 Tomcat lib。
  2. 在專案 web.xml 註冊 ProtectTaskListener。
  3. 於 Config.CHECK_TIME 設定掃描間隔(毫秒)。

效果:應用啟動後自動定時清理非白名單部署檔案,降低惡意 WAR 執行風險。配合檔案完整性監控(如 Tripwire、AIDE)可構建更完整防禦體系。

Copyright © Windows教程網 All Rights Reserved