繁体   English   中英

解码 base64 字符串是否安全

[英]Is decoding base64 strings safe

我正在提交一个用户提交的文件(它应该是一个图像),但可以提交一个 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,而不是将其保存为文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM