简体   繁体   中英

printf and unsafe formatting strings

The application in question allows users to define their own messages (mainly for customization and/or localization purposes) in plain-text configuration file, which are passed to printf-style functions at runtime. If the user-defined formatting string is faulty, a whole lot of bad things can happen.

What is the best way to sanitize such user-inputted formatting strings? Or should I drop this approach entirely and use another method to let users safely customize the messages?

Solution must be somehow portable (Windows, Linux, BSD, x86, x86-64).

定义您自己的格式化语言,您的代码将转换为有效的格式字符串,从而限制用户可以遇到的麻烦(例如,根本不允许%,并定义您自己的符号/标记用于指示%应该出现在输出中)。

You have two choices:

  1. Let the user's mess-ups (intentional or not) mess up only themselves, ie don't let the users' personal configurations interfere with each other

  2. Don't let users customize the results. Or if you do, make the customization so limited that there is nothing they can do that is harmful.
    For example, I've frequently done things where users are allowed to provide their own input to things like printf() , but the filters only allowed for things with a certain (very limited) character set. Eg, I'll use a regexp of something like ^[a-zA-Z0-9_]+$ and don't let anything else in.

Any time you offer customization, you open the door to problems. Walk carefully in these grounds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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