当前位置:   article > 正文

WEB安全之代码安全----ESAPI_org.owasp.esapi.errors.intrusionexception: input v

org.owasp.esapi.errors.intrusionexception: input validation failure

ESAPI是owasp提供的一套API级别的web应用解决方案。简单的说,ESAPI就是为了编写出更加安全的代码而设计出来的一些API,方便使用者调用,从而方便的编写安全的代码

其官方网站为:https://www.owasp.org/,其有很多针对不同语言的版本,其J2ee的版本需要jre1.5及以上支持


目录

 

安装篇

第一步:引入Jar

第二步:直接下载Jar

配置

测试

使用

1. 针对xss漏洞

2. 针对sql注入漏洞

3. 验证输入

4. 验证恶意文件


安装篇

第一步:引入Jar

Maven

  1. <dependency>
  2. <groupId>org.owasp.esapi</groupId>
  3. <artifactId>esapi</artifactId>
  4. <version>2.1.0.1</version>
  5. </dependency>

gradle

compile group: 'org.owasp.esapi', name: 'esapi', version: '2.1.0.1'1


第二步:直接下载Jar

https://search.maven.org/search?q=g:org.owasp.esapi


配置

在工程的资源文件目录下增加配置文件ESAPI.properties及validation.properties,文件内容可为空。如果为空则都取默认值。建议参考以下文件内容设置

 

ESAPI.properties

  1. # 是否要打印配置属性,默认为true
  2. ESAPI.printProperties=true
  3. ESAPI.AccessControl=org.owasp.esapi.reference.DefaultAccessController
  4. ESAPI.Authenticator=org.owasp.esapi.reference.FileBasedAuthenticator
  5. ESAPI.Encoder=org.owasp.esapi.reference.DefaultEncoder
  6. ESAPI.Encryptor=org.owasp.esapi.reference.crypto.JavaEncryptor
  7. ESAPI.Executor=org.owasp.esapi.reference.DefaultExecutor
  8. ESAPI.HTTPUtilities=org.owasp.esapi.reference.DefaultHTTPUtilities
  9. ESAPI.IntrusionDetector=org.owasp.esapi.reference.DefaultIntrusionDetector
  10. ESAPI.Logger=org.owasp.esapi.reference.JavaLogFactory
  11. ESAPI.Randomizer=org.owasp.esapi.reference.DefaultRandomizer
  12. ESAPI.Validator=org.owasp.esapi.reference.DefaultValidator
  13. #===========================================================================
  14. # ESAPI Encoder
  15. Encoder.AllowMultipleEncoding=false
  16. Encoder.AllowMixedEncoding=false
  17. Encoder.DefaultCodecList=HTMLEntityCodec,PercentCodec,JavaScriptCodec
  18. #===========================================================================
  19. # ESAPI 加密模块
  20. Encryptor.PreferredJCEProvider=
  21. Encryptor.EncryptionAlgorithm=AES
  22. Encryptor.CipherTransformation=AES/CBC/PKCS5Padding
  23. Encryptor.cipher_modes.combined_modes=GCM,CCM,IAPM,EAX,OCB,CWC
  24. Encryptor.cipher_modes.additional_allowed=CBC
  25. Encryptor.EncryptionKeyLength=128
  26. Encryptor.ChooseIVMethod=random
  27. Encryptor.fixedIV=0x000102030405060708090a0b0c0d0e0f
  28. Encryptor.CipherText.useMAC=true
  29. Encryptor.PlainText.overwrite=true
  30. Encryptor.HashAlgorithm=SHA-512
  31. Encryptor.HashIterations=1024
  32. Encryptor.DigitalSignatureAlgorithm=SHA1withDSA
  33. Encryptor.DigitalSignatureKeyLength=1024
  34. Encryptor.RandomAlgorithm=SHA1PRNG
  35. Encryptor.CharacterEncoding=UTF-8
  36. Encryptor.KDF.PRF=HmacSHA256
  37. #===========================================================================
  38. # ESAPI Http工具
  39. HttpUtilities.UploadDir=C:\\ESAPI\\testUpload
  40. HttpUtilities.UploadTempDir=C:\\temp
  41. # Force flags on cookies, if you use HttpUtilities to set cookies
  42. HttpUtilities.ForceHttpOnlySession=false
  43. HttpUtilities.ForceSecureSession=false
  44. HttpUtilities.ForceHttpOnlyCookies=true
  45. HttpUtilities.ForceSecureCookies=true
  46. # Maximum size of HTTP headers
  47. HttpUtilities.MaxHeaderSize=4096
  48. # File upload configuration
  49. HttpUtilities.ApprovedUploadExtensions=.zip,.pdf,.doc,.docx,.ppt,.pptx,.tar,.gz,.tgz,.rar,.war,.jar,.ear,.xls,.rtf,.properties,.java,.class,.txt,.xml,.jsp,.jsf,.exe,.dll
  50. HttpUtilities.MaxUploadFileBytes=500000000
  51. # Using UTF-8 throughout your stack is highly recommended. That includes your database driver,
  52. # container, and any other technologies you may be using. Failure to do this may expose you
  53. # to Unicode transcoding injection attacks. Use of UTF-8 does not hinder internationalization.
  54. HttpUtilities.ResponseContentType=text/html; charset=UTF-8
  55. # This is the name of the cookie used to represent the HTTP session
  56. # Typically this will be the default "JSESSIONID"
  57. HttpUtilities.HttpSessionIdName=JSESSIONID
  58. #===========================================================================
  59. # ESAPI Executor
  60. Executor.WorkingDirectory=
  61. Executor.ApprovedExecutables=
  62. #===========================================================================
  63. # ESAPI Logging
  64. # Set the application name if these logs are combined with other applications
  65. Logger.ApplicationName=ExampleApplication
  66. # If you use an HTML log viewer that does not properly HTML escape log data, you can set LogEncodingRequired to true
  67. Logger.LogEncodingRequired=false
  68. # Determines whether ESAPI should log the application name. This might be clutter in some single-server/single-app environments.
  69. Logger.LogApplicationName=true
  70. # Determines whether ESAPI should log the server IP and port. This might be clutter in some single-server environments.
  71. Logger.LogServerIP=true
  72. # LogFileName, the name of the logging file. Provide a full directory path (e.g., C:\\ESAPI\\ESAPI_logging_file) if you
  73. # want to place it in a specific directory.
  74. Logger.LogFileName=ESAPI_logging_file
  75. # MaxLogFileSize, the max size (in bytes) of a single log file before it cuts over to a new one (default is 10,000,000)
  76. Logger.MaxLogFileSize=10000000
  77. #===========================================================================
  78. # ESAPI Intrusion Detection
  79. IntrusionDetector.Disable=false
  80. IntrusionDetector.event.test.count=2
  81. IntrusionDetector.event.test.interval=10
  82. IntrusionDetector.event.test.actions=disable,log
  83. IntrusionDetector.org.owasp.esapi.errors.IntrusionException.count=1
  84. IntrusionDetector.org.owasp.esapi.errors.IntrusionException.interval=1
  85. IntrusionDetector.org.owasp.esapi.errors.IntrusionException.actions=log,disable,logout
  86. IntrusionDetector.org.owasp.esapi.errors.IntegrityException.count=10
  87. IntrusionDetector.org.owasp.esapi.errors.IntegrityException.interval=5
  88. IntrusionDetector.org.owasp.esapi.errors.IntegrityException.actions=log,disable,logout
  89. IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.count=2
  90. IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.interval=10
  91. IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.actions=log,logout
  92. #===========================================================================
  93. # ESAPI 校验器
  94. #校验器的配置文件
  95. Validator.ConfigurationFile=validation.properties
  96. # Validators used by ESAPI
  97. Validator.AccountName=^[a-zA-Z0-9]{3,20}$
  98. Validator.SystemCommand=^[a-zA-Z\\-\\/]{1,64}$
  99. Validator.RoleName=^[a-z]{1,20}$
  100. #the word TEST below should be changed to your application
  101. #name - only relative URL's are supported
  102. Validator.Redirect=^\\/test.*$
  103. # Global HTTP Validation Rules
  104. # Values with Base64 encoded data (e.g. encrypted state) will need at least [a-zA-Z0-9\/+=]
  105. Validator.HTTPScheme=^(http|https)$
  106. Validator.HTTPServerName=^[a-zA-Z0-9_.\\-]*$
  107. Validator.HTTPParameterName=^[a-zA-Z0-9_]{1,32}$
  108. Validator.HTTPParameterValue=^[a-zA-Z0-9.\\-\\/+=@_ ]*$
  109. Validator.HTTPCookieName=^[a-zA-Z0-9\\-_]{1,32}$
  110. Validator.HTTPCookieValue=^[a-zA-Z0-9\\-\\/+=_ ]*$
  111. # Note that max header name capped at 150 in SecurityRequestWrapper!
  112. Validator.HTTPHeaderName=^[a-zA-Z0-9\\-_]{1,50}$
  113. Validator.HTTPHeaderValue=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$
  114. Validator.HTTPContextPath=^\\/?[a-zA-Z0-9.\\-\\/_]*$
  115. Validator.HTTPServletPath=^[a-zA-Z0-9.\\-\\/_]*$
  116. Validator.HTTPPath=^[a-zA-Z0-9.\\-_]*$
  117. Validator.HTTPQueryString=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ %]*$
  118. Validator.HTTPURI=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$
  119. Validator.HTTPURL=^.*$
  120. Validator.HTTPJSESSIONID=^[A-Z0-9]{10,30}$
  121. # Validation of file related input
  122. Validator.FileName=^[a-zA-Z0-9!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$
  123. Validator.DirectoryName=^[a-zA-Z0-9:/\\\\!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$
  124. # Validation of dates. Controls whether or not 'lenient' dates are accepted.
  125. # See DataFormat.setLenient(boolean flag) for further details.
  126. Validator.AcceptLenientDates=false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  127. validation.properties
  128. # 校验某个字段的正则表达式
  129. Validator.SafeString=^[.\\p{Alnum}\\p{Space}]{0,1024}$
  130. Validator.Email=^[A-Za-z0-9._%'-]+@[A-Za-z0-9.-]+\\.[a-zA-Z]{2,4}$
  131. Validator.IPAddress=^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
  132. Validator.URL=^(ht|f)tp(s?)\\:\\/\\/[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*(:(0-9)*)*(\\/?)([a-zA-Z0-9\\-\\.\\?\\,\\:\\'\\/\\\\\\+=&amp;%\\$#_]*)?$
  133. Validator.CreditCard=^(\\d{4}[- ]?){3}\\d{4}$
  134. Validator.SSN=^(?!000)([0-6]\\d{2}|7([0-6]\\d|7[012]))([ -]?)(?!00)\\d\\d\\3(?!0000)\\d{4}$
  135. 12345678


测试

增加测试类:

  1. import org.owasp.esapi.ESAPI;
  2. public class Test {
  3. public static void main(String args[]) {
  4. System.out.println(ESAPI.encoder().encodeForHTML("<a href='sdfs'></a> < script > alert(); </ script >"));
  5. }
  6. }12345678

运行结果如下即为安装成功:

&lt;a href&#x3d;&#x27;sdfs&#x27;&gt;&lt;&#x2f;a&gt; &lt; script &gt; alert&#x28;&#x29;&#x3b; &lt;&#x2f; script &gt;1

使用

1. 针对xss漏洞

  1. //对用户输入“input”进行HTML编码,防止XSS
  2. input = ESAPI.encoder().encodeForHTML(input);
  3. //根据自己不同的需要可以选用以下方法
  4. //input = ESAPI.encoder().encodeForHTMLAttribute(input);
  5. //input = ESAPI.encoder().encodeForJavaScript(input);
  6. //input = ESAPI.encoder().encodeForCSS(input);
  7. //input = ESAPI.encoder().encodeForURL(input);
  8. //针对富文本进行html编码123456789

2. 针对sql注入漏洞

除了支持mysql还支持oracle

  1. String input1="用户输入1";
  2. String input2="用户输入2";
  3. //解决注入问题
  4. input1 = ESAPI.encoder().encodeForSQL(new MySQLCodec(MySQLCodec.Mode.STANDARD),input1);
  5. input2 = ESAPI.encoder().encodeForSQL(new MySQLCodec(MySQLCodec.Mode.STANDARD),input2);
  6. String sqlStr="select name from tableA where id="+input1 +"and date_created ='" + input2+"'";
  7. //执行SQL12345678910

3. 验证输入

检查每个输入的有效性,让每个输入合法。这里面的关键是一切都进行验证。ESAPI提供了很多常见的校验,可以方便针对不同的需要做校验。

  1. //type就是定义在validate.properties文件中的正则表达式
  2. //ESAPI.validator().getValidInput(java.lang.String context,java.lang.String input, java.lang.String type,int maxLength,boolean allowNull);
  3. //ESAPI.validator().isValidInput(java.lang.String context,java.lang.String input, java.lang.String type,int maxLength,boolean allowNull);
  4. //实际使用参考如下:
  5. String input="xxxx.com";
  6. if(!ESAPI.validator().isValidInput("",input,"Email",11,false)){
  7. System.out.println("出错了");
  8. }
  9. try{
  10. input = ESAPI.validator().getValidInput("",input,"Email",11,false);
  11. }catch (Exception e){
  12. System.out.println("输入错误");
  13. e.printStackTrace();
  14. }
  15. 1234567891011121314151617181920

4. 验证恶意文件

  1. //校验文件名
  2. String inputfilename ="xxxx.txt";
  3. ArrayList<String> allowedExtension = new ArrayList<String>();
  4. allowedExtension.add("exe");
  5. allowedExtension.add("jpg");
  6. if(!ESAPI.validator().isValidFileName("upload",inputfilename, allowedExtension,false)){
  7. //文件名不合法,throw exception
  8. System.out.println("出错了");
  9. }
  10. //获取随机文件名
  11. System.out.println(ESAPI.randomizer().getRandomFilename("exe"));
  12. //得到结果rnQO8AK4ymmv.exe1234567891011121314

 

转载链接:https://blog.csdn.net/frog4/article/details/81876462

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/150544
推荐阅读
相关标签
  

闽ICP备14008679号