用于crlf注入(cwe-93/cwe-117)预防的python日志格式化程序
logging-formatter-anticrlf的Python项目详细描述
记录格式化程序以清除CRLF错误(CWE-93,某些形式的CWE-117)
这个类是logging.Formatter的替换项,并且具有 完全相同的构造参数。但是,作为格式化 日志行,它转义回车(\r)和换行符(\n)。
默认情况下,这些替换为它们的转义等价物(请参见Examples)。 但是可以修改replacements字典来更改此行为。
此清理应解决CWE-93错误和基于CRLF的版本 CWE-117。一些cwe-117错误是关于日志中的xss缺陷,例如 可能在浏览器中查看;此格式化程序无法处理 CWE-117表格。
安装
pip install logging-formatter-anticrlf
示例
import anticrlf handler = logging.StreamHandler(sys.stderr) handler.setFormatter(anticrlf.LogFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) logger = logging.getLogger(__name__) logger.addHandler(handler) logger.setLevel(logging.INFO) logger.info("Example text with a newline\nhere")
这将导致:
2017-02-03 08:43:52,557 - __main__ - INFO - Example text with a newline\nhere
而使用默认的Formatter,则是:
2017-02-03 08:43:52,557 - __main__ - INFO - Example text with a newline here
如果您想用\x0a代替换行符,可以:
formatter = anticrlf.LogFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') formatter.replacements["\n"] = "\\x0A" # Note the double backslash for literal! handler.setFormatter(formatter)
更换部件
格式化程序的replacements字段是行为的SubstitutionMap对象 像dict一样,有几个例外是为了帮助开发人员避免犯不安全的错误。
具体来说:
- “empty”SubstitutionMap对象将包含CR和LF字符的默认映射
- 对cr或lf键调用del将重置值,而不是delete键
- 任何创建键值对的尝试,其结果是任何包含任何键的值 将筹集UnsafeSubstitutionError
最后一项的基本原理是replacements字段的键是字符串 被认为是不安全的。用另一个不安全的字符串替换一个不安全的字符串会破坏 使用此模块。
另外,如果您将一个常规的dict分配给replacements字段,并尝试记录 使用该配置的东西,anticrlf.LogFormatter将重置replacements 字段设置为其默认值,并为此发出UserWarning。
这意味着:
formatter.replacements["\n"] = "\\x0A" # replace LF chars with '\x0A' del formatter.replacements["\n"] # return to replacing LF with '\n' formatter.replacements["\t"] = "\\t" # replace tabs with '\t' formatter.replacements["\n"] = "<\t>" # raises UnsafeSubstitutionError
最后一次出现是因为值<\t>包含\t,该值以前是作为键创建的。
以及:
formatter.replacements = { "\n": "\r" } # this is a mistake! logger.info("example")
将导致,如果该记录器正在使用该格式化程序,则在replacements中返回 安全的默认值和一个关于正在发出的UserWarning的值。