How can references to private class members be dangerouse

邮差的信 提交于 2019-12-10 11:19:54

问题


I am currently reading the CERT Secure Coding Standard for Java.

I am struggling with this rule. The severity of this rule is high, which means a violation of this rule can lead to a privilege escalation or execution of code.

I don't really understand how a violation of this rule can lead to such fatal things. Can somebody make an example of an attack on a code which violates this rule?


回答1:


You might have an invariant which you establish in the constructor of the class, e.g. that date contains the creation time of the instance:

class Foo {
  private final Date date;

  Foo() { this.date = new Date(); }

  Date getDate() { return date; }
}

Now, if I call getDate().setTime(0), I can make the instance look like it was created at 1970-1-1 00:00:00Z.

If you have some logic based on the creation date of a Foo, it can be manipulated to behave differently in this way.




回答2:


If you expose reference to the private mutable object (for example Date or any modifiable Collection) over the getter, you can modify the state of your object from outside.

Imagine you have List<String> getNames() method in your class:

public class MyClass {
    // fields and constructors are omitted
    List<String> getNames() {
        // return any mutable List implementation; for instance, ArrayList
    }
}

You can call myClass.getNames().add("name"), and this will modify the state of the MyClass instance. So the person who use your class can modify internal state of its instances.

See also J. Bloch's "Effective Java" 2nd edition, Item 39 "Make defensive copies when needed", p. 184, you can find very good explanation on this tiopic there.




回答3:


In Java, you are circumventing the private specifier by having a non-private function that returns a reference to the member.

That's because it's possible to modify the the object to which the member is referring through that reference.

You may as well be honest about things, and mark the private member with the same access specifier as the function.



来源:https://stackoverflow.com/questions/38375990/how-can-references-to-private-class-members-be-dangerouse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!