Does the Java 'final' keyword actually improve security?

前端 未结 12 801
遥遥无期
遥遥无期 2021-01-07 19:07

While there are many reasons to use the \'final\' keyword in Java, one of the ones I keep hearing over and over again is that it makes your code more secure. While this seem

12条回答
  •  花落未央
    2021-01-07 19:15

    The "final" keyword does indeed have some security implications. Imagine you are designing a secure system which has a service that, given a string, does something if and only if the string is valid. You might write:

    public void doSomethingUseful(String argument) {
        checkValidity(argument);
        /* prepare to do something useful... preparation takes a bit of time! */
        reallyDoTheUsefulTask(argument);
    }
    

    If String were not final, some clever attacker could subclass String. Their string is not immutable like the stock String class is - and in fact, they can spawn another thread and try to do attacks on your method by changing the argument after checkValidity but before you actually use the argument. Then your "useful task" suddenly does something completely wrong, possibly compromising security. They've just bypassed your checks! Because java.lang.String is final, however, you have good guarantees that when you ask for a String parameter it is, in fact, the standard immutable String. This is a pretty big deal - there was an entire class of kernel-mode attacks based around improper parameter handling with syscalls.

    So yes, final can have some security considerations.

提交回复
热议问题