A guide to executing an HTTP request using Frida's JavaScript capabilities

This project is utilized for hooking Android processes.

https://github.com/iGio90/FridaAndroidInjector

It enables the injection of Frida agents from an Android application.

It functions flawlessly.

When aiming to hook into this function:

com.ex.MediaPlayMgr.play(final InputStream inputStream, final String str)

The hooking code is as follows:

function log(what) {
    Java.performNow(function() {
        Java.use('android.util.Log').e("FridaAndroidInject", "kenshinx " + what.toString());
    });
}

Java.perform(function() {
        let MediaPlayMgr = Java.use("com.ex.MediaPlayMgr");
    MediaPlayMgr["play"].overload('java.io.InputStream', 'java.lang.String', 'boolean', 'boolean', 'int').implementation = function (inputStream, str, z, z2, i) {
//        this["play"](inputStream, str, z, z2, i);
//        Java.send({'str': str});
        log("step0:")
        var downloadTask = new Promise(function (resolve, reject) {
          // Asynchronous code...
           log("step1:" + str)
           var OkHttpClient = Java.use("okhttp3.OkHttpClient$Builder").$new().build();
           log("step2:" + OkHttpClient)
           var request = Java.use("okhttp3.Request$Builder").$new().url("http://com.ex.com/api").build();
           log("step3:" + request)
           var response = OkHttpClient.newCall(request).execute();
           log("step4:" + response)
           if (response) {
              resolve(response.byteStream(), "paimen")
           } else {
              reject(inputStream, str)
           }
        });
        log("step5:")
        function doPlay(stream, word) {
            log("stepx:" + stream + ", " + word)
            this.play(stream, word, z, z2, i);
        }
        log("step6:")
        downloadTask.then(doPlay, doPlay);
        log("step7:")
    };
});

The logging stops at step3. There is no step4.

Therefore, how can an HTTP request be made in JavaScript?

10:27:21.997 16391-16391 FridaAndroidInject   com...plication.floatball  E  kenshinx step0:
10:27:21.997 16391-16391 FridaAndroidInject   com...plication.floatball  E  kenshinx step1:哈哈哈
10:27:22.000 16391-16391 FridaAndroidInject   com...plication.floatball  E  kenshinx step2:okhttp3.OkHttpClient@1af90ef
10:27:22.003 16391-16391 FridaAndroidInject   com...plication.floatball  E  kenshinx step3:Request{method=GET, url=http://com.ex.com/api}
10:27:22.006 16391-16391 FridaAndroidInject   com...plication.floatball  E  kenshinx step5:
10:27:22.006 16391-16391 FridaAndroidInject   com...plication.floatball  E  kenshinx step6:
10:27:22.006 16391-16391 FridaAndroidInject   com...plication.floatball  E  kenshinx step7:
10:27:22.007 16391-16391 FridaAndroidInject   com...plication.floatball  E  kenshinx stepx:Error: android.os.NetworkOnMainThreadException, undefined

I attempted using java.net.URL and java.net.HTTPConnect, but it did not work.

I aim to replace the inputStream in play() with my own stream.

Answer №1

Robert's insight pinpointed the issue as a thread problem, which was resolved with the following code implementation.

            var OkHttp = Java.use("okhttp3.OkHttpClient$Builder").$new().build();
    log('step1:' + OkHttp)
    var request = Java.use("okhttp3.Request$Builder").$new().url("http://com.ex.api").tag(this).build();
    log('step2:' + request)
    var Callback = Java.use("okhttp3.Callback");
    log('step3:' + Callback)
    const DownloadCallback = Java.registerClass({
               name:'com.ka.tts.player.DownloadCallback',
               implements: [Callback],
               methods: {
                    onFailure(call, e) {
                        log('stepA:'+call)
                        var that = call.request().tag()
                        log('stepB:'+that)
                        var that1 = Java.cast(that, Java.use("com.ka.tts.player.audiotrack.AudioTrackPlayerImpl"))
                        Java.scheduleOnMainThread(function(){
                            that1.play(mediaResource.stream, str, i);
                        });
             },
             onResponse(call, response){
                 log('step4:' + call)
                 var that = call.request().tag()
                 log('step5:'+that)
                 var that1 = Java.cast(that, Java.use("com.ka.tts.player.audiotrack.AudioTrackPlayerImpl"))
                 try {
                     if (response.code() === 200) {
                         var stream = response.body().byteStream()
                         log("step6:" + stream)
                         Java.scheduleOnMainThread(function(){
                             that1.play(stream, str, i);
                        })
                     } else {
                         log("step7:")
                         Java.scheduleOnMainThread(function(){
                             that1.play(mediaResource.stream, str, i);
                        })
                     }
                     log("step8:")
                 } catch (e) {
                     log("error:" + e)
                     Java.scheduleOnMainThread(function(){
                         that1.play(mediaResource.stream, str, i);
                        })
                    }
                },
              }
           });
OkHttp.newCall(request).enqueue(DownloadCallback.$new());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Apply a CSS class when the tab key is pressed by the user

Currently in my Angular 14 project, I am working on a feature where I need to apply "display: block" to an element once the user reaches it using the tab key. However, I am struggling with removing the "display: block" when the user tabs out of the element ...

Retrieve both the key and corresponding value from a JSON object

I am attempting to extract the key and value pairs from a JSON dataset. $.get(url, function (data) { console.log(data); if (data.Body != null) { console.log(data.Body); } }); These are my current logs: { $id: "1", Exceptions ...

Laravel Mix causes errors when running `npm run dev` and breaks the package

My nodejs package is built using ES6 features such as 'let', the spread operator (...) and default values for function arguments. However, when I run npm run production with Laravel Mix, an error message appears: ERROR Failed to compile with ...

The functionality of getAttribute has changed in Firefox 3.5 and IE8, no longer behaving as it did before

Creating a JavaScript function to locate an anchor in a page (specifically with, not an id) and then going through its parent elements until finding one that contains a specified class. The code below works perfectly in Firefox 3.0 but encounters issues wi ...

Incorporating an HTML image into a div or table using jQuery

I am a beginner in using JQuery within Visual Studio 2013. My question is how to insert an img tag into a table or div using JQuery? For example, I have a div and I would like to generate an image dynamically using JQuery. Or, I have a dynamically create ...

IE8 is proving to be a major hurdle for the successful operation of AngularJS $http

Currently, I am faced with the challenge of creating an Angular application that needs to be compatible with IE8. However, I'm encountering difficulties in establishing a connection with the server. Surprisingly, whenever I attempt a $http.get, the en ...

Transfer or duplicate an SVG image from the bottom div to the top div

Is there a way to move a div from the chart_div to the movehere div? I've tried duplicating it below the current svg, but I'm having trouble targeting just the header row ('g' element) specifically. Here is the HTML: <script type= ...

Increasing the size of elements with jQuery animate method

I've been utilizing the animate function in jQuery to dynamically resize a content area upon hovering over the element. Although the script is functioning correctly, I'm facing a challenge in preventing the script from resizing the content multi ...

Error: Jest react testing encountered an issue when attempting to read the property 'type' from an undefined value

While conducting tests on my app components created with the material UI library using jest and enzyme, I encountered an error in one of my packages. Here is a screenshot of the error: Click here to view ...

The function is not being called as expected when using `onclick` or `eventListener('click')`

I'm in the process of developing a login form for my website that will offer 2 options - "login" and "signup". The concept is similar to mini tabs and iframe windows. Essentially, I have two divs side by side for "login" and "signup". When the user cl ...

Guide to Crafting a Location Object

When attempting to create a new location and specify its latitude and longitude in Kotlin, you may encounter the following issue: var targetlocation = Location("") // The code snippet below does not function as expected targetlocation.setLatitude(55.55555 ...

Having trouble loading images in JavaScript due to an issue with JSON: undefined.jpg not found

I'm struggling to concatenate my image names in this JavaScript code as a newbie, especially since it's pulling from JSON. Any assistance would be greatly appreciated! Below is the JS code snippet I'm working with: function log(msg){ ...

How can we use jQuery to compare two blocks and set them to have the same height value?

Is there a way to compare and set equal height for two blocks within the main div? <div class="main-content"> <div class="content-1"></div> <div class="content-2"></div> </div> Javascript Code: var $content1 = $(&ap ...

Insert a THREE.Points element into the scene: Error in THREE.Object3D.add: The object being added is not a valid instance of THREE.Object3D (

Trying to incorporate a system of particles, a THREE.Points element into the scene has resulted in the following error: "THREE.Object3D.add: object not an instance of THREE.Object3D. undefined" The code used for this is as follows: var backCount = 1800; ...

Using the $.ajax function with the PUT method and sending an OPTIONS request

Here is my code snippet: function test(segmentId) { var url = "http://...../api/avoidsegments/123456"; $.ajax({ url: url, type: "PUT", contentType: "application/json", data : { "appID": ig_appID, ...

Looking to transform a list into JSON format using JavaScript?

I have a collection that looks like this: <ol class="BasketballPlayers"> <li id="1">Player: LeBron, TotalPoints: 28753, MVP: true</li> <li id="2">Player: Steph, TotalPoints: 17670, MVP: true< ...

Adjust form elements dynamically depending on the selected option in a dropdown menu using Ruby on Rails

I currently have the following database tables set up: Departments ID| Department_name | Manager_ID Employees ID| Name | Department_ID Salaries ID| Employee_ID | Salary_Amount The departments table holds information about different departments within t ...

Error: Type Error - 'style' is not defined in the Progress Bar Project

Having recently started learning Javascript, I have been engaging with various tutorials and projects in order to gain familiarity with the language. One particular tutorial that caught my attention is a Progress-Bar tutorial by "dcode" available at this l ...

Internet Explorer does not return results when using AJAX during the onchange event (specifically for IE only

My code is functioning correctly on other browsers, however in IE it does not provide any result when I select the dropdown button. Instead, it changes and displays an empty result. This is my AJAX: $("#book").change(function(){ var DOMBULK = $(" ...

Troublesome Issue with ngAnimate and ngHide: Missing 'ng-hide-animate' Hook Class

I am working on a case where I need to add animation to a DOM object using the ngHide directive: Check out this example here Within this scenario, I have an array of JSON objects: $scope.items = [ {"key": 1, "values": []}, {"key": 2, "values": [ ...