JavaScript过滤XSS

  1. var filterXSS=function(oriStr){
  2. if(!oriStr){
  3. return oriStr;
  4. }
  5. var charCodes=['3c','3e','27','22','28','29','60',{format:'script{}',chr:'3a'}];//要转义字符的16进制ASCII码[1< 2> 3' 4" 5( 6) 7`]
  6. var xssChars=[],filterChars=[],tmpFormat='{}',tmpChr;
  7. for(var i=0;i<charCodes.length;i++){
  8. if('string'==typeof charCodes[i]){
  9. tmpFormat='{}';
  10. tmpChr=charCodes[i];
  11. }else{
  12. tmpFormat=charCodes[i].format;
  13. tmpChr=charCodes[i].chr
  14. }
  15. xssChars.push(tmpFormat.replace('{}','\\u00'+tmpChr));
  16. xssChars.push(tmpFormat.replace('{}','%'+tmpChr));//1次encode
  17. xssChars.push(tmpFormat.replace('{}','%25'+tmpChr));//2次encode
  18. filterChars.push(tmpFormat.replace('{}','&#x'+tmpChr+';'));
  19. filterChars.push(tmpFormat.replace('{}','%26%23x'+tmpChr+'%3B'));//1次encode
  20. filterChars.push(tmpFormat.replace('{}','%2526%2523x' + tmpChr + '%253B'));//2次encode
  21. }
  22. for(var i=0;i<xssChars.length;i++){
  23. oriStr=oriStr.replace(new RegExp(xssChars[i],'gi'),filterChars[i]);
  24. }
  25. //预防script:
  26. oriStr=oriStr.replace(/script[\u000d\u000a\u0020]+\:/,'script:');
  27. return oriStr;
  28. }

猜你喜欢

转载自blog.csdn.net/weixin_39664733/article/details/121479896