Dump memory show user and password info - android

I've been checking memory information dumping data hold in memory and I've seen a JSON structure of the request I use for login to the server.
For security reasons that information shouldn't be hold in memory so I've had to find out what is storing these data.
I tried to check OKHttp3 for avoiding caching any info but seems it could be GSON Converter.
this line https://github.com/square/retrofit/issues/2305 is from a guy complaining about Strings hold in memory.
I'd like to know if I could be right thinking about GSON as the problem and if there is any chance to let GSON know that I don't want to cache a concrete class.
Thanks

I think the problem is here :
There is two ways to add string in the string pool.
first if you declare your string literal like below, the string will add to pool.
String test = "test"
second if you call intern method in string Object. like this.
String test = new String("test");
test.intern();
so if you declare you username and password like this :
String username = new String("YOUR_PASSWORD");
it will not add to pool unless you call intern method.
so try the above way or use StringBuilder class. The garbage collection happens on your data.

Related

How to Safely Zero and release all memory pages used by an Android App?

I'm a software engineer building an Android App that will be used by a government agency.
One requirement in our contract is that the app must be FIPS 140 compliant.
https://en.wikipedia.org/wiki/FIPS_140
To be FIPS compliant our app must zeroize and clear any password objects in RAM, when the android app is closed. (By zeroing and clearing the password from RAM, we reduce the window of opportunity for attackers. i.e. this mitigates cold-boot attack risk: https://en.wikipedia.org/wiki/Cold_boot_attack)
To satisfy this requirement, we initially followed the advice in the following two SO posts to capture the user password as a CharArray instead of a string
Why is char[] preferred over String for passwords?
Getting a char array from the user without using a String
//First collect the password from Edit Text as a []char
int pl = passwordEditText.length();
char[] password = new char[pl];
passwordEditText.getText().getChars(0, pl, password, 0);
//Now set the password on viewmodel
viewModel.setPassword(password)
Once we have the password, we use it to call a 3rd party webservice library that fetches data for display on the screen.
ViewModel pseudocode:
public DataObject getData(char[] password){
return this.webService.getData(password);
}
When the user is done with our app, we call the following method to zeroize and clear the password
ViewModel pseudocode:
public zeroPassword(){
Arrays.fill(this.password, 0);
this.password = null;
}
This is all fine and dandy because char arrays in java are passed by reference (unlike Strings that are immutable), and we effectively zeroize any trace of the password character array from memory in the zeroPassword method.
HOWEVER...
We dug into the 3rd party WebService code (this.webService.getData(password))
and it turns out that under the covers, the webservice converts the char array password into a string, and then passes it around before making a network call.
Basically - Even though we zeroize the char array reference in our Android ViewModel code, because the char array is taken by a 3rd party lib and used to create a string, the Password will still exist in memory :(
OPTIONS
At this point we're considering two options:
Option 1 is to get a copy of the third party library and modify it so that it doesn't work with password strings. This way we can change any password string usage to use char arrays, buffers etc - all objects that we can zeroize at some point)
Option 2 - We investigate some way to zeroize and clear all memory pages used by our android app (i.e. shut down the whole app and clear RAM), when the user closes the app.
As a team we prefer option 2 because it would cover all of our bases. Option 1 will be challenging, invasive, time consuming, and messy.
UPDATE - Based on the answer here, it seems like Option 1 wont even actually work How can I ensure the destruction of a String object in Java?
Java uses generational garbage collection, and copies objects all over the place, even char arrays, so zeroing char arrays isn't guaranteed to remove the password from RAM.
Is there a way to accomplish what we've been asked to do? i.e. fully wipe any trace of the password from memory?
Can android security experts please opine?
Thanks
According to ViewModel Docs:
When the owner activity is finished, the framework calls the ViewModel
objects's onCleared() method so that it can clean up resources.
You don't need to manually create/call destructor to clean up ViewModel resources, because this lifecycle component already has a mechanism to clean-up its own resources.
To make it easier to understand, ViewModel has the following behavior:
When Activity is re-created on configuration changes: we still have the same ViewModel instance.
When Activity is finished: ViewModel will automatically call onCleared() to cleanup resources for us, so we don’t even have to do manual unbind/clean-up.
The reason why some ViewModel object still exist in the memory is because the Activity (which has the ViewModel) is still active, OR there might be another class which holds reference to this Activity.
Using V8 to run a service worker at app shutoff, for example something like:
addEventListener("fetch", event => {
event.respondWith(fetchAndReplace(event.request));
});
async function fetchAndReplace(request) {
const response = await fetch(request);
let type = response.headers.get("Content-Type") || "";
if (!type.startsWith("application/")) {
return response;
}
let newHeaders = new Headers(response.headers);
newHeaders.set('Clear-Site-Data', '"cache", "cookies", "storage",
"executionContexts"');
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders
});
}
See Clear-Site-Data on MDN. "Site" is misleading as "site" ~= only websites.

Which is better: using a map inside array list or a pojo class to interact with json response

I'm a bit confused, as from a long time i am saving the json response directly to an ArrayList> and displaying to my listView, but now, looking on other people code i noticed that they are using POJO class to interact with JSON, Is it is better way? if it is please explain why? cause using POJO means I have to write extra code, But if saving the response directly to the arraylist make my work done, then why should i use a POJO class?
So, Pojo usage better due to OOP pattern, because you work at runtime with your Java object without intermediate Json parse. Manual json parsing too ugly due to code style(its my opinion).
But if saving the response directly to the arraylist make my work done
If, you collect your object in Maps, you can apply different features out of the box(sort, compare etc) to your map, but in case when your map contains POJO instead of JSONS.
Encapsulation. When you work with dates for examples or with type, its pretty good to use getters/setters for data mapping instead of manual parsing again and again.
4.Object scaling and mapping:
Lets image that we have some object user:
public class User{
int id;
#SerializedName("specific_id_for_blah_blah")
private int mSpecId
#SerializedName("date_of_birthaday")
private String mBDay;
public Date getBirthday() {
return new Date(mBDay);
}
}
What I want to say by this example.
You can map your json to POJO with one line of code only
User user = new Gson.fromJson(response, User.class);
Pretty simple isn't?.
Name serialization. When your response contain key name which looks to long or weird, you can use your own style naming with easy changes, just with small annotation. mSpecId returns value of "specific_id_for_blah_blah"
Platform specific encapsulation. You can use only platform specific object at your runtime, instead parsing operations in your business logic. String with data -> Date or Calendar
Also you can override Object methods in your POJO (equals, hashcode, toString) for your logic spec. operations.
If your serverside change some key you can change name of key in POJO instead looking through where you parse it before. IN same case you can add new field and setter/getter, if some of parameter will be added to your response
There is no right and wrong answer here. It all depends on your use case. If your solution works, and you are happy with it, I don't see why do you need to change it.
If I had to choose, I would go with a POJO class to represent the response, but this is a subjective opinion. I think that you have the following benefits:
It's cleaner - having a separate, dedicated class to represent your payload gives you the ability to be more specific in your code. You are no longer manipulating Maps of key - value pairs, but instances of a specific class, that can have a more specific behaviour. You can specify natural ordering, criteria for equality, etc - things that may be useful for your program's logic
It's simpler - I would prefer calling a getter every time then accessing a map by a property name and getting an Object back. The logic of the program will be much simpler and safer.
It's better in terms of OOP best practices - the whole point behind OOP is to have objects, that define properties and behaviours. IMHO, using POJOs to represent responses forces you to adhere more closely to best practices.
There are also some cases that will fit the no - POJO approach better - for example, if you only display your data, not manipulating it in any way inside the app. Or if you want to shave off some time for the complex parsing that may be needed if you are trying to inflate object hierarchies.
My best suggestion is - profile your app, check your use cases and make an educated decision which approach is better.

What is the best way to parse JsonObject containing just one enormous JsonObject (Gson)

I have a Json of this type :
{
"4f958ef28ecd651095af6ab6": {
enormous JsonObject
}
}
the "4f958ef28ecd651095af6ab6" is different each time (but I know what it will be as it is a parameter of my api call), it corresponds to the id of the following object. I have a Gson-configured model to parse the enormous JsonObject.
My question is : is it performant to use simply
new JSONObject(jsonresponse).getJSONObject("4f958ef28ecd651095af6ab6")
and parse with Gson from there ?
Is there a better way to do so ?
I guess the real question would be, what does "new JSONObject(String)" realy do ?
Thanks
What you are doing is:
You load all the Json string into the phone memory (memory issue + long time to load entirely)
You create a big JSONObject (same issues) in order to have access to each key.
You write few code but this is not the most performant solution.
To minimized the memory impact and accelerate the operation of objects' creation, you can use Gson in stream mode.
By directly read the input stream, you avoid to load too much data and you can directly start to populate your object piece by piece.
And about the JSONObject, it will mostly check if your json string is correct (or it will throw a JsonException) and it will let you look into the object when you search for a key and its value.
I would recommend use hybrid (native and gson) since i am not sure how to get unknown jsonobject with GSON.
You need to get your response as a JSONArray, then itarete for each JSONObject. You can experiment parsing code as trying. Please check JSONArray.getJSONObject(int index) method. Then we can use GSON to get our data model to get known attributes.
If you can post complete json data, we can give it chance to parse together.

Reading from SharedPreferences vs. keeping an instance of the object

THE SCENARIO
I have a class that makes use of a request list set by the user. The request list is stored in SharedPreferences. The dilemma I'm facing is to whether to keep an instance of the request list or to read from SharedPreferences every time the request list is needed (which is very frequent).
Also not that Gson is used to deserialize the object.
The code goes like this:
public List<PrayerTimesCalculator.Time> getDefaultRequestList() {
if (mRequestList != null) return mRequestList;
// Try getting request list from preferences;
Gson gson = new Gson();
String json = mSharedPref.getString(KEY_PREF_REQUEST_LIST, null);
Type listType = new TypeToken<List<Time>>() {
}.getType();
mRequestList = gson.fromJson(json, listType);
if (mRequestList != null) return mRequestList;
// Create default list;
mRequestList = Arrays.asList(
Time.DAWN,
Time.MORNING,
Time.AFTERNOON,
Time.EVENING,
Time.MID_NIGHT);
return mRequestList;
}
THE GOAL
My concern is that if I keep around an instance of the request list, and there are multiple instances of this class, an update to the request list in one instance of the class would not be reflected in the rest of the instances until they are recreated.
Thus, I'm leaning towards reading from SharedPreferences unless there is a better way to keep the request list objected updated in all instances.
THE QUESTION
(1) So, how efficient is it to read the same key from SharedPreferences quite frequently by multiple instances of the object? and (2) Is there a better way to keep the request list objected updated in all instances?
So there are a couple of approaches you can take to this.
First, your object is small - re-reading SharedPreferences thousands of times would hardly be noticeable. It's not like SharedPreferences is on a remote drive or has a "bad connection."
Second, if you don't like that answer, then you need a DAO (Data Access Object). SharedPreferences is a form of this already. It provides a means to store and retrieve data with confidence that you have the most recent data available. But, if you feel like you can improve on it's optimization (because it's generic, and this is your app), then you can provide access to you data through a static object that performs both "read" and "write" operations. This will guarantee that access to the object is done with the most recent data. Of course, you will need to be thread aware, etc. (something that is not always guaranteed by SharedPreferences).
Next, you could persist your data in a database and use Cursors or other built-in or custom DAOs. This requires another level of complexity and a lot of overhead, but is useful when several components of your app might need access to the data, provide updates or needs real-time monitoring of changes because background threads or other objects may make modifications that will change your app behavior or result in UI updates.
Last, you could use more complex data stores like a Content Provider. This is really required for cases where you want/need other apps to access data provided by your app (and your app may also consume the data). That's a complex solution and implementation is well outside the scope of this question.
But I mention it because you seem interested in being certain that frequent reads of SharedPreferences is acceptable. It definitely is acceptable - otherwise there would be something else besides it, databases and Content Providers.

android: send & get String besides by using extra() method

I just wonder what method can be use to send String from one to another activity besides by using intent.putExtra(), and getIntent.getExtra().
Cause my project getting unexpected result when using putExtra(), just want to another for send String.
Any suggestion and examples? Thanks.
you can also send by following ways
How do I pass data between Activities/Services within a single application?
Non-Persistent Objects
For sharing complex non-persistent user-defined objects for short duration, the following approaches are recommended:
Singleton class - Ref Here:
A public static field/method
A HashMap of WeakReferences to Objects

Categories

Resources