首先,我不是這方面的專家,我只是在學習並享受使用人工智慧工具的樂趣。
也就是說...我正在為朋友做開發,他有一個100張的PDF,有銀行交易記錄。您需要將這些記錄儲存在 Excel 中以便日後能夠處理。
透過使用Github copilot,我製作了一個使用python和一些庫進行資料擷取的腳本...三個多力多滋之後...作為早餐、午餐和晚餐系統,我建立了一個flask伺服器,來為腳本提供服務通過前端的端點,使用html、css 和js 純粹而簡單。
在與Copilot互動過程中,出現部分程式碼存在「路徑注入」類型漏洞的警報。這個警報很有趣:D
由於我想了解更多關於電腦安全的知識,所以我在這裡寫部落格來記錄這段旅程......
這裡人工智慧開始說話。
攻擊者可以透過操縱使用者輸入來存取伺服器檔案系統上未經授權的檔案或目錄,從而利用路徑注入漏洞。以下是如何做到這一點的範例:
路徑注入範例
假設您的 Flask 應用程式中有一個路由,允許使用者上傳檔案並將其儲存到伺服器。如果您不驗證或清理檔案名,攻擊者可能會發送惡意檔案名稱來嘗試存取系統上的敏感檔案。
易受攻擊的代碼
@app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] filename = file.filename # Nombre del archivo proporcionado por el usuario save_path = os.path.join('uploads', filename) # Guardar el archivo sin validar el nombre del archivo with open(save_path, 'wb') as f: f.write(file.read()) return 'File uploaded successfully'
路徑注入攻擊
攻擊者可以發送帶有惡意檔案名稱的請求,例如../../etc/passwd。這可能會導致以下路線:
上傳/../../etc/passwd
如果伺服器未驗證或清理檔案名,該檔案可能會保存到不需要的位置,從而允許攻擊者覆蓋系統上的敏感檔案。
解決方案:驗證並清理條目
為了避免這些類型的攻擊,您必須在儲存檔案名稱之前驗證和清理檔案名稱。這是程式碼的安全版本:
安全代碼
import os import re from flask import Flask, render_template, request, send_file import requests from datetime import datetime app = Flask(__name__) def sanitize_filename(filename): # Eliminar caracteres no permitidos del nombre del archivo return re.sub(r'[^a-zA-Z0-9_\-\.]', '', filename) @app.route('/') def index(): return render_template('index.html') @app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] response = requests.post('http://127.0.0.1:5001/pdf-to-excel', files={'file': file}) # Obtener la fecha actual current_date = datetime.now().strftime("%Y%m%d") # Obtener el nombre original del archivo sin la extensión original_filename = os.path.splitext(file.filename)[0] # Sanitizar el nombre del archivo sanitized_filename = sanitize_filename(original_filename) # Crear el nuevo nombre del archivo con la fecha al final output_filename = f'{sanitized_filename}_{current_date}.xlsx' # Crear la ruta completa del archivo save_path = os.path.join('uploads', output_filename) # Asegurarse de que la ruta sea absoluta save_path = os.path.abspath(save_path) # Guardar el archivo Excel resultante localmente con el nuevo nombre with open(save_path, 'wb') as f: f.write(response.content) # Enviar el archivo Excel de vuelta al usuario con el nuevo nombre return send_file(save_path, as_attachment=True, download_name=output_filename) if __name__ == '__main__': app.run(port=5000, debug=True)
安全代碼說明
清理檔案名稱: sanitize_filename 函數使用正規表示式從檔案名稱中刪除非法字元。
建立完整檔案路徑: os.path.join 函數用於建立完整檔案路徑,將目標目錄(上傳)與清除後的檔案名稱(output_filename)組合起來。
確保路徑是絕對路徑:os.path.abspath 函數將路徑轉換為絕對路徑,以避免使用相對路徑進行操作。
儲存檔案:最後將檔案儲存到指定路徑。
總結
路徑注入:攻擊者可以操縱使用者輸入來存取未經授權的檔案或目錄。
驗證和清理:始終驗證和清理使用者輸入以避免路徑注入攻擊。
絕對路由:使用絕對路由來避免相對路由的操作。
透過遵循這些做法,您可以保護您的應用程式免受路徑注入攻擊並提高系統的整體安全性。
這裡我問他如何進行攻擊。此外,我還註冊了日誌以便能夠調試這些情況。
為了保護您的應用程式免受路徑注入攻擊,了解如何執行這些攻擊非常有用。在這裡,我向您展示攻擊者如何嘗試利用您的應用程式以及如何在日誌中偵測這些活動。
1. 從瀏覽器
操作 HTML 表單
攻擊者可以操縱 HTML 表單來提交惡意檔案名稱。
一步一步:
- 開啟有檔案上傳表單的網頁。
- 使用瀏覽器的開發者工具 (F12) 檢查表單。
- 修改檔案欄位的值以包含惡意路徑,例如../../etc/passwd。
- 發送表格。
- 日誌中的偵測:記錄日誌中接收到的檔案的名稱。
@app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] filename = file.filename # Nombre del archivo proporcionado por el usuario save_path = os.path.join('uploads', filename) # Guardar el archivo sin validar el nombre del archivo with open(save_path, 'wb') as f: f.write(file.read()) return 'File uploaded successfully'
2.使用Postman等工具
發送經過操縱的 HTTP 請求
攻擊者可以使用 Postman 直接向伺服器發送精心設計的 HTTP 請求。
一步一步:
- 開啟 Postman 並設定 POST 要求到 http://127.0.0.1:5000/upload。
- 在請求正文中,選擇 form-data 並新增一個檔案字段,檔案名稱為 ../../etc/passwd。
- 提交請求。
- 日誌中的偵測:記錄日誌中收到的檔案的名稱。
3.透過自動化腳本
使用 Python 腳本
攻擊者可以使用Python腳本發送惡意HTTP請求。
Python 腳本範例:
import os import re from flask import Flask, render_template, request, send_file import requests from datetime import datetime app = Flask(__name__) def sanitize_filename(filename): # Eliminar caracteres no permitidos del nombre del archivo return re.sub(r'[^a-zA-Z0-9_\-\.]', '', filename) @app.route('/') def index(): return render_template('index.html') @app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] response = requests.post('http://127.0.0.1:5001/pdf-to-excel', files={'file': file}) # Obtener la fecha actual current_date = datetime.now().strftime("%Y%m%d") # Obtener el nombre original del archivo sin la extensión original_filename = os.path.splitext(file.filename)[0] # Sanitizar el nombre del archivo sanitized_filename = sanitize_filename(original_filename) # Crear el nuevo nombre del archivo con la fecha al final output_filename = f'{sanitized_filename}_{current_date}.xlsx' # Crear la ruta completa del archivo save_path = os.path.join('uploads', output_filename) # Asegurarse de que la ruta sea absoluta save_path = os.path.abspath(save_path) # Guardar el archivo Excel resultante localmente con el nuevo nombre with open(save_path, 'wb') as f: f.write(response.content) # Enviar el archivo Excel de vuelta al usuario con el nuevo nombre return send_file(save_path, as_attachment=True, download_name=output_filename) if __name__ == '__main__': app.run(port=5000, debug=True)
日誌中的偵測:記錄日誌中收到的檔案的名稱。
日誌偵測的實作
這是一個完整的實現,其中包括用於檢測可疑檔案名稱的日誌記錄:
@app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] filename = file.filename # Nombre del archivo proporcionado por el usuario save_path = os.path.join('uploads', filename) # Guardar el archivo sin validar el nombre del archivo with open(save_path, 'wb') as f: f.write(file.read()) return 'File uploaded successfully'
總結
從瀏覽器:操作 HTML 表單或使用瀏覽器開發工具。
使用 Postman 等工具:將精心設計的 HTTP 請求直接傳送到伺服器。
使用自動化腳本:使用 Python、Bash 或任何其他語言的腳本傳送惡意 HTTP 請求。
日誌偵測:在日誌中記錄接收到的檔案的名稱和其他可疑活動,以偵測可能的攻擊。
透過實施這些措施,您可以提高應用程式的安全性並偵測可能表明企圖攻擊的可疑活動。
結論:在使用人工智慧進行結對程式設計的學習和開發背景下,我發現平台上的此類警報對於檢測漏洞非常有用。今天我醒來時以為我要部署 Heroku,但在這裡我發現自己發現了不同的漏洞 :D
編碼愉快!
以上是如何執行和偵測路徑注入攻擊的詳細內容。更多資訊請關注PHP中文網其他相關文章!

toAppendElementStoApythonList,usetheappend()方法forsingleements,Extend()formultiplelements,andinsert()forspecificpositions.1)useeAppend()foraddingoneOnelementAttheend.2)useextendTheEnd.2)useextendexendExendEnd(

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

金融、科研、医疗和AI等领域中,高效存储和处理数值数据至关重要。1)在金融中,使用内存映射文件和NumPy库可显著提升数据处理速度。2)科研领域,HDF5文件优化数据存储和检索。3)医疗中,数据库优化技术如索引和分区提高数据查询性能。4)AI中,数据分片和分布式训练加速模型训练。通过选择适当的工具和技术,并权衡存储与处理速度之间的trade-off,可以显著提升系统性能和可扩展性。

pythonarraysarecreatedusiseThearrayModule,notbuilt-Inlikelists.1)importThearrayModule.2)指定tefifythetypecode,例如,'i'forineizewithvalues.arreaysofferbettermemoremorefferbettermemoryfforhomogeNogeNogeNogeNogeNogeNogeNATATABUTESFELLESSFRESSIFERSTEMIFICETISTHANANLISTS。

除了shebang線,還有多種方法可以指定Python解釋器:1.直接使用命令行中的python命令;2.使用批處理文件或shell腳本;3.使用構建工具如Make或CMake;4.使用任務運行器如Invoke。每個方法都有其優缺點,選擇適合項目需求的方法很重要。

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

記事本++7.3.1
好用且免費的程式碼編輯器