標籤:捷徑 uid 對比 notepad++ windows 國際 equals 內容 伺服器
最近項目的測試哥們提了一個linux系統軟連結攻擊的問題,項目中匯出伺服器上某個檔案的時,通過軟串連漏洞可以擷取到其他檔案的資訊。
具體過程自己寫了個下載的Demo類比了一下:
下載的servlet和html如下,下載/opt/temp/a.txt,國際慣例,內容是hello world,檔案大小12kb。
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Download File</title><script type="text/javascript"> function download() { window.open("download.do"); }</script></head><body> <input type="button" value="Download" onclick="download()" /></body></html>View Code
package com.dj.servlet;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.net.URLEncoder;import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.tomcat.util.http.fileupload.IOUtils;/** * @author DU * */@WebServlet("/download.do")public class DownloadDemoServlet extends HttpServlet{ private static final long serialVersionUID = 1L; public DownloadDemoServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileName = "a.txt"; response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); String filePath = "/opt/temp/" + fileName; FileInputStream is = new FileInputStream(new File(filePath)); ServletOutputStream os = response.getOutputStream(); IOUtils.copy(is, os); os.close(); is.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}View Code
這樣下載下來的檔案沒有任何問題,接下來就涉及軟連結的問題,在伺服器上/home目錄下有一個npp.7.3.3.Installer.x64.exe的檔案,當然這是個notepad++的安裝檔案,我自己放進去的。先將/opt/temp/a.txt刪除掉,然後用xshell執行命令ln -s /home/npp.7.3.3.Installer.x64.exe /opt/temp/a.txt 建立.exe的軟連結檔案為a.txt,關於軟連結檔案這裡不細表,可以自行百度,可以理解為類似windows的捷徑,建立成功之後是這樣的,注意這時候檔案大小已經是2.84M了。
然後再次點擊下載,這個時候下載下來的是這樣的:
是的,下載軟連結會直接下載軟連結指向的源檔案,如果是敏感檔案的話就很不好了。當然,筆者依然處於菜鳥階段,還不是很清楚惡意攻擊者可以通過怎樣的手段達到建立出這個軟連結。
接下來就是如何規避這個問題了:
第一種方式是通過對比檔案的絕對路徑和規整化路徑,如果是源檔案的話這兩個路徑應該是一樣的,否則就是連結檔案。
// 對比絕對路徑和規整化路徑 String absolutePath = file.getAbsolutePath(); String canonicalPath = file.getCanonicalPath(); if (!absolutePath.equals(canonicalPath)) { response.getWriter().append("Download Failed!"); return; }View Code
第二種方式可以直接通過jdk1.7開始出現的java.nio.file.Files類提供的介面判斷。
// 直接通過java.nio.file包中提供的介面判斷 Path path = Paths.get(filePath); boolean isSymbolicLink = Files.isSymbolicLink(path); if (isSymbolicLink) { response.getWriter().append("Download Failed!"); return; }View Code
,校正成功!
Java後台Linux軟連結檔案下載檢驗