优化Java被测件

wuhaoyang
wuhaoyang 10 months ago
parent 07c325f619
commit 292ff060d6
  1. 7
      sonar-keyware-plugins-java/src/test/files/ABCVarNameRule.java
  2. 2
      sonar-keyware-plugins-java/src/test/files/AbsolutePathDetectorRule.java
  3. 6
      sonar-keyware-plugins-java/src/test/files/AuthenticationChecker.java
  4. 7
      sonar-keyware-plugins-java/src/test/files/AvoidSensitiveInfoInLogsCheck.java
  5. 7
      sonar-keyware-plugins-java/src/test/files/CookieSensitiveParameterCheck.java
  6. 17
      sonar-keyware-plugins-java/src/test/files/DynamicCodeCheckerRule.java
  7. 2
      sonar-keyware-plugins-java/src/test/files/DynamicLibraryLoadChecker.java
  8. 7
      sonar-keyware-plugins-java/src/test/files/ErrorMessageRule.java
  9. 2
      sonar-keyware-plugins-java/src/test/files/FileCheck.java
  10. 29
      sonar-keyware-plugins-java/src/test/files/HashSaltPassWordRule.java
  11. 9
      sonar-keyware-plugins-java/src/test/files/HttpInputDataRule.java
  12. 3
      sonar-keyware-plugins-java/src/test/files/InputSQLVerifyRule.java
  13. 25
      sonar-keyware-plugins-java/src/test/files/Md5PassWordVerifyRule.java
  14. 12
      sonar-keyware-plugins-java/src/test/files/OptionsVerifyRule.java
  15. 5
      sonar-keyware-plugins-java/src/test/files/PasswordRegexCheck.java
  16. 16
      sonar-keyware-plugins-java/src/test/files/PathAndKeywordCheck.java
  17. 6
      sonar-keyware-plugins-java/src/test/files/RSAEncryptionRule.java
  18. 9
      sonar-keyware-plugins-java/src/test/files/RedirectUrlChecker.java
  19. 6
      sonar-keyware-plugins-java/src/test/files/SecurityCookieRule.java
  20. 10
      sonar-keyware-plugins-java/src/test/files/SendMessageVerifyRule.java
  21. 8
      sonar-keyware-plugins-java/src/test/files/SessionCacheParamsChecker.java
  22. 7
      sonar-keyware-plugins-java/src/test/files/SystemFunctionChecker.java
  23. 38
      sonar-keyware-plugins-java/src/test/files/UploadFileVerifyRule.java
  24. 4
      sonar-keyware-plugins-java/src/test/files/UpperCycleLimitRule.java
  25. 18
      sonar-keyware-plugins-java/src/test/files/options/OptionsVerifyOneRule.java
  26. 8
      sonar-keyware-plugins-java/src/test/files/options/OptionsVerifyTwoRule.java

@ -1,4 +1,5 @@
class VarNameRule{ public class ABCVarNameRule {
private static String ABC = "abc"; // Noncompliant {{不能使用ABC作为变量名}} private static String ABC = "abc"; // Noncompliant {{不能使用ABC作为变量名}}
private static String edf = "edf"; private static String edf = "edf";
@ -8,4 +9,6 @@ class VarNameRule{
public void test(){ public void test(){
System.out.println(ABC); System.out.println(ABC);
} }
}
}

@ -1,5 +1,5 @@
class PathDetectorRule{ public class AbsolutePathDetectorRule{
// 使用绝对路径读取配置文件,触发规则 // 使用绝对路径读取配置文件,触发规则
String configFilePath = "/path/to/config.properties"; // Noncompliant {{读取配置文件或者服务器中文件时不可使用绝对路径}} String configFilePath = "/path/to/config.properties"; // Noncompliant {{读取配置文件或者服务器中文件时不可使用绝对路径}}

@ -1,7 +1,9 @@
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller @Controller
public class AuthController { public class AuthenticationChecker {
@PostMapping("/account/aa") @PostMapping("/account/aa")
public String login() { public String login() {

@ -1,8 +1,7 @@
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
public class AvoidSensitiveInfoInLogsCheck {
public class ExampleClass { private static final Logger logger = LoggerFactory.getLogger(AvoidSensitiveInfoInLogsCheck.class);
private static final Logger logger = LoggerFactory.getLogger(ExampleClass.class);
public void sensitiveOperation() { public void sensitiveOperation() {
String password = "password"; String password = "password";
@ -17,4 +16,4 @@ public class ExampleClass {
logger.trace(password); // Noncompliant {{日志中包含敏感信息}} logger.trace(password); // Noncompliant {{日志中包含敏感信息}}
} }
} }

@ -1,16 +1,15 @@
import javax.servlet.http.Cookie; import javax.servlet.http.Cookie;
class CookieSensitiveParameterCheck{ public class CookieSensitiveParameterCheck {
public void func1(){ public void func1(){
String password = ""; String password = "";
Cookie invalidCookie1 = new Cookie("password", "1321"); // Noncompliant {{Cookie参数设置中包含敏感字段}} Cookie invalidCookie1 = new Cookie("password", "1321"); // Noncompliant {{Cookie参数设置中包含敏感字段}}
Cookie invalidCookie2 = new Cookie(password, 1); // Noncompliant {{Cookie参数设置中包含敏感字段}} Cookie invalidCookie2 = new Cookie(password, "1"); // Noncompliant {{Cookie参数设置中包含敏感字段}}
Cookie invalidCookie3 = new Cookie("213", password); // Noncompliant {{Cookie参数设置中包含敏感字段}} Cookie invalidCookie3 = new Cookie("213", password); // Noncompliant {{Cookie参数设置中包含敏感字段}}
}
}
} }

@ -1,5 +1,16 @@
class DynamicCode { import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class DynamicCodeCheckerRule {
public void dyan() { public void dyan() {
String args1 = "args1";
String args2 = "args2";
String args3 = "args3";
String regular = "function regular(args1,args2,args3){................}"; String regular = "function regular(args1,args2,args3){................}";
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript"); ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
try { try {
@ -15,8 +26,10 @@ class DynamicCode {
} else { } else {
System.out.println("error"); System.out.println("error");
} }
} catch (ScriptException e) { } catch (ScriptException | NoSuchMethodException e) {
System.out.println("表达式runtime错误:" + e.getMessage()); System.out.println("表达式runtime错误:" + e.getMessage());
} }
} }
} }

@ -1,5 +1,5 @@
// 在动态加载库前对输入数据进行验证,确保输入数据仅能用于加载允许加载的代码库 // 在动态加载库前对输入数据进行验证,确保输入数据仅能用于加载允许加载的代码库
class DynamicLibraryLoadCheckerExample { public class DynamicLibraryLoadChecker {
public void loadLibrary(String libraryName, int number) { public void loadLibrary(String libraryName, int number) {
String abc = "bac"; String abc = "bac";

@ -1,10 +1,3 @@
/*
* Copyright (c) 2023 - 2024. KeyWare.Co.Ltd All rights reserved.
* 项目名称信息安全性设计准则检查插件
* 项目描述用于检查源代码的安全性设计准则的Sonarqube插件
* 版权说明本软件属北京关键科技股份有限公司所有在未获得北京关键科技股份有限公司正式授权情况下任何企业和个人不能获取阅读安装传播本软件涉及的任何受知识产权保护的内容
*/
public class ErrorMessageRule { public class ErrorMessageRule {
public static void main(String[] args) { public static void main(String[] args) {
try { try {

@ -1,4 +1,4 @@
class FileCheck{ public class FileCheck{
public String FileName(){ public String FileName(){
String fileName = ""; String fileName = "";

@ -1,11 +1,32 @@
class HashSaltPassWordRule{
public static void cs(Student studnet){ public class HashSaltPassWordRule {
public static void cs(Student student){
// 结合盐值和口令进行散列计算 // 结合盐值和口令进行散列计算
// String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt()); // String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
studnet.setPassWord(hashedPassword);// Noncompliant {{应使用盐值计算口令}} student.setPassWord("password");// Noncompliant {{应使用盐值计算口令}}
} }
static class Student {
private String name;
private String password;
public Student(String name, String password) {
this.name = name;
this.password = password;
}
public void setPassWord(String password) {
this.password = password;
}
@Override
public String toString() {
return "Student{" + "name='" + name + '\'' + ", password='" + password + '\'' + '}';
}
}
} }

@ -1,3 +1,12 @@
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Locale;
public class HttpInputDataRule { public class HttpInputDataRule {
public static void main(String[] args) { public static void main(String[] args) {

@ -1,3 +1,6 @@
import java.sql.*;
public class InputSQLVerifyRile { public class InputSQLVerifyRile {
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase"; private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "username"; private static final String USER = "username";

@ -1,10 +1,29 @@
class Md5PassWordVerifyRule{ public class Md5PassWordVerifyRule{
public static void cs(Student studnet){ public static void cs(Student student){
// 结合盐值和口令进行散列计算 // 结合盐值和口令进行散列计算
// String password = DigestUtils.md5Hex(str); // String password = DigestUtils.md5Hex(str);
studnet.setPassWord(password);// Noncompliant {{应使用单向不可逆的加密算法}} student.setPassWord("password");// Noncompliant {{应使用单向不可逆的加密算法}}
} }
static class Student {
private String name;
private String password;
public Student(String name, String password) {
this.name = name;
this.password = password;
}
public void setPassWord(String password) {
this.password = password;
}
@Override
public String toString() {
return "Student{" + "name='" + name + '\'' + ", password='" + password + '\'' + '}';
}
}
} }

@ -1,15 +1,10 @@
/*
* Copyright (c) 2023 - 2024. KeyWare.Co.Ltd All rights reserved.
* 项目名称信息安全性设计准则检查插件
* 项目描述用于检查源代码的安全性设计准则的Sonarqube插件
* 版权说明本软件属北京关键科技股份有限公司所有在未获得北京关键科技股份有限公司正式授权情况下任何企业和个人不能获取阅读安装传播本软件涉及的任何受知识产权保护的内容
*/
import javax.servlet.*; import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
public class OptionsVerifyChecker implements Filter { public class OptionsVerifyRule implements Filter {
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException {} public void init(FilterConfig filterConfig) throws ServletException {}
@ -25,9 +20,8 @@ public class OptionsVerifyChecker implements Filter {
@Override @Override
public void destroy() {} public void destroy() {}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.setHeader("X-Frame-Options", "DENY"); // 或者使用SAMEORIGIN,ALLOW-FROM等其他策略 response.setHeader("X-Frame-Options", "DENY"); // 或者使用SAMEORIGIN,ALLOW-FROM等其他策略
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
} }
} }

@ -1,7 +1,8 @@
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class PasswordStrengthValidator { public class PasswordRegexCheck {
@ -9,7 +10,7 @@ public class PasswordStrengthValidator {
String asdasd = "asdfsdfsdf"; String asdasd = "asdfsdfsdf";
Pattern pattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*#?&])[A-Za-z\\d@$!%*#?&]{8,}$"); Pattern pattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*#?&])[A-Za-z\\d@$!%*#?&]{8,}$");
Matcher matcher1 = pattern.matcher(asdasd); Matcher matcher1 = pattern.matcher(asdasd);
Matcher matcher3 = pattern.matcher(); Matcher matcher3 = pattern.matcher("");
return password; return password;
} }

@ -1,10 +1,14 @@
class PathAndKeywordCheckRule { import java.io.File;
import java.net.URI;
import java.net.URL;
public class PathAndKeywordCheck {
public void getParameter(String arg,String brg,String crg) throws Exception {
URL url1 = new URL(arg);// Noncompliant {{避免在参数中使用禁止的关键字}}
URI url2 = new URI(brg);// Noncompliant {{避免在参数中使用禁止的关键字}}
File url3 = new File(crg);// Noncompliant {{避免在参数中使用禁止的关键字}}
public void getParameter(int arg,String brg,float crg) {
URL url = new URL(arg);// Noncompliant {{避免在参数中使用禁止的关键字}}
URI url = new URI(brg);// Noncompliant {{避免在参数中使用禁止的关键字}}
File url = new File(crg);// Noncompliant {{避免在参数中使用禁止的关键字}}
} }
} }

@ -1,6 +1,10 @@
import javax.crypto.Cipher;
import java.security.*;
public class RSAEncryptionRule { public class RSAEncryptionRule {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
// 生成RSA密钥对 // 生成RSA密钥对
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
@ -27,4 +31,4 @@ public class RSAEncryptionRule {
System.out.println("加密后的数据:" + new String(encryptedBytes)); System.out.println("加密后的数据:" + new String(encryptedBytes));
System.out.println("解密后的数据:" + new String(decryptedBytes)); System.out.println("解密后的数据:" + new String(decryptedBytes));
} }
} }

@ -1,6 +1,10 @@
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.view.RedirectView;
@Controller @Controller
public class MyController { public class RedirectUrlChecker {
@GetMapping("/old-url") @GetMapping("/old-url")
public RedirectView redirectOldUrl(String url) { // Compliant,因为重定向的路径不是由方法传递进来的 public RedirectView redirectOldUrl(String url) { // Compliant,因为重定向的路径不是由方法传递进来的
@ -29,8 +33,9 @@ public class MyController {
} }
@GetMapping("/old-url5") @GetMapping("/old-url5")
public String redirectOldUrl4(String url) { public String redirectOldUrl5(String url) {
// 302临时重定向到新的URL // 302临时重定向到新的URL
return url; // Noncompliant {{在重定向前对输入数据进行验证}} return url; // Noncompliant {{在重定向前对输入数据进行验证}}
} }
} }

@ -1,6 +1,10 @@
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
public class SecurityCookieRule { public class SecurityCookieRule {
public void setCookie(HttpServletResponse response) { // Noncompliant {{设置HTTPS会话中cookie的安全属性}} public void setCookie(HttpServletResponse response) { // Noncompliant {{设置HTTPS会话中cookie的安全属性}}
// 创建一个新的Cookie // 创建一个新的Cookie
Cookie cookie = new Cookie("cookieName", "cookieValue"); Cookie cookie = new Cookie("cookieName", "cookieValue");
@ -17,4 +21,4 @@ public class SecurityCookieRule {
// 将Cookie添加到HTTP响应头中 // 将Cookie添加到HTTP响应头中
response.addCookie(cookie); response.addCookie(cookie);
} }
} }

@ -1,11 +1,9 @@
/* import java.io.DataOutputStream;
* Copyright (c) 2023 - 2024. KeyWare.Co.Ltd All rights reserved. import java.net.ServerSocket;
* 项目名称信息安全性设计准则检查插件 import java.net.Socket;
* 项目描述用于检查源代码的安全性设计准则的Sonarqube插件
* 版权说明本软件属北京关键科技股份有限公司所有在未获得北京关键科技股份有限公司正式授权情况下任何企业和个人不能获取阅读安装传播本软件涉及的任何受知识产权保护的内容
*/
public class SendMessageVerifyRule { public class SendMessageVerifyRule {
public static void sendName(String name) { public static void sendName(String name) {
try { try {
ServerSocket ss = new ServerSocket(6666); //建立服务器Socket并绑定端口 ServerSocket ss = new ServerSocket(6666); //建立服务器Socket并绑定端口

@ -1,9 +1,13 @@
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.*; import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionCacheParamsChecker {
public class ExampleServlet extends HttpServlet {
private static final long serialVersionUID = 1391640560504378168L; private static final long serialVersionUID = 1391640560504378168L;
public void doGet(HttpServletRequest request, HttpServletResponse response) { public void doGet(HttpServletRequest request, HttpServletResponse response) {

@ -1,7 +1,10 @@
class SystemFunctionChecker{ import java.io.IOException;
public void add(String command){
public class SystemFunctionChecker {
public void add(String command) throws IOException {
Process process = Runtime.getRuntime().exec(command); // Noncompliant {{在构建命令前对输入数据进行验证}} Process process = Runtime.getRuntime().exec(command); // Noncompliant {{在构建命令前对输入数据进行验证}}
} }

@ -1,20 +1,26 @@
/** import lombok.extern.slf4j.Slf4j;
* @author hj import org.springframework.beans.factory.annotation.Value;
*/ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Slf4j @Slf4j
@RestController @RestController
@RequestMapping("/file") @RequestMapping("/file")
public class UploadFileVerifyRule { public class UploadFileVerifyRule {
//文件磁盘路径 //文件磁盘路径
@Value("${files.upload.path}") @Value("${files.upload.path}")
private String fileUploadPath; private String fileUploadPath;
@PostMapping("/upload") @PostMapping("/upload")
public Result upload(@RequestParam MultipartFile file) throws IOException { // Noncompliant {{程序设计时,应以“白名单”方式限制允许用户上传的文件的类型}} public String upload(@RequestParam MultipartFile file) throws IOException { // Noncompliant {{程序设计时,应以“白名单”方式限制允许用户上传的文件的类型}}
file.setExecutable(true);
file.setReadable(true);
file.setWritable(true);
long size = file.getSize(); long size = file.getSize();
@ -27,7 +33,21 @@ public class UploadFileVerifyRule {
// if(type == ""){ // if(type == ""){
// //
// } // }
return Result.success("");
File localFile = new File(fileUploadPath + File.separator + originalFilename);
localFile.setExecutable(true);
localFile.setReadable(true);
localFile.setWritable(true);
file.transferTo(localFile);
return "上传成功";
} }
}
class FileUtil{
public static String extName(String filename){
// 根据文件名获取文件后缀
return filename.substring(filename.lastIndexOf(".") + 1);
}
}
}

@ -1,4 +1,5 @@
class UpperCycleLimitRule{ public class UpperCycleLimitRule {
public static void Upper(int number){ public static void Upper(int number){
for(int i = 0; i < number; i++){ // Noncompliant {{规定循环次数的上限,在将用户输入的数据用于循环条件前进行验证用户输入的数据是否超过上限}} for(int i = 0; i < number; i++){ // Noncompliant {{规定循环次数的上限,在将用户输入的数据用于循环条件前进行验证用户输入的数据是否超过上限}}
@ -13,5 +14,4 @@ class UpperCycleLimitRule{
}while (number > 0); // Noncompliant {{规定循环次数的上限,在将用户输入的数据用于循环条件前进行验证用户输入的数据是否超过上限}} }while (number > 0); // Noncompliant {{规定循环次数的上限,在将用户输入的数据用于循环条件前进行验证用户输入的数据是否超过上限}}
}; };
} }

@ -1,18 +1,13 @@
/*
* Copyright (c) 2023 - 2024. KeyWare.Co.Ltd All rights reserved.
* 项目名称信息安全性设计准则检查插件
* 项目描述用于检查源代码的安全性设计准则的Sonarqube插件
* 版权说明本软件属北京关键科技股份有限公司所有在未获得北京关键科技股份有限公司正式授权情况下任何企业和个人不能获取阅读安装传播本软件涉及的任何受知识产权保护的内容
*/
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException; import javax.servlet.*;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
public class XFrameOptionsFilter extends OncePerRequestFilter { public class OptionsVerifyOneRule extends OncePerRequestFilter {
@Override @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
@ -22,12 +17,11 @@ public class XFrameOptionsFilter extends OncePerRequestFilter {
} }
// 注册过滤器 // 注册过滤器
public class WebConfig implements WebApplicationInitializer { class WebConfig implements WebApplicationInitializer {
@Override @Override
public void onStartup(ServletContext servletContext) throws ServletException { public void onStartup(ServletContext servletContext) throws ServletException {
// ...其他配置... // ...其他配置...
Dynamic registration = servletContext.addFilter("xFrameOptionsFilter", new XFrameOptionsFilter()); FilterRegistration.Dynamic registration = servletContext.addFilter("xFrameOptionsFilter", new OptionsVerifyOneRule());
registration.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
} }
} }

@ -1,15 +1,9 @@
/*
* Copyright (c) 2023 - 2024. KeyWare.Co.Ltd All rights reserved.
* 项目名称信息安全性设计准则检查插件
* 项目描述用于检查源代码的安全性设计准则的Sonarqube插件
* 版权说明本软件属北京关键科技股份有限公司所有在未获得北京关键科技股份有限公司正式授权情况下任何企业和个人不能获取阅读安装传播本软件涉及的任何受知识产权保护的内容
*/
import javax.servlet.*; import javax.servlet.*;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
public class XFrameOptionsFilter implements Filter { public class OptionsVerifyTwoRule implements Filter {
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException {} public void init(FilterConfig filterConfig) throws ServletException {}

Loading…
Cancel
Save