Java: Why shouldn't clone() be used for defensive copying?

前端 未结 3 523
醉梦人生
醉梦人生 2021-01-13 09:19

In Effective Java (Chapter 7), it says

Note also that we did not use Date’s clone method to make the defensive copies. Because Date is nonfinal, the c

3条回答
  •  生来不讨喜
    2021-01-13 09:51

    I haven't read the book you quoted from, but that paragraph gives a poor justification and offers no protection against any sort of attack.

    The quote mentions that an attacker with the ability to load code into your program could potentially submit a Date subclass with malicious methods, for example returning a subclass of Date from clone.

    But that's only a minor way an attacker with the ability to load code can cause harm. They could also:

    • Use reflection to get read+write access to pretty much anything marked private,
    • Mess with the class loaders to load their own versions of classes,
    • Call System.exit() to stop your program, and
    • Do anything your program could do, like spawn other programs or access files.

    If the attacker is running code in your process, the game's over and your process is compromised, and this silly little guard is not going to help.

    Maybe you think that clone is bad from a design standpoint, and that's fine, but please don't pretend that not using it will protect you from some security threat, because it won't.

提交回复
热议问题