Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between non- final public static and non- final public instance fields in terms of security?

I am going through this link , OBJ10-J. Do not use public static nonfinal fields and it says that ,

Client code can trivially access public static fields because access to such fields are not checked by a security manager.

what do they actually mean by that? i.e what do they mean by escaping from security manager?

If they simply meant it because field being non-final and public , then how come non-final , public instance fields different than their static counterparts? ( as far as code security is concerned )

I have been through this question and have not seen any mention in terms of security , Why are static variables considered evil

public class's public static fields would be accessible from anywhere and so public instance fields too, so where is the difference? Why non-final public instance fields not a security issue but being static is?

like image 295
Sabir Khan Avatar asked Jan 11 '16 09:01

Sabir Khan


2 Answers

Why non-final public instance fields not a security issue but being static is?

If you want to access an instance field you need the reference to that object instance. If you don't have a reference you can't access it.

So your code can control to which objects a refernce is passed. If malicious code tries to hijack one of your objects using reflection to get a reference you can install a security manager to prevent this.

On the other side a public static field can be accessed from everybody that has access to the class, because the Class object is accessible. So malicious code might only use

YourClass.PUBLIC_INSTANCE_FIELD = someValue;

or the reflection way

Class clazz = Class.forName("YourClass");
Field publicStaticField = clazz.getDeclaredField("PUBLIC_INSTANCE_FIELD");
publicStaticField.set(null, someValue);
like image 166
René Link Avatar answered Nov 17 '22 13:11

René Link


That's because the case of non-static fields is already covered by OBJ01-J. Limit accessibility of fields

public instance field are covered by OBJ01-J for slightly different reasons. For one, you need to have a reference to an instance before you can change public instance fields, while public static fields can be accessed directly at class level. But both are against the CERT rules.

like image 28
Erwin Bolwidt Avatar answered Nov 17 '22 15:11

Erwin Bolwidt