假设你已经有了sonarqube-java源码,并且已经把sonarqube部署到电脑上
1、在check 里面创建文件 MyTxtBlockCheck.java
package org.sonar.samples.java.checks; import org.sonar.check.Rule; import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; import org.sonar.plugins.java.api.tree.LiteralTree; import org.sonar.plugins.java.api.tree.Tree; import org.sonar.plugins.java.api.tree.Tree.Kind; import java.util.Collections; import java.util.List; @Rule(key = "MyTxtBlockCheck") public class MyTxtBlockCheck extends IssuableSubscriptionVisitor { @Override public List<Kind> nodesToVisit() { return Collections.singletonList(Kind.TEXT_BLOCK); } @Override public void visitNode(Tree tree) { if (tree.is(Kind.TEXT_BLOCK)) { LiteralTree textBlock = (LiteralTree) tree; String value = textBlock.value().toLowerCase(); if (value.contains("username") || value.contains("password")) { reportIssue(tree, "Sensitive information detected: 'username' or 'password'."); } } } }
2、在resouces/org.sonar.I10n.rules.java创建 MyTxtBlockCheck.json 和MyTxtBlockCheck.html
MyTxtBlockCheck.html如下
<!DOCTYPE html> <html> <head> <title>Sensitive Information Rule TXT TXT</title> </head> <body> <h1>Sensitive Information Rule TXT TXT</h1> <p>This rule detects hardcoded sensitive information such as 'username' or 'password' in the code.</p> <h2>Rule Description</h2> <p>Hardcoding sensitive information can lead to security vulnerabilities and is considered a bad practice. This rule helps identify such cases in your codebase.</p> <h2>Examples</h2> <h3>Non-compliant Code</h3> <pre> private static final String username = "myUsername"; private static final String password = "myPassword"; </pre> <h3>Compliant Code</h3> <pre> private static final String someValue = "value"; // Use configuration files or environment variables </pre> <h2>Best Practices</h2> <ul> <li>Do not hardcode sensitive information in your codebase.</li> <li>Use configuration files or environment variables to manage sensitive data securely.</li> </ul> </body> </html>
MyTxtBlockCheck.json 如下
{ "title": "Sensitive Information Rule txt txt", "type": "Bug", "status": "ready", "tags": [ "bugs", "gandalf", "magic" ], "defaultSeverity": "Critical" }
3、将MyTxtBlockCheck添加到RulesList.java
4、在测试文件中加入新规则MyTxtBlockCheck,测试文件:MyJavaFileCheckRegistrarTest.java
目录
5、代码到此写好;开始构建
进入pom文件所在文件夹
使用命令:
mvn clean install -f .\pom_SQ_9_9_LTS.xml
构建成功
6、拿到构建好的jar
7、将jar放到 sonarqube-安装目录\extensions\plugins中
8、重启项目
9、进入http://localhost:9000/
添加新加的规则进行扫描
使用默认规则文件,激活新规则
加入新规则
使用新规则进行扫描请参考:
sonarqube如何创建maven项目进行扫描 - yxchun - 博客园 (cnblogs.com)
标签:username,java,自定义,sonarqube,tree,MyTxtBlockCheck,org,sonar,import From: https://www.cnblogs.com/ychun/p/18366920