python - 解码 base64 字符串是否安全
问题描述
我正在提交用户提交的文件(应该是图像),但可以提交 python 文件。它作为base64
编码字符串发送到后端 Flask 服务器,并解码为子目录中的文件。我担心安全性,因为用户提交的文件将作为img
src="/images/fileThatIDecoded.jpg"
标签包含在动态生成的 HTML 中。我自己设置名称和文件扩展名。如何验证解码后的 base64 字符串是否为有效图像?为了使用 imghdr 模块,我必须已经将解码的字符串保存到一个文件中,这可能是不安全的。
我的代码:
mainPond.onaddfile = (err, item) => {
if (err) {
console.warn(err);
return;
}
const base64String = item.getFileEncodeBase64String();
console.log(base64String)
document.getElementById("hiddenFile").value = base64String
}
document.getElementById("submitbtn").onclick = function() {
if (validateForm()) {
document.getElementById("form").submit()
}
}
@app.route("/create", methods=["GET","POST"])
@login_required
def create():
if request.method == "GET":
return render_template("create.html")
else:
imgdata = request.form.get("mainFile")
if helpers.verifyImage(imgdata[:44]):
imgdata = base64.b64decode(imgdata)
filename = 'some_image.jpg'
filename = os.path.join(os.path.abspath(os.curdir), "images", filename)
with open(filename, 'wb') as f:
f.write(imgdata)
解决方案
假设用户提供的文件是安全的是不安全的。base64 编码对安全没有任何影响。
要验证提供的文件是否为图像,您可以使用标准库中的imghdr 模块,该模块“确定文件或字节流中包含的图像类型”。
您可以将图像作为字节流直接传递给 imghdr,而不是将其保存为文件。
推荐阅读
- linux - 从bash创建多个用户命名和编号的文件而不循环
- c - 如何在 Gradle 中为 C 源代码构建二进制文件,但不可执行?
- azure-functions - 部署 Azure 功能
- scapy - 使用底层的字段来填充字段
- apache-spark - spark coalesce(20) 覆盖 repartition(1000).groupby(xxx).apply(func) 的并行性
- unicode - “凸起的先生标志”未正确呈现
- php - 如何从字符串javascript中获取价值?
- javascript - 具有“获取”功能的 Javascript 无法在 Android 5.1.1 上运行
- migration - 部分事件源应用程序,以及从常规到事件源应用程序的路线图
- rust - Rust - 所有权和借款