Constructing a string array with Frida - javascript

I'm trying to call a function with Frida that takes a string array as one of its arguments.
public void coolFunction(long value, String[] strArr);
Within Java it gets called like this:
long importantValue = 4L;
String[] importantArr = new String[]{"TEST"};
coolFunction(importantValue, importantArr);
The overload looks like this: .overload('long', '[Ljava.lang.String;')
I could probably create a string array from scratch, but I don't know how to express it in Javascript. What's the Frida equivalent of new String[]{"TEST"}?
Because of that I tried to turn an ArrayList<String> into a String[], which also wasn't successful.
As far as I can tell there are two simple ways to turn ArrayList<String> into String[]:
Attempt #1:
List<String> list = new ArrayList<String>();
list.add("TEST");
String[] stringArray = list.toArray(new String[0]);
If I try to express it with Javascript it looks like this:
var AL_class = Java.use("java.util.ArrayList");
var arrList = AL_class.$new();
arrList.add("TEST");
var stringArray = arrList.toArray(Java.use("[Ljava.lang.String;").$new(0));
This fails with the following error message:
Error: no supported overloads
Attempt #2:
List<String> list = new ArrayList<String>();
list.add("TEST");
Object[] objectArray = list.toArray();
String[] stringArray = (String[]) objectArray;
Javascript:
var AL_class = Java.use("java.util.ArrayList");
var arrList = AL_class.$new();
arrList.add("TEST");
var arrayButAsObject = arrList.toArray();
var stringArray = Java.cast(arrayButAsObject, "[Ljava.lang.String;");
This fails because it assumes that I want to use Javascript's toArray() function.
The solution to this problem is probably very simple but I've been stuck here for quite a while now and can't seem to figure it out. Any help would be appreciated.

Instead of trying to construct a java.util.List and then convert it to an array I would use the Frida function Java.array and directly construct a Java String array:
var javaStringArray = Java.array('java.lang.String', [ "Test" ]);

Related

Accessing a java HashMap from JSP page using JavaScript

I have a controller class in Spring MVC, where i am returning a HaspMap as Model attribute -
#ModelAttribute("regPrefix")
public Map<String, String> getRegPrefixesOfDepartmentforGroup(final Model model, final HttpServletRequest request) {
final Map<String, String> regPrefixOfDept = new HashMap<String, String>();
regPrefixOfDept.put(regKey, regPrefix);
return regPrefixOfDept;
}
Now in the corresponding JSP page, i am trying to access the Hashmap and store the key/value pairs of the Hasmap in a variable using JavaScript. I am trying like below but its not right. Can anyone suggest how to do that
<script>
$("#deptIdSelection").change(function()
{
var obj = document.getElementById("deptIdSelection");
var textItem = obj.options[obj.selectedIndex].text;
alert(textItem);
var mapObj = "${regPrefix}";
for(var key in mapObj)
alert(key +" ->"+ mapObj[key]);
}
);
</script>
Try to access map values like this:
${regPrefix.key}
If you want to iterate through the map keys, it is not so easy: JSTL is executed on the server side and is rendered to a plain text - no JavaScript objects are created. The following line var mapObj = "${regPrefix}"; will be rendered to a string representation of HashMap, not to a JavaScript object.
To convert your map to a JavaScript object I suggest you to use one of the following methods:
1) Convert your map to JSON and pass it as a String. So when it is rendered to a JavaScript code, it will look like a regular JS object: var mapObj = {"key": "value", ...};. You can use Gson or any other JSON library to achieve this:
final Map<String, String> regPrefixOfDept = new HashMap<String, String>();
regPrefixOfDept.put(regKey, new Gson().toJson(regPrefixOfDept));
And then var mapObj = ${regPrefix}; (note that you need no quotes around because you want mapObj to be a JS object, not a string)
2) Iterate through your map using <c:forEach> to generate a JS object:
var mapObj = {
<c:forEach items="${regPrefix}" var="item" varStatus="loop">
${item.key}: '${item.value}' ${not loop.last ? ',' : ''}
</c:forEach>
};
In both cases you should be able to then call
for(var key in mapObj)
alert(key +" ->"+ mapObj[key]);

How to pass list of object from JavaScript to Windows Runtime Component C#?

I have created a WinRT component in C# which accepts a IEnumarable as a parameter
C#
public sealed class MyClass
{
public IEnumarable<DtoClass> MyFunction(IEnumarable<DtoClass> properties) {
return properties;
}
}
Java script
var Test=[];
for (var i = 0; i < res1.length; i++)
{
Test.push({ category_id: res1[i].category_id });
}
var Conncetion = WindowsRTSqlite.MyClass();
var result = Conncetion.MyFunction(Test);
I'm returning the same input parameters which I'm sending to MyFunction method but it's not return any result. I am not sure why this is not working. Any Ideas?
Thanks in advance.
How to pass list of object from JavaScript to Windows Runtime Component C#?
Actually the correct way is to serialize the collection to a json string and pass this string to the Windows Runtime Component. And deserialize the json string in the runtime component side for data dealing. After that return back the serialized json string to JavaScript uwp app. For how to serialize in JavaScript please reference this class, for how to serialize in C# you can reference this namespcase. So your code on the JavaScript side may as follows:
var Test = [];
for (var i = 1; i < 6; i++) {
Test.push({ category_id: i });
}
var Conncetion = RuntimeComponent1.MyClass();
var Testserialation = JSON.stringify(Test);
var resultnew = Conncetion.newFunction(Testserialation);
var Testreturn = JSON.parse(resultnew);
And in windows runtime component:
public sealed class MyClass
{
public string NewFunction(string jsonstring)
{
JsonArray entity= JsonArray.Parse(jsonstring);
return entity.ToString();
}
}
I am not sure why this is not working.
According to your code snippet, you created an object array and trying to pass it to the runtime component as IEnumarable<DtoClass>. You passed an array, in my opinion you should be able receive it as an array. And I don't think object can be parsed to DtoClass automatically. If you use a string or int array that can be recognized. For example , an int array:
var newTest = [1, 2, 3, 4];
var result2 = Conncetion.changeArray(newTest);
Code in component:
public int[] ChangeArray([ReadOnlyArray()] int[] input)
{
int[] output =(int[])input.Clone();
// Manipulate the copy.
// ...
return output;
}
More details about passing arrays to a Windows Runtime Component please reference this article.

Java: Get JavaScript Array Elements from page

I am at a point where I can pull a single javascript declaration such as:
var cars = ["Saab", "Volvo", "BMW"];
parsed from a page.
I would like to be able to get all the elements of the array ("Saab", "Volvo", "BMW") from this declaration.
Should I be using some javascript engine for this, or what else would be the best way to get javascript variable values from my Java code.
I would hate to reinvent the wheel if something is already out there that is able to do this, so I am just looking for advice on something I can use to do this function.
I assume you found a way to transport that javascript object/array into your Java domain as a String or Stream. What you want now is a JSON parser.
One way is to use json.org or other libraries. Further information about json parsing can be found in this thread:
How to parse JSON in Java
The [org.json][1] library is easy to use. Example code below:
import org.json.*;
JSONObject obj = new JSONObject(" .... ");
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......
} You may find extra examples from: [Parse JSON in Java][2]
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
[1]: http://www.json.org/java/index.html
[2]: http://theoryapp.com/parse-json-in-java/
You might also want to look into jsonb (https://jcp.org/en/jsr/detail?id=353) that was introduced with Java 7. You can bind an object model and transform JSON objects into java objects and vice versa.
you can iterate through all the values in 'window'
for ( var key in window )
{
if ( typeof window]key] == 'object' && window]key].length > 0 )
{
//this is the array you are looking for
}
}
You can get access to javascript object from java by using httpunit
Method 1: JSON parser, as Alex's answer.
Method 2: Javascript parser for Java
Method 3: Regular Expression (A weird way I figured out!)
First pattern is var\s+([a-zA-Z0-9]+)\s+=\s+\[(.*)\]\s*;*
var + one or more space(s) + variable name($1) + one or more space(s) + equals sign + one or more space(s) + array content($2) + ......
Second pattern is "(.*?)", get the string between two quotation marks.
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JSParser {
public String arrayName;
private String tempValues;
public ArrayList<String> values = new ArrayList<String>();
public boolean parseJSArray(String arrayStr){
String p1 = "var\\s+([a-zA-Z0-9]+)\\s+=\\s+\\[(.*)\\]\\s*;*";
Pattern pattern1 = Pattern.compile(p1);
Matcher matcher = pattern1.matcher(arrayStr);
if(matcher.find()){
arrayName = matcher.group(1);
tempValues = matcher.group(2);
Pattern getVal = Pattern.compile("\"(.*?)\"");
Matcher valMatcher = getVal.matcher(tempValues);
while (valMatcher.find()) { // find next match
String value = valMatcher.group(1);
values.add(value);
}
return true;
}else{
return false;
}
}
}
With JDK 8 the code bellow works :
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
String js = "var carsfromjs = [\"Saab\", \"Volvo\", \"BMW\"]";
engine.eval(js);
String[] cars = (String[])engine.eval("Java.to(carsfromjs, \"java.lang.String[]\")");
for(int i=0; i<cars.length; i++){
System.out.println(cars[i]);
}
You can find many ways to access Javascript code throught "nashorn" :
http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/
http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html
http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/

How to assign a List<string> to a ViewBag and use in JavaScript?

I create and assign values to a list of strings in my controller. I want to assign the list of values to a JavaScript variable. How can I do this?
Controller:
List<string> fruits = new List<string>();
list.Add('Apple');
list.Add('Banana');
list.Add('Kiwi');
ViewBag.FruitList = fruits;
View:
var fruitList = '#ViewBag.FruitList';
When I run the program fruitList comes back as System.Collections.Generic.List 1[System.String]
Way 1:
You can use Html.Raw() and Json.Encode for it:
var fruitList = #Html.Raw(Json.Encode(ViewBag.FruitList));
Way 2:
you can use Json.Parse() in combination with Html.Raw() to parse the raw string in to json:
var fruitList = JSON.parse('#Html.Raw(ViewBag.FruitList)');
Way 3:
you can also use JsonConvert class using NewtonSoft JSON to serialize it to json:
var fruitList = '#JsonConvert.Serialize(ViewBag.FruitList)';

Iterate over custom list setting and return all entries

If I have a Salesforce custom list setting, 'Info_List__c' with 1 field, 'Info_Field__c'.
What would a method look like that would iterate through the list and return all entries.
And how would I call that method from a VF page and store the results in a JS object?
In controller
global with sharing class Ctrl{
#RemoteAction
global static List<String> getList(){
List<String> result = new List<String>();
List<Info_List__c> lst = [Select Info_Field__c from Info_List__c];
for(Info_List__c lstObj : lst){
result.add(lstObj.Info_Field__c);
}
return result;
}
}
And in JS side
var strArr = Ctrl.getList();
If you have namespace it would be (e.g. NS)
var strArr = NS.Ctrl.getList();

Categories