伺服器屢遭入侵,webapps 目錄頻繁出現不明惡意 .war 檔案。對策:
webapps。webapps 與 work 目錄,自動刪除非白名單檔案。server.xml 虛擬主機路徑在 C 槽建立 C:/webApp、C:/webWork 兩目錄,修改 <Host> 節點:
<Host appBase="C:/webApp/" autoDeploy="true" name="localhost" unpackWARs="true" workDir="C:/webWork/"></Host>
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();
}
}
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();
}
}
}
WEB-INF/classes 或獨立 JAR 放入 Tomcat lib。web.xml 註冊 ProtectTaskListener。Config.CHECK_TIME 設定掃描間隔(毫秒)。效果:應用啟動後自動定時清理非白名單部署檔案,降低惡意 WAR 執行風險。配合檔案完整性監控(如 Tripwire、AIDE)可構建更完整防禦體系。