Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malicious code vulnerability - Field should be package protected

Tags:

java

sonarqube

Sonar is giving me the message:

Malicious code vulnerability - Field should be package protected for static array FORMATS.

Why is this code considered malicious? I have a public class to store all the constants.

public class Constants
{
    /*
    all the public static final constants of primitive datatypes for which 
    there is no sonar warning.
    */
    public static final String[] FORMATS = new String[] {
        "yyyy-MM-dd HH:mm:ss.S z", 
        "yyyy-MM-dd HH:mm:ss.S"
}
like image 453
dumper Avatar asked May 20 '13 09:05

dumper


1 Answers

Probably because another piece of code could execute:

Constants.FORMATS[0] = "SOME GARBAGE";

And break the rest of your code.

In other words your array is constant but not its content.

Examples of alternatives:

  • you can store each format as a separate String constant
  • you can use an immutable list instead: public static final List<String> FORMATS = Collections.unmodifiableList(Arrays.asList("yyyy-MM-dd HH:mm:ss.S z", "yyyy-MM-dd HH:mm:ss.S"));
  • make it a method:

    public static String[] formats() {
      return new String[] { "yyyy-MM-dd HH:mm:ss.S z", "yyyy-MM-dd HH:mm:ss.S" };
    }
    
  • ignore the warning if you are confident that (i) only your own code will access that class and (ii) there is no way you/your colleagues would even think of reassigning one of the values.
like image 174
assylias Avatar answered Oct 12 '22 23:10

assylias