如何清理用户为网络应用程序创建的文件名?
我正在开发一个即时消息应用程序,用户可以在其中接收来自朋友的文件。
接收到的文件的名称由文件的发送者设置,并且可以将多个文件连同子目录一起发送。例如,一起发送的两个文件可能是“1”和“sub/2”,这样下载的结果应该类似于“downloads/1”和“downloads/sub/2”。
我担心这会带来安全影响。我突然想到,对于类 Unix 用户来说,两个潜在危险的文件名可能是“../../../somethingNasty”或“~/somethingNasty”。我想到的其他潜在问题是文件名中包含目标文件系统不支持的字符,但这似乎更难,最好忽略?
我正在考虑剥离收到的“..”和“~”文件名,但我个人认为问题案例的这种黑名单方法似乎不太像是良好安全性的秘诀。建议使用什么方法来清理文件名以确保不会发生任何危险的情况?
如果有什么不同的话,我的应用程序正在使用 QT 框架在 C++ 上运行。
I'm working on an instant messaging app, where users can receive files from their friends.
The names of the files received are set by the sender of the file, and multiple files can be sent together with the possibility of subdirectories. For example, two files sent together might be "1" and "sub/2" such that the downloaded results should be like "downloads/1" and "downloads/sub/2".
I'm worried about the security implications of this. Right off the top of my head, two potentially dangerous filnames would be something like "../../../somethingNasty" or "~/somethingNasty" for Unix-like users. Other potential issues that cross my mind are filenames with characters that are unsupported on the target filesystem, but that seems much harder and may just be better to ignore?
I'm considering stripping received filenames for ".." and "~" but this type of blacklist approach where I individually think of problem cases hardly seems like the recipe for good security. What's the recommended way to sanitize filenames to ensure nothing sinister happens?
If it makes a difference, my app is running on C++ with the QT framework.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更明智的做法是将“..”替换为 XXX,将 ~ 替换为 YYY。这样您就可以将任何无效路径转换为完全有效的路径。即,如果用户想要上传“../../../somethingNasty” - 没问题,让他上传文件并将其存储在 XXX/XXX/XXX/somethingNasty 中。
或者更好的是,您可以使用 %XY 对所有非字母数字字符(斜线除外)进行编码,其中 XY 是字符的十六进制代码。这样你就会有 %2E%2E/%2E%2E/%2E%2E/SomethingNasty
It's wiser to replace ".." with say XXX and ~ with say YYY. This way you convert any invalid path to a perfectly valid path. I.e. if the user wants to upload "../../../somethingNasty" - no problems, let him upload the file and store it in XXX/XXX/XXX/somethingNasty.
Or even better, you can encode all nonalphanumeric characters (except slashes) with %XY where XY is hexidecimal code of the character. This way you would have %2E%2E/%2E%2E/%2E%2E/SomethingNasty