billlee
V2EX  ›  编程

如何有效防止「正则表达式注入」?

  •  1
     
  •   billlee · Nov 4, 2016 · 4811 views
    This topic created in 3479 days ago, the information mentioned may be changed or developed.

    我们知道,在应用中从外界接受输入拼接正则表达式,很容易被 DoS 攻击。即使不考虑 DoS 攻击的问题,如果输入含有特殊字符,也会造成正则表达式的语义出错。

    一般在根据外界输入进行搜索是,都是使用 startsWith, contains 这些不使用正则表达式,直接做字符串查找的方法。但是有些情况下是不得不使用正则的,例如,在 mongodb 里按字符串前缀检索数据,就必须用正则。

    在这样的情况下,有没有什么比较通用、可靠的方法来防止「正则表达式注入」?

    4 replies    2016-11-05 01:52:22 +08:00
    oott123
        1
    oott123  
       Nov 5, 2016 via Android
    语义问题就转义呗
    转义了的话,好好写正则应该不会被 DoS 了吧?
    langmoe
        2
    langmoe  
       Nov 5, 2016   ❤️ 1
    @oott123 我估计楼主想说的不是注入,是类似这种的攻击
    http://www.zhouhua.info/2015/06/02/trap/
    binux
        3
    binux  
       Nov 5, 2016
    正则也有转义的啊
    terence4444
        4
    terence4444  
       Nov 5, 2016 via iPad
    /E /Q 可以转义吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2781 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 11:32 · PVG 19:32 · LAX 04:32 · JFK 07:32
    ♥ Do have faith in what you're doing.