简体   繁体   English

解码 base64 字符串是否安全

[英]Is decoding base64 strings safe

I am submitting a user submitted file (which is supposed to be an image) but it is possible to submit a python file instead.我正在提交一个用户提交的文件(它应该是一个图像),但可以提交一个 python 文件。 It is sent to the backend Flask server as a base64 encoded string, and decoded into a file in a child directory.它作为base64编码的字符串发送到后端 Flask 服务器,并解码为子目录中的文件。 I am worried about security, as the user submitted file will be included in dynamically generated HTML as a img src="/images/fileThatIDecoded.jpg" tag.我担心安全性,因为用户提交的文件将作为img src="/images/fileThatIDecoded.jpg"标签包含在动态生成的 HTML 中。 I set the name and file extension myself.我自己设置了名称和文件扩展名。 How can I validate that the decoded base64 string is a valid image?如何验证解码的 base64 字符串是有效图像? In order to use the imghdr module, I must already save the decoded string into a file, which might be unsafe.为了使用 imghdr 模块,我必须已经将解码的字符串保存到一个文件中,这可能是不安全的。


My code:我的代码:

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)

It is not safe to assume that a user provided file is safe.假设用户提供的文件是安全的是不安全的。 The base64 encoding does not have any effect on safety. base64 编码对安全性没有任何影响。

To validate if the provided file is an image, you can use the imghdr module in the standard library, which "determines the type of image contained in a file or byte stream."要验证提供的文件是否为图像,您可以使用标准库中的imghdr 模块,该模块“确定文件或字节流中包含的图像类型”。

You can pass the image as a byte stream directly to imghdr rather than saving it as a file.您可以将图像作为字节流直接传递给 imghdr,而不是将其保存为文件。

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

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