Malicious code vulnerability - May expose internal representation by returning reference to mutable object

匿名 (未验证) 提交于 2019-12-03 01:47:02

问题:

Hi I'm getting the violation as below:

Malicious code vulnerability - May expose internal representation by returning reference to mutable object

in my code i wrote like this

public String[] chkBox() {     return chkBox; } 

How we can solve it.

回答1:

As the error message states, you're returning internal state (chkBox is - most likely - part of the internal state of an object even though you're not showing its definition)

This can cause problems if you - for example - do

String[] box = obj.chkBox(); box[0] = null; 

Since an array object, as all Java objects, is passed by reference, this will change the original array stored inside your object as well.

What you most likely want to do to fix this is a simple

return (String[])chkBox.clone(); 

which returns a copy of the array instead of the actual array.



回答2:

Let's suppose the following:

  1. Your class does something that matters from a security or privacy perspective, and that the state of chkbox is somehow used in the classes implementation of its privacy / security mechanisms.

  2. The chkBox() method can be called by some code that is not trusted.

Now consider this code:

// ... in an untrusted method ...  Foo foo = ...  String[] mwahaha = foo.chkBox(); mwahaha[0] = "Gotcha!"; // ... this changes the effective state of `Foo` 

By returning a reference to the actual array that represents the chkbox, you are allowing code external to the Foo class to reach in and change its state.

This is bad from a design perspective (it is called a "leaky abstraction"). However, if this class is used in a context where there may also be untrusted code, this (the chkBox() method) is a potential security hole. That is what the violation message is telling you.

(Of course, the code checker has no way of knowing if this particular class is really security critical. That's for you to understand. What it is actually saying to you is "Hey! Look here! This is suspicious!")


The fix depends on whether this code (or indeed the entire library or application) is security critical ... or code be security critical in some future deployment. If this is a false alarm, you could just suppress the violation; i.e. mark it so that will be ignored by the checker. If this is a real issue (or could become a real issue), then either return a copy of the array:

    return (String[]) chkBox.clone(); 

But clearly, there is a performance cost in cloning the array each time you call chkBox. Alternatively, you could modify the chkBox method to return a selected element of the array:

    public String chkBox(int i) {        return chkBox[i];     } 

In this case, I suspect that the alternative approach will be better ... though it depends on how the method is currently used.



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