搜索
首页后端开发Python教程如何执行和检测路径注入攻击

Cómo Realizar y Detectar Ataques de Path Injection

首先,我不是这方面的专家,我只是在学习并享受使用人工智能工具的乐趣。

也就是说...我正在为一个朋友做开发,他有一个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中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
您如何将元素附加到Python列表中?您如何将元素附加到Python列表中?May 04, 2025 am 12:17 AM

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

您如何创建Python列表?举一个例子。您如何创建Python列表?举一个例子。May 04, 2025 am 12:16 AM

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

讨论有效存储和数值数据的处理至关重要的实际用例。讨论有效存储和数值数据的处理至关重要的实际用例。May 04, 2025 am 12:11 AM

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

您如何创建Python数组?举一个例子。您如何创建Python数组?举一个例子。May 04, 2025 am 12:10 AM

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

使用Shebang系列指定Python解释器有哪些替代方法?使用Shebang系列指定Python解释器有哪些替代方法?May 04, 2025 am 12:07 AM

除了shebang线,还有多种方法可以指定Python解释器:1.直接使用命令行中的python命令;2.使用批处理文件或shell脚本;3.使用构建工具如Make或CMake;4.使用任务运行器如Invoke。每个方法都有其优缺点,选择适合项目需求的方法很重要。

列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?May 03, 2025 am 12:11 AM

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

说明如何将内存分配给Python中的列表与数组。说明如何将内存分配给Python中的列表与数组。May 03, 2025 am 12:10 AM

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

您如何在Python数组中指定元素的数据类型?您如何在Python数组中指定元素的数据类型?May 03, 2025 am 12:06 AM

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

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版