📦
3357 /agent/ssl_log.js.map
4339 /agent/ssl_log.js
4924 /agent/android/android_agent.js.map
7065 /agent/android/android_agent.js
948 /agent/android/android_java_tls_libs.js.map
1150 /agent/android/android_java_tls_libs.js
4372 /agent/android/bouncycastle.js.map
5111 /agent/android/bouncycastle.js
5430 /agent/android/conscrypt.js.map
8619 /agent/android/conscrypt.js
3969 /agent/android/cronet_android.js.map
6016 /agent/android/cronet_android.js
2285 /agent/android/flutter_android.js.map
3238 /agent/android/flutter_android.js
1403 /agent/android/gnutls_android.js.map
1475 /agent/android/gnutls_android.js
993 /agent/android/mbedTLS_android.js.map
1248 /agent/android/mbedTLS_android.js
2296 /agent/android/mono_btls_android.js.map
3295 /agent/android/mono_btls_android.js
3748 /agent/android/nss_android.js.map
5167 /agent/android/nss_android.js
3192 /agent/android/openssl_boringssl_android.js.map
3912 /agent/android/openssl_boringssl_android.js
3578 /agent/android/pattern_android.js.map
5027 /agent/android/pattern_android.js
8944 /agent/android/rustls_android.js.map
16440 /agent/android/rustls_android.js
1998 /agent/android/s2ntls_android.js.map
2247 /agent/android/s2ntls_android.js
3101 /agent/android/wolfssl_android.js.map
3892 /agent/android/wolfssl_android.js
1853 /agent/ios/cronet_ios.js.map
2275 /agent/ios/cronet_ios.js
2032 /agent/ios/flutter_ios.js.map
2548 /agent/ios/flutter_ios.js
2156 /agent/ios/ios_agent.js.map
2598 /agent/ios/ios_agent.js
2241 /agent/ios/openssl_boringssl_ios.js.map
3640 /agent/ios/openssl_boringssl_ios.js
1483 /agent/linux/cronet_linux.js.map
1523 /agent/linux/cronet_linux.js
1352 /agent/linux/gnutls_linux.js.map
1399 /agent/linux/gnutls_linux.js
2762 /agent/linux/linux_agent.js.map
3363 /agent/linux/linux_agent.js
993 /agent/linux/matrixssl_linux.js.map
1251 /agent/linux/matrixssl_linux.js
962 /agent/linux/mbedTLS_linux.js.map
1214 /agent/linux/mbedTLS_linux.js
3618 /agent/linux/nss_linux.js.map
4660 /agent/linux/nss_linux.js
2502 /agent/linux/openssl_boringssl_linux.js.map
2906 /agent/linux/openssl_boringssl_linux.js
6628 /agent/linux/rustls_linux.js.map
10217 /agent/linux/rustls_linux.js
1992 /agent/linux/s2ntls_linux.js.map
2245 /agent/linux/s2ntls_linux.js
3094 /agent/linux/wolfssl_linux.js.map
3886 /agent/linux/wolfssl_linux.js
1483 /agent/macos/cronet_macos.js.map
1514 /agent/macos/cronet_macos.js
2084 /agent/macos/macos_agent.js.map
2614 /agent/macos/macos_agent.js
2297 /agent/macos/openssl_boringssl_macos.js.map
3869 /agent/macos/openssl_boringssl_macos.js
9230 /agent/misc/socket_tracer.js.map
10733 /agent/misc/socket_tracer.js
1320 /agent/shared/library_identification.js.map
1620 /agent/shared/library_identification.js
15501 /agent/shared/pattern_based_hooking.js.map
23701 /agent/shared/pattern_based_hooking.js
11971 /agent/shared/shared_functions.js.map
15429 /agent/shared/shared_functions.js
661 /agent/shared/shared_structures.js.map
501 /agent/shared/shared_structures.js
3527 /agent/ssl_lib/cronet.js.map
5026 /agent/ssl_lib/cronet.js
2878 /agent/ssl_lib/flutter.js.map
3950 /agent/ssl_lib/flutter.js
6814 /agent/ssl_lib/gnutls.js.map
7899 /agent/ssl_lib/gnutls.js
2736 /agent/ssl_lib/java_ssl_libs.js.map
5235 /agent/ssl_lib/java_ssl_libs.js
5921 /agent/ssl_lib/matrixssl.js.map
7056 /agent/ssl_lib/matrixssl.js
6977 /agent/ssl_lib/mbedTLS.js.map
7038 /agent/ssl_lib/mbedTLS.js
2880 /agent/ssl_lib/monobtls.js.map
3954 /agent/ssl_lib/monobtls.js
34060 /agent/ssl_lib/nss.js.map
59226 /agent/ssl_lib/nss.js
13536 /agent/ssl_lib/openssl_boringssl.js.map
16673 /agent/ssl_lib/openssl_boringssl.js
8949 /agent/ssl_lib/rustls.js.map
11976 /agent/ssl_lib/rustls.js
5327 /agent/ssl_lib/s2ntls.js.map
6576 /agent/ssl_lib/s2ntls.js
4781 /agent/ssl_lib/wolfssl.js.map
5718 /agent/ssl_lib/wolfssl.js
14225 /agent/util/anti_root.js.map
18094 /agent/util/anti_root.js
747 /agent/util/log.js.map
451 /agent/util/log.js
3266 /agent/util/process_infos.js.map
4381 /agent/util/process_infos.js
1489 /agent/windows/cronet_windows.js.map
1530 /agent/windows/cronet_windows.js
985 /agent/windows/gnutls_windows.js.map
1035 /agent/windows/gnutls_windows.js
1030 /agent/windows/matrixssl_windows.js.map
1102 /agent/windows/matrixssl_windows.js
993 /agent/windows/mbedTLS_windows.js.map
1248 /agent/windows/mbedTLS_windows.js
1233 /agent/windows/nss_windows.js.map
1459 /agent/windows/nss_windows.js
1275 /agent/windows/openssl_boringssl_windows.js.map
1558 /agent/windows/openssl_boringssl_windows.js
13144 /agent/windows/sspi.js.map
16416 /agent/windows/sspi.js
2599 /agent/windows/windows_agent.js.map
3351 /agent/windows/windows_agent.js
1303 /agent/windows/wolfssl_windows.js.map
1426 /agent/windows/wolfssl_windows.js
✄
{"version":3,"file":"ssl_log.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ssl_log.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AACxF,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAA;AAC9D,OAAO,EAAU,GAAG,EAAE,MAAM,eAAe,CAAC;AAE5C,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AC,CAAC;YACjC,iBAAiB,EAAE,CAAC;SACvB;QACD,IAAG,qBAAqB,EAAC;YACrB,oBAAoB,EAAE,CAAC;SAC1B;QACD,0BAA0B,EAAE,CAAA;KAC/B;SAAK,IAAG,OAAO,EAAE,EAAC;QACf,IAAG,qBAAqB,EAAC;YACrB,oBAAoB,EAAE,CAAC;SAC1B;QACD,GAAG,CAAC,yBAAyB,CAAC,CAAA;QAC9B,wBAAwB,EAAE,CAAA;KAC7B;SAAK,IAAG,KAAK,EAAE,EAAC;QACb,IAAG,qBAAqB,EAAC;YACrB,oBAAoB,EAAE,CAAC;SAC1B;QACD,GAAG,CAAC,uBAAuB,CAAC,CAAA;QAC5B,sBAAsB,EAAE,CAAA;KAC3B;SAAK,IAAG,OAAO,EAAE,EAAC;QACf,IAAG,qBAAqB,EAAC;YACrB,oBAAoB,EAAE,CAAC;SAC1B;QACD,GAAG,CAAC,yBAAyB,CAAC,CAAA;QAC9B,wBAAwB,EAAE,CAAA;KAC7B;SAAI;QACD,GAAG,CAAC,qCAAqC,CAAC,CAAA;QAC1C,GAAG,CAAC,0HAA0H,CAAC,CAAA;KAClI;AAEL,CAAC;AAED,sBAAsB,EAAE,CAAA"}
✄
import { load_android_hooking_agent } from "./android/android_agent.js";
import { load_ios_hooking_agent } from "./ios/ios_agent.js";
import { load_macos_hooking_agent } from "./macos/macos_agent.js";
import { load_linux_hooking_agent } from "./linux/linux_agent.js";
import { load_windows_hooking_agent } from "./windows/windows_agent.js";
import { isWindows, isLinux, isAndroid, isiOS, isMacOS } from "./util/process_infos.js";
import { anti_root_execute } from "./util/anti_root.js";
import { socket_trace_execute } from "./misc/socket_tracer.js";
import { log } from "./util/log.js";
// global address which stores the addresses of the hooked modules which aren't loaded via the dynamic loader
global.init_addresses = {};
global.global_counter = 0;
//@ts-ignore
export let offsets = "{OFFSETS}";
//@ts-ignore
export let experimental = false;
//@ts-ignore
export let enable_socket_tracing = false;
//@ts-ignore
export let anti_root = false;
//@ts-ignore
export let enable_default_fd = false;
//@ts-ignore
export let patterns = "{PATTERNS}";
/*
Our way to get the JSON strings into the loaded frida script
*/
send("offset_hooking");
const enable_offset_based_hooking_state = recv('offset_hooking', value => {
    if (value.payload !== null && value.payload !== undefined) {
        offsets = value.payload;
    }
});
enable_offset_based_hooking_state.wait();
send("pattern_hooking");
const enable_pattern_based_hooking_state = recv('pattern_hooking', value => {
    if (value.payload !== null && value.payload !== undefined) {
        patterns = value.payload;
    }
});
enable_pattern_based_hooking_state.wait();
/*
This way we are providing boolean values from the commandline directly to our frida script
*/
send("socket_tracing");
const enable_socket_tracing_state = recv('socket_tracing', value => {
    enable_socket_tracing = value.payload;
});
enable_socket_tracing_state.wait();
send("defaultFD");
const enable_default_fd_state = recv('defaultFD', value => {
    enable_default_fd = value.payload;
});
enable_default_fd_state.wait();
send("experimental");
const exp_recv_state = recv('experimental', value => {
    experimental = value.payload;
});
exp_recv_state.wait();
send("anti");
const antiroot_recv_state = recv('antiroot', value => {
    anti_root = value.payload;
});
antiroot_recv_state.wait(); /* */
/*

create the TLS library for your first prototpye as a lib in ./ssl_lib and than extend this class for the OS where this new lib was tested.

Further keep in mind, that properties of an class only visible inside the Interceptor-onEnter/onLeave scope when they are static.
As an alternative you could make a local variable inside the calling functions which holds an reference to the class property.

*/
export function getOffsets() {
    return offsets;
}
// Function to check if the patterns have been replaced
export function isPatternReplaced() {
    if (patterns === null) {
        return false;
    }
    // The default placeholder is quite short, so if the length exceeds a certain threshold, we assume it's replaced
    return patterns.length > 10;
}
function load_os_specific_agent() {
    if (isWindows()) {
        log('Running Script on Windows');
        load_windows_hooking_agent();
    }
    else if (isAndroid()) {
        log('Running Script on Android');
        if (anti_root) {
            log('Applying anti root checks');
            anti_root_execute();
        }
        if (enable_socket_tracing) {
            socket_trace_execute();
        }
        load_android_hooking_agent();
    }
    else if (isLinux()) {
        if (enable_socket_tracing) {
            socket_trace_execute();
        }
        log('Running Script on Linux');
        load_linux_hooking_agent();
    }
    else if (isiOS()) {
        if (enable_socket_tracing) {
            socket_trace_execute();
        }
        log('Running Script on iOS');
        load_ios_hooking_agent();
    }
    else if (isMacOS()) {
        if (enable_socket_tracing) {
            socket_trace_execute();
        }
        log('Running Script on MacOS');
        load_macos_hooking_agent();
    }
    else {
        log('Running Script on unknown plattform');
        log("Error: not supported plattform!\nIf you want to have support for this plattform please make an issue at our github page.");
    }
}
load_os_specific_agent();
✄
{"version":3,"file":"android_agent.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/android/android_agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAqB,MAAM,gCAAgC,CAAC;AAC3F,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAC1G,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,gCAAgC,EAAE,gCAAgC,EAAE,MAAM,qCAAqC,CAAC;AACzH,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAChE,OAAO,EAAE,YAAY,EAAC,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,iBA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BAAiB,CAAC,CAAC;QAC/D,CAAC,gBAAgB,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;QACzD,CAAC,oBAAoB,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;QAC7D,CAAC,wBAAwB,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;QACjE,CAAC,qBAAqB,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;QAC9D,CAAC,mBAAmB,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;KAAC,CAAC;IAGlE,kBAAkB,EAAE,CAAC;IACrB,4BAA4B,CAAC,sBAAsB,EAAE,IAAI,CAAC,CAAC;IAC3D,2BAA2B,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAAC;IAC3D,IAAI,iBAAiB,EAAE,EAAC;QACpB,2BAA2B,EAAE,CAAC;KACjC;IAED;;OAEG;IACH,IAAG;QACC,IAAI,cAAc,GAAG,gCAAgC,EAAE,CAAC;QACxD,IAAI,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE;YAC3B,MAAM,0BAA0B,GAA0D,EAAE,CAAC;YAE7F,0BAA0B,CAAC,cAAc,CAAC,GAAG,gCAAgC,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;YAC9G,4BAA4B,CAAC,0BAA0B,EAAE,KAAK,CAAC,CAAC;YAChE,2BAA2B,CAAC,0BAA0B,EAAE,KAAK,CAAC,CAAC;YAC/D,GAAG,CAAC,iEAAiE,CAAC,CAAC;SAC1E;KACJ;IAAA,OAAO,SAAS,EAAC;QACd,MAAM,CAAC,2CAA2C,GAAG,SAAS,CAAC,CAAC;KACnE;AACL,CAAC"}
✄
import { module_library_mapping } from "../shared/shared_structures.js";
import { getModuleNames, ssl_library_loader, invokeHookingFunction } from "../shared/shared_functions.js";
import { log, devlog } from "../util/log.js";
import { findModulesWithSSLKeyLogCallback, createModuleLibraryMappingExtend } from "../shared/library_identification.js";
import { gnutls_execute } from "./gnutls_android.js";
import { wolfssl_execute } from "./wolfssl_android.js";
import { nss_execute } from "./nss_android.js";
import { mbedTLS_execute } from "./mbedTLS_android.js";
import { boring_execute } from "./openssl_boringssl_android.js";
import { java_execute } from "./android_java_tls_libs.js";
import { cronet_execute } from "./cronet_android.js";
import { conscrypt_native_execute } from "./conscrypt.js";
import { flutter_execute } from "./flutter_android.js";
import { s2ntls_execute } from "./s2ntls_android.js";
import { mono_btls_execute } from "./mono_btls_android.js";
import { patterns, isPatternReplaced } from "../ssl_log.js";
import { pattern_execute } from "./pattern_android.js";
import { rustls_execute } from "./rustls_android.js";
var plattform_name = "linux";
var moduleNames = getModuleNames();
global.addresses = {};
export const socket_library = "libc";
function install_java_hooks() {
    java_execute();
}
function hook_Android_Dynamic_Loader(module_library_mapping, is_base_hook) {
    try {
        const regex_libdl = /.*libdl.*\.so/;
        const libdl = moduleNames.find(element => element.match(regex_libdl));
        if (libdl === undefined) {
            throw "Android Dynamic loader not found!";
        }
        let dl_exports = Process.getModuleByName(libdl).enumerateExports();
        var dlopen = "dlopen";
        for (var ex of dl_exports) {
            if (ex.name === "android_dlopen_ext") {
                dlopen = "android_dlopen_ext";
                break;
            }
        }
        Interceptor.attach(Module.getExportByName(libdl, dlopen), {
            onEnter: function (args) {
                this.moduleName = args[0].readCString();
            },
            onLeave: function (retval) {
                if (this.moduleName != undefined) {
                    for (let map of module_library_mapping[plattform_name]) {
                        let regex = map[0];
                        let func = map[1];
                        if (regex.test(this.moduleName)) {
                            log(`${this.moduleName} was loaded & will be hooked on Android!`);
                            try {
                                func(this.moduleName, is_base_hook);
                            }
                            catch (error_msg) {
                                devlog(`[-] Error in hooking ${this.moduleName}: ${error_msg}`);
                            }
                        }
                    }
                }
            }
        });
        log(`[*] Android dynamic loader hooked.`);
    }
    catch (error) {
        devlog("Dynamic loader error: " + error);
        log("No dynamic loader present for hooking on Android.");
    }
}
function hook_native_Android_SSL_Libs(module_library_mapping, is_base_hook) {
    ssl_library_loader(plattform_name, module_library_mapping, moduleNames, "Android", is_base_hook);
}
function loadPatternsFromJSON(jsonContent) {
    try {
        let data = JSON.parse(jsonContent);
        return data;
    }
    catch (error) {
        devlog("[-] Error loading or parsing JSON pattern:  " + error);
        return null;
    }
}
// Support for this feature is currently limited to Android systems.
function install_pattern_based_hooks() {
    try {
        let data = loadPatternsFromJSON(patterns);
        if (data !== null && data.modules) {
            for (const moduleName in data.modules) {
                if (Object.prototype.hasOwnProperty.call(data.modules, moduleName)) {
                    log("[*] Module name:" + moduleName);
                    module_library_mapping[plattform_name] = [
                        [moduleName, invokeHookingFunction(pattern_execute)]
                    ];
                    hook_native_Android_SSL_Libs(module_library_mapping, true);
                }
            }
        }
    }
    catch (e) {
    }
    //console.log("data: \n"+data);
    /*
    for (const moduleName in data.modules) {
        /*if (Object.prototype.hasOwnProperty.call(data.modules, moduleName)) {
          console.log("[*] Module name:", moduleName);
        }
      }*/
    /*
    const hooker = new PatternBasedHooking(cronetModule);
    hooker.hook_DumpKeys(this.module_name,"libcronet.so",patterns,(args: any[]) => {
              devlog("Installed ssl_log_secret() hooks using byte patterns.");
              this.dumpKeys(args[1], args[0], args[2]);  // Unpack args into dumpKeys
          });
    */
}
export function load_android_hooking_agent() {
    module_library_mapping[plattform_name] = [
        [/.*libssl_sb.so/, invokeHookingFunction(boring_execute)],
        [/.*libssl\.so/, invokeHookingFunction(boring_execute)],
        [/libconscrypt_gmscore_jni.so/, invokeHookingFunction(conscrypt_native_execute)],
        [/ibconscrypt_jni.so/, invokeHookingFunction(conscrypt_native_execute)],
        [/.*flutter.*\.so/, invokeHookingFunction(flutter_execute)],
        [/.*libgnutls\.so/, invokeHookingFunction(gnutls_execute)],
        [/.*libwolfssl\.so/, invokeHookingFunction(wolfssl_execute)],
        [/.*libnss[3-4]\.so/, invokeHookingFunction(nss_execute)],
        [/libmbedtls\.so.*/, invokeHookingFunction(mbedTLS_execute)],
        [/.*libs2n.so/, invokeHookingFunction(s2ntls_execute)],
        [/.*mono-btls.*\.so/, invokeHookingFunction(mono_btls_execute)],
        [/.*cronet.*\.so/, invokeHookingFunction(cronet_execute)],
        [/.*monochrome.*\.so/, invokeHookingFunction(cronet_execute)],
        [/.*libwarp_mobile.*\.so/, invokeHookingFunction(cronet_execute)],
        [/.*lib*quiche*.*\.so/, invokeHookingFunction(cronet_execute)],
        [/.*librustls.*\.so/, invokeHookingFunction(rustls_execute)]
    ];
    install_java_hooks();
    hook_native_Android_SSL_Libs(module_library_mapping, true);
    hook_Android_Dynamic_Loader(module_library_mapping, false);
    if (isPatternReplaced()) {
        install_pattern_based_hooks();
    }
    /*
     * Our simple approach to find the modules which might use BoringSSL internally
     */
    try {
        let matchedModules = findModulesWithSSLKeyLogCallback();
        if (matchedModules.length > 0) {
            const moduleLibraryMappingExtend = {};
            moduleLibraryMappingExtend[plattform_name] = createModuleLibraryMappingExtend(matchedModules, boring_execute);
            hook_native_Android_SSL_Libs(moduleLibraryMappingExtend, false);
            hook_Android_Dynamic_Loader(moduleLibraryMappingExtend, false);
            log("[*] Hooked additional modules with SSL_CTX_set_keylog_callback.");
        }
    }
    catch (error_msg) {
        devlog("[-] Error in hooking additional modules: " + error_msg);
    }
}
✄
{"version":3,"file":"android_java_tls_libs.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/android/android_java_tls_libs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD,MAAM,OAAO,gBAAiB,SAAQ,QAAQ;IAG1C,0BAA0B;QACtB,IAAI,IAAI,CAAC,SAAS,EAAE;YAChB,UAAU,CAAC;gBAEP,IAAI,CAAC,OAAO,CAAC;oBAET,4BAA4B;oBAC5B,IAAI;wBACA,oFAAoF;wBACpF,IAAI,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,oDAAoD,CAAC,CAAA;wBAC7E,GAAG,CAAC,qCAAqC,CAAC,CAAA;wBAC1C,cAAc,EAAE,CAAA;qBACnB;oBAAC,OAAO,KAAK,EAAE;wBACZ,2BAA2B;qBAC9B;gBACL,CAAC,CAAC,CAAC;YACP,CAAC,EAAE,CAAC,CAAC,CAAC;SACT;IACL,CAAC;IAGD,aAAa;QACT,IAAI,CAAC,0BAA0B,EAAE,CAAC;QAClC,IAAI,CAAC,kBAAkB,EAAE,CAAC;IAC9B,CAAC;CAEJ;AAGD,MAAM,UAAU,YAAY;IACxB,IAAI,QAAQ,GAAG,IAAI,gBAAgB,EAAE,CAAC;IACtC,QAAQ,CAAC,aAAa,EAAE,CAAC;AAC7B,CAAC"}
✄
import { log } from "../util/log.js";
import { execute as bouncy_execute } from "./bouncycastle.js";
import { SSL_Java } from "../ssl_lib/java_ssl_libs.js";
export class SSL_Java_Android extends SSL_Java {
    install_java_android_hooks() {
        if (Java.available) {
            setTimeout(function () {
                Java.perform(function () {
                    // Bouncycastle/Spongycastle
                    try {
                        //If we can load a class of spongycastle, we know its present and we have to hook it
                        var testLoad = Java.use("org.spongycastle.jsse.provider.ProvSSLSocketDirect");
                        log("Bouncycastle/Spongycastle detected.");
                        bouncy_execute();
                    }
                    catch (error) {
                        //On error, just do nothing
                    }
                });
            }, 0);
        }
    }
    execute_hooks() {
        this.install_java_android_hooks();
        this.install_java_hooks();
    }
}
export function java_execute() {
    var java_ssl = new SSL_Java_Android();
    java_ssl.execute_hooks();
}
✄
{"version":3,"file":"bouncycastle.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/android/bouncycastle.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,YAAY,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAChI,MAAM,UAAU,OAAO;IACnB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C,uBAAuB,CAAC,cAAc,GAAG,UAAU,CAAM;gBAEzE,IAAI,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAA;gBAClC,IAAI,kBAAkB,GAAG,QAAQ,CAAC,kBAAkB,CAAC,KAAK,CAAA;gBAC1D,IAAI,YAAY,GAAG,kBAAkB,CAAC,YAAY,CAAC,KAAK,CAAA;gBACxD,IAAI,eAAe,GAAG,YAAY,CAAC,kBAAkB,EAAE,cAAc,CAAC,CAAA;gBAEtE,2FAA2F;gBAC3F,IAAI,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAA;gBACvC,IAAI,oBAAoB,GAAG,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,QAAQ,EAAE,EAAE,KAAK,CAAC,CAAC,aAAa,EAAE,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAA;gBAChH,oBAAoB,CAAC,aAAa,CAAC,IAAI,CAAC,CAAA;gBACxC,IAAI,wBAAwB,GAAG,oBAAoB,CAAC,GAAG,CAAC,eAAe,CAAC,CAAA;gBACxE,IAAI,OAAO,GAA2B,EAAE,CAAA;gBACxC,OAAO,CAAC,aAAa,CAAC,GAAG,QAAQ,CAAA;gBACjC,OAAO,CAAC,QAAQ,CAAC,GAAG,gBAAgB,GAAG,iBAAiB,CAAC,YAAY,CAAC,GAAG,GAAG,GAAG,2BAA2B,CAAC,wBAAwB,CAAC,CAAA;gBACpI,IAAI,CAAC,OAAO,CAAC,CAAA;gBACb,OAAO,IAAI,CAAC,uBAAuB,CAAC,CAAC,CAAC,CAAA;YAC1C,CAAC,CAAA;QAEL,CAAC,CAAC,CAAA;IACN,CAAC,EAAE,CAAC,CAAC,CAAC;AAEV,CAAC"}
✄
import { log } from "../util/log.js";
import { byteArrayToString, byteArrayToNumber, getAttribute, reflectionByteArrayToString } from "../shared/shared_functions.js";
export function execute() {
    setTimeout(function () {
        Java.perform(function () {
            //Hook the inner class "AppDataOutput/input" of ProvSSLSocketDirect, so we can access the 
            //socket information in its outer class by accessing this.this$0
            var appDataOutput = Java.use("org.spongycastle.jsse.provider.ProvSSLSocketDirect$AppDataOutput");
            appDataOutput.write.overload('[B', 'int', 'int').implementation = function (buf, offset, len) {
                var result = [];
                for (var i = 0; i < len; ++i) {
                    result.push(buf[i] & 0xff);
                }
                var message = {};
                message["contentType"] = "datalog";
                message["src_port"] = this.this$0.value.getLocalPort();
                message["dst_port"] = this.this$0.value.getPort();
                var localAddress = this.this$0.value.getLocalAddress().getAddress();
                var inetAddress = this.this$0.value.getInetAddress().getAddress();
                if (localAddress.length == 4) {
                    message["src_addr"] = byteArrayToNumber(localAddress);
                    message["dst_addr"] = byteArrayToNumber(inetAddress);
                    message["ss_family"] = "AF_INET";
                }
                else {
                    message["src_addr"] = byteArrayToString(localAddress);
                    message["dst_addr"] = byteArrayToString(inetAddress);
                    message["ss_family"] = "AF_INET6";
                }
                message["ssl_session_id"] = byteArrayToString(this.this$0.value.getConnection().getSession().getId());
                //log(message["ssl_session_id"])
                message["function"] = "writeApplicationData";
                send(message, result);
                return this.write(buf, offset, len);
            };
            var appDataInput = Java.use("org.spongycastle.jsse.provider.ProvSSLSocketDirect$AppDataInput");
            appDataInput.read.overload('[B', 'int', 'int').implementation = function (buf, offset, len) {
                var bytesRead = this.read(buf, offset, len);
                var result = [];
                for (var i = 0; i < bytesRead; ++i) {
                    result.push(buf[i] & 0xff);
                }
                var message = {};
                message["contentType"] = "datalog";
                message["ss_family"] = "AF_INET";
                message["src_port"] = this.this$0.value.getPort();
                message["dst_port"] = this.this$0.value.getLocalPort();
                var localAddress = this.this$0.value.getLocalAddress().getAddress();
                var inetAddress = this.this$0.value.getInetAddress().getAddress();
                if (localAddress.length == 4) {
                    message["src_addr"] = byteArrayToNumber(inetAddress);
                    message["dst_addr"] = byteArrayToNumber(localAddress);
                    message["ss_family"] = "AF_INET";
                }
                else {
                    message["src_addr"] = byteArrayToString(inetAddress);
                    message["dst_addr"] = byteArrayToString(localAddress);
                    message["ss_family"] = "AF_INET6";
                }
                message["ssl_session_id"] = byteArrayToString(this.this$0.value.getConnection().getSession().getId());
                log(message["ssl_session_id"]);
                message["function"] = "readApplicationData";
                send(message, result);
                return bytesRead;
            };
            //Hook the handshake to read the client random and the master key
            var ProvSSLSocketDirect = Java.use("org.spongycastle.jsse.provider.ProvSSLSocketDirect");
            ProvSSLSocketDirect.notifyHandshakeComplete.implementation = function (x) {
                var protocol = this.protocol.value;
                var securityParameters = protocol.securityParameters.value;
                var clientRandom = securityParameters.clientRandom.value;
                var masterSecretObj = getAttribute(securityParameters, "masterSecret");
                //The key is in the AbstractTlsSecret, so we need to access the superclass to get the field
                var clazz = Java.use("java.lang.Class");
                var masterSecretRawField = Java.cast(masterSecretObj.getClass(), clazz).getSuperclass().getDeclaredField("data");
                masterSecretRawField.setAccessible(true);
                var masterSecretReflectArray = masterSecretRawField.get(masterSecretObj);
                var message = {};
                message["contentType"] = "keylog";
                message["keylog"] = "CLIENT_RANDOM " + byteArrayToString(clientRandom) + " " + reflectionByteArrayToString(masterSecretReflectArray);
                send(message);
                return this.notifyHandshakeComplete(x);
            };
        });
    }, 0);
}
✄
{"version":3,"file":"conscrypt.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/android/conscrypt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAC,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACnE,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAElE,MAAM,OAAO,4BAA6B,SAAQ,iBAAiB;IAE/D,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,IAAI,sBAAsB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A+B,KAAK,IAAI,IAAI,qBAAqB,KAAM,IAAI,IAAI,+BAA+B,KAAK,SAAS,EAAE;oBAC9H,MAAM,CAAC,mEAAmE,CAAC,CAAA;iBAC9E;qBAAI;oBAED,IAAG,qBAAqB,KAAK,IAAI,EAAC;wBAC9B,qBAAqB,CAAC,cAAc,CAAC,cAAc,GAAG;4BAClD,MAAM,CAAC,4CAA4C,CAAC,CAAA;wBAExD,CAAC,CAAA;qBACJ;yBAAI;wBAEL,+BAA+B,CAAC,eAAe,CAAC,cAAc,GAAG,UAAU,OAAY;4BACnF,MAAM,CAAC,wCAAwC,CAAC,CAAA;wBACpD,CAAC,CAAA;wBACD,+BAA+B,CAAC,oBAAoB,CAAC,cAAc,GAAG,UAAU,OAAY,EAAE,QAAa;4BACvG,MAAM,CAAC,6CAA6C,CAAC,CAAA;4BACrD,QAAQ,CAAC,mBAAmB,EAAE,CAAA;wBAClC,CAAC,CAAA;qBACJ;iBACA;aACJ;YAAA,OAAO,KAAK,EAAE;gBACX,YAAY,CAAC,6CAA6C,CAAC,CAAA;gBAC3D,IAAG,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,kCAAkC,CAAC,EAAC;oBAC9D,YAAY,CAAC,qBAAqB,GAAC,KAAK,CAAC,CAAC;iBAC7C;gBACD,qCAAqC;aACxC;SAEJ;IACL,CAAC,CAAC,CAAA;AAIN,CAAC"}
✄
import { devlog, devlog_error, log } from "../util/log.js";
import { getAndroidVersion } from "../util/process_infos.js";
import { OpenSSL_BoringSSL } from "../ssl_lib/openssl_boringssl.js";
import { socket_library } from "./android_agent.js";
import { isSymbolAvailable } from "../shared/shared_functions.js";
export class Consycrypt_BoringSSL_Android extends OpenSSL_BoringSSL {
    constructor(moduleName, socket_library, is_base_hook) {
        var library_method_mapping = {};
        library_method_mapping[`*${moduleName}*`] = ["SSL_CTX_new", "SSL_CTX_set_keylog_callback"];
        super(moduleName, socket_library, is_base_hook, library_method_mapping);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    install_conscrypt_tls_keys_callback_hook() {
        this.SSL_CTX_set_keylog_callback = new NativeFunction(this.addresses[this.module_name]["SSL_CTX_set_keylog_callback"], "void", ["pointer", "pointer"]);
        var instance = this;
        if (isSymbolAvailable(this.module_name, "SSL_CTX_new")) {
            Interceptor.attach(this.addresses[this.module_name]["SSL_CTX_new"], {
                onLeave: function (retval) {
                    const ssl = new NativePointer(retval);
                    if (!ssl.isNull()) {
                        instance.SSL_CTX_set_keylog_callback(ssl, OpenSSL_BoringSSL.keylog_callback);
                    }
                }
            });
        }
    }
    execute_conscrypt_hooks() {
        this.install_conscrypt_tls_keys_callback_hook();
    }
}
export function conscrypt_native_execute(moduleName, is_base_hook) {
    var boring_ssl = new Consycrypt_BoringSSL_Android(moduleName, socket_library, is_base_hook);
    try {
        boring_ssl.execute_conscrypt_hooks();
    }
    catch (error_msg) {
        devlog(`conscrypt_execute error: ${error_msg}`);
    }
    if (is_base_hook) {
        try {
            const init_addresses = boring_ssl.addresses[moduleName];
            // ensure that we only add it to global when we are not 
            if (Object.keys(init_addresses).length > 0) {
                global.init_addresses[moduleName] = init_addresses;
            }
        }
        catch (error_msg) {
            devlog(`conscrypt_execute base-hook error: ${error_msg}`);
        }
    }
}
function findProviderInstallerImplFromClassloaders(currentClassLoader, backupImplementation) {
    var providerInstallerImpl = null;
    var classLoaders = Java.enumerateClassLoadersSync();
    for (var cl of classLoaders) {
        try {
            var classFactory = Java.ClassFactory.get(cl);
            providerInstallerImpl = classFactory.use("com.google.android.gms.common.security.ProviderInstallerImpl");
            break;
        }
        catch (error) {
            if (!error.toString().includes("java.lang.ClassNotFoundException")) {
                devlog_error("Error in hooking ProviderInstallerImpl (findProviderInstallerImplFromClassloaders):");
                devlog_error("Error message: (findProviderInstallerImplFromClassloaders): " + error);
            }
            providerInstallerImpl = null;
            // On error we return null
        }
    }
    var version = getAndroidVersion();
    if (version <= 12) {
        //Revert the implementation to avoid an infinitloop of "Loadclass"
        currentClassLoader.loadClass.overload("java.lang.String").implementation = backupImplementation;
    }
    return providerInstallerImpl;
}
function findProviderInstallerFromClassloaders(currentClassLoader, backupImplementation) {
    var providerInstaller = null;
    var classLoaders = Java.enumerateClassLoadersSync();
    for (var cl of classLoaders) {
        try {
            var classFactory = Java.ClassFactory.get(cl);
            providerInstaller = classFactory.use("com.google.android.gms.security.ProviderInstaller");
            break;
        }
        catch (error) {
            if (!error.toString().includes("java.lang.ClassNotFoundException")) {
                devlog_error("Error in hooking ProviderInstallerImpl (findProviderInstallerFromClassloaders):");
                devlog_error("Error message (findProviderInstallerFromClassloaders): " + error);
            }
            providerInstaller = null;
            // On error we return null
        }
    }
    var version = getAndroidVersion();
    //log("is here the error")
    //log(typeof version)
    if (version <= 12) {
        //Revert the implementation to avoid an infinitloop of "Loadclass"
        currentClassLoader.loadClass.overload("java.lang.String").implementation = backupImplementation;
    }
    return providerInstaller;
}
export function execute() {
    //We have to hook multiple entrypoints: ProviderInstallerImpl and ProviderInstaller
    Java.perform(function () {
        //Part one: Hook ProviderInstallerImpl
        var javaClassLoader = Java.use("java.lang.ClassLoader");
        var backupImplementation = javaClassLoader.loadClass.overload("java.lang.String").implementation;
        //The classloader for ProviderInstallerImpl might not be present on startup, so we hook the loadClass method.  
        javaClassLoader.loadClass.overload("java.lang.String").implementation = function (className) {
            let retval = this.loadClass(className);
            if (className.endsWith("ProviderInstallerImpl")) {
                log("Process is loading ProviderInstallerImpl");
                var providerInstallerImpl = findProviderInstallerImplFromClassloaders(javaClassLoader, backupImplementation);
                if (providerInstallerImpl === null) {
                    log("ProviderInstallerImpl could not be found, although it has been loaded");
                }
                else {
                    providerInstallerImpl.insertProvider.implementation = function () {
                        log("ProviderinstallerImpl redirection/blocking");
                    };
                }
            }
            return retval;
        };
        //Part two: Hook Providerinstaller
        try {
            var providerInstaller = Java.use("com.google.android.gms.security.ProviderInstaller");
            providerInstaller.installIfNeeded.implementation = function (context) {
                devlog("Providerinstaller redirection/blocking");
            };
            providerInstaller.installIfNeededAsync.implementation = function (context, callback) {
                devlog("ProviderinstallerAsncy redirection/blocking");
                callback.onProviderInstalled();
            };
        }
        catch (error) {
            try {
                // probably class wasn't loaded by the app's main class loader therefore we load it
                var providerInstallerImpl = null;
                var providerInstallerFromClassloder = findProviderInstallerFromClassloaders(javaClassLoader, backupImplementation);
                if (providerInstallerFromClassloder === null) {
                    providerInstallerImpl = findProviderInstallerImplFromClassloaders(javaClassLoader, backupImplementation);
                }
                if (providerInstallerFromClassloder === null && providerInstallerImpl === null || providerInstallerFromClassloder === undefined) {
                    devlog("ProviderInstaller could not be found, although it has been loaded");
                }
                else {
                    if (providerInstallerImpl !== null) {
                        providerInstallerImpl.insertProvider.implementation = function () {
                            devlog("ProviderinstallerImpl redirection/blocking");
                        };
                    }
                    else {
                        providerInstallerFromClassloder.installIfNeeded.implementation = function (context) {
                            devlog("Providerinstaller redirection/blocking");
                        };
                        providerInstallerFromClassloder.installIfNeededAsync.implementation = function (context, callback) {
                            devlog("ProviderinstallerAsync redirection/blocking");
                            callback.onProviderInstalled();
                        };
                    }
                }
            }
            catch (error) {
                devlog_error("Some error in hooking the Providerinstaller");
                if (!error.toString().includes("java.lang.ClassNotFoundException")) {
                    devlog_error("[-] Error message: " + error);
                }
                // As it is not available, do nothing
            }
        }
    });
}
✄
{"version":3,"file":"cronet_android.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/android/cronet_android.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAC,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAClG,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAGxC,MAAM,OAAO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AAA,OAAM,SAAS,EAAC;QACb,MAAM,CAAC,yBAAyB,SAAS,EAAE,CAAC,CAAA;KAC/C;IAED,IAAI,YAAY,EAAE;QACd,IAAI;YACA,MAAM,cAAc,GAAG,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;YACpD,wDAAwD;YACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;gBACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;aAC/D;SACJ;QAAA,OAAM,SAAS,EAAC;YACb,MAAM,CAAC,mCAAmC,SAAS,EAAE,CAAC,CAAA;SACzD;KACJ;AAEL,CAAC"}
✄
import { Cronet } from "../ssl_lib/cronet.js";
import { socket_library } from "./android_agent.js";
import { PatternBasedHooking, get_CPU_specific_pattern } from "../shared/pattern_based_hooking.js";
import { patterns, isPatternReplaced } from "../ssl_log.js";
import { devlog } from "../util/log.js";
export class Cronet_Android extends Cronet {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library, is_base_hook);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.default_pattern = {
            "x64": {
                primary: "41 57 41 56 41 55 41 54 53 48 83 EC ?? 48 8B 47 68 48 83 B8 20 02 00 00 00 0F 84",
                fallback: "55 41 57 41 56 41 54 53 48 83 EC 30 48 8B 47 68 48 83 B8 20 02 00 00 00 0F 84" // Fallback pattern
            },
            "x86": {
                primary: "55 53 57 56 83 EC 4C E8 00 00 00 00 5B 81 C3 A9 CB 13 00 8B 44 24 60 8B 40 34",
                fallback: "55 53 57 56 83 EC 4C E8 00 00 00 00 5B 81 C3 A9 CB 13 00 8B 44 24 60" // Fallback pattern
            },
            "arm64": {
                primary: "3F 23 03 D5 FF ?3 01 D1 FD 7B 0? A9 F6 57 0? A9 F4 4F 0? A9 FD ?3 0? 91 08 34 40 F9 08 1? 41 F9 ?8 0? 00 B4",
                //fallback: "3F 23 03 D5 FF 03 02 D1 FD 7B 04 A9 F7 2B 00 F9 F6 57 06 A9 F4 4F 07 A9 FD 03 01 91 08 34 40 F9 08 ?? 41 F9 ?8 0? 00 B4",  // old Fallback pattern
                fallback: "3F 23 03 D5 FF ?3 02 D1 FD 7B 0? A9 F? ?? 0? ?9 F6 57 0? A9 F4 4F 0? A9 FD ?3 01 91 08 34 40 F9 08 ?? 41 F9 ?8 ?? 00 B4",
                second_fallback: "3F 23 03 D5 FF C3 05 D1 FD 7B 14 A9 FC 57 15 A9 F4 4F 16 A9 FD 03 05 91 54 D0 3B D5 88 16 40 F9 40 00 80 52 F3",
            },
            "arm": {
                primary: "2D E9 F0 43 89 B0 04 46 40 6B D0 F8 2C 01 00 28 49 D0",
                fallback: "2D E9 F0 41 86 B0 04 46 40 6B D0 F8 30 01 00 28 53 D0" // Fallback pattern
            }
        };
    }
    getSoName(modulePath) {
        // Match the last segment ending in “.so”
        const m = modulePath.match(/([^\/\\]+\.so)$/);
        return m ? m[1] : modulePath;
    }
    install_key_extraction_hook() {
        let cronetModule = Process.findModuleByName(this.module_name);
        if (cronetModule === null) {
            const soName = this.getSoName(this.module_name);
            cronetModule = Process.findModuleByName(soName);
            if (cronetModule === null) {
                devlog("[-] Cronet Error: Unable to find module: " + this.module_name);
                return;
            }
        }
        const hooker = new PatternBasedHooking(cronetModule);
        if (isPatternReplaced()) {
            devlog("Hooking libcronet functions by patterns from JSON file");
            hooker.hook_DumpKeys(this.module_name, "libcronet.so", patterns, (args) => {
                devlog("Installed ssl_log_secret() hooks using byte patterns.");
                this.dumpKeys(args[1], args[0], args[2]); // Unpack args into dumpKeys
            });
        }
        else {
            // This are the default patterns for hooking ssl_log_secret in BoringSSL inside Cronet
            hooker.hookModuleByPattern(get_CPU_specific_pattern(this.default_pattern), (args) => {
                devlog("Installed ssl_log_secret() hooks using byte patterns.");
                this.dumpKeys(args[1], args[0], args[2]); // Hook args passed to dumpKeys
            });
        }
        return hooker;
    }
    // instead of relying on pattern we check if the target module has a symbol of ssl_log_secret()
    execute_symbol_based_hooking(hooker) {
        if (hooker === undefined || hooker === null) {
            devlog("[-] Error: Hooker is undefined.");
            return;
        }
        // Capture the dumpKeys function with the correct 'this'
        let dumpKeysFunc = this.dumpKeys.bind(this);
        if (this.module_name.includes("libwarp_mobile")) {
            console.log("[!] The extracted CLIENT_RANDOM from libwarp_mobile.so is currently not working correctly.");
        }
        if (hooker.no_hooking_success) {
            let symbols = Process.getModuleByName(this.module_name).enumerateSymbols().filter(exports => exports.name.toLowerCase().includes("ssl_log"));
            if (symbols.length > 0) {
                devlog("Installed ssl_log_secret() hooks using sybmols.");
                try {
                    Interceptor.attach(symbols[0].address, {
                        onEnter: function (args) {
                            dumpKeysFunc(args[1], args[0], args[2]);
                        }
                    });
                }
                catch (e) {
                    // right now we ingore error's here
                }
            }
        }
    }
    execute_hooks() {
        // hooking ssl_log_secret() from BoringSSL
        let hooker_instance = this.install_key_extraction_hook();
        return hooker_instance;
    }
}
export function cronet_execute(moduleName, is_base_hook) {
    let cronet = new Cronet_Android(moduleName, socket_library, is_base_hook);
    try {
        let hooker = cronet.execute_hooks();
        // wait 1 sec before we continue
        setTimeout(function () {
            try {
                cronet.execute_symbol_based_hooking(hooker);
            }
            catch (e) {
                devlog("[-] Error in cronet.execute_symbol_based_hooking: " + e);
            }
        }, 1000);
    }
    catch (error_msg) {
        devlog(`cronet_execute error: ${error_msg}`);
    }
    if (is_base_hook) {
        try {
            const init_addresses = cronet.addresses[moduleName];
            // ensure that we only add it to global when we are not 
            if (Object.keys(init_addresses).length > 0) {
                global.init_addresses[moduleName] = init_addresses;
            }
        }
        catch (error_msg) {
            devlog(`cronet_execute base-hook error: ${error_msg}`);
        }
    }
}
✄
{"version":3,"file":"flutter_android.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/android/flutter_android.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAA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U_specific_pattern } from "../shared/pattern_based_hooking.js";
import { patterns, isPatternReplaced } from "../ssl_log.js";
import { devlog, devlog_error } from "../util/log.js";
export class Flutter_Android extends Flutter {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library, is_base_hook);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.default_pattern = {
            "x64": {
                primary: "55 41 57 41 56 41 55 41 54 53 48 83 EC 48 48 8B 47 68 48 83 B8 20 02 00 00 00 0F 84 FE 00 00 00",
                fallback: "55 41 57 41 56 41 55 41 54 53 48 83 EC 38 48 8B 47 68 48 83 B8 10 02 00 00 00 0F 84 19 01 00 00" // Fallback pattern
            },
            "x86": {
                primary: "55 53 57 56 83 EC 4C E8 00 00 00 00 5B 81 C3 A9 CB 13 00 8B 44 24 60 8B 40 34",
                fallback: "55 89 E5 53 57 56 83 E4 F0 83 EC 50 E8 00 00 00 00" // Fallback pattern
            },
            "arm64": {
                primary: "E0 03 13 AA E2 03 16 AA 6D 62 FA 17",
                fallback: "FF 83 01 D1 F6 1B 00 F9 F5 53 04 A9 F3 7B 05 A9 08 34 40 F9 08 09 41 F9 68 07 00 B4" // Fallback pattern
            },
            "arm": {
                primary: "2D E9 F0 43 89 B0 04 46 40 6B D0 F8 2C 01 00 28 49 D0",
                fallback: "2D E9 F0 41 86 B0 04 46 40 6B D0 F8 30 01 00 28 53 D0" // Fallback pattern
            }
        };
    }
    install_key_extraction_hook() {
        const flutterModule = Process.findModuleByName(this.module_name);
        const hooker = new PatternBasedHooking(flutterModule);
        if (isPatternReplaced()) {
            devlog("Hooking libflutter functions by patterns from JSON file");
            hooker.hook_DumpKeys(this.module_name, "libflutter.so", patterns, (args) => {
                this.dumpKeys(args[1], args[0], args[2]); // Unpack args into dumpKeys
            });
        }
        else {
            // This are the default patterns for hooking ssl_log_secret in BoringSSL inside Flutter
            hooker.hookModuleByPattern(get_CPU_specific_pattern(this.default_pattern), (args) => {
                this.dumpKeys(args[1], args[0], args[2]); // Hook args passed to dumpKeys
            });
        }
    }
    execute_hooks() {
        this.install_key_extraction_hook();
    }
}
export function flutter_execute(moduleName, is_base_hook) {
    var flutter = new Flutter_Android(moduleName, socket_library, is_base_hook);
    try {
        flutter.execute_hooks();
    }
    catch (error_msg) {
        devlog_error(`flutter_execute error: ${error_msg}`);
    }
    if (is_base_hook) {
        try {
            const init_addresses = flutter.addresses[moduleName];
            // ensure that we only add it to global when we are not 
            if (Object.keys(init_addresses).length > 0) {
                global.init_addresses[moduleName] = init_addresses;
            }
        }
        catch (error_msg) {
            devlog_error(`flutter_execute base-hook error: ${error_msg}`);
        }
    }
}
✄
{"version":3,"file":"gnutls_android.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/android/gnutls_android.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAExC,MAAM,OAAO,YAAa,SAAQ,MAAM;IAEpC,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,KAAK,CAAC,UAAU,EAAC,cAAc,CAAC,CAAC;QADlB,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAElE,CAAC;IAGD,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;QACnC,IAAI,CAAC,4BAA4B,EAAE,CAAC;QACpC,IAAI,CAAC,8BAA8B,EAAE,CAAC;IAC1C,CAAC;IAED,8BAA8B;QAC1B,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,aAAa,CAAC,EACtE;YACI,OAAO,EAAE,UAAU,IAAS;gBACxB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;YAC1B,CAAC;YACD,OAAO,EAAE,UAAU,MAAW;gBAC1B,MAAM,CAAC,mCAAmC,GAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBACzD,MAAM,CAAC,kCAAkC,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,MAAM,CAAC,eAAe,CAAC,CAAA;YAEjG,CAAC;SACJ,CAAC,CAAA;IAEF,CAAC;CACJ;AAGD,MAAM,UAAU,cAAc,CAAC,UAAiB,EAAE,YAAqB;IACnE,IAAI,UAAU,GAAG,IAAI,YAAY,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IAC3E,UAAU,CAAC,aAAa,EAAE,CAAC;IAE3B,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,UAAU,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACxD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AAEL,CAAC"}
✄
import { GnuTLS } from "../ssl_lib/gnutls.js";
import { socket_library } from "./android_agent.js";
import { devlog } from "../util/log.js";
export class GnuTLS_Linux extends GnuTLS {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        this.install_tls_keys_callback_hook();
    }
    install_tls_keys_callback_hook() {
        Interceptor.attach(this.addresses[this.module_name]["gnutls_init"], {
            onEnter: function (args) {
                this.session = args[0];
            },
            onLeave: function (retval) {
                devlog("[!] Logging session information: " + this.session);
                GnuTLS.gnutls_session_set_keylog_function(this.session.readPointer(), GnuTLS.keylog_callback);
            }
        });
    }
}
export function gnutls_execute(moduleName, is_base_hook) {
    var gnutls_ssl = new GnuTLS_Linux(moduleName, socket_library, is_base_hook);
    gnutls_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = gnutls_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"mbedTLS_android.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/android/mbedTLS_android.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,MAAM,OAAO,gBAAiB,SAAQ,QAAQ;IAE1C,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,KAAK,CAAC,UAAU,EAAC,cAAc,CAAC,CAAC;QADlB,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAElE,CAAC;IAED;;;;;;MAME;IACF,8BAA8B;QAC1B,8BAA8B;IAClC,CAAC;IAED,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;QACnC,IAAI,CAAC,4BAA4B,EAAE,CAAC;IACxC,CAAC;CAEJ;AAGD,MAAM,UAAU,eAAe,CAAC,UAAiB,EAAE,YAAqB;IACpE,IAAI,WAAW,GAAG,IAAI,gBAAgB,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IAChF,WAAW,CAAC,aAAa,EAAE,CAAC;IAE5B,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,WAAW,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACzD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AAGL,CAAC"}
✄
import { mbed_TLS } from "../ssl_lib/mbedTLS.js";
import { socket_library } from "./android_agent.js";
export class mbed_TLS_Android extends mbed_TLS {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    /*
    SSL_CTX_set_keylog_callback not exported by default on windows.

    We need to find a way to install the callback function for doing that

    Alternatives?:SSL_export_keying_material, SSL_SESSION_get_master_key
    */
    install_tls_keys_callback_hook() {
        // install hooking for windows
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
    }
}
export function mbedTLS_execute(moduleName, is_base_hook) {
    var mbedTLS_ssl = new mbed_TLS_Android(moduleName, socket_library, is_base_hook);
    mbedTLS_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = mbedTLS_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"mono_btls_android.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/android/mono_btls_android.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAC,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAClG,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AAC3D,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAGtD,MAAM,OAAO,iBAAkB,SAAQ,SAAS;IAG5C,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,KAAK,CAAC,UAAU,EAAC,cAAc,EAAC,YAAY,CAAC,CAAC;QAD/B,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;QAG9D,IAAI,CAAC,eAAe,GAAG;Y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I,CAAC,2BAA2B,EAAE,CAAC;IACvC,CAAC;CAEJ;AAGD,MAAM,UAAU,iBAAiB,CAAC,UAAiB,EAAE,YAAqB;IACtE,IAAI,SAAS,GAAG,IAAI,iBAAiB,CAAC,UAAU,EAAC,cAAc,EAAC,YAAY,CAAC,CAAC;IAC9E,IAAI;QACA,SAAS,CAAC,aAAa,EAAE,CAAC;KAC7B;IAAA,OAAM,SAAS,EAAC;QACb,YAAY,CAAC,4BAA4B,SAAS,EAAE,CAAC,CAAA;KACxD;IAED,IAAI,YAAY,EAAE;QACd,IAAI;YACA,MAAM,cAAc,GAAG,SAAS,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;YACvD,wDAAwD;YACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;gBACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;aAC/D;SACJ;QAAA,OAAM,SAAS,EAAC;YACb,YAAY,CAAC,sCAAsC,SAAS,EAAE,CAAC,CAAA;SAClE;KACJ;AAEL,CAAC"}
✄
import { Mono_BTLS } from "../ssl_lib/monobtls.js";
import { socket_library } from "./android_agent.js";
import { PatternBasedHooking, get_CPU_specific_pattern } from "../shared/pattern_based_hooking.js";
import { patterns, isPatternReplaced } from "../ssl_log.js";
import { devlog, devlog_error } from "../util/log.js";
export class Mono_BTLS_Android extends Mono_BTLS {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library, is_base_hook);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.default_pattern = {
            "x64": {
                primary: "55 41 57 41 56 41 54 53 49 89 D4 49 89 F6 48 89 FB E8 5A F8 FF FF",
                fallback: "55 41 57 41 56 41 55 41 54 53 48 83 EC 38 48 8B 47 68 48 83 B8 10 02 00 00 00 0F 84 19 01 00 00" // Fallback pattern
            },
            "x86": {
                primary: "55 89 E5 53 57 56 83 E4 F0 83 EC 10 E8 00 00 00 00",
                fallback: "55 53 57 56 83 EC 4C E8 00 00 00 00 5B 81 C3 A9 CB 13 00 8B 44 24 60 8B 40 34" // Fallback pattern
            },
            "arm64": {
                primary: "F6 57 BD A9 F4 4F 01 A9 FD 7B 02 A9 FD 83 00 91 F3 03 02 AA F4 03 01 AA F5 03 00 AA 1F FE FF 97",
                fallback: "FF 83 01 D1 F6 1B 00 F9 F5 53 04 A9 F3 7B 05 A9 08 34 40 F9 08 09 41 F9 68 07 00 B4" // Fallback pattern
            },
            "arm": {
                primary: "F0 B5 03 AF 4D F8 04 8D 14 46 0D 46 06 46 FF F7 5F FD",
                fallback: "2D E9 F0 41 86 B0 04 46 40 6B D0 F8 30 01 00 28 53 D0" // Fallback pattern
            }
        };
    }
    install_key_extraction_hook() {
        const flutterModule = Process.findModuleByName(this.module_name);
        const hooker = new PatternBasedHooking(flutterModule);
        if (isPatternReplaced()) {
            devlog("Hooking Libmono functions by patterns from JSON file");
            hooker.hook_DumpKeys(this.module_name, "libmono-btls-shared.so", patterns, (args) => {
                this.dumpKeys(args[1], args[0], args[2]); // Unpack args into dumpKeys
            });
        }
        else {
            // This are the default patterns for hooking ssl_log_secret in BoringSSL inside Libmono
            hooker.hookModuleByPattern(get_CPU_specific_pattern(this.default_pattern), (args) => {
                this.dumpKeys(args[1], args[0], args[2]); // Hook args passed to dumpKeys
            });
        }
    }
    execute_hooks() {
        this.install_key_extraction_hook();
    }
}
export function mono_btls_execute(moduleName, is_base_hook) {
    var mono_btls = new Mono_BTLS_Android(moduleName, socket_library, is_base_hook);
    try {
        mono_btls.execute_hooks();
    }
    catch (error_msg) {
        devlog_error(`mono_btls_execute error: ${error_msg}`);
    }
    if (is_base_hook) {
        try {
            const init_addresses = mono_btls.addresses[moduleName];
            // ensure that we only add it to global when we are not 
            if (Object.keys(init_addresses).length > 0) {
                global.init_addresses[moduleName] = init_addresses;
            }
        }
        catch (error_msg) {
            devlog_error(`mono_btls_execute base-hook error: ${error_msg}`);
        }
    }
}
✄
{"version":3,"file":"nss_android.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/android/nss_android.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAExC,MAAM,OAAO,WAAY,SAAQ,GAAG;IAEhC,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,IAAI,sBAAsB,GAAqC,EAAE,CAAC;QAClE,MAAM,CAAC,iBAAiB,GAAC,UAAU,CAAC,CAAC;QACrC,sBAAsB,CAAC,IAAI,UAAU,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,SAAS,EAAE,0BAA0B,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,cAAc,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,iBAAiB,CAAC,CAAA;QAClQ,sCAAsC;QACtC,mFAAmF;QACnF,uGAAuG;QACvG,sBAAsB,CAAC,IAAI,cAAc,GAAG,CAAC,GAAG,CAAC,aAAa,EAAE,aAAa,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;QAEhG,KAAK,CAAC,UAAU,EAAC,cAAc,EAAC,sBAAsB,CAAC,CAAC;QATzC,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAUlE,CAAC;IAKD,aAAa;QACT,qCAAqC;QACrC,sCAAsC;QACtC,IAAG;YACC,MAAM,CAAC,kEAAkE,CAAC,CAAC;YAC3E,IAAI,CAAC,8BAA8B,EAAE,CAAA,CAAC,cAAc;SACvD;QAAA,OAAM,CAAC,EAAC;YACL,MAAM,CAAC,4DAA4D,CAAC,CAAC;YACrE,MAAM,CAAC,kBAAkB,GAAC,CAAC,CAAC,CAAC;SAChC;IACL,CAAC;IAED,8BAA8B;QA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W,CAAC,CAAC;oBACtC,CAAC;oBACD,OAAO,CAAC,MAAW;oBACnB,CAAC;iBACJ,CAAC,CAAC;YAEX,CAAC;YACD,OAAO,CAAC,MAAW;YACnB,CAAC;SAEJ,CAAC,CAAC;IAGX,CAAC;CAIJ;AAGD,MAAM,UAAU,WAAW,CAAC,UAAiB,EAAE,YAAqB;IAChE,IAAI,OAAO,GAAG,IAAI,WAAW,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IACvE,OAAO,CAAC,aAAa,EAAE,CAAC;IAExB,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACrD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AAEL,CAAC"}
✄
import { NSS } from "../ssl_lib/nss.js";
import { socket_library } from "./android_agent.js";
import { devlog } from "../util/log.js";
export class NSS_Android extends NSS {
    constructor(moduleName, socket_library, is_base_hook) {
        var library_method_mapping = {};
        devlog("Hooking module " + moduleName);
        library_method_mapping[`*${moduleName}*`] = ["PR_Write", "PR_Read", "PR_FileDesc2NativeHandle", "PR_GetPeerName", "PR_GetSockName", "PR_GetNameForIdentity", "PR_GetDescType", "SSL_ImportFD", "SSL_HandshakeCallback", "PK11_ExtractKeyValue", "PK11_GetKeyData"];
        // "SSL_GetSessionID" is not available
        //library_method_mapping[`*libnss.*`] = ["PK11_ExtractKeyValue", "PK11_GetKeyData"]
        //library_method_mapping["*libssl*.so"] = ["SSL_ImportFD", "SSL_GetSessionID", "SSL_HandshakeCallback"]
        library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        super(moduleName, socket_library, library_method_mapping);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    execute_hooks() {
        //this.install_plaintext_read_hook();
        //this.install_plaintext_write_hook();
        try {
            devlog("[!] NSS 1.3 Client Random working; keys are still not exported..");
            this.install_tls_keys_callback_hook(); // might fail 
        }
        catch (e) {
            devlog("Installing NSS key hooking - still early development stage");
            devlog("NSS Error code: " + e);
        }
    }
    install_tls_keys_callback_hook() {
        NSS.getDescType = new NativeFunction(this.addresses[this.module_name]['PR_GetDescType'], "int", ["pointer"]);
        // SSL Handshake Functions:
        NSS.PR_GetNameForIdentity = new NativeFunction(this.addresses[this.module_name]['PR_GetNameForIdentity'], "pointer", ["pointer"]);
        /*
                SECStatus SSL_HandshakeCallback(PRFileDesc *fd, SSLHandshakeCallback cb, void *client_data);
                more at https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/SSL_functions/sslfnc#1112702
        */
        NSS.get_SSL_Callback = new NativeFunction(this.addresses[this.module_name]["SSL_HandshakeCallback"], "int", ["pointer", "pointer", "pointer"]);
        // SSL Key helper Functions 
        NSS.PK11_ExtractKeyValue = new NativeFunction(this.addresses[this.module_name]["PK11_ExtractKeyValue"], "int", ["pointer"]);
        NSS.PK11_GetKeyData = new NativeFunction(this.addresses[this.module_name]["PK11_GetKeyData"], "pointer", ["pointer"]);
        Interceptor.attach(this.addresses[this.module_name]["SSL_ImportFD"], {
            onEnter(args) {
                this.fd = args[1];
            },
            onLeave(retval) {
                if (retval.isNull()) {
                    devlog("[-] SSL_ImportFD error: unknow null");
                    return;
                }
                var retValue = NSS.get_SSL_Callback(retval, NSS.keylog_callback, NULL);
                NSS.register_secret_callback(retval);
                // typedef enum { PR_FAILURE = -1, PR_SUCCESS = 0 } PRStatus;
                if (retValue < 0) {
                    devlog("Callback Error");
                    var getErrorText = new NativeFunction(Module.getExportByName('libnspr4.so', 'PR_GetErrorText'), "int", ["pointer"]);
                    var outbuffer = Memory.alloc(200); // max out size
                    devlog("typeof outbuffer: " + typeof outbuffer);
                    devlog("outbuffer: " + outbuffer); // should be a pointer
                    getErrorText(outbuffer.readPointer());
                    devlog("Error msg: " + outbuffer);
                }
                else {
                    devlog("[*] keylog callback successfull installed");
                }
            }
        });
        /*
            SECStatus SSL_HandshakeCallback(
                PRFileDesc *fd,
                SSLHandshakeCallback cb,
                void *client_data
            );
         */
        Interceptor.attach(this.addresses[this.module_name]["SSL_HandshakeCallback"], {
            onEnter(args) {
                this.originalCallback = args[1];
                Interceptor.attach(ptr(this.originalCallback), {
                    onEnter(args) {
                        var sslSocketFD = args[0];
                        devlog("[*] NSS keylog callback successfull installed via applications callback function");
                        NSS.ssl_RecordKeyLog(sslSocketFD);
                    },
                    onLeave(retval) {
                    }
                });
            },
            onLeave(retval) {
            }
        });
    }
}
export function nss_execute(moduleName, is_base_hook) {
    var nss_ssl = new NSS_Android(moduleName, socket_library, is_base_hook);
    nss_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = nss_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"openssl_boringssl_android.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/android/openssl_boringssl_android.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACnE,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,MAAM,OAAO,yBAA0B,SAAQ,iBAAiB;IAE5D,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,KAAK,CAAC,UAAU,EAAC,cAAc,EAAC,YAAY,CAAC,CAAC;QAD/B,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAElE,CAAC;IAED,8BAA8B;QAE1B,IAAI,CAAC,2BAA2B,GAAG,IAAI,cAAc,CAAC,IAAI,CAAC,SAAS,CA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AAU,GAAG,IAAI,yBAAyB,CAAC,UAAU,EAAC,cAAc,EAAC,YAAY,CAAC,CAAC;IACvF,IAAI;QACA,UAAU,CAAC,aAAa,EAAE,CAAC;KAC9B;IAAA,OAAM,SAAS,EAAC;QACb,MAAM,CAAC,yBAAyB,SAAS,EAAE,CAAC,CAAA;KAC/C;IAED,IAAI,YAAY,EAAE;QACd,IAAI;YACJ,MAAM,cAAc,GAAG,UAAU,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;YACxD,wDAAwD;YACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;gBACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;aAC/D;SAAC;QAAA,OAAM,SAAS,EAAC;YACd,MAAM,CAAC,mCAAmC,SAAS,EAAE,CAAC,CAAA;SACzD;KACJ;AAEL,CAAC"}
✄
import { OpenSSL_BoringSSL } from "../ssl_lib/openssl_boringssl.js";
import { devlog } from "../util/log.js";
import { socket_library } from "./android_agent.js";
export class OpenSSL_BoringSSL_Android extends OpenSSL_BoringSSL {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library, is_base_hook);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    install_tls_keys_callback_hook() {
        this.SSL_CTX_set_keylog_callback = new NativeFunction(this.addresses[this.module_name]["SSL_CTX_set_keylog_callback"], "void", ["pointer", "pointer"]);
        var instance = this;
        if (this.addresses[this.module_name]["SSL_CTX_new"] === null) {
            Interceptor.attach(this.addresses[this.module_name]["SSL_new"], {
                onEnter: function (args) {
                    instance.SSL_CTX_set_keylog_callback(args[0], OpenSSL_BoringSSL.keylog_callback);
                }
            });
        }
        else {
            Interceptor.attach(this.addresses[this.module_name]["SSL_CTX_new"], {
                onLeave: function (retval) {
                    instance.SSL_CTX_set_keylog_callback(retval, OpenSSL_BoringSSL.keylog_callback);
                }
            });
        }
        // In case a callback is set by the application, we attach to this callback instead
        // Only succeeds if SSL_CTX_new is available
        let setter_address = ObjC.available ? "SSL_CTX_set_info_callback" : "SSL_CTX_set_keylog_callback";
        Interceptor.attach(this.addresses[this.module_name][setter_address], {
            onEnter: function (args) {
                let callback_func = args[1];
                Interceptor.attach(callback_func, {
                    onEnter: function (args) {
                        var message = {};
                        message["contentType"] = "keylog";
                        message["keylog"] = args[1].readCString();
                        send(message);
                    }
                });
            }
        });
    }
    install_conscrypt_tls_keys_callback_hook() {
        try {
            this.SSL_CTX_set_keylog_callback = new NativeFunction(this.addresses[this.module_name]["SSL_CTX_set_keylog_callback"], "void", ["pointer", "pointer"]);
            var instance = this;
            Interceptor.attach(this.addresses[this.module_name]["SSL_CTX_new"], {
                onLeave: function (retval) {
                    const ssl = new NativePointer(retval);
                    if (!ssl.isNull()) {
                        instance.SSL_CTX_set_keylog_callback(ssl, OpenSSL_BoringSSL.keylog_callback);
                    }
                }
            });
        }
        catch (e) {
            // right now this will sillently fail
        }
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        this.install_tls_keys_callback_hook();
        this.install_conscrypt_tls_keys_callback_hook();
        this.install_extended_hooks();
    }
    execute_conscrypt_hooks() {
        this.install_conscrypt_tls_keys_callback_hook();
    }
}
export function boring_execute(moduleName, is_base_hook) {
    var boring_ssl = new OpenSSL_BoringSSL_Android(moduleName, socket_library, is_base_hook);
    try {
        boring_ssl.execute_hooks();
    }
    catch (error_msg) {
        devlog(`boring_execute error: ${error_msg}`);
    }
    if (is_base_hook) {
        try {
            const init_addresses = boring_ssl.addresses[moduleName];
            // ensure that we only add it to global when we are not 
            if (Object.keys(init_addresses).length > 0) {
                global.init_addresses[moduleName] = init_addresses;
            }
        }
        catch (error_msg) {
            devlog(`boring_execute base-hook error: ${error_msg}`);
        }
    }
}
✄
{"version":3,"file":"pattern_android.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/android/pattern_android.ts"],"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AC,UAAU,CAAC,CAAC;oBAC7D,wDAAwD;oBACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;wBACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;qBAC/D;iBACJ;gBAAA,OAAM,SAAS,EAAC;oBACb,MAAM,CAAC,oCAAoC,SAAS,EAAE,CAAC,CAAA;iBAC1D;aACJ;KACR;AAIL,CAAC"}
✄
import { Cronet } from "../ssl_lib/cronet.js";
import { socket_library } from "./android_agent.js";
import { PatternBasedHooking } from "../shared/pattern_based_hooking.js";
import { patterns, isPatternReplaced } from "../ssl_log.js";
import { devlog } from "../util/log.js";
import { rustls_execute } from "./rustls_android.js";
export class Pattern_Android extends Cronet {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library, is_base_hook);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    install_key_extraction_hook() {
        if (isPatternReplaced) {
            const patternModuleName = Process.findModuleByName(this.module_name);
            const hooker = new PatternBasedHooking(patternModuleName);
            hooker.hook_DumpKeys(this.module_name, this.module_name, patterns, (args) => {
                devlog(`Installed ssl_log_secret() hooks using byte patterns for module ${this.module_name}`);
                this.dumpKeys(args[1], args[0], args[2]); // Unpack args into dumpKeys
            });
            return hooker;
        }
        else {
            return null;
        }
    }
    // instead of relying on pattern we check if the target module has a symbol of ssl_log_secret()
    execute_symbol_based_hooking(hooker) {
        // Capture the dumpKeys function with the correct 'this'
        let dumpKeysFunc = this.dumpKeys.bind(this);
        if (hooker.no_hooking_success) {
            let symbols = Process.getModuleByName(this.module_name).enumerateSymbols().filter(exports => exports.name.toLowerCase().includes("ssl_log"));
            if (symbols.length > 0) {
                devlog("Installed ssl_log_secret() hooks using sybmols.");
                try {
                    Interceptor.attach(symbols[0].address, {
                        onEnter: function (args) {
                            dumpKeysFunc(args[1], args[0], args[2]);
                        }
                    });
                }
                catch (e) {
                    // right now we ingore error's here
                }
            }
        }
    }
    execute_boring_ssl_log_secret_hooks() {
        // hooking ssl_log_secret() from BoringSSL
        let hooker_instance = this.install_key_extraction_hook();
        return hooker_instance;
    }
}
export function pattern_execute(moduleName, is_base_hook) {
    switch (true) {
        case moduleName.includes("boringssl"):
            let pattern_BoringSSL = new Pattern_Android(moduleName, socket_library, is_base_hook);
            try {
                let hooker = pattern_BoringSSL.execute_boring_ssl_log_secret_hooks();
                if (hooker != null) {
                    // wait 1 sec before we continue
                    setTimeout(function () {
                        pattern_BoringSSL.execute_symbol_based_hooking(hooker);
                    }, 1000);
                }
            }
            catch (error_msg) {
                devlog(`pattern_execute error: ${error_msg}`);
            }
            if (is_base_hook) {
                try {
                    const init_addresses = pattern_BoringSSL.addresses[moduleName];
                    // ensure that we only add it to global when we are not 
                    if (Object.keys(init_addresses).length > 0) {
                        global.init_addresses[moduleName] = init_addresses;
                    }
                }
                catch (error_msg) {
                    devlog(`pattern_execute base-hook error: ${error_msg}`);
                }
            }
            break;
        case moduleName.includes("rustls"):
            rustls_execute(moduleName, is_base_hook);
            break;
        default:
            devlog(`Unsupported Module: ${moduleName}! Trying to hook boringssl (default) with patterns!`);
            let pattern_Default = new Pattern_Android(moduleName, socket_library, is_base_hook);
            try {
                let hooker = pattern_Default.execute_boring_ssl_log_secret_hooks();
                if (hooker != null) {
                    // wait 1 sec before we continue
                    setTimeout(function () {
                        pattern_Default.execute_symbol_based_hooking(hooker);
                    }, 1000);
                }
            }
            catch (error_msg) {
                devlog(`pattern_execute error: ${error_msg}`);
            }
            if (is_base_hook) {
                try {
                    const init_addresses = pattern_Default.addresses[moduleName];
                    // ensure that we only add it to global when we are not 
                    if (Object.keys(init_addresses).length > 0) {
                        global.init_addresses[moduleName] = init_addresses;
                    }
                }
                catch (error_msg) {
                    devlog(`pattern_execute base-hook error: ${error_msg}`);
                }
            }
    }
}
✄
{"version":3,"file":"rustls_android.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap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E,YAAY,CAAC,CAAC;IAC1E,IAAG,sBAAsB,CAAC,UAAU,CAAC,EAAC;QAClC,MAAM,CAAC,wCAAwC,CAAC,CAAC;QACjD,MAAM,CAAC,aAAa,EAAE,CAAC;KAC1B;SAAI;QACD,MAAM,CAAC,yCAAyC,CAAC,CAAC;QAClD,MAAM,CAAC,qBAAqB,EAAE,CAAC;KAClC;IAGD,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACpD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { socket_library } from "./android_agent.js";
import { RusTLS } from "../ssl_lib/rustls.js";
import { devlog } from "../util/log.js";
import { hasMoreThanFiveExports } from "../shared/shared_functions.js";
import { PatternBasedHooking, get_CPU_specific_pattern } from "../shared/pattern_based_hooking.js";
import { patterns, isPatternReplaced } from "../ssl_log.js";
export class Rustls_Android extends RusTLS {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library, is_base_hook);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        /*
        used for the librustls_android_13.so and its variants
        */
        this.default_pattern_tls13 = {
            "x64": {
                //primary:  "41 57 41 56 41 55 41 54 53 48 83 EC ?? 48 8B 47 68 48 83 B8 20 02 00 00 00 0F 84", // Primary pattern
                primary: "55 41 57 41 56 41 55 41 54 53 48 81 EC C8 00 00 00 4D 89 CD 4C 89 44 24 10 48 89 4C 24 18 49 89 D6 49 89 F4 48 89 FB 0F B6 C1 C1 E0 03 48 8D",
                fallback: "55 41 57 41 56 41 55 41 54 53 48 81 EC C8 00 00 00 4D 89 CD 4C 89 44 24 10 48 89 4C" // Fallback pattern
            },
            "x86": {
                primary: "55 53 57 56 83 EC 4C E8 00 00 00 00 5B 81 C3 A9 CB 13 00 8B 44 24 60 8B 40 34",
                fallback: "55 53 57 56 83 EC 4C E8 00 00 00 00 5B 81 C3 A9 CB 13 00 8B 44 24 60" // Fallback pattern
            },
            "arm64": {
                primary: "FF 83 04 D1 FD 7B 0C A9 FC 6F 0D A9 FA 67 0E A9 F8 5F 0F A9 F6 57 10 A9 F4 4F 11 A9 F6 03 03 2A ?8 0? 00 ?0 08 ?1 ?? 91 C9 1E 40",
                fallback: "FF 83 04 D1 FD 7B 0C A9 FC 6F 0D A9 FA 67 0E A9 F8 5F 0F A9 F6 57 10 A9 F4 4F 11 A9 F6 03 03 2A ?8 0? 00 ?0 08" // Fallback pattern
            },
            "arm": {
                primary: "2D E9 F0 43 89 B0 04 46 40 6B D0 F8 2C 01 00 28 49 D0",
                fallback: "2D E9 F0 41 86 B0 04 46 40 6B D0 F8 30 01 00 28 53 D0" // Fallback pattern
            }
        };
        /*
       used for the librustls_android_13_ex.so and its variants
       */
        this.default_pattern_ex_tls13 = {
            "x64": {
                //primary:  "41 57 41 56 41 55 41 54 53 48 83 EC ?? 48 8B 47 68 48 83 B8 20 02 00 00 00 0F 84", // Primary pattern
                primary: "55 41 57 41 56 41 55 41 54 53 48 81 EC C8 00 00 00 4D 89 CD 4C 89 44 24 10 48 89 4C 24 18 49 89 D6 49 89 F4 48 89 FB 0F B6 C1 C1 E0 03 48 8D",
                fallback: "55 41 57 41 56 41 55 41 54 53 48 81 EC C8 00 00 00 4D 89 CD 4C 89 44 24 10 48 89 4C" // Fallback pattern
            },
            "x86": {
                primary: "55 53 57 56 83 EC 4C E8 00 00 00 00 5B 81 C3 A9 CB 13 00 8B 44 24 60 8B 40 34",
                fallback: "55 53 57 56 83 EC 4C E8 00 00 00 00 5B 81 C3 A9 CB 13 00 8B 44 24 60" // Fallback pattern
            },
            "arm64": {
                primary: "FF 83 04 D1 FD 7B 0C A9 FC 6F 0D A9 FA 67 0E A9 F8 5F 0F A9 F6 57 10 A9 F4 4F 11 A9 F6 03 03 2A 88 0C 00 F0 08 E1 3B 91 C9 1E 40",
                fallback: "FF 83 04 D1 FD 7B 0C A9 FC 6F 0D A9 FA 67 0E A9 F8 5F 0F A9 F6 57 10 A9 F4 4F 11 A9 F6 03 03 2A 88 0C 00 F0 08 E1" // Fallback pattern
            },
            "arm": {
                primary: "2D E9 F0 43 89 B0 04 46 40 6B D0 F8 2C 01 00 28 49 D0",
                fallback: "2D E9 F0 41 86 B0 04 46 40 6B D0 F8 30 01 00 28 53 D0" // Fallback pattern
            }
        };
        // FF 83 04 D1 FD 7B 0C A9 FC 6F 0D A9 FA 67 0E A9 F8 5F 0F A9 F6 57 10 A9 F4 4F 11 A9 F6 03 03 2A E8 0B 00 90 08 E1 14 91 C9 1E 40 92 1F 20 03 D5 0A 60 8A 10 1C 79 69 F8 48 14 40 F9 FB 93 40 F9 5D 79 69 F8 F3 03 00 AA E0 03 01 AA F4 03 07 AA F5 03 06 AA F8 03 05 AA F9 03 04 AA FA 03 02 AA F7 03 01 AA 00 01 3F D6
        this.default_pattern_tls12 = {
            "x64": {
                primary: "55 41 57 41 56 41 55 41 54 53 48 81 ec 48 01 00 00 4c 89 c0 49 89 cb 49 89 d6 49 89 f7 48 89 fb 48 8b 8c 24 88 01 00 00 48 8b 94 24 80 01 00",
                fallback: "55 41 57 41 56 41 55 41 54 53 48 81 ec 48 01 00 00 4c 89 c0 49 89 cb 49 89 d6 49 89 f7 48 89 fb 48 8b 8c 24 88 01 00 00 48 8b"
            },
            "arm64": {
                primary: "FF 03 07 D1 FD 7B 19 A9 F6 57 1A A9 F4 4F 1B A9 A1 08 40 AD 03 E4 00 6F F3 03 08 AA 88 00 40 B9 EB 03 03 AA E9 03 02 AA F4 03 01 AA F5 03 00 AA E1 0B 01 AD A0 04 41 AD F6 43 02 91 E3 8F 03 AD E6 0F 00 F9 E0 03 84 3C E1 8F 02 AD",
                fallback: "FF 03 07 D1 FD 7B 19 A9 F6 57 1A A9 F4 4F 1B A9 A1 08 40 AD 03 E4 00 6F F3 03 08 AA 88 00 40 B9 EB 03 03 AA E9 03 02 AA F4 03 01 AA F5 03 00 AA E1 0B 01 AD A0 04 41 AD F6 43 02 91 E3" // Fallback pattern
            },
            "arm": {
                primary: "2D E9 F0 4F D1 B0 0A AD 8A 46 05 F1 44 07 81 46 30 21 1C 46 38 46 93 46 FB F0 A8 F9 5C 9E 28 1D 40 22 31 46 FB F0 2D FA 5B 99 DD F8 74 81 CD",
                fallback: "2D E9 F0 4F D1 B0 0A AD 8A 46 05 F1 44 07 81 46 30 21 1C 46 38 46 93 46 FB F0 A8 F9 5C 9E 28 1D 40 22 31 46 FB F0 2D FA 5B 99"
            }
        };
    }
    execute_pattern_hooks() {
        this.install_key_extraction_hook();
    }
    install_key_extraction_hook() {
        const rusTLSModule = Process.findModuleByName(this.module_name);
        const hooker = new PatternBasedHooking(rusTLSModule);
        const isEx = this.module_name.includes("_ex");
        const isX64 = Process.arch === "x64";
        this.install_key_extraction_hook_tls13(hooker, isEx, isX64);
        if (!isPatternReplaced()) {
            // Currently no support for tls12 json pattern
            this.install_key_extraction_hook_tls12(hooker, isEx, isX64);
        }
    }
    // This has been tested for x86_64 and ARM
    install_key_extraction_hook_tls12(hooker, isEx, isX64) {
        const doDumpKeysLogic = (args, retval) => {
            let client_random_ptr;
            let master_secret_ptr;
            if (Process.arch === "arm64") {
                /*
                ARM LAYOUT:
                    args[3] = 0x20 (random_size?)
                    args[5] = | client_random (32 byte) | server_random (32 byte) | padding (8 byte) |
                              | client_random (32 byte) | server_random (32 byte) | master_secret (48 byte) |
                    args[7] = some address (cannot read or attach)
                    args[8] = NULL
                    retval = status code of some kind
                */
                client_random_ptr = args[5];
                master_secret_ptr = args[5].add(136);
            }
            else {
                // works for x64
                client_random_ptr = args[6];
                // retval structure:
                // | header (8 bytes) | client_random(32 bytes) | server_random(32 bytes) | master_secret(48 bytes) |
                master_secret_ptr = retval.add(72);
            }
            this.dumpKeysFromPRF(client_random_ptr, master_secret_ptr);
        };
        // Wrapper 1: for the "normal" pattern. Only proceed if retval is null.
        const normalPatternCallback = (args, retval) => {
            if (!retval) {
                devlog("retval is null");
                return; // In case hooking is onEnter, ignore
            }
            if (!retval.isNull()) {
                //devlog("[normal pattern] [TLS 1.2] hooking triggered, retval is null. Doing work.");
                doDumpKeysLogic(args, retval);
            }
        };
        // Decide whether to hook from JSON patterns or from built-in patterns ( “_ex” vs. normal)
        if (isPatternReplaced()) {
            devlog(`[Hooking with JSON patterns onReturn] isEx = ${isEx}`);
            hooker.hook_DumpKeys(this.module_name, 
            // Pick the JSON module name based on whether it’s “ex”
            isEx ? "librustls_ex.so" : "librustls.so", patterns, normalPatternCallback, true, // onReturn so we get retval
            isX64 ? 7 : 8);
        }
        else {
            devlog(`[Hooking with built-in fallback patterns onReturn] isEx = ${isEx}`);
            hooker.hookModuleByPatternOnReturn(
            // Pick the default pattern based on whether it’s “ex”
            get_CPU_specific_pattern(isEx ? this.default_pattern_tls12 : this.default_pattern_tls12), normalPatternCallback, isX64 ? 7 : 8);
        }
    }
    install_key_extraction_hook_tls13(hooker, isEx, isX64) {
        const doDumpKeysLogic = (args, retval) => {
            // Decide offsets for client_random_ptr, key, key_len, label_enum
            let client_random_ptr;
            let key;
            let key_len;
            let label_enum;
            // tested for x86_64, and ARM64
            client_random_ptr = args[9];
            key = args[0];
            key_len = args[5].toInt32();
            label_enum = args[3].toInt32();
            this.dumpKeysFromDeriveSecrets(client_random_ptr, key, key_len, label_enum);
        };
        // Wrapper 1: for the "normal" pattern. Only proceed if retval is null.
        const normalPatternCallback = (args, retval) => {
            //devlog("[TLS 1.3] normalPatternCallback");
            if (!retval)
                return; // to ensure we don't get a runtime exception when retval is undefined
            if (retval.isNull()) {
                doDumpKeysLogic(args, retval);
            }
            else {
                if (Process.arch === "x64" || Process.arch === "arm64") {
                    doDumpKeysLogic(args, retval);
                }
            }
        };
        // Wrapper 2: for the "ex" pattern. Only proceed if retval is not null.
        const exPatternCallback = (args, retval) => {
            //devlog("[TLS 1.3] exPatternCallback");
            if (!retval)
                return; // to ensure we don't get a runtime exception when retval is undefined
            if (!retval.isNull()) {
                doDumpKeysLogic(args, retval);
            }
            else {
                //
            }
        };
        // Decide whether to hook from JSON patterns or from built-in patterns ( “_ex” vs. normal)
        if (isPatternReplaced()) {
            devlog(`[Hooking with JSON patterns onReturn] isEx = ${isEx}`);
            hooker.hook_DumpKeys(this.module_name, 
            // Pick the JSON module name based on whether it’s “ex”
            isEx ? "librustls_ex.so" : "librustls.so", patterns, isEx ? exPatternCallback : normalPatternCallback, true, // onReturn so we get retval
            isX64 ? 7 : 9);
        }
        else {
            devlog(`[Hooking with built-in fallback patterns onReturn] isEx = ${isEx}`);
            hooker.hookModuleByPatternOnReturn(
            // Pick the default pattern based on whether it’s “ex”
            get_CPU_specific_pattern(isEx ? this.default_pattern_ex_tls13 : this.default_pattern_tls13), isEx ? exPatternCallback : normalPatternCallback, isX64 ? 7 : 9);
            // Note: for ARM it seems, that normalPatternCallback is used for both client types (but it succeeds to extract the secrets)
        }
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        this.install_tls_keys_callback_hook();
    }
    // Extract the configBuilder from call to rustls_client_config_builder_new / _custom and set keyLogCB
    install_tls_keys_callback_hook() {
        RusTLS.rustls_client_config_set_key_log = new NativeFunction(this.addresses[this.moduleName]["rustls_client_config_builder_set_key_log"], 'uint32', ['pointer', 'pointer', 'pointer']);
        // Attach to both functions, which can create a config builder
        Interceptor.attach(this.addresses[this.moduleName]["rustls_client_config_builder_new"], {
            onLeave: function (retval) {
                if (retval.isNull()) {
                    devlog("Error: retval is null");
                    return;
                }
                RusTLS.rustls_client_config_set_key_log(retval, RusTLS.keyLogCB, ptr('0'));
                devlog("Attached keyLogCB to rustls_client_config_set_key_log");
            }
        });
        Interceptor.attach(this.addresses[this.moduleName]["rustls_client_config_builder_new_custom"], {
            onLeave: function (retval) {
                if (retval.isNull()) {
                    devlog("Error: retval is null");
                    return;
                }
                RusTLS.rustls_client_config_set_key_log(retval, RusTLS.keyLogCB, ptr('0'));
                devlog("Attached keyLogCB to rustls_client_config_set_key_log");
            }
        });
        // If the target sets its own Callback, Rustls.keyLogCB will be overwritten.
        // In this case we want to hook the Callback set by user.
        Interceptor.attach(this.addresses[this.moduleName]["rustls_client_config_builder_set_key_log"], {
            onEnter: function (args) {
                // Extract the Address of the new Callback
                var userCallbackAddress = args[1];
                devlog("User set CB to: " + userCallbackAddress);
                this.userCallbackAddress = userCallbackAddress;
            },
            onLeave: function (retval) {
                // Check if the Callback was set
                if (retval != 7000) {
                    // If the Callback was not set the keyLogCB has not been overwritten.
                    return;
                }
                else {
                    // In case the keyLogCB has been overwritten, we attach to it.
                    Interceptor.attach(this.userCallbackAddress, {
                        onEnter(args) {
                            devlog("Hooking user-defined callback for Rustls");
                            var message = {};
                            message["contentType"] = "keylog";
                            // Parse the arguments
                            var labelPtr = args[0];
                            var label_len = args[1].toInt32();
                            var client_random = args[2];
                            var client_random_len = args[3].toInt32();
                            var secret = args[4];
                            var secret_len = args[5].toInt32();
                            if (client_random.isNull() || client_random_len != 32) {
                                devlog("Invalid client_random: " + client_random + " or client_random_lenght: " + client_random_len);
                                return;
                            }
                            if (secret.isNull() || secret_len <= 0 || secret_len > 48) {
                                devlog("Invalid secret or secret_length");
                                return;
                            }
                            // Read the client random and secrets as strings
                            var clientRandomStr = client_random.readByteArray(client_random_len);
                            var secretStr = secret.readByteArray(secret_len);
                            var labelStr = labelPtr.readUtf8String(label_len);
                            // Convert byte arrays to hex strings for better logging
                            var clientRandomHex = Array.from(new Uint8Array(clientRandomStr)).map(b => b.toString(16).padStart(2, '0')).join('');
                            var secretHex = Array.from(new Uint8Array(secretStr)).map(b => b.toString(16).padStart(2, '0')).join('');
                            // Construct the keylog message
                            message["keylog"] = `${labelStr} ${clientRandomHex} ${secretHex}`;
                            send(message);
                            return 1;
                        }
                    });
                }
            }
        });
    }
}
export function rustls_execute(moduleName, is_base_hook) {
    var rusTLS = new Rustls_Android(moduleName, socket_library, is_base_hook);
    if (hasMoreThanFiveExports(moduleName)) {
        devlog("Trying to hook RusTLS using symbols...");
        rusTLS.execute_hooks();
    }
    else {
        devlog("Trying to hook RusTLS using patterns...");
        rusTLS.execute_pattern_hooks();
    }
    if (is_base_hook) {
        const init_addresses = rusTLS.addresses[moduleName];
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"s2ntls_android.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/android/s2ntls_android.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAG9C,MAAM,OAAO,cAAe,SAAQ,MAAM;IAEtC,YAAmB,UAAkB,EAAS,cAAsB,EAAE,YAAqB;QACvF,KAAK,CAAC,UAAU,EAAE,cAAc,CAAC,CAAC;QADnB,eAAU,GAAV,UAAU,CAAQ;QAAS,mBAAc,GAAd,cAAc,CAAQ;IAEpE,CAAC;IAED,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;QACnC,IAAI,CAAC,4BAA4B,EAAE,CAAC;QACpC,IAAI,CAAC,8BAA8B,EAAE,CAAC;IAC1C,CAAC;IAED,qDAAqD;IACrD,8BAA8B;QAE1B,MAAM,CAAC,kBAAkB,GAAG,IAAI,cAAc,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,2BAA2B,CAAC,EAAE,KAAK,EAAE,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC,CAAC;QAExJ,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,gBAAgB,CAAC,EACjE;YACA,OAAO,EAAE,UAAS,MAAW;gBAEzB,IAAI,YAAY,GAAG,GAAG,CAAC,GAAG,CAA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c,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { socket_library } from "./android_agent.js";
import { S2nTLS } from "../ssl_lib/s2ntls.js";
export class S2nTLS_Android extends S2nTLS {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        this.install_tls_keys_callback_hook();
    }
    //if set_config is called, the keylog callback is set
    install_tls_keys_callback_hook() {
        S2nTLS.s2n_set_key_log_cb = new NativeFunction(this.addresses[this.module_name]["s2n_config_set_key_log_cb"], "int", ["pointer", "pointer", "pointer"]);
        Interceptor.attach(this.addresses[this.module_name]["s2n_config_new"], {
            onLeave: function (retval) {
                let emptyPointer = ptr("0");
                S2nTLS.s2n_set_key_log_cb(retval, S2nTLS.keylog_callback, emptyPointer);
            }
        });
        // In case a callback is set by the appliction, we attach to this callback instead
        Interceptor.attach(this.addresses[this.module_name]["s2n_config_set_key_log_cb"], {
            onEnter: function (args) {
                let user_callback = args[1];
                Interceptor.attach(user_callback, {
                    onEnter: function (args) {
                        let logline = args[2];
                        let len = args[3];
                        var message = {};
                        message["contentType"] = "keylog";
                        message["keylog"] = logline.readCString(len.toInt32());
                        send(message);
                    }
                });
            }
        });
    }
}
export function s2ntls_execute(moduleName, is_base_hook) {
    var s2n_tls = new S2nTLS_Android(moduleName, socket_library, is_base_hook);
    s2n_tls.execute_hooks();
    if (is_base_hook) {
        const init_addresses = s2n_tls.addresses[moduleName];
        // ensure that we only add it to global when we are not
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"wolfssl_android.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/android/wolfssl_android.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,cAA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O,CAAC,8BAA8B,CAAC,IAAI,CAAC,OAAO,EAAE,YAAY,EAAE,uBAAuB,CAAC,CAAA;gBAC3F,IAAI,WAAW,GAAG,YAAY,CAAC,aAAa,CAAC,uBAAuB,CAAC,CAAA;gBACrE,UAAU,GAAG,GAAG,UAAU,eAAe,WAAW,CAAC,WAAW,CAAC,IAAI,CAAA;gBAGrE,IAAI,OAAO,GAA8C,EAAE,CAAA;gBAC3D,OAAO,CAAC,aAAa,CAAC,GAAG,QAAQ,CAAA;gBACjC,OAAO,CAAC,QAAQ,CAAC,GAAG,UAAU,CAAA;gBAC9B,IAAI,CAAC,OAAO,CAAC,CAAA;YAEjB,CAAC;SACJ,CAAC,CAAA;IACN,CAAC;CAGJ;AAGD,MAAM,UAAU,eAAe,CAAC,UAAiB,EAAE,YAAqB;IACpE,IAAI,QAAQ,GAAG,IAAI,eAAe,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IAC5E,QAAQ,CAAC,aAAa,EAAE,CAAC;IAEzB,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,QAAQ,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACtD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AAEL,CAAC"}
✄
import { WolfSSL } from "../ssl_lib/wolfssl.js";
import { socket_library } from "./android_agent.js";
import { toHexString } from "../shared/shared_functions.js";
export class WolfSSL_Android extends WolfSSL {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        this.install_tls_keys_callback_hook();
    }
    install_tls_keys_callback_hook() {
        WolfSSL.wolfSSL_get_client_random = new NativeFunction(this.addresses[this.module_name]["wolfSSL_get_client_random"], "int", ["pointer", "pointer", "int"]);
        WolfSSL.wolfSSL_get_server_random = new NativeFunction(this.addresses[this.module_name]["wolfSSL_get_server_random"], "int", ["pointer", "pointer", "int"]);
        //https://www.wolfssl.com/doxygen/group__Setup.html#gaf18a029cfeb3150bc245ce66b0a44758
        WolfSSL.wolfSSL_SESSION_get_master_key = new NativeFunction(this.addresses[this.module_name]["wolfSSL_SESSION_get_master_key"], "int", ["pointer", "pointer", "int"]);
        Interceptor.attach(this.addresses[this.module_name]["wolfSSL_connect"], {
            onEnter: function (args) {
                this.ssl = args[0];
            },
            onLeave: function (retval) {
                this.session = WolfSSL.wolfSSL_get_session(this.ssl);
                var keysString = "";
                //https://www.wolfssl.com/doxygen/group__Setup.html#ga927e37dc840c228532efa0aa9bbec451
                var requiredClientRandomLength = WolfSSL.wolfSSL_get_client_random(this.session, NULL, 0);
                var clientBuffer = Memory.alloc(requiredClientRandomLength);
                WolfSSL.wolfSSL_get_client_random(this.ssl, clientBuffer, requiredClientRandomLength);
                var clientBytes = clientBuffer.readByteArray(requiredClientRandomLength);
                keysString = `${keysString}CLIENT_RANDOM: ${toHexString(clientBytes)}\n`;
                //https://www.wolfssl.com/doxygen/group__Setup.html#ga987035fc600ba9e3b02e2b2718a16a6c
                var requiredServerRandomLength = WolfSSL.wolfSSL_get_server_random(this.session, NULL, 0);
                var serverBuffer = Memory.alloc(requiredServerRandomLength);
                WolfSSL.wolfSSL_get_server_random(this.ssl, serverBuffer, requiredServerRandomLength);
                var serverBytes = serverBuffer.readByteArray(requiredServerRandomLength);
                keysString = `${keysString}SERVER_RANDOM: ${toHexString(serverBytes)}\n`;
                //https://www.wolfssl.com/doxygen/group__Setup.html#gaf18a029cfeb3150bc245ce66b0a44758
                var requiredMasterKeyLength = WolfSSL.wolfSSL_SESSION_get_master_key(this.session, NULL, 0);
                var masterBuffer = Memory.alloc(requiredMasterKeyLength);
                WolfSSL.wolfSSL_SESSION_get_master_key(this.session, masterBuffer, requiredMasterKeyLength);
                var masterBytes = masterBuffer.readByteArray(requiredMasterKeyLength);
                keysString = `${keysString}MASTER_KEY: ${toHexString(masterBytes)}\n`;
                var message = {};
                message["contentType"] = "keylog";
                message["keylog"] = keysString;
                send(message);
            }
        });
    }
}
export function wolfssl_execute(moduleName, is_base_hook) {
    var wolf_ssl = new WolfSSL_Android(moduleName, socket_library, is_base_hook);
    wolf_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = wolf_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"cronet_ios.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ios/cronet_ios.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAC,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAClG,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAExC,MAAM,OAAO,UAAW,SAAQ,MAAM;IAGlC,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,KAAK,CAAC,UAAU,EAAC,cAAc,EAAC,YAAY,CAAC,CAAC;QAD/B,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;QAG9D,IAAI,CAAC,eAAe,GAAG;YACnB,OAAO,EAAE;gBACL,OAAO,EAAE,iGAAiG;gBAC1G,QAAQ,EAAE,yHAAyH,CAAE,mBAAmB;aAC3J;SACJ,CAAC;IACN,CAAC;IAED,2BAA2B;QACvB,MAAM,YAAY,GAAG,OAAO,CAAC,gBAAgB,CAAC,IAA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KACJ;AAEL,CAAC"}
✄
import { Cronet } from "../ssl_lib/cronet.js";
import { socket_library } from "./ios_agent.js";
import { PatternBasedHooking, get_CPU_specific_pattern } from "../shared/pattern_based_hooking.js";
import { patterns, isPatternReplaced } from "../ssl_log.js";
import { devlog } from "../util/log.js";
export class Cronet_iOS extends Cronet {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library, is_base_hook);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.default_pattern = {
            "arm64": {
                primary: "FF 83 01 D1 F6 57 03 A9 F4 4F 04 A9 FD 7B 05 A9 FD 43 01 91 08 34 40 F9 08 51 41 F9 48 08 00 B4",
                fallback: "3F 23 03 D5 FF 03 02 D1 FD 7B 04 A9 F7 2B 00 F9 F6 57 06 A9 F4 4F 07 A9 FD 03 01 91 08 34 40 F9 08 11 41 F9 E8 0F 00 B4" // Fallback pattern
            }
        };
    }
    install_key_extraction_hook() {
        const cronetModule = Process.findModuleByName(this.module_name);
        const hooker = new PatternBasedHooking(cronetModule);
        if (isPatternReplaced()) {
            devlog("Hooking Cronet functions by pattern\nThis is still untested and might fail");
            hooker.hook_DumpKeys(this.module_name, "Cronet", patterns, (args) => {
                this.dumpKeys(args[1], args[0], args[2]); // Unpack args into dumpKeys
            });
        }
        else {
            // This are the default patterns for hooking ssl_log_secret in BoringSSL inside Cronet
            hooker.hookModuleByPattern(get_CPU_specific_pattern(this.default_pattern), (args) => {
                this.dumpKeys(args[1], args[0], args[2]); // Hook args passed to dumpKeys
            });
        }
    }
    execute_hooks() {
        this.install_key_extraction_hook();
    }
}
export function cronet_execute(moduleName, is_base_hook) {
    var cronet = new Cronet_iOS(moduleName, socket_library, is_base_hook);
    cronet.execute_hooks();
    if (is_base_hook) {
        const init_addresses = cronet.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"flutter_ios.js","sourceRoot":"/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AC,CAAC;SACN;aAAI;YACD,uFAAuF;YACvF,MAAM,CAAC,mBAAmB,CACtB,wBAAwB,CAAC,IAAI,CAAC,eAAe,CAAC,EAC9C,CAAC,IAAI,EAAE,EAAE;gBACL,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAE,+BAA+B;YAC9E,CAAC,CACJ,CAAC;SACL;IAEL,CAAC;IAED,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;IACvC,CAAC;CAEJ;AAGD,MAAM,UAAU,eAAe,CAAC,UAAiB,EAAE,YAAqB;IACpE,IAAI,OAAO,GAAG,IAAI,WAAW,CAAC,UAAU,EAAC,cAAc,EAAC,YAAY,CAAC,CAAC;IACtE,IAAI;QACA,OAAO,CAAC,aAAa,EAAE,CAAC;KAC3B;IAAA,OAAM,SAAS,EAAC;QACb,YAAY,CAAC,0BAA0B,SAAS,EAAE,CAAC,CAAA;KACtD;IAED,IAAI,YAAY,EAAE;QACd,IAAI;YACA,MAAM,cAAc,GAAG,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;YACrD,wDAAwD;YACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;gBACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;aAC/D;SACJ;QAAA,OAAM,SAAS,EAAC;YACb,YAAY,CAAC,oCAAoC,SAAS,EAAE,CAAC,CAAA;SAChE;KACJ;AAEL,CAAC"}
✄
import { Flutter } from "../ssl_lib/flutter.js";
import { socket_library } from "./ios_agent.js";
import { PatternBasedHooking, get_CPU_specific_pattern } from "../shared/pattern_based_hooking.js";
import { patterns, isPatternReplaced } from "../ssl_log.js";
import { devlog, devlog_error } from "../util/log.js";
export class Flutter_iOS extends Flutter {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library, is_base_hook);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.default_pattern = {
            "arm64": {
                primary: "FF 83 01 D1 F6 57 03 A9 F4 4F 04 A9 FD 7B 05 A9 FD 43 01 91 08 34 40 F9 08 51 41 F9 48 08 00 B4",
                fallback: "3F 23 03 D5 FF 03 02 D1 FD 7B 04 A9 F7 2B 00 F9 F6 57 06 A9 F4 4F 07 A9 FD 03 01 91 08 34 40 F9 08 11 41 F9 E8 0F 00 B4" // Fallback pattern
            }
        };
    }
    install_key_extraction_hook() {
        const flutterModule = Process.findModuleByName(this.module_name);
        const hooker = new PatternBasedHooking(flutterModule);
        if (isPatternReplaced()) {
            devlog("Hooking Flutter functions by patterns from JSON file");
            hooker.hook_DumpKeys(this.module_name, "Flutter", patterns, (args) => {
                this.dumpKeys(args[1], args[0], args[2]); // Unpack args into dumpKeys
            });
        }
        else {
            // This are the default patterns for hooking ssl_log_secret in BoringSSL inside Flutter
            hooker.hookModuleByPattern(get_CPU_specific_pattern(this.default_pattern), (args) => {
                this.dumpKeys(args[1], args[0], args[2]); // Hook args passed to dumpKeys
            });
        }
    }
    execute_hooks() {
        this.install_key_extraction_hook();
    }
}
export function flutter_execute(moduleName, is_base_hook) {
    var flutter = new Flutter_iOS(moduleName, socket_library, is_base_hook);
    try {
        flutter.execute_hooks();
    }
    catch (error_msg) {
        devlog_error(`flutter_execute error: ${error_msg}`);
    }
    if (is_base_hook) {
        try {
            const init_addresses = flutter.addresses[moduleName];
            // ensure that we only add it to global when we are not 
            if (Object.keys(init_addresses).length > 0) {
                global.init_addresses[moduleName] = init_addresses;
            }
        }
        catch (error_msg) {
            devlog_error(`flutter_execute base-hook error: ${error_msg}`);
        }
    }
}
✄
{"version":3,"file":"ios_agent.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ios/ios_agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAqB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AAC,CAAA;wBACjB,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE;4BAC7B,GAAG,CAAC,GAAG,IAAI,CAAC,UAAU,sCAAsC,CAAC,CAAA;4BAC7D,IAAG;gCACC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,YAAY,CAAC,CAAA;6BACtC;4BAAA,OAAM,SAAS,EAAC;gCACb,MAAM,CAAC,6BAA6B,SAAS,EAAE,CAAC,CAAA;6BACnD;yBAEJ;qBAEJ;iBACJ;YACL,CAAC;SAGJ,CAAC,CAAA;QAEF,GAAG,CAAC,gCAAgC,CAAC,CAAA;KACxC;IAAC,OAAO,KAAK,EAAE;QACZ,MAAM,CAAC,gBAAgB,GAAG,KAAK,CAAC,CAAA;QAChC,GAAG,CAAC,+CAA+C,CAAC,CAAA;KACvD;AACL,CAAC;AAGD,SAAS,iBAAiB,CAAC,sBAA0E,EAAE,YAAqB;IACxH,kBAAkB,CAAC,cAAc,EAAE,sBAAsB,EAAC,WAAW,EAAC,KAAK,EAAC,YAAY,CAAC,CAAA;AAC7F,CAAC;AAID,MAAM,UAAU,sBAAsB;IAClC,sBAAsB,CAAC,cAAc,CAAC,GAAG;QACrC,CAAC,uBAAuB,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;QAChE,CAAC,mBAAmB,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;QAC5D,CAAC,oBAAoB,EAAE,qBAAqB,CAAC,eAAe,CAAC,CAAC;KAAC,CAAA;IAEnE,iBAAiB,CAAC,sBAAsB,EAAE,IAAI,CAAC,CAAC;IAChD,uBAAuB,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAAC;AAC3D,CAAC"}
✄
import { module_library_mapping } from "../shared/shared_structures.js";
import { log, devlog } from "../util/log.js";
import { getModuleNames, ssl_library_loader, invokeHookingFunction } from "../shared/shared_functions.js";
import { boring_execute } from "./openssl_boringssl_ios.js";
import { cronet_execute } from "./cronet_ios.js";
import { flutter_execute } from "./flutter_ios.js";
var plattform_name = "darwin";
var moduleNames = getModuleNames();
export const socket_library = "libSystem.B.dylib";
function hook_iOS_Dynamic_Loader(module_library_mapping, is_base_hook) {
    try {
        const regex_libdl = /libSystem.B.dylib/;
        const libdl = moduleNames.find(element => element.match(regex_libdl));
        if (libdl === undefined) {
            throw "Darwin Dynamic loader not found!";
        }
        var dlopen = "dlopen";
        Interceptor.attach(Module.getExportByName(libdl, dlopen), {
            onEnter: function (args) {
                this.moduleName = args[0].readCString();
            },
            onLeave: function (retval) {
                if (this.moduleName != undefined) {
                    for (let map of module_library_mapping[plattform_name]) {
                        let regex = map[0];
                        let func = map[1];
                        if (regex.test(this.moduleName)) {
                            log(`${this.moduleName} was loaded & will be hooked on iOS!`);
                            try {
                                func(this.moduleName, is_base_hook);
                            }
                            catch (error_msg) {
                                devlog(`iOS dynamic loader error: ${error_msg}`);
                            }
                        }
                    }
                }
            }
        });
        log(`[*] iOS dynamic loader hooked.`);
    }
    catch (error) {
        devlog("Loader error: " + error);
        log("No dynamic loader present for hooking on iOS.");
    }
}
function hook_iOS_SSL_Libs(module_library_mapping, is_base_hook) {
    ssl_library_loader(plattform_name, module_library_mapping, moduleNames, "iOS", is_base_hook);
}
export function load_ios_hooking_agent() {
    module_library_mapping[plattform_name] = [
        [/.*libboringssl\.dylib/, invokeHookingFunction(boring_execute)],
        [/.*cronet.*\.dylib/, invokeHookingFunction(cronet_execute)],
        [/.*flutter.*\.dylib/, invokeHookingFunction(flutter_execute)]
    ];
    hook_iOS_SSL_Libs(module_library_mapping, true);
    hook_iOS_Dynamic_Loader(module_library_mapping, false);
}
✄
{"version":3,"file":"openssl_boringssl_ios.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ios/openssl_boringssl_ios.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACnE,OAAO,EAAE,cAAc,EAAE,MAAM,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AE,UAAU,IAAU;oBAC3B,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,YAAY,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAAC;gBACpF,CAAC;aACF,CAAC,CAAC;SAEJ;IAEP,CAAC;IAGD,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QAErF,IAAI,sBAAsB,GAAqC,EAAE,CAAA;QAEjE,yIAAyI;QACzI,sKAAsK;QACtK,sBAAsB,CAAC,IAAI,UAAU,GAAG,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAA;QACzE,yLAAyL;QAEzL,KAAK,CAAC,UAAU,EAAC,cAAc,EAAC,YAAY,EAAC,sBAAsB,CAAC,CAAC;QATtD,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAUlE,CAAC;IAED,aAAa;QAET;;;;UAIE;QAEF,IAAI,CAAC,8BAA8B,EAAE,CAAC;IAC1C,CAAC;CAIJ;AAGD,MAAM,UAAU,cAAc,CAAC,UAAiB,EAAE,YAAqB;IACnE,IAAI,UAAU,GAAG,IAAI,qBAAqB,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IACpF,UAAU,CAAC,aAAa,EAAE,CAAC;IAE3B,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,UAAU,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACxD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { OpenSSL_BoringSSL } from "../ssl_lib/openssl_boringssl.js";
import { socket_library } from "./ios_agent.js";
import { devlog } from "../util/log.js";
export class OpenSSL_BoringSSL_iOS extends OpenSSL_BoringSSL {
    install_tls_keys_callback_hook() {
        //console.log(this.addresses) // currently only for debugging purposes will be removed in future releases
        if (ObjC.available) { // inspired from https://codeshare.frida.re/@andydavies/ios-tls-keylogger/
            var CALLBACK_OFFSET = 0x2A8;
            var foundationNumber = Module.findExportByName('CoreFoundation', 'kCFCoreFoundationVersionNumber')?.readDouble();
            devlog("[*] Calculating offset to keylog callback based on the FoundationVersionNumber on iOS: " + foundationNumber);
            if (foundationNumber == undefined) {
                devlog("Installing callback for iOS < 14");
                CALLBACK_OFFSET = 0x2A8;
            }
            else if (foundationNumber >= 1751.108 && foundationNumber < 1854) {
                devlog("Installing callback for iOS >= 14");
                CALLBACK_OFFSET = 0x2B8; // >= iOS 14.x 
            }
            else if (foundationNumber >= 1854 && foundationNumber < 1946.102) {
                devlog("Installing callback for iOS >= 15");
                CALLBACK_OFFSET = 0x2F8; // >= iOS 15.x 
            }
            else if (foundationNumber >= 1946.102 && foundationNumber <= 1979.1) {
                devlog("Installing callback for iOS >= 16");
                CALLBACK_OFFSET = 0x300; // >= iOS 16.x 
            }
            else if (foundationNumber > 1979.1) {
                devlog("Installing callback for iOS >= 17");
                CALLBACK_OFFSET = 0x308; // >= iOS 17.x 
            }
            Interceptor.attach(this.addresses[this.module_name]["SSL_CTX_set_info_callback"], {
                onEnter: function (args) {
                    ptr(args[0]).add(CALLBACK_OFFSET).writePointer(OpenSSL_BoringSSL.keylog_callback);
                }
            });
        }
    }
    constructor(moduleName, socket_library, is_base_hook) {
        var library_method_mapping = {};
        // the iOS implementation needs some further improvements - currently we are not able to get the sockfd from an SSL_read/write invocation
        //library_method_mapping[`*${moduleName}*`] = ["SSL_read", "SSL_write", "BIO_get_fd", "SSL_get_session", "SSL_SESSION_get_id", "SSL_new", "SSL_CTX_set_info_callback"]
        library_method_mapping[`*${moduleName}*`] = ["SSL_CTX_set_info_callback"];
        //library_method_mapping[`*${socket_library}*`] = ["getpeername*", "getsockname*", "ntohs*", "ntohl*"] // currently those functions gets only identified if we at an asterisk at the end 
        super(moduleName, socket_library, is_base_hook, library_method_mapping);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    execute_hooks() {
        /*
        currently these function hooks aren't implemented
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        */
        this.install_tls_keys_callback_hook();
    }
}
export function boring_execute(moduleName, is_base_hook) {
    var boring_ssl = new OpenSSL_BoringSSL_iOS(moduleName, socket_library, is_base_hook);
    boring_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = boring_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"cronet_linux.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/linux/cronet_linux.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAC,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACxE,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAExC,MAAM,OAAO,YAAa,SAAQ,MAAM;IAEpC,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,KAAK,CAAC,UAAU,EAAC,cAAc,EAAC,YAAY,CAAC,CAAC;QAD/B,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAElE,CAAC;IAED,2BAA2B;QACvB,MAAM,YAAY,GAAG,OAAO,CAAC,gBAAgB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAChE,MAAM,MAAM,GAAG,IAAI,mBAAmB,CAAC,YAAY,CAAC,CAAC;QAErD,IAAI,iBAAiB,EAAE,EAAC;YACpB,MAAM,CAAC,wCAAwC,CAAC,CAAC;YACjD,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,WAAW,EAAC,cAAc,EAAC,QAAQ,EAAC,CAAC,IAAW,EAAE,EAAE;gBAC1E,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAE,4BAA4B;YAC3E,CAAC,CAAC,CAAC;SACN;IAOL,CAAC;IAED,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;IACvC,CAAC;CAEJ;AAGD,MAAM,UAAU,cAAc,CAAC,UAAiB,EAAE,YAAqB;IACnE,IAAI,MAAM,GAAG,IAAI,YAAY,CAAC,UAAU,EAAC,cAAc,EAAC,YAAY,CAAC,CAAC;IACtE,MAAM,CAAC,aAAa,EAAE,CAAC;IAEvB,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACpD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AAEL,CAAC"}
✄
import { Cronet } from "../ssl_lib/cronet.js";
import { socket_library } from "./linux_agent.js";
import { PatternBasedHooking } from "../shared/pattern_based_hooking.js";
import { patterns, isPatternReplaced } from "../ssl_log.js";
import { devlog } from "../util/log.js";
export class Cronet_Linux extends Cronet {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library, is_base_hook);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    install_key_extraction_hook() {
        const cronetModule = Process.findModuleByName(this.module_name);
        const hooker = new PatternBasedHooking(cronetModule);
        if (isPatternReplaced()) {
            devlog("Hooking libcronet functions by pattern");
            hooker.hook_DumpKeys(this.module_name, "libcronet.so", patterns, (args) => {
                this.dumpKeys(args[1], args[0], args[2]); // Unpack args into dumpKeys
            });
        }
    }
    execute_hooks() {
        this.install_key_extraction_hook();
    }
}
export function cronet_execute(moduleName, is_base_hook) {
    var cronet = new Cronet_Linux(moduleName, socket_library, is_base_hook);
    cronet.execute_hooks();
    if (is_base_hook) {
        const init_addresses = cronet.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"gnutls_linux.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/linux/gnutls_linux.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,MAAM,OAAO,YAAa,SAAQ,MAAM;IAEpC,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,KAAK,CAAC,UAAU,EAAC,cAAc,CAAC,CAAC;QADlB,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAElE,CAAC;IAGD,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;QACnC,IAAI,CAAC,4BAA4B,EAAE,CAAC;QACpC,IAAI,CAAC,8BAA8B,EAAE,CAAC;IAC1C,CAAC;IAED,8BAA8B;QAC1B,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,aAAa,CAAC,EACtE;YACI,OAAO,EAAE,UAAU,IAAS;gBACxB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;YAC1B,CAAC;YACD,OAAO,EAAE,UAAU,MAAW;gBAC1B,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;gBACzB,MAAM,CAAC,kCAAkC,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,MAAM,CAAC,eAAe,CAAC,CAAA;YAEjG,CAAC;SACJ,CAAC,CAAA;IAEF,CAAC;CAEJ;AAKD,MAAM,UAAU,cAAc,CAAC,UAAiB,EAAE,YAAqB;IACnE,IAAI,UAAU,GAAG,IAAI,YAAY,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IAC3E,UAAU,CAAC,aAAa,EAAE,CAAC;IAE3B,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,UAAU,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACxD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AAEL,CAAC"}
✄
import { GnuTLS } from "../ssl_lib/gnutls.js";
import { socket_library } from "./linux_agent.js";
export class GnuTLS_Linux extends GnuTLS {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        this.install_tls_keys_callback_hook();
    }
    install_tls_keys_callback_hook() {
        Interceptor.attach(this.addresses[this.module_name]["gnutls_init"], {
            onEnter: function (args) {
                this.session = args[0];
            },
            onLeave: function (retval) {
                console.log(this.session);
                GnuTLS.gnutls_session_set_keylog_function(this.session.readPointer(), GnuTLS.keylog_callback);
            }
        });
    }
}
export function gnutls_execute(moduleName, is_base_hook) {
    var gnutls_ssl = new GnuTLS_Linux(moduleName, socket_library, is_base_hook);
    gnutls_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = gnutls_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"linux_agent.js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CAAC;QACzD,CAAC,cAAc,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;QACvD,CAAC,gBAAgB,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;QACzD,CAAC,iBAAiB,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;QAC1D,CAAC,kBAAkB,EAAE,qBAAqB,CAAC,eAAe,CAAC,CAAC;QAC5D,CAAC,qBAAqB,EAAE,qBAAqB,CAAC,WAAW,CAAC,CAAC;QAC3D,CAAC,kBAAkB,EAAE,qBAAqB,CAAC,eAAe,CAAC,CAAC;QAC5D,CAAC,YAAY,EAAE,qBAAqB,CAAC,iBAAiB,CAAC,CAAC;QACxD,CAAC,aAAa,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;QACtD,CAAC,YAAY,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;KAAC,CAAA;IAE1D,mBAAmB,CAAC,sBAAsB,EAAE,IAAI,CAAC,CAAC;IAClD,yBAAyB,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAAC;AAC7D,CAAC"}
✄
import { module_library_mapping } from "../shared/shared_structures.js";
import { log, devlog } from "../util/log.js";
import { getModuleNames, ssl_library_loader, invokeHookingFunction } from "../shared/shared_functions.js";
import { gnutls_execute } from "./gnutls_linux.js";
import { wolfssl_execute } from "./wolfssl_linux.js";
import { nss_execute } from "./nss_linux.js";
import { mbedTLS_execute } from "./mbedTLS_linux.js";
import { boring_execute } from "./openssl_boringssl_linux.js";
import { matrixSSL_execute } from "./matrixssl_linux.js";
import { s2ntls_execute } from "./s2ntls_linux.js";
import { cronet_execute } from "./cronet_linux.js";
import { rustls_execute } from "./rustls_linux.js";
var plattform_name = "linux";
var moduleNames = getModuleNames();
export const socket_library = "libc";
function hook_Linux_Dynamic_Loader(module_library_mapping, is_base_hook) {
    try {
        const regex_libdl = /.*libdl.*\.so/;
        const libdl = moduleNames.find(element => element.match(regex_libdl));
        if (libdl === undefined) {
            throw "Linux Dynamic loader not found!";
        }
        var dlopen = "dlopen";
        Interceptor.attach(Module.getExportByName(libdl, dlopen), {
            onEnter: function (args) {
                this.moduleName = args[0].readCString();
            },
            onLeave: function (retval) {
                if (this.moduleName != undefined) {
                    for (let map of module_library_mapping[plattform_name]) {
                        let regex = map[0];
                        let func = map[1];
                        if (regex.test(this.moduleName)) {
                            log(`${this.moduleName} was loaded & will be hooked on Linux!`);
                            try {
                                func(this.moduleName, is_base_hook);
                            }
                            catch (error_msg) {
                                devlog(`Linux dynamic loader error: ${error_msg}`);
                            }
                        }
                    }
                }
            }
        });
        log(`[*] Linux dynamic loader hooked.`);
    }
    catch (error) {
        devlog("Loader error: " + error);
        log("No dynamic loader present for hooking.");
    }
}
function hook_Linux_SSL_Libs(module_library_mapping, is_base_hook) {
    ssl_library_loader(plattform_name, module_library_mapping, moduleNames, "Linux", is_base_hook);
}
export function load_linux_hooking_agent() {
    module_library_mapping[plattform_name] = [
        [/.*libssl_sb.so/, invokeHookingFunction(boring_execute)],
        [/.*libssl\.so/, invokeHookingFunction(boring_execute)],
        [/.*cronet.*\.so/, invokeHookingFunction(cronet_execute)],
        [/.*libgnutls\.so/, invokeHookingFunction(gnutls_execute)],
        [/.*libwolfssl\.so/, invokeHookingFunction(wolfssl_execute)],
        [/.*libnspr[0-9]?\.so/, invokeHookingFunction(nss_execute)],
        [/libmbedtls\.so.*/, invokeHookingFunction(mbedTLS_execute)],
        [/libssl_s.a/, invokeHookingFunction(matrixSSL_execute)],
        [/.*libs2n.so/, invokeHookingFunction(s2ntls_execute)],
        [/.*rustls.*/, invokeHookingFunction(rustls_execute)]
    ];
    hook_Linux_SSL_Libs(module_library_mapping, true);
    hook_Linux_Dynamic_Loader(module_library_mapping, false);
}
✄
{"version":3,"file":"matrixssl_linux.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/linux/matrixssl_linux.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,UAAU,EAAE,MAAM,yBAAyB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,MAAM,OAAO,gBAAiB,SAAQ,UAAU;IAE5C,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,KAAK,CAAC,UAAU,EAAC,cAAc,CAAC,CAAC;QADlB,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAElE,CAAC;IAED;;;;;;MAME;IACF,8BAA8B;QAC1B,8BAA8B;IAClC,CAAC;IAED,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;QACnC,IAAI,CAAC,4BAA4B,EAAE,CAAC;IACxC,CAAC;CAEJ;AAGD,MAAM,UAAU,iBAAiB,CAAC,UAAiB,EAAE,YAAqB;IACtE,IAAI,UAAU,GAAG,IAAI,gBAAgB,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IAC/E,UAAU,CAAC,aAAa,EAAE,CAAC;IAE3B,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,UAAU,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACxD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { matrix_SSL } from "../ssl_lib/matrixssl.js";
import { socket_library } from "./linux_agent.js";
export class matrix_SSL_Linux extends matrix_SSL {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    /*
    SSL_CTX_set_keylog_callback not exported by default on windows.

    We need to find a way to install the callback function for doing that

    Alternatives?:SSL_export_keying_material, SSL_SESSION_get_master_key
    */
    install_tls_keys_callback_hook() {
        // install hooking for windows
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
    }
}
export function matrixSSL_execute(moduleName, is_base_hook) {
    var matrix_ssl = new matrix_SSL_Linux(moduleName, socket_library, is_base_hook);
    matrix_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = matrix_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"mbedTLS_linux.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/linux/mbedTLS_linux.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,MAAM,OAAO,cAAe,SAAQ,QAAQ;IAExC,YAAmB,UAAiB,EAAS,cAAqB;QAC9D,KAAK,CAAC,UAAU,EAAC,cAAc,CAAC,CAAC;QADlB,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAElE,CAAC;IAED;;;;;;MAME;IACF,8BAA8B;QAC1B,8BAA8B;IAClC,CAAC;IAED,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;QACnC,IAAI,CAAC,4BAA4B,EAAE,CAAC;IACxC,CAAC;CAEJ;AAGD,MAAM,UAAU,eAAe,CAAC,UAAiB,EAAE,YAAqB;IACpE,IAAI,WAAW,GAAG,IAAI,cAAc,CAAC,UAAU,EAAC,cAAc,CAAC,CAAC;IAChE,WAAW,CAAC,aAAa,EAAE,CAAC;IAE5B,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,WAAW,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACzD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { mbed_TLS } from "../ssl_lib/mbedTLS.js";
import { socket_library } from "./linux_agent.js";
export class mbed_TLS_Linux extends mbed_TLS {
    constructor(moduleName, socket_library) {
        super(moduleName, socket_library);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    /*
    SSL_CTX_set_keylog_callback not exported by default on windows.

    We need to find a way to install the callback function for doing that

    Alternatives?:SSL_export_keying_material, SSL_SESSION_get_master_key
    */
    install_tls_keys_callback_hook() {
        // install hooking for windows
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
    }
}
export function mbedTLS_execute(moduleName, is_base_hook) {
    var mbedTLS_ssl = new mbed_TLS_Linux(moduleName, socket_library);
    mbedTLS_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = mbedTLS_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"nss_linux.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/linux/nss_linux.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAO,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAE7C,MAAM,OAAO,SAAU,SAAQ,GAAG;IAE9B,YAAmB,UAAiB,EAAS,cAAqB;QAC9D,IAAI,sBAAsB,GAAqC,EAAE,CAAC;QAClE,sBAAsB,CAAC,IAAI,UAAU,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,SAAS,EAAE,0BAA0B,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,gBAAgB,CAAC,CAAA;QAC9K,sBAAsB,CAAC,UAAU,CAAC,GAAG,CAAC,sBAAsB,EAAE,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H,MAAM,CAAC,+CAA+C,CAAC,CAAA;iBAC1D;YAEL,CAAC;SAEJ,CAAC,CAAC;QAMP;;;;;;WAMG;QACH,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,uBAAuB,CAAC,EACxE;YACI,OAAO,CAAC,IAAS;gBAEb,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;gBAEhC,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,gBAAgB,CAAC,EACzC;oBACI,OAAO,CAAC,IAAS;wBACb,IAAI,WAAW,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;wBAC1B,MAAM,CAAC,8EAA8E,CAAC,CAAC;wBACvF,GAAG,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAC;oBACtC,CAAC;oBACD,OAAO,CAAC,MAAW;oBACnB,CAAC;iBACJ,CAAC,CAAC;YAEX,CAAC;YACD,OAAO,CAAC,MAAW;YACnB,CAAC;SAEJ,CAAC,CAAC;IAGX,CAAC;CAEJ;AAGD,MAAM,UAAU,WAAW,CAAC,UAAiB,EAAE,YAAqB;IAChE,IAAI,OAAO,GAAG,IAAI,SAAS,CAAC,UAAU,EAAC,cAAc,CAAC,CAAC;IACvD,OAAO,CAAC,aAAa,EAAE,CAAC;IAExB,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACrD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { NSS } from "../ssl_lib/nss.js";
import { socket_library } from "./linux_agent.js";
import { devlog } from "../util/log.js";
export class NSS_Linux extends NSS {
    constructor(moduleName, socket_library) {
        var library_method_mapping = {};
        library_method_mapping[`*${moduleName}*`] = ["PR_Write", "PR_Read", "PR_FileDesc2NativeHandle", "PR_GetPeerName", "PR_GetSockName", "PR_GetNameForIdentity", "PR_GetDescType"];
        library_method_mapping[`*libnss*`] = ["PK11_ExtractKeyValue", "PK11_GetKeyData"];
        library_method_mapping["*libssl*.so"] = ["SSL_ImportFD", "SSL_GetSessionID", "SSL_HandshakeCallback"];
        library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        super(moduleName, socket_library, library_method_mapping);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        this.install_tls_keys_callback_hook();
    }
    install_tls_keys_callback_hook() {
        NSS.getDescType = new NativeFunction(this.addresses[this.module_name]['PR_GetDescType'], "int", ["pointer"]);
        // SSL Handshake Functions:
        NSS.PR_GetNameForIdentity = new NativeFunction(this.addresses[this.module_name]['PR_GetNameForIdentity'], "pointer", ["pointer"]);
        /*
                SECStatus SSL_HandshakeCallback(PRFileDesc *fd, SSLHandshakeCallback cb, void *client_data);
                more at https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/SSL_functions/sslfnc#1112702
        */
        NSS.get_SSL_Callback = new NativeFunction(this.addresses[this.module_name]["SSL_HandshakeCallback"], "int", ["pointer", "pointer", "pointer"]);
        // SSL Key helper Functions 
        NSS.PK11_ExtractKeyValue = new NativeFunction(this.addresses[this.module_name]["PK11_ExtractKeyValue"], "int", ["pointer"]);
        NSS.PK11_GetKeyData = new NativeFunction(this.addresses[this.module_name]["PK11_GetKeyData"], "pointer", ["pointer"]);
        Interceptor.attach(this.addresses[this.module_name]["SSL_ImportFD"], {
            onEnter(args) {
                this.fd = args[1];
            },
            onLeave(retval) {
                if (retval.isNull()) {
                    devlog("[-] SSL_ImportFD error: unknow null");
                    return;
                }
                var retValue = NSS.get_SSL_Callback(retval, NSS.keylog_callback, NULL);
                NSS.register_secret_callback(retval);
                // typedef enum { PR_FAILURE = -1, PR_SUCCESS = 0 } PRStatus;
                if (retValue < 0) {
                    devlog("Callback Error");
                    var getErrorText = new NativeFunction(Module.getExportByName('libnspr4.so', 'PR_GetErrorText'), "int", ["pointer"]);
                    var outbuffer = Memory.alloc(200); // max out size
                    devlog("typeof outbuffer: " + typeof outbuffer);
                    devlog("outbuffer: " + outbuffer); // should be a pointer
                    getErrorText(outbuffer.readPointer());
                    devlog("Error msg: " + outbuffer);
                }
                else {
                    devlog("[*] NSS keylog callback successfull installed");
                }
            }
        });
        /*
            SECStatus SSL_HandshakeCallback(
                PRFileDesc *fd,
                SSLHandshakeCallback cb,
                void *client_data
            );
         */
        Interceptor.attach(this.addresses[this.module_name]["SSL_HandshakeCallback"], {
            onEnter(args) {
                this.originalCallback = args[1];
                Interceptor.attach(ptr(this.originalCallback), {
                    onEnter(args) {
                        var sslSocketFD = args[0];
                        devlog("[*] keylog callback successfull installed via applications callback function");
                        NSS.ssl_RecordKeyLog(sslSocketFD);
                    },
                    onLeave(retval) {
                    }
                });
            },
            onLeave(retval) {
            }
        });
    }
}
export function nss_execute(moduleName, is_base_hook) {
    var nss_ssl = new NSS_Linux(moduleName, socket_library);
    nss_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = nss_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"openssl_boringssl_linux.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/linux/openssl_boringssl_linux.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACnE,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAGlD,MAAM,OAAO,uBAAwB,SAAQ,iBAAiB;IAE1D,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF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G,cAAc,CAAC;SAC/D;KACJ;AAEL,CAAC"}
✄
import { OpenSSL_BoringSSL } from "../ssl_lib/openssl_boringssl.js";
import { socket_library } from "./linux_agent.js";
export class OpenSSL_BoringSSL_Linux extends OpenSSL_BoringSSL {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library, is_base_hook);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    install_tls_keys_callback_hook() {
        this.SSL_CTX_set_keylog_callback = ObjC.available ? new NativeFunction(this.addresses[this.module_name]["SSL_CTX_set_info_callback"], "void", ["pointer", "pointer"]) : new NativeFunction(this.addresses[this.module_name]["SSL_CTX_set_keylog_callback"], "void", ["pointer", "pointer"]);
        var instance = this;
        if (this.addresses[this.module_name]["SSL_CTX_new"] === null) {
            Interceptor.attach(this.addresses[this.module_name]["SSL_new"], {
                onEnter: function (args) {
                    instance.SSL_CTX_set_keylog_callback(args[0], OpenSSL_BoringSSL.keylog_callback);
                }
            });
        }
        else {
            Interceptor.attach(this.addresses[this.module_name]["SSL_CTX_new"], {
                onLeave: function (retval) {
                    instance.SSL_CTX_set_keylog_callback(retval, OpenSSL_BoringSSL.keylog_callback);
                }
            });
        }
        // In case a callback is set by the appliction, we attach to this callback instead 
        // Only succeeds if SSL_CTX_new is available
        let setter_address = ObjC.available ? "SSL_CTX_set_info_callback" : "SSL_CTX_set_keylog_callback";
        Interceptor.attach(this.addresses[this.module_name][setter_address], {
            onEnter: function (args) {
                let callback_func = args[1];
                //devlog("args[1]: " + callback_func);
                Interceptor.attach(callback_func, {
                    onEnter: function (args) {
                        var message = {};
                        message["contentType"] = "keylog";
                        message["keylog"] = args[1].readCString();
                        send(message);
                    }
                });
            }
        });
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        this.install_tls_keys_callback_hook();
        this.install_extended_hooks();
    }
}
export function boring_execute(moduleName, is_base_hook) {
    var boring_ssl = new OpenSSL_BoringSSL_Linux(moduleName, socket_library, is_base_hook);
    boring_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = boring_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"rustls_linux.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/linux/rustls_linux.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAO,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAC5C,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AACnG,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAC,MAAM,eAAe,CAAA;AAE1D,MAAM,OAAO,YAAa,SAAQ,MAAM;IAIpC,YAAmB,UAAkB,EAAS,cAAsB,EAAE,YAAqB;QACvF,KAAK,CAAC,UAAU,EAAE,cAAc,EAAE,YAAY,CAAC,CAAC;QADjC,eAAU,GAAV,UAAU,CAAQ;QAAS,mBAAc,GAAd,cAAc,CAAQ;QAGhE,IAAI,CAAC,eAAe,GAAG;YACnB,KAAK,EAAE;gBACH,OAAO,EAAG,8IAA8I;gBACxJ,QAAQ,EAAE,kIAAkI;aAC/I;SACJ,CAAC;QAEF,IAAI,CAAC,kBAAkB,GAAG;YACtB,KAAK,EAAE;gBACH,OAAO,EAAG,iJAAiJ;gBAC3J,QAAQ,EAAE,kIAAkI;aAC/I;SACJ,CAAA;IACL,CAAC;IAED,qBAAqB;QACjB,IAAI,CAAC,2BAA2B,EAAE,CAAC;IAEvC,CAAC;IAGD,2BAA2B;QACvB,MAAM,YAAY,GAAG,OAAO,CAAC,gBAAgB,CAAC,IAAI,CAAC,WAAW,C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G,sBAAsB,CAAC,UAAU,CAAC,EAAC;QAClC,MAAM,CAAC,wCAAwC,CAAC,CAAC;QACjD,MAAM,CAAC,aAAa,EAAE,CAAC;KAC1B;SAAI;QACD,MAAM,CAAC,yCAAyC,CAAC,CAAC;QAClD,MAAM,CAAC,qBAAqB,EAAE,CAAC;KAClC;IAGD,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACpD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { socket_library } from "./linux_agent.js";
import { RusTLS } from "../ssl_lib/rustls.js";
import { devlog } from "../util/log.js";
import { hasMoreThanFiveExports } from "../shared/shared_functions.js";
import { PatternBasedHooking, get_CPU_specific_pattern } from "../shared/pattern_based_hooking.js";
import { patterns, isPatternReplaced } from "../ssl_log.js";
export class Rustls_Linux extends RusTLS {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library, is_base_hook);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.default_pattern = {
            "x64": {
                primary: "48 81 EC 18 01 00 00 4C 89 4C 24 40 48 89 7C 24 48 88 D0 48 89 7C 24 50 48 8B 94 24 28 01 00 00 48 89 54 24 58 48 8B 94 24 20 01 00 00 48 89",
                fallback: "48 81 EC 18 01 00 00 4C 89 4C 24 40 48 89 7C 24 48 88 D0 48 89 7C 24 50 48 8B 94 24 28 01 00 00 48 89 54 24 58 48 8B 94 24 20 01"
            }
        };
        this.default_pattern_12 = {
            "x64": {
                primary: "41 57 41 56 53 48 81 ec c0 04 00 00 4c 89 8c 24 a0 00 00 00 4c 89 44 24 70 48 89 4c 24 78 48 89 bc 24 80 00 00 00 48 89 bc 24 88 00 00 00 48 8b",
                fallback: "41 57 41 56 53 48 81 ec c0 04 00 00 4c 89 8c 24 a0 00 00 00 4c 89 44 24 70 48 89 4c 24 78 48 89 bc 24 80 00 00 00 48 89 bc 24 88"
            }
        };
    }
    execute_pattern_hooks() {
        this.install_key_extraction_hook();
    }
    install_key_extraction_hook() {
        const rusTLSModule = Process.findModuleByName(this.module_name);
        const hooker = new PatternBasedHooking(rusTLSModule);
        this.install_key_extraction_hook_tls(hooker);
        this.install_key_extraction_hook_tls_12(hooker);
    }
    install_key_extraction_hook_tls_12(hooker) {
        const doDumpKeysLogic = (args, retval) => {
            let client_random_ptr;
            let master_secret_ptr;
            client_random_ptr = args[6];
            // retval structure: 
            // | header (8 bytes) | client_random(32 bytes) | server_random(32 bytes) | master_secret(48 bytes) |
            master_secret_ptr = retval.add(72);
            this.dumpKeysFromPRF(client_random_ptr, master_secret_ptr);
        };
        // Wrapper 1: for the "normal" pattern. Only proceed if retval is null.
        const normalPatternCallback = (args, retval) => {
            if (!retval) {
                devlog("retval is null");
                return; // In case hooking is onEnter, ignore
            }
            if (!retval.isNull()) {
                //devlog("[normal pattern] [TLS 1.2] hooking triggered, retval is null. Doing work.");
                doDumpKeysLogic(args, retval);
            }
        };
        // Decide whether to hook from JSON patterns or from built-in patterns ( “_ex” vs. normal) 
        if (isPatternReplaced()) {
            hooker.hook_DumpKeys(this.module_name, 
            // Pick the JSON module name based on whether it’s “ex”
            "rustls", patterns, normalPatternCallback, true, // onReturn so we get retval
            7);
        }
        else {
            hooker.hookModuleByPatternOnReturn(
            // Pick the default pattern based on whether it’s “ex”
            get_CPU_specific_pattern(this.default_pattern_12), normalPatternCallback, 7);
        }
    }
    install_key_extraction_hook_tls(hooker) {
        const doDumpKeysLogic = (args, retval) => {
            // Decide offsets for client_random_ptr, key, key_len, label_enum
            let client_random_ptr;
            let key;
            let label_enum;
            client_random_ptr = args[7];
            key = args[0];
            label_enum = args[2].toInt32();
            this.dumpKeysFromDeriveLogged(client_random_ptr, key, label_enum);
        };
        // Wrapper 1: for the "normal" pattern. Only proceed if retval is null.
        const normalPatternCallback = (args, retval) => {
            //devlog("[TLS 1.3] normalPatternCallback");
            if (!retval)
                return; // to ensure we don't get a runtime exception when retval is undefined
            if (retval.isNull()) {
                doDumpKeysLogic(args, retval);
            }
            else {
                // 
                if (Process.arch === "x64") {
                    doDumpKeysLogic(args, retval);
                }
            }
        };
        // Decide whether to hook from JSON patterns or from built-in patterns
        if (isPatternReplaced()) {
            hooker.hook_DumpKeys(this.module_name, "rustls", patterns, normalPatternCallback, true, // onReturn so we get retval
            9);
        }
        else {
            hooker.hookModuleByPatternOnReturn(get_CPU_specific_pattern(this.default_pattern), normalPatternCallback, 9);
        }
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        this.install_tls_keys_callback_hook();
    }
    // Extract the configBuilder from call to rustls_client_config_builder_new / _custom and set keyLogCB
    install_tls_keys_callback_hook() {
        RusTLS.rustls_client_config_set_key_log = new NativeFunction(this.addresses[this.moduleName]["rustls_client_config_builder_set_key_log"], 'uint32', ['pointer', 'pointer', 'pointer']);
        // Attach to both functions, which can create a config builder
        Interceptor.attach(this.addresses[this.moduleName]["rustls_client_config_builder_new"], {
            onLeave: function (retval) {
                if (retval.isNull()) {
                    devlog("Error: retval is null");
                    return;
                }
                RusTLS.rustls_client_config_set_key_log(retval, RusTLS.keyLogCB, ptr('0'));
                devlog("Attached keyLogCB to rustls_client_config_set_key_log");
            }
        });
        Interceptor.attach(this.addresses[this.moduleName]["rustls_client_config_builder_new_custom"], {
            onLeave: function (retval) {
                if (retval.isNull()) {
                    devlog("Error: retval is null");
                    return;
                }
                RusTLS.rustls_client_config_set_key_log(retval, RusTLS.keyLogCB, ptr('0'));
                devlog("Attached keyLogCB to rustls_client_config_set_key_log");
            }
        });
        // If the target sets its own Callback, Rustls.keyLogCB will be overwritten.
        // In this case we want to hook the Callback set by user. 
        Interceptor.attach(this.addresses[this.moduleName]["rustls_client_config_builder_set_key_log"], {
            onEnter: function (args) {
                // Extract the Address of the new Callback
                var userCallbackAddress = args[1];
                devlog("User set CB to: " + userCallbackAddress);
                this.userCallbackAddress = userCallbackAddress;
            },
            onLeave: function (retval) {
                // Check if the Callback was set
                if (retval != 7000) {
                    // If the Callback was not set the keyLogCB has not been overwritten.
                    return;
                }
                else {
                    // In case the keyLogCB has been overwritten, we attach to it.
                    Interceptor.attach(this.userCallbackAddress, {
                        onEnter(args) {
                            devlog("Hooking user-defined callback for Rustls");
                            var message = {};
                            message["contentType"] = "keylog";
                            // Parse the arguments
                            var labelPtr = args[0];
                            var label_len = args[1].toInt32();
                            var client_random = args[2];
                            var client_random_len = args[3].toInt32();
                            var secret = args[4];
                            var secret_len = args[5].toInt32();
                            if (client_random.isNull() || client_random_len != 32) {
                                devlog("Invalid client_random: " + client_random + " or client_random_lenght: " + client_random_len);
                                return;
                            }
                            if (secret.isNull() || secret_len <= 0 || secret_len > 48) {
                                devlog("Invalid secret or secret_length");
                                return;
                            }
                            // Read the client random and secrets as strings
                            var clientRandomStr = client_random.readByteArray(client_random_len);
                            var secretStr = secret.readByteArray(secret_len);
                            var labelStr = labelPtr.readUtf8String(label_len);
                            // Convert byte arrays to hex strings for better logging
                            var clientRandomHex = Array.from(new Uint8Array(clientRandomStr)).map(b => b.toString(16).padStart(2, '0')).join('');
                            var secretHex = Array.from(new Uint8Array(secretStr)).map(b => b.toString(16).padStart(2, '0')).join('');
                            // Construct the keylog message
                            message["keylog"] = `${labelStr} ${clientRandomHex} ${secretHex}`;
                            send(message);
                            return 1;
                        }
                    });
                }
            }
        });
    }
}
export function rustls_execute(moduleName, is_base_hook) {
    var rusTLS = new Rustls_Linux(moduleName, socket_library, is_base_hook);
    if (hasMoreThanFiveExports(moduleName)) {
        devlog("Trying to hook RusTLS using symbols...");
        rusTLS.execute_hooks();
    }
    else {
        devlog("Trying to hook RusTLS using patterns...");
        rusTLS.execute_pattern_hooks();
    }
    if (is_base_hook) {
        const init_addresses = rusTLS.addresses[moduleName];
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"s2ntls_linux.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/linux/s2ntls_linux.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAE9C,MAAM,OAAO,YAAa,SAAQ,MAAM;IAEpC,YAAmB,UAAkB,EAAS,cAAsB,EAAE,YAAqB;QACvF,KAAK,CAAC,UAAU,EAAE,cAAc,CAAC,CAAC;QADnB,eAAU,GAAV,UAAU,CAAQ;QAAS,mBAAc,GAAd,cAAc,CAAQ;IAEpE,CAAC;IAED,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;QACnC,IAAI,CAAC,4BAA4B,EAAE,CAAC;QACpC,IAAI,CAAC,8BAA8B,EAAE,CAAC;IAC1C,CAAC;IAED,yDAAyD;IACzD,8BAA8B;QAC1B,MAAM,CAAC,kBAAkB,GAAG,IAAI,cAAc,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,2BAA2B,CAAC,EAAE,KAAK,EAAE,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC,CAAC;QAExJ,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,gBAAgB,CAAC,EACjE;YACA,OAAO,EAAE,UAAS,MAAW;gBAEzB,IAAI,YAAY,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;gBAC5B,MAAM,CAAC,kBAAkB,CAAC,MAAM,EAAE,MAAM,CAAC,eAAe,EAAE,YAAY,CAAC,CAAC;YAC5E,CAAC;SACJ,CAAC,CAAA;QAEF,kFAAkF;QAClF,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,2BAA2B,CAAC,EAC5E;YACI,OAAO,EAAE,UAAS,IAAS;gBACvB,IAAI,aAAa,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;gBAE5B,WAAW,CAAC,MAAM,CAAC,aAAa,EAAE;oBAC9B,OAAO,EAAE,UAAS,IAAS;wBACvB,IAAI,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;wBACtB,IAAI,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;wBAClB,IAAI,OAAO,GAA8C,EAAE,CAAC;wBAC5D,OAAO,CAAC,aAAa,CAAC,GAAG,QAAQ,CAAC;wBAClC,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC;wBACvD,IAAI,CAAC,OAAO,CAAC,CAAC;oBAClB,CAAC;iBACJ,CAAC,CAAA;YACN,CAAC;SACJ,CAAC,CAAA;IAEV,CAAC;CACJ;AAED,MAAM,UAAU,cAAc,CAAC,UAAkB,EAAE,YAAqB;IACpE,IAAI,OAAO,GAAG,IAAI,YAAY,CAAC,UAAU,EAAE,cAAc,EAAE,YAAY,CAAC,CAAC;IACzE,OAAO,CAAC,aAAa,EAAE,CAAC;IAExB,IAAI,YAAY,EAAC;QACb,MAAM,cAAc,GAAG,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACrD,uDAAuD;QACvD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAC;YACtC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { socket_library } from "./linux_agent.js";
import { S2nTLS } from "../ssl_lib/s2ntls.js";
export class S2nTLS_Linux extends S2nTLS {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        this.install_tls_keys_callback_hook();
    }
    //if s2n_config_new is called, the keylog callback is set
    install_tls_keys_callback_hook() {
        S2nTLS.s2n_set_key_log_cb = new NativeFunction(this.addresses[this.module_name]["s2n_config_set_key_log_cb"], "int", ["pointer", "pointer", "pointer"]);
        Interceptor.attach(this.addresses[this.module_name]["s2n_config_new"], {
            onLeave: function (retval) {
                let emptyPointer = ptr("0");
                S2nTLS.s2n_set_key_log_cb(retval, S2nTLS.keylog_callback, emptyPointer);
            }
        });
        // In case a callback is set by the appliction, we attach to this callback instead
        Interceptor.attach(this.addresses[this.module_name]["s2n_config_set_key_log_cb"], {
            onEnter: function (args) {
                let user_callback = args[1];
                Interceptor.attach(user_callback, {
                    onEnter: function (args) {
                        let logline = args[2];
                        let len = args[3];
                        var message = {};
                        message["contentType"] = "keylog";
                        message["keylog"] = logline.readCString(len.toInt32());
                        send(message);
                    }
                });
            }
        });
    }
}
export function s2ntls_execute(moduleName, is_base_hook) {
    var s2n_tls = new S2nTLS_Linux(moduleName, socket_library, is_base_hook);
    s2n_tls.execute_hooks();
    if (is_base_hook) {
        const init_addresses = s2n_tls.addresses[moduleName];
        // ensure that we only add it to global when we are not
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"wolfssl_linux.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/linux/wolfssl_linux.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAE5D,MAAM,OAAO,aAAc,SAAQ,OAAO;IAEtC,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,KAAK,CAAC,UAAU,EAAC,cAAc,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AW,CAAC,IAAI,CAAA;gBAGrE,IAAI,OAAO,GAA8C,EAAE,CAAA;gBAC3D,OAAO,CAAC,aAAa,CAAC,GAAG,QAAQ,CAAA;gBACjC,OAAO,CAAC,QAAQ,CAAC,GAAG,UAAU,CAAA;gBAC9B,IAAI,CAAC,OAAO,CAAC,CAAA;YAEjB,CAAC;SACJ,CAAC,CAAA;IACN,CAAC;CAEJ;AAGD,MAAM,UAAU,eAAe,CAAC,UAAiB,EAAE,YAAqB;IACpE,IAAI,QAAQ,GAAG,IAAI,aAAa,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IAC1E,QAAQ,CAAC,aAAa,EAAE,CAAC;IAEzB,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,QAAQ,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACtD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { WolfSSL } from "../ssl_lib/wolfssl.js";
import { socket_library } from "./linux_agent.js";
import { toHexString } from "../shared/shared_functions.js";
export class WolfSSL_Linux extends WolfSSL {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        this.install_tls_keys_callback_hook();
    }
    install_tls_keys_callback_hook() {
        WolfSSL.wolfSSL_get_client_random = new NativeFunction(this.addresses[this.module_name]["wolfSSL_get_client_random"], "int", ["pointer", "pointer", "int"]);
        WolfSSL.wolfSSL_get_server_random = new NativeFunction(this.addresses[this.module_name]["wolfSSL_get_server_random"], "int", ["pointer", "pointer", "int"]);
        //https://www.wolfssl.com/doxygen/group__Setup.html#gaf18a029cfeb3150bc245ce66b0a44758
        WolfSSL.wolfSSL_SESSION_get_master_key = new NativeFunction(this.addresses[this.module_name]["wolfSSL_SESSION_get_master_key"], "int", ["pointer", "pointer", "int"]);
        Interceptor.attach(this.addresses[this.module_name]["wolfSSL_connect"], {
            onEnter: function (args) {
                this.ssl = args[0];
            },
            onLeave: function (retval) {
                this.session = WolfSSL.wolfSSL_get_session(this.ssl);
                var keysString = "";
                //https://www.wolfssl.com/doxygen/group__Setup.html#ga927e37dc840c228532efa0aa9bbec451
                var requiredClientRandomLength = WolfSSL.wolfSSL_get_client_random(this.session, NULL, 0);
                var clientBuffer = Memory.alloc(requiredClientRandomLength);
                WolfSSL.wolfSSL_get_client_random(this.ssl, clientBuffer, requiredClientRandomLength);
                var clientBytes = clientBuffer.readByteArray(requiredClientRandomLength);
                keysString = `${keysString}CLIENT_RANDOM: ${toHexString(clientBytes)}\n`;
                //https://www.wolfssl.com/doxygen/group__Setup.html#ga987035fc600ba9e3b02e2b2718a16a6c
                var requiredServerRandomLength = WolfSSL.wolfSSL_get_server_random(this.session, NULL, 0);
                var serverBuffer = Memory.alloc(requiredServerRandomLength);
                WolfSSL.wolfSSL_get_server_random(this.ssl, serverBuffer, requiredServerRandomLength);
                var serverBytes = serverBuffer.readByteArray(requiredServerRandomLength);
                keysString = `${keysString}SERVER_RANDOM: ${toHexString(serverBytes)}\n`;
                //https://www.wolfssl.com/doxygen/group__Setup.html#gaf18a029cfeb3150bc245ce66b0a44758
                var requiredMasterKeyLength = WolfSSL.wolfSSL_SESSION_get_master_key(this.session, NULL, 0);
                var masterBuffer = Memory.alloc(requiredMasterKeyLength);
                WolfSSL.wolfSSL_SESSION_get_master_key(this.session, masterBuffer, requiredMasterKeyLength);
                var masterBytes = masterBuffer.readByteArray(requiredMasterKeyLength);
                keysString = `${keysString}MASTER_KEY: ${toHexString(masterBytes)}\n`;
                var message = {};
                message["contentType"] = "keylog";
                message["keylog"] = keysString;
                send(message);
            }
        });
    }
}
export function wolfssl_execute(moduleName, is_base_hook) {
    var wolf_ssl = new WolfSSL_Linux(moduleName, socket_library, is_base_hook);
    wolf_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = wolf_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"cronet_macos.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/macos/cronet_macos.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAC,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACxE,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAGxC,MAAM,OAAO,YAAa,SAAQ,MAAM;IAEpC,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,KAAK,CAAC,UAAU,EAAC,cAAc,EAAC,YAAY,CAAC,CAAC;QAD/B,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAElE,CAAC;IAED,2BAA2B;QACvB,MAAM,YAAY,GAAG,OAAO,CAAC,gBAAgB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAChE,MAAM,MAAM,GAAG,IAAI,mBAAmB,CAAC,YAAY,CAAC,CAAC;QAErD,IAAI,iBAAiB,EAAE,EAAC;YACpB,MAAM,CAAC,qCAAqC,CAAC,CAAC;YAC9C,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,WAAW,EAAC,QAAQ,EAAC,QAAQ,EAAC,CAAC,IAAW,EAAE,EAAE;gBACpE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAE,4BAA4B;YAC3E,CAAC,CAAC,CAAC;SACN;IAOL,CAAC;IAED,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;IACvC,CAAC;CAEJ;AAGD,MAAM,UAAU,cAAc,CAAC,UAAiB,EAAE,YAAqB;IACnE,IAAI,MAAM,GAAG,IAAI,YAAY,CAAC,UAAU,EAAC,cAAc,EAAC,YAAY,CAAC,CAAC;IACtE,MAAM,CAAC,aAAa,EAAE,CAAC;IAEvB,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACpD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AAEL,CAAC"}
✄
import { Cronet } from "../ssl_lib/cronet.js";
import { socket_library } from "./macos_agent.js";
import { PatternBasedHooking } from "../shared/pattern_based_hooking.js";
import { patterns, isPatternReplaced } from "../ssl_log.js";
import { devlog } from "../util/log.js";
export class Cronet_MacOS extends Cronet {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library, is_base_hook);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    install_key_extraction_hook() {
        const cronetModule = Process.findModuleByName(this.module_name);
        const hooker = new PatternBasedHooking(cronetModule);
        if (isPatternReplaced()) {
            devlog("Hooking Cronet functions by pattern");
            hooker.hook_DumpKeys(this.module_name, "Cronet", patterns, (args) => {
                this.dumpKeys(args[1], args[0], args[2]); // Unpack args into dumpKeys
            });
        }
    }
    execute_hooks() {
        this.install_key_extraction_hook();
    }
}
export function cronet_execute(moduleName, is_base_hook) {
    var cronet = new Cronet_MacOS(moduleName, socket_library, is_base_hook);
    cronet.execute_hooks();
    if (is_base_hook) {
        const init_addresses = cronet.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"macos_agent.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/macos/macos_agent.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAqB,MAAM,gCAAgC,CAAC;AAC3F,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAC1G,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAGlD,IAAI,cAAc,GAAG,QAAQ,CAAC;AAC9B,IAAI,WAAW,GAAkB,cAAc,EAAE,CAAA;AAEjD,MAAM,CAAC,MAAM,cAAc,GAAG,mBAAmB,CAAA;AAGjD,SAAS,yBAAyB,CAAC,sBAA0E,EAAE,YAAqB;IAChI,IAAI;QACA,MAAM,WAAW,GAAG,mBAAmB,CAAA;QACvC,MAAM,KAAK,GAAG,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAA;QACrE,IAAI,KAAK,KAAK,SAAS,EAAE;YACrB,MAAM,kCAAkC,CAAA;SAC3C;QAED,IAAI,MAAM,GAAG,QAAQ,CAAA;QAErB,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,mBAAmB,EAAE,MAAM,CAAC,EAAE;YACpE,OAAO,EAAE,UAAU,IAAI;gBACnB,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAA;YAC3C,CAAC;YACD,OAAO,EAAE,UAAU,MAAW;gBAC1B,IAA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library_mapping } from "../shared/shared_structures.js";
import { log, devlog } from "../util/log.js";
import { getModuleNames, ssl_library_loader, invokeHookingFunction } from "../shared/shared_functions.js";
import { boring_execute } from "./openssl_boringssl_macos.js";
import { cronet_execute } from "./cronet_macos.js";
var plattform_name = "darwin";
var moduleNames = getModuleNames();
export const socket_library = "libSystem.B.dylib";
function hook_macOS_Dynamic_Loader(module_library_mapping, is_base_hook) {
    try {
        const regex_libdl = /libSystem.B.dylib/;
        const libdl = moduleNames.find(element => element.match(regex_libdl));
        if (libdl === undefined) {
            throw "Darwin Dynamic loader not found!";
        }
        var dlopen = "dlopen";
        Interceptor.attach(Module.getExportByName("libSystem.B.dylib", dlopen), {
            onEnter: function (args) {
                this.moduleName = args[0].readCString();
            },
            onLeave: function (retval) {
                if (this.moduleName != undefined) {
                    for (let map of module_library_mapping[plattform_name]) {
                        let regex = map[0];
                        let func = map[1];
                        if (regex.test(this.moduleName)) {
                            log(`${this.moduleName} was loaded & will be hooked on MacOS!`);
                            try {
                                func(this.moduleName, is_base_hook);
                            }
                            catch (error_msg) {
                                devlog(`MacOS dynamic loader error: ${error_msg}`);
                            }
                        }
                    }
                }
            }
        });
        log("MacOS dynamic loader hooked.");
    }
    catch (error) {
        devlog("Loader error: " + error);
        log("No dynamic loader present for hooking on MacOS.");
    }
}
function hook_macOS_SSL_Libs(module_library_mapping, is_base_hook) {
    ssl_library_loader(plattform_name, module_library_mapping, moduleNames, "MacOS", is_base_hook);
}
export function load_macos_hooking_agent() {
    module_library_mapping[plattform_name] = [
        [/.*libboringssl\.dylib/, invokeHookingFunction(boring_execute)],
        [/.*cronet.*\.dylib/, invokeHookingFunction(cronet_execute)]
    ];
    hook_macOS_SSL_Libs(module_library_mapping, true); // actually we are using the same implementation as we did on iOS, therefore this needs addtional testing
    hook_macOS_Dynamic_Loader(module_library_mapping, false);
}
✄
{"version":3,"file":"openssl_boringssl_macos.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap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,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { OpenSSL_BoringSSL } from "../ssl_lib/openssl_boringssl.js";
import { socket_library } from "./macos_agent.js";
import { devlog } from "../util/log.js";
export class OpenSSL_BoringSSL_MacOS extends OpenSSL_BoringSSL {
    install_tls_keys_callback_hook() {
        //console.log(this.addresses) // currently only for debugging purposes will be removed in future releases
        if (ObjC.available) { // inspired from https://codeshare.frida.re/@andydavies/ios-tls-keylogger/
            var CALLBACK_OFFSET = 0x2A8;
            var foundationNumber = Module.findExportByName('CoreFoundation', 'kCFCoreFoundationVersionNumber')?.readDouble();
            devlog("[*] Calculating offset to keylog callback based on the FoundationVersionNumber on MacOS: " + foundationNumber);
            if (foundationNumber == undefined) {
                CALLBACK_OFFSET = 0x2A8;
                devlog("Installing callback for MacOS < 14 using callback offset: " + CALLBACK_OFFSET);
            }
            else if (foundationNumber >= 1751.108 && foundationNumber < 1854) {
                CALLBACK_OFFSET = 0x2B8; // >= iOS 14.x 
                devlog("Installing callback for MacOS >= 14 using callback offset: " + CALLBACK_OFFSET);
            }
            else if (foundationNumber >= 1854 && foundationNumber < 1946.102) {
                CALLBACK_OFFSET = 0x2F8; // >= iOS 15.x 
                devlog("Installing callback for MacOS >= 15 using callback offset: " + CALLBACK_OFFSET);
            }
            else if (foundationNumber >= 1946.102 && foundationNumber <= 1979.1) {
                CALLBACK_OFFSET = 0x300; // >= iOS 16.x 
                devlog("Installing callback for MacOS >= 16 using callback offset: " + CALLBACK_OFFSET);
            }
            else if (foundationNumber > 1979.1) {
                CALLBACK_OFFSET = 0x2F8; // >= iOS 17.x
                devlog("Installing callback for MacOS >= 17 using callback offset: " + CALLBACK_OFFSET);
            }
            Interceptor.attach(this.addresses[this.module_name]["SSL_CTX_set_info_callback"], {
                onEnter: function (args) {
                    ptr(args[0]).add(CALLBACK_OFFSET).writePointer(OpenSSL_BoringSSL.keylog_callback);
                }
            });
        }
    }
    constructor(moduleName, socket_library, is_base_hook) {
        var library_method_mapping = {};
        // the MacOS implementation needs some further improvements - currently we are not able to get the sockfd from an SSL_read/write invocation
        //library_method_mapping[`*${moduleName}*`] = ["SSL_read", "SSL_write", "BIO_get_fd", "SSL_get_session", "SSL_SESSION_get_id", "SSL_new", "SSL_CTX_set_info_callback"]
        library_method_mapping[`*${moduleName}*`] = ["SSL_CTX_set_info_callback"];
        //library_method_mapping[`*${socket_library}*`] = ["getpeername*", "getsockname*", "ntohs*", "ntohl*"] // currently those functions gets only identified if we at an asterisk at the end 
        super(moduleName, socket_library, is_base_hook, library_method_mapping);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    execute_hooks() {
        /*
        currently these function hooks aren't implemented
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        */
        this.install_tls_keys_callback_hook();
    }
}
export function boring_execute(moduleName, is_base_hook) {
    var boring_ssl = new OpenSSL_BoringSSL_MacOS(moduleName, socket_library, is_base_hook);
    boring_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = boring_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"socket_tracer.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/misc/socket_tracer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAU,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC;AACpE,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AACpF,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,SAAS,qBAAqB,CAAC,EAAW;IACtC,IAAI,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC/B,IAAI,QAAQ,KAAK,KAAK,IAAI,QAAQ,KAAK,MAAM,IAAI,QAAQ,KA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AAG,IAAI,KAAK,KAAK,EAAC;QACd,YAAY,GAAG,KAAK,CAAC;KACxB;SAAK,IAAG,IAAI,KAAK,OAAO,EAAC;QACtB,YAAY,GAAG,KAAK,CAAC;KACxB;SAAK,IAAG,IAAI,KAAK,MAAM,EAAC;QACrB,YAAY,GAAG,UAAU,CAAC;KAC7B;SAAI;QACD,YAAY,GAAG,SAAS,CAAA;KAC3B;IACD,OAAO,YAAY,CAAA;AAEvB,CAAC;AAID;;;;;;;iFAOiF;AAGjF,SAAS,yBAAyB;IAC9B,OAAO,2BAA2B,CAAC,sBAAsB,EAAE,CAAC,CAAC;AACjE,CAAC;AAED;;;GAGG"}
✄
import { log } from "../util/log.js";
import { get_process_architecture } from "../util/process_infos.js";
import { readAddresses, getPortsAndAddresses } from "../shared/shared_functions.js";
import { enable_default_fd } from "../ssl_log.js";
function has_valid_socket_type(fd) {
    var socktype = Socket.type(fd);
    if (socktype === 'tcp' || socktype === 'tcp6' || socktype === 'udp' || socktype === 'udp6') {
        if (socktype === 'udp6' && ObjC.available) {
            return false; // on iOS this leads always to empty addresses
        }
        return true;
    }
    return true;
}
export function socket_trace_execute() {
    //log("Doing a full packet capture\nUse -k in order to get TLS keys.");
    var socket_library = "";
    switch (Process.platform) {
        case "linux":
            socket_library = "libc";
            break;
        case "windows":
            socket_library = "WS2_32.dll";
            break;
        case "darwin":
            socket_library = "libSystem.B.dylib";
            break;
        default:
            log(`Platform "${Process.platform} currently not supported!`);
    }
    var library_method_mapping = {};
    const socketFDs = new Map();
    if (ObjC.available) {
        // currently those libraries gets only detected on iOS if we add an *-sign
        library_method_mapping[`*${socket_library}*`] = ["getpeername*", "getsockname*", "socket*", "ntohs*", "ntohl*", "recv*", "recvfrom*", "send*", "sendto*", "read*", "write*"];
    }
    else {
        library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl", "socket", "recv", "recvfrom", "send", "sendto", "read", "write", "connect"];
    }
    var addresses;
    addresses = readAddresses(socket_library, library_method_mapping);
    if (!addresses[socket_library] || !addresses[socket_library]["socket"] || !addresses[socket_library]["connect"]) {
        throw new Error(`Missing required functions in ${socket_library}. Ensure "socket" and "connect" are exported by the library.`);
    }
    Interceptor.attach(addresses[socket_library]["socket"], {
        onEnter: function (args) {
        },
        onLeave: function (retval) {
            this.fd = retval.toInt32();
            if (socketFDs.has(this.fd)) {
                return;
            }
            if (has_valid_socket_type(this.fd)) {
                var message = getPortsAndAddresses(this.fd, false, addresses[socket_library], enable_default_fd);
                if (message === null) {
                    return;
                }
                message["function"] = "Full_read";
                message["contentType"] = "netlog";
                socketFDs.set(this.fd, message["dst_addr"]);
                send(message);
            }
        }
    });
    Interceptor.attach(addresses[socket_library]["connect"], {
        onEnter: function (args) {
            this.fd = args[0].toInt32();
        },
        onLeave: function (retval) {
            if (socketFDs.has(this.fd)) {
                return;
            }
            if (has_valid_socket_type(this.fd)) {
                var message = getPortsAndAddresses(this.fd, false, addresses[socket_library], enable_default_fd);
                if (message === null) {
                    return;
                }
                message["function"] = "Full_read";
                message["contentType"] = "netlog";
                socketFDs.set(this.fd, message["dst_addr"]);
                send(message);
            }
        }
    });
    Interceptor.attach(addresses[socket_library]["read"], {
        onEnter: function (args) {
            this.fd = args[0].toInt32();
        },
        onLeave: function (retval) {
            if (socketFDs.has(this.fd)) {
                return;
            }
            if (has_valid_socket_type(this.fd)) {
                var message = getPortsAndAddresses(this.fd, true, addresses[socket_library], enable_default_fd);
                if (message === null) {
                    return;
                }
                message["function"] = "Full_read";
                message["contentType"] = "netlog";
                socketFDs.set(this.fd, message["src_addr"]);
                send(message);
            }
        }
    });
    Interceptor.attach(addresses[socket_library]["recv"], {
        onEnter: function (args) {
            this.fd = args[0].toInt32();
        },
        onLeave: function (retval) {
            if (socketFDs.has(this.fd)) {
                return;
            }
            if (has_valid_socket_type(this.fd)) {
                var message = getPortsAndAddresses(this.fd, true, addresses[socket_library], enable_default_fd);
                if (message === null) {
                    return;
                }
                message["function"] = "Full_read";
                message["contentType"] = "netlog";
                socketFDs.set(this.fd, message["src_addr"]);
                send(message);
            }
        }
    });
    Interceptor.attach(addresses[socket_library]["recvfrom"], {
        onEnter: function (args) {
            this.fd = args[0].toInt32();
        },
        onLeave: function (retval) {
            if (socketFDs.has(this.fd)) {
                return;
            }
            if (has_valid_socket_type(this.fd)) {
                var message = getPortsAndAddresses(this.fd, true, addresses[socket_library], enable_default_fd);
                if (message === null) {
                    return;
                }
                message["function"] = "Full_read";
                message["contentType"] = "netlog";
                socketFDs.set(this.fd, message["src_addr"]);
                send(message);
            }
        }
    });
    Interceptor.attach(addresses[socket_library]["send"], {
        onEnter: function (args) {
            this.fd = args[0].toInt32();
        },
        onLeave: function (retval) {
            if (socketFDs.has(this.fd)) {
                return;
            }
            if (has_valid_socket_type(this.fd)) {
                var message = getPortsAndAddresses(this.fd, false, addresses[socket_library], enable_default_fd);
                if (message === null) {
                    return;
                }
                message["function"] = "Full_write";
                message["contentType"] = "netlog";
                socketFDs.set(this.fd, message["dst_addr"]);
                send(message);
            }
        }
    });
    Interceptor.attach(addresses[socket_library]["sendto"], {
        onEnter: function (args) {
            this.fd = args[0].toInt32();
        },
        onLeave: function (retval) {
            if (socketFDs.has(this.fd)) {
                return;
            }
            if (has_valid_socket_type(this.fd)) {
                var message = getPortsAndAddresses(this.fd, false, addresses[socket_library], enable_default_fd);
                if (message === null) {
                    return;
                }
                message["function"] = "Full_write";
                message["contentType"] = "netlog";
                socketFDs.set(this.fd, message["dst_addr"]);
                send(message);
            }
        }
    });
    Interceptor.attach(addresses[socket_library]["write"], {
        onEnter: function (args) {
            this.fd = args[0].toInt32();
        },
        onLeave: function (retval) {
            if (socketFDs.has(this.fd)) {
                return;
            }
            if (has_valid_socket_type(this.fd)) {
                var message = getPortsAndAddresses(this.fd, false, addresses[socket_library], enable_default_fd);
                if (message === null) {
                    return;
                }
                message["function"] = "Full_write";
                message["contentType"] = "netlog";
                socketFDs.set(this.fd, message["dst_addr"]);
                send(message);
            }
        }
    });
    if (ObjC.available) {
        Interceptor.attach(Module.getExportByName("libsystem_kernel.dylib", "write"), {
            onEnter: function (args) {
                var fd = args[0].toInt32();
                if (socketFDs.has(fd)) {
                    return;
                }
                if (has_valid_socket_type(fd)) {
                    var message = getPortsAndAddresses(fd, false, addresses[socket_library], enable_default_fd);
                    if (message === null) {
                        //devlog("Skipping this socket due to unsupported address family."); To noisy
                        return;
                    }
                    message["function"] = "Full_write";
                    message["contentType"] = "netlog";
                    socketFDs.set(this.fd, message["dst_addr"]);
                    send(message);
                }
            },
            onLeave: function (retval) {
            }
        });
        Interceptor.attach(Module.getExportByName("libsystem_kernel.dylib", "read"), {
            onEnter: function (args) {
                this.fd = args[0].toInt32();
            },
            onLeave: function (retval) {
                if (socketFDs.has(this.fd)) {
                    return;
                }
                if (has_valid_socket_type(this.fd)) {
                    var message = getPortsAndAddresses(this.fd, true, addresses[socket_library], enable_default_fd);
                    if (message === null) {
                        return;
                    }
                    message["function"] = "Full_read";
                    message["contentType"] = "netlog";
                    socketFDs.set(this.fd, message["src_addr"]);
                    send(message);
                }
            }
        });
    }
}
// the low level part is under development and currently not exported for usage
var socket_syscall_lookup_table = {
    "Android_arm64": 198
};
function get_syscall_intruction() {
    var arch = get_process_architecture();
    var syscall_inst = "";
    if (arch === "arm") {
        syscall_inst = "swi";
    }
    else if (arch === "arm64") {
        syscall_inst = "svc";
    }
    else if (arch === "ia32") {
        syscall_inst = "int 0x80";
    }
    else {
        syscall_inst = "syscall";
    }
    return syscall_inst;
}
/*

Process
Process.id: property containing the PID as a number

Process.arch: property containing the string ia32, x64, arm or arm64

Process.platform: property containing the string windows, darwin, linux or qnx */
function get_socket_syscall_number() {
    return socket_syscall_lookup_table[get_syscall_intruction()];
}
/*
fuction get_socket_syscall(){
    // ARM64    [198,"socket",0xc6,["int","int","int"]],
}*/ 
✄
{"version":3,"file":"library_identification.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/shared/library_identification.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CAAC,eAAe,CAAC;SACzC,CAAC,CAAC;KACN;IAED,OAAO,0BAA0B,CAAC;AACpC,CAAC"}
✄
import { devlog } from "../util/log.js";
import { invokeHookingFunction } from "../shared/shared_functions.js";
export function findModulesWithSSLKeyLogCallback() {
    const modules = Process.enumerateModules();
    const matchedModules = [];
    for (const mod of modules) {
        // Skip modules we are already hooking
        if (/.*libssl_sb\.so/.test(mod.name) || /.*libssl\.so/.test(mod.name) || /ibconscrypt_jni.so/.test(mod.name) || /libconscrypt_gmscore_jni.so/.test(mod.name)) {
            continue;
        }
        /*
        in future releases we want the below checks to be done only on these packages
        let targetAppPackageName = getPackageName();
        if (targetAppPackageName && mod.path.includes(targetAppPackageName)) {
        }
        */
        const targetModule = Process.getModuleByName(mod.name);
        const exports = targetModule.enumerateExports();
        for (const exp of exports) {
            if (exp.name === "SSL_CTX_set_keylog_callback") {
                matchedModules.push(mod.name);
                // Once we know it has the symbol, no need to check other exports
                break;
            }
        }
    }
    return matchedModules;
}
export function createModuleLibraryMappingExtend(matchedModules, hookingFunction) {
    const moduleLibraryMappingExtend = [];
    for (const mod of matchedModules) {
        devlog("[!] Installing BoringSSL hooks for " + mod);
        moduleLibraryMappingExtend.push([
            new RegExp(`.*${mod}`),
            invokeHookingFunction(hookingFunction)
        ]);
    }
    return moduleLibraryMappingExtend;
}
✄
{"version":3,"file":"pattern_based_hooking.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/shared/pattern_based_hooking.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,KAAK,EAAC,OAAO,EAAE,MAAM,0BAA0B,CAAA;AAgBnE,MAAM,UAAU,wBAAwB,CACpC,eAAoG;IAEpG,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC,yCAAyC;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E,YAAY,CAAC,CAAC;SACtG;aAAK;YACF,KAAK,MAAM,cAAc,IAAI,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE;gBAChD,IAAI,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE;oBACzB,IAAI,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,EAAE;wBAC1G,IAAI,CAAC,4BAA4B,CAAC,WAAW,EAAE,cAAc,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,CAAC,CAAC;qBAChG;iBACJ;qBAAI;oBACD,MAAM,CAAC,qEAAqE,CAAC,CAAC;iBACjF;aACJ;SAEJ;IACL,CAAC;CACJ"}
✄
import { devlog, devlog_error, log } from "../util/log.js";
import { isAndroid, isiOS, isMacOS } from "../util/process_infos.js";
export function get_CPU_specific_pattern(default_pattern) {
    let arch = Process.arch.toString(); // Get architecture, e.g., "x64", "arm64"
    if (arch === "ia32") {
        arch = "x86";
    }
    devlog("Trying Pattern: " + JSON.stringify(default_pattern[arch]));
    if (default_pattern[arch]) {
        return default_pattern[arch]; // Return the pattern for the architecture
    }
    else {
        throw new Error(`No patterns found for CPU architecture: ${arch}`);
    }
}
export class PatternBasedHooking {
    constructor(module) {
        this.patterns = {};
        this.rescannedRanges = new Set(); // Set to keep track of memory ranges that have been rescanned
        this.found_ssl_log_secret = false;
        this.module = module;
        if (this.module === null) {
            devlog_error("[-] PatternBasedHooking Error: Unable to find module: " + this.module.name);
            devlog_error("[-] PatternBasedHooking Error: Abborting...");
            return;
        }
        this.no_hooking_success = true;
    }
    createRegexFromModule(moduleName) {
        // Match the base name and ensure it ends with .so
        const baseName = moduleName.replace(/\d+(\.\d+)*\.so$/, '.so');
        // Create the regex to match the base name with any version numbers
        const regexPattern = `.*${baseName.replace(/\./g, '\\.')}$`;
        return new RegExp(regexPattern);
    }
    hookByPatternOnReturn(patterns, pattern_name, userCallback, maxArgs, onCompleteCallback) {
        const moduleBase = this.module.base;
        const moduleSize = this.module.size;
        this.found_ssl_log_secret = false;
        let pattern;
        if (pattern_name === "primary_pattern") {
            pattern = patterns.primary;
        }
        else {
            pattern = patterns.fallback;
        }
        Memory.scan(moduleBase, moduleSize, pattern, {
            onMatch: (address) => {
                this.found_ssl_log_secret = true;
                this.no_hooking_success = false;
                var module_by_address = Process.findModuleByAddress(address);
                log(`Pattern found at (${pattern_name}) address: ${address} in module ${module_by_address.name}`);
                log(`Pattern-based hooks installed (onReturn).`);
                Interceptor.attach(address, {
                    onEnter: function (args) {
                        // store the arguments so we can use them onLeave
                        //(this as any).storedArgs = Array.from(args);
                        const stored = [];
                        // We do a small loop up to maxArgs
                        for (let i = 0; i <= maxArgs; i++) {
                            try {
                                stored.push(args[i]);
                            }
                            catch (_e) {
                                console.log("error :" + i + " with error :" + _e);
                                // Possibly out-of-range => break
                                break;
                            }
                        }
                        this.storedArgs = stored;
                    },
                    onLeave: function (retval) {
                        const storedArgs = this.storedArgs || [];
                        userCallback(storedArgs, retval);
                    },
                });
            },
            onError: (reason) => {
                if (!this.found_ssl_log_secret) {
                    devlog_error("There was an error scanning memory: " + reason);
                    devlog_error("Trying to rescan memory with permissions in mind");
                    this.hookByPatternOnlyReadablePartsOnReturn(patterns, pattern_name, userCallback, (patternSuccess) => {
                        if (!patternSuccess) {
                            devlog("Primary pattern failed, trying fallback pattern (onReturn)...");
                            this.hookByPatternOnlyReadablePartsOnReturn(patterns, "fallback_pattern", userCallback, (patternSuccessAlt) => {
                                if (!patternSuccessAlt) {
                                    devlog("None of the patterns worked. Adjust or fallback.");
                                    this.no_hooking_success = true;
                                }
                            }, maxArgs);
                        }
                    }, maxArgs);
                }
            },
            onComplete: () => {
                onCompleteCallback(this.found_ssl_log_secret);
            },
        });
    }
    /**
 *  For hooking modules with either the primary or fallback pattern (onReturn)
 */
    hookModuleByPatternOnReturn(patterns, userCallback, maxArgs) {
        const moduleBase = this.module.base;
        const moduleSize = this.module.size;
        devlog(`Module Base Address: ${moduleBase}`);
        devlog(`Module Size: ${moduleSize}`);
        this.hookByPatternOnReturn(patterns, "primary_pattern", userCallback, maxArgs, (pattern_success) => {
            if (!pattern_success) {
                devlog("Primary pattern failed, trying fallback pattern (onReturn)...");
                this.hookByPatternOnReturn(patterns, "fallback_pattern", userCallback, maxArgs, (pattern_success_alt) => {
                    if (!pattern_success_alt) {
                        devlog("None of the onReturn patterns worked. Adjust patterns as needed.");
                        this.no_hooking_success = true;
                    }
                });
            }
        });
    }
    invoke_pattern_based_hooking_onReturn(action, module_name, platform, arch, userCallback, maxArgs) {
        const action_specific_patterns = this.get_action_specific_pattern(module_name, platform, arch, action);
        devlog(`Using ${action} patterns for ${platform} on ${arch} (onReturn)`);
        this.hookModuleByPatternOnReturn(action_specific_patterns, userCallback, maxArgs);
    }
    hook_with_pattern_from_json_onReturn(action_type, module_name, json_module_name, jsonContent, userCallback, maxArgs) {
        this.loadPatternsFromJSON(jsonContent);
        let platform = Process.platform.toString(); // e.g., "linux", "android"
        if (isAndroid())
            platform = "android";
        else if (isiOS())
            platform = "ios";
        else if (isMacOS())
            platform = "macos";
        let arch = Process.arch.toString(); // e.g., "x64", "arm64"
        if (arch === "ia32")
            arch = "x86";
        const regex = this.createRegexFromModule(module_name);
        if (this.patterns.modules[module_name] &&
            this.patterns.modules[module_name][platform] &&
            this.patterns.modules[module_name][platform][arch]) {
            this.invoke_pattern_based_hooking_onReturn(action_type, module_name, platform, arch, userCallback, maxArgs);
        }
        else if (this.patterns.modules[json_module_name] &&
            this.patterns.modules[json_module_name][platform] &&
            this.patterns.modules[json_module_name][platform][arch]) {
            this.invoke_pattern_based_hooking_onReturn(action_type, json_module_name, platform, arch, userCallback, maxArgs);
        }
        else {
            for (const jsonModuleName in this.patterns.modules) {
                if (regex.test(module_name)) {
                    if (this.patterns.modules[jsonModuleName][platform] &&
                        this.patterns.modules[jsonModuleName][platform][arch]) {
                        this.invoke_pattern_based_hooking_onReturn(action_type, jsonModuleName, platform, arch, userCallback, maxArgs);
                    }
                }
                else {
                    devlog("[-] No patterns available for the current platform or architecture.");
                }
            }
        }
    }
    // Method to hook by pattern, with a custom function to handle onEnter and onLeave
    hookByPattern(patterns, pattern_name, onMatchCallback, onCompleteCallback) {
        const moduleName = this.module?.name;
        devlog(`Trying to scan ${moduleName} ...`);
        const moduleBase = this.module.base;
        const moduleSize = this.module.size;
        this.found_ssl_log_secret = false;
        let pattern;
        if (pattern_name === "primary_pattern") {
            pattern = patterns.primary;
        }
        else if (pattern_name === "fallback_pattern") {
            pattern = patterns.fallback;
        }
        else if (pattern_name === "second_fallback_pattern" && patterns.second_fallback) {
            pattern = patterns.second_fallback;
        }
        else {
            devlog_error(`Pattern ${pattern_name} not found or not provided.`);
            onCompleteCallback(false);
            return;
        }
        Memory.scan(moduleBase, moduleSize, pattern, {
            onMatch: (address) => {
                this.found_ssl_log_secret = true;
                this.no_hooking_success = false;
                if (!moduleName) {
                    log(`Pattern found at (${pattern_name}) address: ${address} for module ${moduleName}`);
                }
                else {
                    log(`Pattern found at (${pattern_name}) address: ${address}`);
                }
                log(`Pattern-based hooks installed.`);
                // Attach the hook using the provided onMatchCallback
                Interceptor.attach(address, {
                    onEnter: function (args) {
                        onMatchCallback(args);
                    },
                });
            },
            onError: (reason) => {
                if (!this.found_ssl_log_secret) {
                    devlog_error('[!] There was an error scanning memory: ' + reason);
                    devlog_error(`[!] Trying to rescan memory with permissions in mind on ${moduleName}`);
                    this.hookByPatternOnlyReadableParts(patterns, pattern_name, onMatchCallback, (primary_success) => {
                        if (!primary_success) {
                            devlog(`[!] Primary pattern failed, trying fallback pattern on ${moduleName}`);
                            this.hookByPatternOnlyReadableParts(patterns, "fallback_pattern", onMatchCallback, (fallback_success) => {
                                if (!fallback_success) {
                                    devlog(`[!] Fallback pattern failed, trying second fallback pattern on ${moduleName}`);
                                    this.hookByPatternOnlyReadableParts(patterns, "second_fallback_pattern", onMatchCallback, (second_fallback_success) => {
                                        if (!second_fallback_success) {
                                            devlog(`[!] None of the patterns worked. You may need to adjust the patterns for ${moduleName}`);
                                            this.no_hooking_success = true;
                                        }
                                    });
                                }
                            });
                        }
                    });
                }
            },
            onComplete: () => {
                onCompleteCallback(this.found_ssl_log_secret);
            },
        });
    }
    // Method to hook by pattern, with a custom function to handle onEnter and onLeave
    hookByPatternOnlyReadableParts(patterns, pattern_name, onMatchCallback, onCompleteCallback) {
        const moduleName = this.module?.name;
        devlog(`trying to scan only readable parts of ${moduleName} ...`);
        var pattern = "";
        if (pattern_name === "primary_pattern") {
            pattern = patterns.primary;
        }
        else if (pattern_name === "fallback_pattern") {
            pattern = patterns.fallback;
        }
        else if (pattern_name === "second_fallback_pattern" && patterns.second_fallback) {
            pattern = patterns.second_fallback;
        }
        else {
            pattern = patterns.fallback;
        }
        // Enumerate all readable memory ranges of the specified module and scan each one
        this.module.enumerateRanges('r--').forEach((range) => {
            const rangeKey = `${range.base}-${range.size}`; // Unique key for each memory range
            // only uncomment this if we need to track a bug
            //devlog(`Scanning readable memory range in module: ${this.module.name}, Range: ${range.base} - ${range.base.add(range.size)}, Size: ${range.size}`);
            Memory.scan(range.base, range.size, pattern, {
                onMatch: (address, size) => {
                    this.found_ssl_log_secret = true;
                    log(`Pattern found at (${pattern_name}) address: ${address.toString()} on ${moduleName}`);
                    log(`Pattern based hooks installed.`);
                    // Attach the hook using the provided onMatchCallback
                    Interceptor.attach(address, {
                        onEnter: function (args) {
                            onMatchCallback(args);
                        },
                        onLeave: function (retval) {
                            // Optionally handle return value or additional behavior
                        }
                    });
                },
                onError: (reason) => {
                    //devlog_error(`Error scanning memory for range: ${range.base} - ${range.base.add(range.size)}, Reason: ${reason}`);
                },
                onComplete: () => {
                    if (this.rescannedRanges.has(rangeKey)) {
                        return;
                    }
                    else {
                        onCompleteCallback(this.found_ssl_log_secret);
                    }
                }
            });
        });
    }
    hookByPatternOnlyReadablePartsOnReturn(patterns, pattern_name, userCallback, onCompleteCallback, maxArgs = 8) {
        devlog(`Trying to scan only readable parts of ${this.module.name} ...`);
        let pattern;
        if (pattern_name === "primary_pattern") {
            pattern = patterns.primary;
        }
        else {
            pattern = patterns.fallback;
        }
        var ranges = Process.enumerateRanges('r--');
        let found = false;
        //ranges.forEach((range: MemoryRange) => {
        for (let i = 0; i < ranges.length; i++) {
            if (found) {
                // If a match was found, stop iterating the ranges altogether.
                break;
            }
            const range = ranges[i];
            const rangeKey = `${range.base}-${range.size}`;
            /*devlog(
                `Scanning readable memory range in module: ${this.module.name}, Range: ${range.base} - ${range.base.add(
                    range.size
                )}, Size: ${range.size}`
            );*/
            Memory.scan(range.base, range.size, pattern, {
                onMatch: (address) => {
                    this.found_ssl_log_secret = true;
                    var module_by_address = Process.findModuleByAddress(address);
                    // In some case findModuleByAddress might return null
                    //devlog(`Pattern: ${pattern}`);
                    if (module_by_address) {
                        log(`Pattern found at (${pattern_name}) address: ${address} in module ${module_by_address.name}`);
                        let local_offset = address.sub(module_by_address.base);
                        log(`Ghidra offset (Base 0x0): ${local_offset}`);
                    }
                    log(`Pattern found at (${pattern_name}) address: ${address} in module <name_not_found>`);
                    log(`Could not get Ghidra offset`);
                    log(`Pattern-based hooks installed (onReturn).`);
                    Interceptor.attach(address, {
                        onEnter: function (args) {
                            // store the arguments so we can use them onLeave
                            //(this as any).storedArgs = Array.from(args);
                            const stored = [];
                            // We do a small loop up to maxArgs
                            for (let i = 0; i <= maxArgs; i++) {
                                try {
                                    stored.push(args[i]);
                                }
                                catch (_e) {
                                    console.log("i = " + i + "  error: " + _e);
                                    // Possibly out-of-range => break
                                    break;
                                }
                            }
                            this.storedArgs = stored;
                        },
                        onLeave: function (retval) {
                            const storedArgs = this.storedArgs || [];
                            userCallback(storedArgs, retval);
                        },
                    });
                    found = true; // So we know to break out of the outer loop
                    return "stop"; // Stop scanning the current range immediately
                },
                onError: (reason) => {
                    // only for debugging purpose
                    /*
                    devlog_error(
                        `Error scanning memory for range: ${range.base} - ${range.base.add(
                            range.size
                        )}, Reason: ${reason}`
                    );
                    */
                },
                onComplete: () => {
                    if (this.rescannedRanges.has(rangeKey)) {
                        return;
                    }
                    else {
                        //onCompleteCallback(this.found_ssl_log_secret);
                    }
                },
            });
        }
        //);
    }
    // Method to hook the module with patterns provided as arguments
    hookModuleByPattern(patterns, onMatchCallback) {
        this.hookByPattern(patterns, "primary_pattern", onMatchCallback, (primary_success) => {
            if (!primary_success) {
                devlog("Primary pattern failed, trying fallback pattern...");
                this.hookByPattern(patterns, "fallback_pattern", onMatchCallback, (fallback_success) => {
                    if (!fallback_success && patterns.second_fallback) {
                        devlog("Fallback pattern failed, trying second fallback pattern...");
                        this.hookByPattern(patterns, "second_fallback_pattern", onMatchCallback, (second_fallback_success) => {
                            if (!second_fallback_success) {
                                devlog("None of the patterns worked. Adjust patterns as needed.");
                                this.no_hooking_success = true;
                            }
                        });
                    }
                    else if (!fallback_success) {
                        devlog("None of the patterns worked. Adjust patterns as needed.");
                        this.no_hooking_success = true;
                    }
                });
            }
        });
    }
    loadPatternsFromJSON(jsonContent) {
        try {
            this.patterns = JSON.parse(jsonContent);
            devlog("Patterns loaded successfully from JSON.");
        }
        catch (error) {
            devlog("[-] Error loading or parsing JSON pattern:  " + error);
        }
    }
    invoke_pattern_based_hooking(action, module_name, platform, arch, hookCallback) {
        var action_specific_patterns = this.get_action_specific_pattern(module_name, platform, arch, action);
        devlog(`Using ${action} patterns for ${platform} on ${arch}`);
        this.hookModuleByPattern(action_specific_patterns, hookCallback);
    }
    // Function to retrieve patterns based on the current CPU architecture and action
    get_action_specific_pattern(module_name, platform, arch, action) {
        const archPatterns = this.patterns.modules[module_name][platform][arch];
        if (archPatterns[action]) {
            return archPatterns[action];
        }
        else {
            devlog(`No patterns found for action: ${action} on architecture: ${arch}`);
        }
    }
    hook_DumpKeys(module_name, json_module_name, jsonContent, hookCallback, onReturn = false, maxArgs = 8) {
        //this.hook_with_pattern_from_json("Dump-Keys",module_name, json_module_name, jsonContent, hookCallback);
        if (!onReturn) {
            // Hook onEnter: callback gets (args, undefined)
            this.hook_with_pattern_from_json("Dump-Keys", module_name, json_module_name, jsonContent, hookCallback);
        }
        else {
            // Hook onReturn: callback gets (args, retval)
            this.hook_with_pattern_from_json_onReturn("Dump-Keys", module_name, json_module_name, jsonContent, hookCallback, maxArgs);
        }
    }
    hook_tls_keylog_callback(module_name, json_module_name, jsonContent, hookCallback) {
        this.hook_with_pattern_from_json("KeyLogCallback-Function", module_name, json_module_name, jsonContent, hookCallback);
        this.hook_with_pattern_from_json("Install-Key-Log-Callback", module_name, json_module_name, jsonContent, hookCallback);
    }
    hook_ssl_read_and_write(module_name, json_module_name, jsonContent, hookCallback) {
        this.hook_with_pattern_from_json("SSL_Read", module_name, json_module_name, jsonContent, hookCallback);
        this.hook_with_pattern_from_json("SSL_Write", module_name, json_module_name, jsonContent, hookCallback);
    }
    // Method to hook functions using patterns from JSON
    hook_with_pattern_from_json(action_type, module_name, json_module_name, jsonContent, hookCallback) {
        // Load patterns from the JSON file
        this.loadPatternsFromJSON(jsonContent);
        let platform = Process.platform.toString(); // e.g., linux, android
        if (isAndroid()) {
            platform = "android";
        }
        else if (isiOS()) {
            platform = "ios";
        }
        else if (isMacOS()) {
            platform = "macos";
        }
        let arch = Process.arch.toString(); // e.g., x64, arm64
        if (arch == "ia32") {
            arch = "x86";
        }
        const regex = this.createRegexFromModule(module_name);
        // Access the relevant pattern for the module based on platform and architecture
        if (this.patterns.modules[module_name] &&
            this.patterns.modules[module_name][platform] &&
            this.patterns.modules[module_name][platform][arch]) {
            this.invoke_pattern_based_hooking(action_type, module_name, platform, arch, hookCallback);
        }
        else if (this.patterns.modules[json_module_name] &&
            this.patterns.modules[json_module_name][platform] &&
            this.patterns.modules[json_module_name][platform][arch]) {
            this.invoke_pattern_based_hooking(action_type, json_module_name, platform, arch, hookCallback);
        }
        else {
            for (const jsonModuleName in this.patterns.modules) {
                if (regex.test(module_name)) {
                    if (this.patterns.modules[jsonModuleName][platform] && this.patterns.modules[jsonModuleName][platform][arch]) {
                        this.invoke_pattern_based_hooking(action_type, jsonModuleName, platform, arch, hookCallback);
                    }
                }
                else {
                    devlog("[-] No patterns available for the current platform or architecture.");
                }
            }
        }
    }
}
✄
{"version":3,"file":"shared_functions.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/shared/shared_functions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,oBAAoB,EAAE,WAAW,EAAqB,MAAM,wBAAwB,CAAC;AAGjH,SAAS,uBAAuB,CAAC,WAAmB;IAChD,IAAI,eAAe,GAAG,CAAC,CAAC;IACxB,IAAI,aAAa,GAAG,MAAM,CAAC,eAAe,CAAC,WAAW,CAAC,CAAC;IACxD,IAAG,aAAa,KAAK,IAAI,IAAI,aAAa,KAAK,IAAI,EAAC;QAChD,GAAG,CAAC,cAAc,GAAC,eAAe,GAAC,mCAAmC,GAAC,WAAW,CAAC,CAAC;QACpF,UAAU,CAAC,uBAAuB,EAAC,eAAe,CAAC,CAAA;KACtD;AACL,CAAC;AAED;;;;;GAKG;AAEH,MAAM,UAAU,kBAAkB,CAAC,cAAsB,EAAE,sBAA0E,EAAE,WAA0B,EAAG,YAAoB,EAAE,YAAqB;IAC3M,KAAI,IAAI,GAAG,IAAI,sBAAsB,CAAC,cAAc,CAAC,EAAC;QAClD,IAAI,KAAK,GAAG,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;QAC9B,IAAI,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,CAAA;QACjB,KAAI,IAAI,MAAM,IAAI,WAAW,EAAC;YAC1B,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,EAAC;gBACnB,IAAG;oBACC,G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AAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,4CAA4C;SAC1G,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,uCAAuC;AAC1D,CAAC;AAGD,MAAM,UAAU,UAAU,CAAC,QAAQ,EAAC,IAAI;IACpC,mBAAmB;IACnB,IAAI;QACA,OAAO,CAAC,GAAG,CAAC,iCAAiC,GAAC,QAAQ,CAAC,CAAC;QACxD,YAAY;QACZ,IAAI,IAAI,GAAG,MAAM,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QAChD,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;QAC3B,OAAO,IAAI,CAAC;QACZ,qFAAqF;KACxF;IAAC,OAAO,KAAK,EAAE;QACZ,OAAO,CAAC,GAAG,CAAC,2BAA2B,GAAG,QAAQ,GAAG,KAAK,GAAG,KAAK,CAAC,CAAC;QACpE,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QACjB,OAAO,IAAI,CAAC;KACf;AACL,CAAC"}
✄
import { log, devlog, devlog_error } from "../util/log.js";
import { AF_INET, AF_INET6, AddressFamilyMapping, unwantedFDs } from "./shared_structures.js";
function wait_for_library_loaded(module_name) {
    let timeout_library = 5;
    let module_adress = Module.findBaseAddress(module_name);
    if (module_adress === NULL || module_adress === null) {
        log("[*] Waiting " + timeout_library + " milliseconds for the loading of " + module_name);
        setTimeout(wait_for_library_loaded, timeout_library);
    }
}
/**
 * This file contains methods which are shared for reading
 * secrets/data from different libraries. These methods are
 * indipendent from the implementation of ssl/tls, but they depend
 * on libc.
 */
export function ssl_library_loader(plattform_name, module_library_mapping, moduleNames, plattform_os, is_base_hook) {
    for (let map of module_library_mapping[plattform_name]) {
        let regex = new RegExp(map[0]);
        let func = map[1];
        for (let module of moduleNames) {
            if (regex.test(module)) {
                try {
                    log(`${module} found & will be hooked on ${plattform_os}!`);
                    try {
                        Module.ensureInitialized(module);
                    }
                    catch (error) {
                        wait_for_library_loaded(module);
                    }
                    // on some Android Apps we encounterd the problem of multiple SSL libraries but only one is used for the SSL encryption/decryption
                    func(module, is_base_hook);
                }
                catch (error) {
                    if (checkNumberOfExports(module) > 3) {
                        devlog_error(`error: skipping module ${module}`);
                        // when we enable the logging of devlogs we can print the error message as well for further improving this part
                        devlog_error("Loader error: " + error);
                        //  {'description': 'Could not find *libssl*.so!SSL_ImportFD', 'type': 'error'}
                    }
                }
            }
        }
    }
}
export function getSocketLibrary() {
    var moduleNames = getModuleNames();
    switch (Process.platform) {
        case "linux":
            return moduleNames.find(element => element.match(/libc.*\.so/));
        case "windows":
            return "WS2_32.dll";
        case "darwin":
            return "libSystem.B.dylib";
        default:
            log(`Platform "${Process.platform} currently not supported!`);
            return "";
    }
}
export function getModuleNames() {
    var moduleNames = [];
    Process.enumerateModules().forEach(item => moduleNames.push(item.name));
    return moduleNames;
}
export function checkNumberOfExports(moduleName) {
    try {
        // Get the module by name
        const module = Process.getModuleByName(moduleName);
        // Enumerate exports of the module
        const exports = module.enumerateExports();
        // Get the number of exports
        const numberOfExports = exports.length;
        // Log the result
        devlog(`The module "${moduleName}" has ${numberOfExports} exports.`);
        return numberOfExports;
    }
    catch (error) {
        devlog(`Error checking exports for module "${moduleName}": ${error}`);
        return -1;
    }
}
export function hasMoreThanFiveExports(moduleName) {
    // Get the target module
    const targetModule = Process.getModuleByName(moduleName);
    // Return false if module doesn't exist
    if (!targetModule) {
        devlog(`Module ${moduleName} not found`);
        return false;
    }
    try {
        // Enumerate exports from the module
        const exports = targetModule.enumerateExports();
        // Return true if there are more than 5 exports
        return exports.length > 5;
    }
    catch (error) {
        devlog(`Error enumerating exports for ${moduleName}:` + error);
        return false;
    }
}
export function readAddresses(moduleName, library_method_mapping) {
    const resolver = new ApiResolver("module");
    const addresses = {};
    // Initialize addresses[moduleName] as an empty object if not already initialized
    if (!addresses[moduleName]) {
        addresses[moduleName] = {};
    }
    for (const library_name in library_method_mapping) {
        library_method_mapping[library_name].forEach(function (method) {
            const matches = resolver.enumerateMatches("exports:" + library_name + "!" + method);
            let match_number = 0;
            let method_name = method.toString();
            if (method_name.endsWith("*")) { // this is for the temporary iOS bug using Frida's ApiResolver
                method_name = method_name.substring(0, method_name.length - 1);
            }
            if (!matches || matches === null) {
                devlog(`Unable to retrieve any matches for statement: exports: ${library_name}!${method}`);
                return;
            }
            if (matches.length == 0) {
                throw "Could not find " + library_name + "!" + method;
            }
            else if (matches.length == 1) {
                devlog("Found " + method + " " + matches[0].address);
            }
            else {
                // Sometimes Frida returns duplicates or it finds more than one result.
                for (let k = 0; k < matches.length; k++) {
                    if (matches[k].name.endsWith(method_name)) {
                        match_number = k;
                        devlog("Found " + method + " " + matches[match_number].address);
                        break;
                    }
                }
            }
            addresses[moduleName][method_name] = matches[match_number].address;
        });
    }
    return addresses;
}
/**
 * Read the addresses for the given methods from the given modules
 * @param {{[key: string]: Array<String> }} library_method_mapping A string indexed list of arrays, mapping modules to methods
 * @param is_base_hook a boolean value to indicate if this hooks are done on the start or during dynamic library loading
 * @return {{[key: string]: { [functionName: string]: NativePointer } }} A string indexed list of NativePointers, which point to the respective methods
 */
export function readAddresses2(moduleName, library_method_mapping) {
    var resolver = new ApiResolver("module");
    var addresses = {};
    // Initialize addresses[library_name] as an empty object if not already initialized
    if (!addresses[moduleName]) {
        addresses[moduleName] = {};
    }
    for (let library_name in library_method_mapping) {
        library_method_mapping[library_name].forEach(function (method) {
            var matches = resolver.enumerateMatches("exports:" + library_name + "!" + method);
            var match_number = 0;
            var method_name = method.toString();
            if (method_name.endsWith("*")) { // this is for the temporary iOS bug using Frida's ApiResolver
                method_name = method_name.substring(0, method_name.length - 1);
            }
            if (matches.length == 0) {
                throw "Could not find " + library_name + "!" + method;
            }
            else if (matches.length == 1) {
                devlog("Found " + method + " " + matches[0].address);
            }
            else {
                // Sometimes Frida returns duplicates or it finds more than one result.
                for (var k = 0; k < matches.length; k++) {
                    if (matches[k].name.endsWith(method_name)) {
                        match_number = k;
                        devlog("Found " + method + " " + matches[match_number].address);
                        break;
                    }
                }
            }
            addresses[moduleName][method_name] = matches[match_number].address;
        });
    }
    return addresses;
}
/**
 * Returns the base address of a given module
 * @param {string} moduleName Name of module to return base address from
 * @returns
 */
export function getBaseAddress(moduleName) {
    devlog("Module to find: " + moduleName);
    const modules = Process.enumerateModules();
    for (const module of modules) {
        if (module.name == moduleName) {
            return module.base;
        }
    }
    return null;
}
/**
* Returns a dictionary of a sockfd's "src_addr", "src_port", "dst_addr", and
* "dst_port".
* @param {int} sockfd The file descriptor of the socket to inspect.
* @param {boolean} isRead If true, the context is an SSL_read call. If
*     false, the context is an SSL_write call.
* @param {{ [key: string]: NativePointer}} methodAddresses Dictionary containing (at least) addresses for getpeername, getsockname, ntohs and ntohl
* @return {{ [key: string]: string | number }} Dictionary of sockfd's "src_addr", "src_port", "dst_addr",
*     and "dst_port".
*/
export function getPortsAndAddresses(sockfd, isRead, methodAddresses, enable_default_fd) {
    var message = {};
    if (enable_default_fd && (sockfd < 0)) {
        message["src" + "_port"] = 1234;
        message["src" + "_addr"] = "127.0.0.1";
        message["dst" + "_port"] = 2345;
        message["dst" + "_addr"] = "127.0.0.1";
        message["ss_family"] = "AF_INET";
        return message;
    }
    // Check if this fd is already marked as unwanted
    if (unwantedFDs.has(sockfd)) {
        return null; // Skip further processing
    }
    var getpeername = new NativeFunction(methodAddresses["getpeername"], "int", ["int", "pointer", "pointer"]);
    var getsockname = new NativeFunction(methodAddresses["getsockname"], "int", ["int", "pointer", "pointer"]);
    var ntohs = new NativeFunction(methodAddresses["ntohs"], "uint16", ["uint16"]);
    var ntohl = new NativeFunction(methodAddresses["ntohl"], "uint32", ["uint32"]);
    var addrlen = Memory.alloc(4);
    var addr = Memory.alloc(128);
    var src_dst = ["src", "dst"];
    for (let i = 0; i < src_dst.length; i++) {
        addrlen.writeU32(128);
        if ((src_dst[i] == "src") !== isRead) {
            devlog("src");
            getsockname(sockfd, addr, addrlen);
        }
        else {
            devlog("dst");
            getpeername(sockfd, addr, addrlen);
        }
        var family = addr.readU16();
        const familyName = AddressFamilyMapping[family] || `UNKNOWN`;
        if (addr.readU16() == AF_INET) {
            message[src_dst[i] + "_port"] = ntohs(addr.add(2).readU16());
            message[src_dst[i] + "_addr"] = ntohl(addr.add(4).readU32());
            message["ss_family"] = "AF_INET";
        }
        else if (addr.readU16() == AF_INET6) {
            message[src_dst[i] + "_port"] = ntohs(addr.add(2).readU16());
            message[src_dst[i] + "_addr"] = "";
            var ipv6_addr = addr.add(8);
            for (var offset = 0; offset < 16; offset += 1) {
                message[src_dst[i] + "_addr"] += ("0" + ipv6_addr.add(offset).readU8().toString(16).toUpperCase()).substr(-2);
            }
            if (message[src_dst[i] + "_addr"].toString().indexOf("00000000000000000000FFFF") === 0) {
                message[src_dst[i] + "_addr"] = ntohl(ipv6_addr.add(12).readU32());
                message["ss_family"] = "AF_INET";
            }
            else {
                message["ss_family"] = "AF_INET6";
            }
        }
        else {
            // only uncomment this if you really need to debug this
            //devlog("[-] getPortsAndAddresses resolving error: Only supporting IPv4/6");
            //devlog(`[-] Inspecting fd: ${sockfd}, Address family: ${family} (${familyName})`);
            //throw "Only supporting IPv4/6"
            if (!unwantedFDs.has(sockfd)) {
                //devlog(`Skipping unsupported address family: ${family}:${familyName} (fd: ${sockfd})`);
            }
            unwantedFDs.add(sockfd); // Mark this fd as unwanted
            return null;
        }
    }
    return message;
}
/**
 * Convert a Java byte array to string
 * @param byteArray The array to convert
 * @returns {string} The resulting string
 */
export function byteArrayToString(byteArray) {
    return Array.from(byteArray, function (byte) {
        return ('0' + (byte & 0xFF).toString(16)).slice(-2);
    }).join('');
}
export function toHexString(byteArray) {
    const byteToHex = [];
    for (let n = 0; n <= 0xff; ++n) {
        const hexOctet = n.toString(16).padStart(2, "0");
        byteToHex.push(hexOctet);
    }
    return Array.prototype.map.call(new Uint8Array(byteArray), n => byteToHex[n]).join("");
}
/**
 * Convert a Java Reflection array to string
 * @param byteArray The array to convert
 * @returns {string} The resulting string
 */
export function reflectionByteArrayToString(byteArray) {
    var result = "";
    var arrayReflect = Java.use("java.lang.reflect.Array");
    for (var i = 0; i < arrayReflect.getLength(byteArray); i++) {
        result += ('0' + (arrayReflect.get(byteArray, i) & 0xFF).toString(16)).slice(-2);
    }
    return result;
}
/**
 * Convert a Java byte arry to number (Big Endian)
 * @param byteArray The array to convert
 * @returns {number} The resulting number
 */
export function byteArrayToNumber(byteArray) {
    var value = 0;
    for (var i = 0; i < byteArray.length; i++) {
        value = (value * 256) + (byteArray[i] & 0xFF);
    }
    return value;
}
/**
 * Access an attribute of a Java Class
 * @param Instance The instace you want to access
 * @param fieldName The name of the attribute
 * @returns The value of the attribute of the requested field
 */
export function getAttribute(Instance, fieldName) {
    var clazz = Java.use("java.lang.Class");
    var field = Java.cast(Instance.getClass(), clazz).getDeclaredField(fieldName);
    field.setAccessible(true);
    return field.get(Instance);
}
/**
 *
 * @param moduleName String of the name of the module e.g. libssl.so
 * @param symbolName the symbol where we do our check e.g. SSL_write_ex
 * @returns
 */
export function isSymbolAvailable(moduleName, symbolName) {
    const resolver = new ApiResolver("module");
    const matches = resolver.enumerateMatches("exports:" + moduleName + "!" + symbolName);
    //devlog(`Matches content: ${matches}`);
    if (matches) {
        return matches.length > 0;
    }
    else {
        return false;
    }
}
// Wrapper function to ensure all execute functions conform to the required signature
export function invokeHookingFunction(func) {
    return (moduleName, is_base_hook) => {
        func(moduleName, is_base_hook);
    };
}
export function get_hex_string_from_byte_array(keyData) {
    return Array
        .from(new Uint8Array(keyData)) // Convert byte array to Uint8Array and then to Array
        .map(byte => byte.toString(16).padStart(2, '0').toUpperCase()) // Convert each byte to a 2-digit hex string
        .join(''); // Join all the hex values with a space
}
export function dumpMemory(ptrValue, size) {
    //var size = 0x100;
    try {
        console.log("[!] dumping memory at address: " + ptrValue);
        //@ts-ignore
        var data = Memory.readByteArray(ptrValue, size);
        console.log(hexdump(data));
        return data;
        // console.log(hexdump(data, { offset: 0, length: size, header: true, ansi: true }));
    }
    catch (error) {
        console.log("Error dumping memory at: " + ptrValue + " - " + error);
        console.log("\n");
        return null;
    }
}
✄
{"version":3,"file":"shared_structures.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/shared/shared_structures.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAG3D,MAAM,CAAC,IAAI,sBAAsB,GAAuD,EAAE,CAAC;AAE3F,MAAM,CAAC,MAAM,WAAW,GAAG,IAAI,GAAG,EAAU,CAAC,CAAC,0DAA0D;AAExG,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,CAAC;AACzB,MAAM,CAAC,MAAM,QAAQ,GAAG,EAAE,CAAC;AAC3B,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,CAAC;AACzB,MAAM,CAAC,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;AAE/C,MAAM,CAAC,MAAM,oBAAoB,GAA8B;IAC3D,CAAC,EAAE,SAAS;IACZ,EAAE,EAAE,UAAU;IACd,CAAC,EAAE,SAAS;IACZ,EAAE,EAAE,WAAW,EAAE,cAAc;IAC/B,uCAAuC;CAC1C,CAAC"}
✄
/* In this file we store global variables and structures */
export var module_library_mapping = {};
export const unwantedFDs = new Set(); // this helps us to track if we alredy encountered this fd
export const AF_INET = 2;
export const AF_INET6 = 10;
export const AF_UNIX = 1;
export const pointerSize = Process.pointerSize;
export const AddressFamilyMapping = {
    2: "AF_INET",
    10: "AF_INET6",
    1: "AF_UNIX",
    17: "AF_PACKET", // Raw packets
    // Add other address families as needed
};
✄
{"version":3,"file":"cronet.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ssl_lib/cronet.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,8BAA8B,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC9F,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC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2B;QACvB,MAAM;IACV,CAAC;IAED,4BAA4B;QACxB,MAAM;IACV,CAAC;IAED,2BAA2B;QACvB,+CAA+C;IACnD,CAAC;CACJ"}
✄
import { get_hex_string_from_byte_array, readAddresses } from "../shared/shared_functions.js";
import { devlog } from "../util/log.js";
export class Cronet {
    constructor(moduleName, socket_library, is_base_hook, passed_library_method_mapping) {
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.passed_library_method_mapping = passed_library_method_mapping;
        // global variables
        this.library_method_mapping = {};
        this.module_name = moduleName;
        this.is_base_hook = is_base_hook;
        if (typeof passed_library_method_mapping !== 'undefined') {
            this.library_method_mapping = passed_library_method_mapping;
        }
        else {
            this.library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        }
        this.addresses = readAddresses(moduleName, this.library_method_mapping);
    }
    get_client_random(s3_ptr, SSL3_RANDOM_SIZE) {
        if (!s3_ptr.isNull()) {
            const client_random_ptr = s3_ptr.add(0x30); // Offset in s3 struct
            //@ts-ignore
            const client_random = Memory.readByteArray(client_random_ptr, SSL3_RANDOM_SIZE);
            // Convert the byte array to a hex string
            const hexClientRandom = get_hex_string_from_byte_array(new Uint8Array(client_random));
            return hexClientRandom;
        }
        else {
            devlog("[Error] s3 pointer is NULL");
            return "";
        }
    }
    get_client_random_from_ssl_struct(ssl_st_ptr) {
        const SSL3_RANDOM_SIZE = 32;
        let offset_s3;
        switch (Process.arch) {
            case 'x64':
                offset_s3 = 0x30;
                break;
            case 'arm64':
                offset_s3 = 0x30;
                break;
            case 'ia32':
                offset_s3 = 0x2C;
                break;
            case 'arm':
                offset_s3 = 0x2C;
                break;
            default:
                devlog("[Error] Unsupported architecture");
                return "";
        }
        const s3_ptr = ssl_st_ptr.add(offset_s3).readPointer();
        return this.get_client_random(s3_ptr, SSL3_RANDOM_SIZE);
    }
    dumpKeys(labelPtr, sslStructPtr, keyPtr) {
        const MAX_KEY_LENGTH = 64;
        const RANDOM_KEY_LENGTH = 32;
        let labelStr = '';
        let client_random = '';
        let secret_key = '';
        // Read the label (the label pointer might contain a C string)
        if (!labelPtr.isNull()) {
            labelStr = labelPtr.readCString() ?? ''; // Read label as a C string
            //devlog(`Label: ${labelStr}`);
        }
        else {
            devlog("[Error] Argument 'labelPtr' is NULL");
        }
        // Extract client_random from the SSL structure
        if (!sslStructPtr.isNull()) {
            client_random = this.get_client_random_from_ssl_struct(sslStructPtr);
        }
        else {
            devlog("[Error] Argument 'sslStructPtr' is NULL");
        }
        if (!keyPtr.isNull()) {
            let KEY_LENGTH = 0;
            let calculatedKeyLength = 0;
            // Iterate through the memory to determine key length
            while (calculatedKeyLength < MAX_KEY_LENGTH) {
                //@ts-ignore
                const byte = Memory.readU8(keyPtr.add(calculatedKeyLength)); // Read one byte at a time
                if (byte === 0) { // Stop if null terminator is found (optional, adjust as needed)
                    if (calculatedKeyLength < 20) {
                        calculatedKeyLength++;
                        continue;
                    }
                    break;
                }
                calculatedKeyLength++;
            }
            if (calculatedKeyLength > 24 && calculatedKeyLength <= 40) {
                KEY_LENGTH = 32; // Closest match is 32 bytes
            }
            else if (calculatedKeyLength >= 46 && calculatedKeyLength <= 49) {
                KEY_LENGTH = 48; // Closest match is 48 bytes
            }
            else {
                KEY_LENGTH = 32; // fall back size
            }
            //@ts-ignore
            const keyData = Memory.readByteArray(keyPtr, KEY_LENGTH); // Read the key data (KEY_LENGTH bytes)
            // Convert the byte array to a string of  hex values
            const hexKey = get_hex_string_from_byte_array(keyData);
            secret_key = hexKey;
        }
        else {
            devlog("[Error] Argument 'key' is NULL");
        }
        //devlog("invoking ssl_log_secret() from BoringSSL statically linked into Cronet");
        var message = {};
        message["contentType"] = "keylog";
        message["keylog"] = labelStr + " " + client_random + " " + secret_key;
        send(message);
    }
    install_plaintext_read_hook() {
        // TBD
    }
    install_plaintext_write_hook() {
        // TBD
    }
    install_key_extraction_hook() {
        // needs to be setup for the specific plattform
    }
}
✄
{"version":3,"file":"flutter.js","sourceRoot":"/Users/daniel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CAAC,iCAAiC,CAAC,YAAY,CAAC,CAAA;SACvE;aAAK;YACF,MAAM,CAAC,yCAAyC,CAAC,CAAC;SACrD;QAED,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,EAAE;YAClB,YAAY;YACZ,MAAM,OAAO,GAAG,MAAM,CAAC,aAAa,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC,uCAAuC;YAEjG,oDAAoD;YACpD,MAAM,MAAM,GAAG,8BAA8B,CAAC,OAAO,CAAC,CAAC;YAEvD,UAAU,GAAG,MAAM,CAAC;SACvB;aAAM;YACH,MAAM,CAAC,gCAAgC,CAAC,CAAC;SAC5C;QAED,oFAAoF;QACpF,IAAI,OAAO,GAA8C,EAAE,CAAA;QAC3D,OAAO,CAAC,aAAa,CAAC,GAAG,QAAQ,CAAA;QACjC,OAAO,CAAC,QAAQ,CAAC,GAAG,QAAQ,GAAC,GAAG,GAAC,aAAa,GAAC,GAAG,GAAC,UAAU,CAAC;QAC9D,IAAI,CAAC,OAAO,CAAC,CAAA;IACjB,CAAC;IAED,2BAA2B;QACvB,MAAM;IACV,CAAC;IAED,4BAA4B;QACxB,MAAM;IACV,CAAC;IAED,2BAA2B;QACvB,+CAA+C;IACnD,CAAC;CACJ"}
✄
import { get_hex_string_from_byte_array, readAddresses } from "../shared/shared_functions.js";
import { devlog } from "../util/log.js";
export class Flutter {
    constructor(moduleName, socket_library, is_base_hook, passed_library_method_mapping) {
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.passed_library_method_mapping = passed_library_method_mapping;
        // global variables
        this.library_method_mapping = {};
        this.module_name = moduleName;
        this.is_base_hook = is_base_hook;
        if (typeof passed_library_method_mapping !== 'undefined') {
            this.library_method_mapping = passed_library_method_mapping;
        }
        else {
            this.library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        }
        this.addresses = readAddresses(moduleName, this.library_method_mapping);
    }
    get_client_random(s3_ptr, SSL3_RANDOM_SIZE) {
        if (!s3_ptr.isNull()) {
            const client_random_ptr = s3_ptr.add(0x30); // Offset in s3 struct
            //@ts-ignore
            const client_random = Memory.readByteArray(client_random_ptr, SSL3_RANDOM_SIZE);
            // Convert the byte array to a hex string
            const hexClientRandom = get_hex_string_from_byte_array(new Uint8Array(client_random));
            return hexClientRandom;
        }
        else {
            devlog("[Error] s3 pointer is NULL");
            return "";
        }
    }
    get_client_random_from_ssl_struct(ssl_st_ptr) {
        const SSL3_RANDOM_SIZE = 32;
        let offset_s3;
        switch (Process.arch) {
            case 'x64':
                offset_s3 = 0x30;
                break;
            case 'arm64':
                offset_s3 = 0x30;
                break;
            case 'ia32':
                offset_s3 = 0x2C;
                break;
            case 'arm':
                offset_s3 = 0x2C;
                break;
            default:
                devlog("[Error] Unsupported architecture");
                return "";
        }
        const s3_ptr = ssl_st_ptr.add(offset_s3).readPointer();
        return this.get_client_random(s3_ptr, SSL3_RANDOM_SIZE);
    }
    dumpKeys(labelPtr, sslStructPtr, keyPtr) {
        const KEY_LENGTH = 32; // Assuming key length is 32 bytes
        let labelStr = '';
        let client_random = '';
        let secret_key = '';
        // Read the label (the label pointer might contain a C string)
        if (!labelPtr.isNull()) {
            labelStr = labelPtr.readCString() ?? ''; // Read label as a C string
            //devlog(`Label: ${labelStr}`);
        }
        else {
            devlog("[Error] Argument 'labelPtr' is NULL");
        }
        // Extract client_random from the SSL structure
        if (!sslStructPtr.isNull()) {
            client_random = this.get_client_random_from_ssl_struct(sslStructPtr);
        }
        else {
            devlog("[Error] Argument 'sslStructPtr' is NULL");
        }
        if (!keyPtr.isNull()) {
            //@ts-ignore
            const keyData = Memory.readByteArray(keyPtr, KEY_LENGTH); // Read the key data (KEY_LENGTH bytes)
            // Convert the byte array to a string of  hex values
            const hexKey = get_hex_string_from_byte_array(keyData);
            secret_key = hexKey;
        }
        else {
            devlog("[Error] Argument 'key' is NULL");
        }
        //devlog("invoking ssl_log_secret() from BoringSSL statically linked into Flutter");
        var message = {};
        message["contentType"] = "keylog";
        message["keylog"] = labelStr + " " + client_random + " " + secret_key;
        send(message);
    }
    install_plaintext_read_hook() {
        // TBD
    }
    install_plaintext_write_hook() {
        // TBD
    }
    install_key_extraction_hook() {
        // needs to be setup for the specific plattform
    }
}
✄
{"version":3,"file":"gnutls.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ssl_lib/gnutls.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAe,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACjH,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAE3D,MAAM,OAAO,MAAM;IAef,YAAmB,UAAiB,EAAS,cAAqB,EAAQ,6BAAgE;QAAvH,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;QAAQ,kCAA6B,GAA7B,6BAA6B,CAAmC;QAb1I,mBAAmB;QACnB,2BAAsB,GAAqC,EAAE,CAAC;QAa1D,IAAG,OAAO,6BAA6B,KAAK,WAAW,EAAC;YACpD,IAAI,CAAC,sBAAsB,GAAG,6BAA6B,CAAC;SAC/D;aAAI;YACD,IAAI,CAAC,sBAAsB,CAAC,IAAI,UAAU,GAAG,CAAC,GAAG,CAAC,oBAAoB,EAAE,oBAAoB,EAAE,oCAAoC,EAAE,0BAA0B,EAAE,uBAAuB,EAAE,aAAa,EAAE,kBAAkB,EAAE,oCAAoC,EAAE,2BAA2B,CAAC,CAAA;YAC9R,IAAI,CAAC,sBAAsB,CAAC,IAAI,cAAc,GAAG,CAAC,GAAG,CAAC,aAAa,EAAE,aAAa,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;SACxG;QAED,IAAI,CAAC,SAAS,GAAG,aAAa,CAAC,UAAU,EAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;QACvE,IAAI,CAAC,WAAW,G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AAO,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAC;KAC7D;IAED,IAAI,iBAAiB,GAAG,EAAE,CAAA;IAC1B,IAAI,iBAAiB,GAAG,EAAE,CAAA;IAC1B,CAAC,GAAG,iBAAiB,CAAC,WAAW,EAAE,CAAA;IACnC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,iBAAiB,EAAE,CAAC,EAAE,EAAE;QACpC,sEAAsE;QACtE,2BAA2B;QAE3B,iBAAiB;YACb,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;KACtE;IACD,OAAO,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC,WAAW,EAAE,GAAG,GAAG,GAAG,iBAAiB,GAAG,GAAG,GAAG,UAAU,CAAA;IACpF,IAAI,CAAC,OAAO,CAAC,CAAA;IACb,OAAO,CAAC,CAAA;AACZ,CAAC,EAAE,KAAK,EAAE,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC,AAxCtB,CAwCsB"}
✄
import { readAddresses, getPortsAndAddresses, getBaseAddress } from "../shared/shared_functions.js";
import { log } from "../util/log.js";
import { offsets, enable_default_fd } from "../ssl_log.js";
export class GnuTLS {
    constructor(moduleName, socket_library, passed_library_method_mapping) {
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.passed_library_method_mapping = passed_library_method_mapping;
        // global variables
        this.library_method_mapping = {};
        if (typeof passed_library_method_mapping !== 'undefined') {
            this.library_method_mapping = passed_library_method_mapping;
        }
        else {
            this.library_method_mapping[`*${moduleName}*`] = ["gnutls_record_recv", "gnutls_record_send", "gnutls_session_set_keylog_function", "gnutls_transport_get_int", "gnutls_session_get_id", "gnutls_init", "gnutls_handshake", "gnutls_session_get_keylog_function", "gnutls_session_get_random"];
            this.library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        }
        this.addresses = readAddresses(moduleName, this.library_method_mapping);
        this.module_name = moduleName;
        // @ts-ignore
        if (offsets != "{OFFSETS}" && offsets.gnutls != null) {
            if (offsets.sockets != null) {
                const socketBaseAddress = getBaseAddress(socket_library);
                for (const method of Object.keys(offsets.sockets)) {
                    //@ts-ignore
                    this.addresses[this.moduleName][`${method}`] = offsets.sockets[`${method}`].absolute || socketBaseAddress == null ? ptr(offsets.sockets[`${method}`].address) : socketBaseAddress.add(ptr(offsets.sockets[`${method}`].address));
                }
            }
            const libraryBaseAddress = getBaseAddress(moduleName);
            if (libraryBaseAddress == null) {
                log("Unable to find library base address! Given address values will be interpreted as absolute ones!");
            }
            for (const method of Object.keys(offsets.gnutls)) {
                //@ts-ignore
                this.addresses[this.moduleName][`${method}`] = offsets.gnutls[`${method}`].absolute || libraryBaseAddress == null ? ptr(offsets.gnutls[`${method}`].address) : libraryBaseAddress.add(ptr(offsets.gnutls[`${method}`].address));
            }
        }
        GnuTLS.gnutls_transport_get_int = new NativeFunction(this.addresses[this.moduleName]["gnutls_transport_get_int"], "int", ["pointer"]);
        GnuTLS.gnutls_session_get_id = new NativeFunction(this.addresses[this.moduleName]["gnutls_session_get_id"], "int", ["pointer", "pointer", "pointer"]);
        GnuTLS.gnutls_session_set_keylog_function = new NativeFunction(this.addresses[this.moduleName]["gnutls_session_set_keylog_function"], "void", ["pointer", "pointer"]);
        GnuTLS.gnutls_session_get_random = new NativeFunction(this.addresses[this.moduleName]["gnutls_session_get_random"], "pointer", ["pointer", "pointer", "pointer"]);
    }
    /**
       * Get the session_id of SSL object and return it as a hex string.
       * @param {!NativePointer} ssl A pointer to an SSL object.
       * @return {dict} A string representing the session_id of the SSL object's
       *     SSL_SESSION. For example,
       *     "59FD71B7B90202F359D89E66AE4E61247954E28431F6C6AC46625D472FF76336".
       */
    static getSslSessionId(session) {
        var len_pointer = Memory.alloc(4);
        var err = GnuTLS.gnutls_session_get_id(session, NULL, len_pointer);
        if (err != 0) {
            if (enable_default_fd) {
                log("using dummy SessionID: 59FD71B7B90202F359D89E66AE4E61247954E28431F6C6AC46625D472FF76337");
                return "59FD71B7B90202F359D89E66AE4E61247954E28431F6C6AC46625D472FF76337";
            }
            return "";
        }
        var len = len_pointer.readU32();
        var p = Memory.alloc(len);
        err = GnuTLS.gnutls_session_get_id(session, p, len_pointer);
        if (err != 0) {
            if (enable_default_fd) {
                log("using dummy SessionID: 59FD71B7B90202F359D89E66AE4E61247954E28431F6C6AC46625D472FF76337");
                return "59FD71B7B90202F359D89E66AE4E61247954E28431F6C6AC46625D472FF76337";
            }
            return "";
        }
        var session_id = "";
        for (var i = 0; i < len; i++) {
            // Read a byte, convert it to a hex string (0xAB ==> "AB"), and append
            // it to session_id.
            session_id +=
                ("0" + p.add(i).readU8().toString(16).toUpperCase()).substr(-2);
        }
        return session_id;
    }
    install_plaintext_read_hook() {
        var current_module_name = this.module_name;
        var lib_addesses = this.addresses;
        Interceptor.attach(this.addresses[this.moduleName]["gnutls_record_recv"], {
            onEnter: function (args) {
                var message = getPortsAndAddresses(GnuTLS.gnutls_transport_get_int(args[0]), true, lib_addesses[current_module_name], enable_default_fd);
                message["ssl_session_id"] = GnuTLS.getSslSessionId(args[0]);
                message["function"] = "SSL_read";
                this.message = message;
                this.buf = args[1];
            },
            onLeave: function (retval) {
                retval |= 0; // Cast retval to 32-bit integer.
                if (retval <= 0) {
                    return;
                }
                this.message["contentType"] = "datalog";
                send(this.message, this.buf.readByteArray(retval));
            }
        });
    }
    install_plaintext_write_hook() {
        var current_module_name = this.module_name;
        var lib_addesses = this.addresses;
        Interceptor.attach(this.addresses[this.moduleName]["gnutls_record_send"], {
            onEnter: function (args) {
                var message = getPortsAndAddresses(GnuTLS.gnutls_transport_get_int(args[0]), false, lib_addesses[current_module_name], enable_default_fd);
                message["ssl_session_id"] = GnuTLS.getSslSessionId(args[0]);
                message["function"] = "SSL_write";
                message["contentType"] = "datalog";
                send(message, args[1].readByteArray(parseInt(args[2])));
            },
            onLeave: function (retval) {
            }
        });
    }
    install_tls_keys_callback_hook() {
    }
}
//NativeCallback
GnuTLS.keylog_callback = new NativeCallback(function (session, label, secret) {
    var message = {};
    message["contentType"] = "keylog";
    var secret_len = secret.add(Process.pointerSize).readUInt();
    var secret_str = "";
    var p = secret.readPointer();
    for (var i = 0; i < secret_len; i++) {
        // Read a byte, convert it to a hex string (0xAB ==> "AB"), and append
        // it to secret_str.
        secret_str +=
            ("0" + p.add(i).readU8().toString(16).toUpperCase()).substr(-2);
    }
    var server_random_ptr = Memory.alloc(Process.pointerSize + 4);
    var client_random_ptr = Memory.alloc(Process.pointerSize + 4);
    if (typeof this !== "undefined") {
        GnuTLS.gnutls_session_get_random(session, client_random_ptr, server_random_ptr);
    }
    else {
        console.log("[-] Error while installing keylog callback");
    }
    var client_random_str = "";
    var client_random_len = 32;
    p = client_random_ptr.readPointer();
    for (i = 0; i < client_random_len; i++) {
        // Read a byte, convert it to a hex string (0xAB ==> "AB"), and append
        // it to client_random_str.
        client_random_str +=
            ("0" + p.add(i).readU8().toString(16).toUpperCase()).substr(-2);
    }
    message["keylog"] = label.readCString() + " " + client_random_str + " " + secret_str;
    send(message);
    return 0;
}, "int", ["pointer", "pointer", "pointer"]);
✄
{"version":3,"file":"java_ssl_libs.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ssl_lib/java_ssl_libs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,OAAO,IAAI,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AACvE,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAGrD,MAAM,OAAO,QAAQ;IAEjB,kBAAkB;QACd,IAAI,IAAI,CAAC,SAAS,EAAE;YAChB,UAAU,CAAC;gBACP,IAAI,CAAC,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AgB,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAA;iCAC5C;gCAED,4NAA4N;gCAC5N,8CAA8C;gCAC9C,4CAA4C;gCAC5C,sEAAsE;6BACzE;4BAED,OAAO,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAA;yBACpC;oBACL,CAAC,CAAA;gBACL,CAAC,CAAC,CAAA;YACN,CAAC,EAAE,CAAC,CAAC,CAAC;SACT;IACL,CAAC;CACJ"}
✄
import { log, devlog } from "../util/log.js";
import { execute as conscrypt_execute } from "../android/conscrypt.js";
import { isAndroid } from "../util/process_infos.js";
export class SSL_Java {
    install_java_hooks() {
        if (Java.available) {
            setTimeout(function () {
                Java.perform(function () {
                    //Conscrypt needs early instrumentation as we block the provider installation
                    var Security = Java.use("java.security.Security");
                    if (Security.getProviders().toString().includes("GmsCore_OpenSSL")) {
                        log("WARNING: PID " + Process.id + " Detected GmsCore_OpenSSL Provider. This can be a bit unstable. If you having issues, rerun with -spawn for early instrumentation. Trying to remove it to fall back on default Provider");
                        Security.removeProvider("GmsCore_OpenSSL");
                        log("Removed GmsCore_OpenSSL");
                    }
                    //As the classloader responsible for loading ProviderInstaller sometimes is not present from the beginning on,
                    //we always have to watch the classloader activity
                    conscrypt_execute();
                    //Now do the same for Ssl_guard
                    if (Security.getProviders().toString().includes("Ssl_Guard")) {
                        log("Ssl_Guard deteced, removing it to fall back on default Provider");
                        Security.removeProvider("Ssl_Guard");
                        log("Removed Ssl_Guard");
                    }
                    //Same thing for Conscrypt provider which has been manually inserted (not by providerinstaller)
                    if (Security.getProviders().toString().includes("Conscrypt version")) {
                        log("Conscrypt detected");
                        Security.removeProvider("Conscrypt");
                        log("Removed Conscrypt");
                    }
                    //Same thing for WolfSSLProvider provider which has been manually inserted (not by providerinstaller)
                    if (Security.getProviders().toString().includes("WolfSSLProvider")) {
                        log("WolfSSLProvider detected");
                        Security.removeProvider("WolfSSLProvider");
                        log("Removed WolfSSLProvider");
                    }
                    // run with -do in order to see which other securiy providers we should remove
                    devlog("Remaining: " + Security.getProviders().toString());
                    // TBD: AndroidOpenSSL version 1.0 or BC version 1.61? 
                    //Hook insertProviderAt/addprovider for dynamic provider blocking
                    Security.insertProviderAt.implementation = function (provider, position) {
                        if (provider.getName().includes("Conscrypt") || provider.getName().includes("Ssl_Guard") || provider.getName().includes("GmsCore_OpenSSL") || provider.getName().includes("WolfSSLProvider")) {
                            log("Blocking provider registration (insertProviderAt) of  " + provider.getName());
                            return position;
                        }
                        else {
                            return this.insertProviderAt(provider, position);
                        }
                    };
                    //Same for addProvider
                    Security.insertProviderAt.implementation = function (provider) {
                        if (provider.getName().includes("Conscrypt") || provider.getName().includes("Ssl_Guard") || provider.getName().includes("GmsCore_OpenSSL") || provider.getName().includes("WolfSSLProvider")) {
                            log("Blocking provider registration (addProvider) of " + provider.getName());
                            return 1;
                        }
                        else {
                            if (isAndroid()) {
                                /*
                                When a NetworkProvider will be installed it is only allow at position 1
                                s. https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/security/net/config/NetworkSecurityConfigProvider.java
                                */
                                if (provider.getName() === "AndroidNSSP") {
                                    return this.insertProviderAt(provider, 1);
                                }
                                // when the "Failed to install provider as highest priority provider. Provider was installed at position"-error is prompted on logcat please uncomment the following line, recompile the typescript and reopen the following
                                // https://github.com/fkie-cad/friTap/issues/1
                                // var android_Version = Java.androidVersion
                                // devlog("highest priority provider error with: "+provider.getName())
                            }
                            return this.addProvider(provider);
                        }
                    };
                });
            }, 0);
        }
    }
}
✄
{"version":3,"file":"matrixssl.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ssl_lib/matrixssl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAE,cAAc,EAAC,MAAM,+BAA+B,CAAC;AACnG,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC3D,OAAO,EAAE,GAAG,EAAE,MAAM,g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AAE;oBACb,OAAM;iBACT;gBAED,IAAI,CAAC,EAAE,GAAG,MAAM,CAAC;YACrB,CAAC;SACJ,CAAC,CAAA;IACN,CAAC;IAED,YAAY,CAAC,GAAQ;QACjB,MAAM,GAAG,GAAG,UAAU,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;QAC5C,MAAM,eAAe,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,OAAO,EAAE,CAAC;QACnE,MAAM,SAAS,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,WAAW,EAAE,CAAC,WAAW,CAAC,eAAe,CAAC,CAAC;QAC1F,OAAO,SAAS,CAAC;IACrB,CAAC;CAGJ"}
✄
import { readAddresses, getPortsAndAddresses, getBaseAddress } from "../shared/shared_functions.js";
import { enable_default_fd, offsets } from "../ssl_log.js";
import { log } from "../util/log.js";
export class matrix_SSL {
    constructor(moduleName, socket_library, passed_library_method_mapping) {
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.passed_library_method_mapping = passed_library_method_mapping;
        // global variables
        this.library_method_mapping = {};
        if (typeof passed_library_method_mapping !== 'undefined') {
            this.library_method_mapping = passed_library_method_mapping;
        }
        else {
            this.library_method_mapping[`*${moduleName}*`] = ["matrixSslReceivedData", "matrixSslGetWritebuf", "matrixSslGetSid", "matrixSslEncodeWritebuf"];
            this.library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl", "socket"];
        }
        this.addresses = readAddresses(moduleName, this.library_method_mapping);
        this.module_name = moduleName;
        // @ts-ignore
        if (offsets != "{OFFSETS}" && offsets.matrixssl != null) {
            if (offsets.sockets != null) {
                const socketBaseAddress = getBaseAddress(socket_library);
                for (const method of Object.keys(offsets.sockets)) {
                    //@ts-ignore
                    this.addresses[this.moduleName][`${method}`] = offsets.sockets[`${method}`].absolute || socketBaseAddress == null ? ptr(offsets.sockets[`${method}`].address) : socketBaseAddress.add(ptr(offsets.sockets[`${method}`].address));
                }
            }
            const libraryBaseAddress = getBaseAddress(moduleName);
            if (libraryBaseAddress == null) {
                log("Unable to find library base address! Given address values will be interpreted as absolute ones!");
            }
            for (const method of Object.keys(offsets.matrixssl)) {
                //@ts-ignore
                this.addresses[this.moduleName][`${method}`] = offsets.matrixssl[`${method}`].absolute || libraryBaseAddress == null ? ptr(offsets.matrixssl[`${method}`].address) : libraryBaseAddress.add(ptr(offsets.matrixssl[`${method}`].address));
            }
        }
        //Creates a new client session. If this happens we will save the id of this new session
        matrix_SSL.matrixSslNewCLientSession = new NativeFunction(this.addresses[this.moduleName]["matrixSslNewClientSession"], "int", ["pointer", "pointer", "pointer", "pointer", "int", "pointer", "pointer", "pointer", "pointer", "pointer"]);
        //This function extracts the sessionID object out of the ssl object
        matrix_SSL.matrixSslGetSid = new NativeFunction(this.addresses[this.moduleName]["matrixSslGetSid"], "pointer", ["pointer"]);
    }
    install_plaintext_read_hook() {
        var current_module_name = this.module_name;
        var lib_addesses = this.addresses;
        Interceptor.attach(this.addresses[this.moduleName]["matrixSslReceivedData"], {
            onEnter: function (args) {
                this.buffer = args[2];
                this.len = args[3];
                var message = getPortsAndAddresses(this.fd, true, lib_addesses[current_module_name], enable_default_fd);
                message["ssl_session_id"] = this.addresses[this.moduleName]["matrixSslGetSid"] === undefined ? matrix_SSL.sessionId : this.getSessionId(args[0]);
                message["function"] = "matrixSslReceivedData";
                this.message = message;
            },
            onLeave: function (retval) {
                retval |= 0; // Cast retval to 32-bit integer.
                if (retval <= 0) {
                    return;
                }
                var data = this.buffer.readByteArray(this.len);
                this.message["contentType"] = "datalog";
                send(this.message, data);
            }
        });
    }
    install_plaintext_write_hook() {
        var current_module_name = this.module_name;
        var lib_addesses = this.addresses;
        //This function is needed to extract the buffer address in which the plaintext will be stored before registring this buffer as the "sent data" buffer.
        Interceptor.attach(this.addresses[this.moduleName]["matrixSslGetWritebuf"], {
            onEnter: function (args) {
                this.outBuffer = args[1];
            },
            onLeave: function (retval) {
                retval |= 0; // Cast retval to 32-bit integer.
                if (retval <= 0) {
                    return;
                }
                this.outBufferLength = retval;
            }
        });
        //This function actual encodes the plaintext. We need to hook this, because the user will fill the data out buffer between matrixSslGetWritebuf and matrixSslEncodeWritebuf call.
        //So at the time this function is called, the buffer with the plaintext will be final 
        Interceptor.attach(this.addresses[this.moduleName]["matrixSslEncodeWritebuf"], {
            onEnter: function (args) {
                var data = this.outBuffer.readByteArray(this.outBufferLength);
                var message = getPortsAndAddresses(this.fd, false, lib_addesses[current_module_name], enable_default_fd);
                message["ssl_session_id"] = this.addresses[this.moduleName]["matrixSslGetSid"] === undefined ? matrix_SSL.sessionId : this.getSessionId(args[0]);
                message["function"] = "matrixSslEncodeWritebuf";
                message["contentType"] = "datalog";
                send(message, data);
            }
        });
    }
    install_tls_keys_callback_hook() {
        // TBD
    }
    install_helper_hook() {
        Interceptor.attach(this.addresses[this.moduleName]["matrixSslNewSessionId"], {
            onEnter: function (args) {
                this.sslSessionPointer = args[0];
            },
            onLeave: function (retval) {
                retval |= 0; // Cast retval to 32-bit integer.
                if (retval <= 0) {
                    return;
                }
                var sessionIdLength = this.sslSessionPointer.add(2 * Process.pointerSize).readU32();
                matrix_SSL.sessionId = this.sslSessionPointer.add(Process.pointerSize).readPointer().readCString(sessionIdLength);
            }
        });
        Interceptor.attach(this.addresses[this.moduleName]["connect"], {
            onEnter: function (args) {
            },
            onLeave: function (retval) {
                retval |= 0; // Cast retval to 32-bit integer.
                if (retval <= 0) {
                    return;
                }
                this.fd = retval;
            }
        });
    }
    getSessionId(ssl) {
        const sid = matrix_SSL.matrixSslGetSid(ssl);
        const sessionIdLength = sid.add(2 * Process.pointerSize).readU32();
        const sessionId = sid.add(Process.pointerSize).readPointer().readCString(sessionIdLength);
        return sessionId;
    }
}
✄
{"version":3,"file":"mbedTLS.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ssl_lib/mbedTL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GAAG,GAAQ,IAAI,CAAC,CAAC,CAAC,CAAC;gBACvB,GAAG,IAAI,CAAC,CAAA,CAAC,iCAAiC;gBAC1C,IAAI,GAAG,IAAI,CAAC,EAAE;oBACV,OAAM;iBACT;gBACD,IAAI,IAAI,GAAG,MAAM,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;gBACrC,IAAI,OAAO,GAAG,oBAAoB,CAAC,QAAQ,CAAC,mBAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAW,EAAE,KAAK,EAAE,YAAY,CAAC,mBAAmB,CAAC,EAAE,iBAAiB,CAAC,CAAA;gBAChJ,OAAO,CAAC,gBAAgB,CAAC,GAAG,QAAQ,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;gBAC1D,OAAO,CAAC,UAAU,CAAC,GAAG,mBAAmB,CAAA;gBACzC,OAAO,CAAC,aAAa,CAAC,GAAG,SAAS,CAAA;gBAClC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;YACvB,CAAC;SACJ,CAAC,CAAC;IAEP,CAAC;IAGD,8BAA8B;QAC1B,MAAM;IACV,CAAC;CAGJ"}
✄
import { readAddresses, getPortsAndAddresses, getBaseAddress } from "../shared/shared_functions.js";
import { offsets, enable_default_fd } from "../ssl_log.js";
import { log } from "../util/log.js";
export class mbed_TLS {
    constructor(moduleName, socket_library, passed_library_method_mapping) {
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.passed_library_method_mapping = passed_library_method_mapping;
        // global variables
        this.library_method_mapping = {};
        if (typeof passed_library_method_mapping !== 'undefined') {
            this.library_method_mapping = passed_library_method_mapping;
        }
        else {
            this.library_method_mapping[`*${moduleName}*`] = ["mbedtls_ssl_read", "mbedtls_ssl_write"];
            this.library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        }
        this.addresses = readAddresses(moduleName, this.library_method_mapping);
        this.module_name = moduleName;
        // @ts-ignore
        if (offsets != "{OFFSETS}" && offsets.mbedtls != null) {
            if (offsets.sockets != null) {
                const socketBaseAddress = getBaseAddress(socket_library);
                for (const method of Object.keys(offsets.sockets)) {
                    //@ts-ignore
                    this.addresses[this.moduleName][`${method}`] = offsets.sockets[`${method}`].absolute || socketBaseAddress == null ? ptr(offsets.sockets[`${method}`].address) : socketBaseAddress.add(ptr(offsets.sockets[`${method}`].address));
                }
            }
            const libraryBaseAddress = getBaseAddress(moduleName);
            if (libraryBaseAddress == null) {
                log("Unable to find library base address! Given address values will be interpreted as absolute ones!");
            }
            for (const method of Object.keys(offsets.mbedtls)) {
                //@ts-ignore
                this.addresses[this.moduleName][`${method}`] = offsets.mbedtls[`${method}`].absolute || libraryBaseAddress == null ? ptr(offsets.mbedtls[`${method}`].address) : libraryBaseAddress.add(ptr(offsets.mbedtls[`${method}`].address));
            }
        }
    }
    static parse_mbedtls_ssl_context_struct(sslcontext) {
        return {
            conf: sslcontext.readPointer(),
            state: sslcontext.add(Process.pointerSize).readS32(),
            renego_status: sslcontext.add(Process.pointerSize + 4).readS32(),
            renego_records_seen: sslcontext.add(Process.pointerSize + 4 + 4).readS32(),
            major_ver: sslcontext.add(Process.pointerSize + 4 + 4 + 4).readS32(),
            minor_ver: sslcontext.add(Process.pointerSize + 4 + 4 + 4 + 4).readS32(),
            badmac_seen: sslcontext.add(Process.pointerSize + 4 + 4 + 4 + 4 + 4).readU32(),
            f_send: sslcontext.add(Process.pointerSize + 4 + 4 + 4 + 4 + 4 + 4).readPointer(),
            f_recv: sslcontext.add(Process.pointerSize + 4 + 4 + 4 + 4 + 4 + 4 + Process.pointerSize).readPointer(),
            f_recv_timeout: sslcontext.add(Process.pointerSize + 4 + 4 + 4 + 4 + 4 + 4 + 2 * Process.pointerSize).readPointer(),
            p_bio: sslcontext.add(Process.platform == 'windows' ? 48 : 56).readPointer(),
            session_in: sslcontext.add(Process.pointerSize + 4 + 4 + 4 + 4 + 4 + 4 + 4 * Process.pointerSize).readPointer(),
            session_out: sslcontext.add(Process.pointerSize + 4 + 4 + 4 + 4 + 4 + 4 + 5 * Process.pointerSize).readPointer(),
            session: {
                start: sslcontext.add(24 + 7 * Process.pointerSize).readPointer().readPointer(),
                ciphersuite: sslcontext.add(24 + 7 * Process.pointerSize).readPointer().add(8).readS32(),
                compression: sslcontext.add(24 + 7 * Process.pointerSize).readPointer().add(8 + 4).readS32(),
                id_len: sslcontext.add(24 + 7 * Process.pointerSize).readPointer().add(8 + 4 + 4).readU32(),
                id: sslcontext.add(24 + 7 * Process.pointerSize).readPointer().add(8 + 4 + 4 + 4).readByteArray(sslcontext.add(24 + 7 * Process.pointerSize).readPointer().add(8 + 4 + 4).readU32())
            }
        };
    }
    static getSocketDescriptor(sslcontext) {
        var ssl_context = mbed_TLS.parse_mbedtls_ssl_context_struct(sslcontext);
        return ssl_context.p_bio.readS32();
    }
    static getSessionId(sslcontext) {
        var ssl_context = mbed_TLS.parse_mbedtls_ssl_context_struct(sslcontext);
        var session_id = '';
        for (var byteCounter = 0; byteCounter < ssl_context.session.id_len; byteCounter++) {
            session_id = `${session_id}${ssl_context.session.id?.unwrap().add(byteCounter).readU8().toString(16).toUpperCase()}`;
        }
        return session_id;
    }
    install_plaintext_read_hook() {
        var current_module_name = this.module_name;
        var lib_addesses = this.addresses;
        //https://tls.mbed.org/api/ssl_8h.html#aa2c29eeb1deaf5ad9f01a7515006ede5
        Interceptor.attach(this.addresses[this.moduleName]["mbedtls_ssl_read"], {
            onEnter: function (args) {
                this.buffer = args[1];
                this.len = args[2];
                this.sslContext = args[0];
                var message = getPortsAndAddresses(mbed_TLS.getSocketDescriptor(args[0]), true, lib_addesses[current_module_name], enable_default_fd);
                message["ssl_session_id"] = mbed_TLS.getSessionId(args[0]);
                message["function"] = "mbedtls_ssl_read";
                this.message = message;
            },
            onLeave: function (retval) {
                retval |= 0; // Cast retval to 32-bit integer.
                if (retval <= 0) {
                    return;
                }
                var data = this.buffer.readByteArray(retval);
                this.message["contentType"] = "datalog";
                send(this.message, data);
            }
        });
    }
    install_plaintext_write_hook() {
        var current_module_name = this.module_name;
        var lib_addesses = this.addresses;
        //https://tls.mbed.org/api/ssl_8h.html#a5bbda87d484de82df730758b475f32e5
        Interceptor.attach(this.addresses[this.moduleName]["mbedtls_ssl_write"], {
            onEnter: function (args) {
                var buffer = args[1];
                var len = args[2];
                len |= 0; // Cast retval to 32-bit integer.
                if (len <= 0) {
                    return;
                }
                var data = buffer.readByteArray(len);
                var message = getPortsAndAddresses(mbed_TLS.getSocketDescriptor(args[0]), false, lib_addesses[current_module_name], enable_default_fd);
                message["ssl_session_id"] = mbed_TLS.getSessionId(args[0]);
                message["function"] = "mbedtls_ssl_write";
                message["contentType"] = "datalog";
                send(message, data);
            }
        });
    }
    install_tls_keys_callback_hook() {
        // TBD
    }
}
✄
{"version":3,"file":"monobtls.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ssl_lib/monobtls.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,8BAA8B,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC9F,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAKxC,MAAM,OAAO,SAAS;IAUlB,YAAmB,UAAiB,EAAS,cAAqB,EAAC,YAAqB,EAAS,6BAAgE;QAA9I,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;QAA+B,kCAA6B,GAA7B,6BAA6B,CAAmC;QAPjK,mBAAmB;QACnB,2BAAsB,GAAqC,EAAE,CAAC;QAO1D,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;QAC9B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QAEjC,IAAG,OAAO,6BAA6B,KAAK,WAAW,EAAC;YACpD,IAAI,CAAC,sBAAsB,GAAG,6BAA6B,CAAC;SAC/D;aAAI;YACD,IAAI,CAAC,sBAAsB,CAAC,IAAI,cAAc,GAAG,CAAC,GAAG,CAAC,aAAa,E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;QACxB,MAAM;IACV,CAAC;IAED,2BAA2B;QACvB,+CAA+C;IACnD,CAAC;CACJ"}
✄
import { get_hex_string_from_byte_array, readAddresses } from "../shared/shared_functions.js";
import { devlog } from "../util/log.js";
export class Mono_BTLS {
    constructor(moduleName, socket_library, is_base_hook, passed_library_method_mapping) {
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.passed_library_method_mapping = passed_library_method_mapping;
        // global variables
        this.library_method_mapping = {};
        this.module_name = moduleName;
        this.is_base_hook = is_base_hook;
        if (typeof passed_library_method_mapping !== 'undefined') {
            this.library_method_mapping = passed_library_method_mapping;
        }
        else {
            this.library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        }
        this.addresses = readAddresses(moduleName, this.library_method_mapping);
    }
    get_client_random(s3_ptr, SSL3_RANDOM_SIZE) {
        if (!s3_ptr.isNull()) {
            const client_random_ptr = s3_ptr.add(0x30); // Offset in s3 struct
            //@ts-ignore
            const client_random = Memory.readByteArray(client_random_ptr, SSL3_RANDOM_SIZE);
            // Convert the byte array to a hex string
            const hexClientRandom = get_hex_string_from_byte_array(new Uint8Array(client_random));
            return hexClientRandom;
        }
        else {
            devlog("[Error] s3 pointer is NULL");
            return "";
        }
    }
    get_client_random_from_ssl_struct(ssl_st_ptr) {
        const SSL3_RANDOM_SIZE = 32;
        let offset_s3;
        switch (Process.arch) {
            case 'x64':
                offset_s3 = 0x30;
                break;
            case 'arm64':
                offset_s3 = 0x30;
                break;
            case 'ia32':
                offset_s3 = 0x2C;
                break;
            case 'arm':
                offset_s3 = 0x2C;
                break;
            default:
                devlog("[Error] Unsupported architecture");
                return "";
        }
        const s3_ptr = ssl_st_ptr.add(offset_s3).readPointer();
        return this.get_client_random(s3_ptr, SSL3_RANDOM_SIZE);
    }
    dumpKeys(labelPtr, sslStructPtr, keyPtr) {
        const KEY_LENGTH = 32; // Assuming key length is 32 bytes
        let labelStr = '';
        let client_random = '';
        let secret_key = '';
        // Read the label (the label pointer might contain a C string)
        if (!labelPtr.isNull()) {
            labelStr = labelPtr.readCString() ?? ''; // Read label as a C string
            //devlog(`Label: ${labelStr}`);
        }
        else {
            devlog("[Error] Argument 'labelPtr' is NULL");
        }
        // Extract client_random from the SSL structure
        if (!sslStructPtr.isNull()) {
            client_random = this.get_client_random_from_ssl_struct(sslStructPtr);
        }
        else {
            devlog("[Error] Argument 'sslStructPtr' is NULL");
        }
        if (!keyPtr.isNull()) {
            //@ts-ignore
            const keyData = Memory.readByteArray(keyPtr, KEY_LENGTH); // Read the key data (KEY_LENGTH bytes)
            // Convert the byte array to a string of  hex values
            const hexKey = get_hex_string_from_byte_array(keyData);
            secret_key = hexKey;
        }
        else {
            devlog("[Error] Argument 'key' is NULL");
        }
        //devlog("invoking ssl_log_secret() from BoringSSL statically linked into Mono BTLS");
        var message = {};
        message["contentType"] = "keylog";
        message["keylog"] = labelStr + " " + client_random + " " + secret_key;
        send(message);
    }
    install_plaintext_read_hook() {
        // TBD
    }
    install_plaintext_write_hook() {
        // TBD
    }
    install_key_extraction_hook() {
        // needs to be setup for the specific plattform
    }
}
✄
{"version":3,"file":"nss.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ssl_lib/nss.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAC1F,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AAChF,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAC,iBAAiB,EAAE,MAAM,eAAe,CAAC;AA6J1D,MAAM,EACF,OAAO,EACP,OAAO,EACP,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,YAAY,EACf,GAAG,aAAa,CAAC,SAAS,CAAC;AAG5B,6FAA6F;AAC7F,MAAM,CAAN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;;;;;;;;;;;;;;;;GAyBG;AACI,mBAAe,GAAG,IAAI,cAAc,CAAC,UAAU,WAA0B,EAAE,KAAa,EAAE,GAAW,EAAE,MAAqB,EAAE,OAAsB;IACvJ,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;QAC7B,GAAG,CAAC,4CAA4C,CAAC,WAAW,EAAE,KAAK,CAAC,CAAC;KACxE;SAAM;QACH,OAAO,CAAC,GAAG,CAAC,2EAA2E,CAAC,CAAC;KAC5F;IAED,OAAO;AACX,CAAC,EAAE,MAAM,EAAE,CAAC,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC,AAR3C,CAQ4C"}
✄
import { readAddresses, getBaseAddress, dumpMemory } from "../shared/shared_functions.js";
import { pointerSize, AF_INET, AF_INET6 } from "../shared/shared_structures.js";
import { log, devlog } from "../util/log.js";
import { offsets, enable_default_fd } from "../ssl_log.js";
const { readU32, readU64, readPointer, writeU32, writeU64, writePointer } = NativePointer.prototype;
// https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/SSL_functions/ssltyp#1026722
export var SECStatus;
(function (SECStatus) {
    SECStatus[SECStatus["SECWouldBlock"] = -2] = "SECWouldBlock";
    SECStatus[SECStatus["SECFailure"] = -1] = "SECFailure";
    SECStatus[SECStatus["SECSuccess"] = 0] = "SECSuccess";
})(SECStatus || (SECStatus = {}));
;
export var PRDescType;
(function (PRDescType) {
    PRDescType[PRDescType["PR_DESC_FILE"] = 1] = "PR_DESC_FILE";
    PRDescType[PRDescType["PR_DESC_SOCKET_TCP"] = 2] = "PR_DESC_SOCKET_TCP";
    PRDescType[PRDescType["PR_DESC_SOCKET_UDP"] = 3] = "PR_DESC_SOCKET_UDP";
    PRDescType[PRDescType["PR_DESC_LAYERED"] = 4] = "PR_DESC_LAYERED";
    PRDescType[PRDescType["PR_DESC_PIPE"] = 5] = "PR_DESC_PIPE";
})(PRDescType || (PRDescType = {}));
PRDescType;
export class NSS {
    constructor(moduleName, socket_library, passed_library_method_mapping) {
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.passed_library_method_mapping = passed_library_method_mapping;
        // global variables
        this.library_method_mapping = {};
        if (typeof passed_library_method_mapping !== 'undefined') {
            this.library_method_mapping = passed_library_method_mapping;
        }
        else {
            this.library_method_mapping[`*${moduleName}*`] = ["PR_Write", "PR_Read", "PR_FileDesc2NativeHandle", "PR_GetPeerName", "PR_GetSockName", "PR_GetNameForIdentity", "PR_GetDescType"];
            this.library_method_mapping[`*libnss.*`] = ["PK11_ExtractKeyValue", "PK11_GetKeyData"];
            this.library_method_mapping["*libssl*.so"] = ["SSL_ImportFD", "SSL_GetSessionID", "SSL_HandshakeCallback"];
            this.library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        }
        this.addresses = readAddresses(moduleName, this.library_method_mapping);
        this.module_name = moduleName;
        // @ts-ignore
        if (offsets != "{OFFSETS}" && offsets.nss != null) {
            if (offsets.sockets != null) {
                const socketBaseAddress = getBaseAddress(socket_library);
                for (const method of Object.keys(offsets.sockets)) {
                    //@ts-ignore
                    this.addresses[this.moduleName][`${method}`] = offsets.sockets[`${method}`].absolute || socketBaseAddress == null ? ptr(offsets.sockets[`${method}`].address) : socketBaseAddress.add(ptr(offsets.sockets[`${method}`].address));
                }
            }
            const libraryBaseAddress = getBaseAddress(moduleName);
            if (libraryBaseAddress == null) {
                log("Unable to find library base address! Given address values will be interpreted as absolute ones!");
            }
            for (const method of Object.keys(offsets.nss)) {
                //@ts-ignore
                this.addresses[this.moduleName][`${method}`] = offsets.nss[`${method}`].absolute || libraryBaseAddress == null ? ptr(offsets.nss[`${method}`].address) : libraryBaseAddress.add(ptr(offsets.nss[`${method}`].address));
            }
        }
        if (!Java.available) {
            NSS.SSL_SESSION_get_id = new NativeFunction(this.addresses[this.moduleName]["SSL_GetSessionID"], "pointer", ["pointer"]);
        }
        NSS.getsockname = new NativeFunction(this.addresses[this.moduleName]["PR_GetSockName"], "int", ["pointer", "pointer"]);
        NSS.getpeername = new NativeFunction(this.addresses[this.moduleName]["PR_GetPeerName"], "int", ["pointer", "pointer"]);
    }
    static get_NSS_version() {
        var getNSSversion = null;
        var version_string = "0";
        if (!Java.available) {
            getNSSversion = new NativeFunction(Module.findExportByName(null, "NSSSSL_GetVersion"), "pointer", []);
        }
        else {
            // we are on Android
            getNSSversion = new NativeFunction(Module.findExportByName("libnss3.so", "NSSSSL_GetVersion"), "pointer", []);
        }
        if (!getNSSversion.isNull()) {
            var ptr_version_string = getNSSversion();
            if (!ptr_version_string.isNull()) {
                version_string = ptr_version_string.readCString();
            }
        }
        // Extract only the numeric part (e.g., "3.108 BETA" → "3.108")
        var match = version_string.match(/^(\d+)\.(\d+)/);
        if (!match) {
            return 0; // Return 0 if the version string is not valid
        }
        // Convert to a numeric version: major * 1000 + minor (e.g., 3.108 → 3108)
        var major = parseInt(match[1], 10);
        var minor = parseInt(match[2], 10);
        return major * 1000 + minor;
    }
    /* PARSING functions */
    static parse_struct_SECItem(secitem) {
        /*
         * struct SECItemStr {
         * SECItemType type;
         * unsigned char *data;
         * unsigned int len;
         * }; --> size = 20
        */
        return {
            "type": secitem.readU64(),
            "data": secitem.add(pointerSize).readPointer(),
            "len": secitem.add(pointerSize * 2).readU32()
        };
    }
    // https://github.com/nss-dev/nss/blob/master/lib/ssl/sslimpl.h#L971
    static parse_struct_sslSocketStr(sslSocketFD) {
        return {
            "fd": sslSocketFD.readPointer(),
            "version": sslSocketFD.add(160),
            "handshakeCallback": sslSocketFD.add(464),
            "secretCallback": sslSocketFD.add(568),
            "ssl3": sslSocketFD.add(1432)
        };
    }
    // https://github.com/nss-dev/nss/blob/master/lib/ssl/sslimpl.h#L771
    static parse_struct_ssl3Str(ssl3_struct) {
        NSS.SS3_VERSIONS_OFFSET = 0; // defaulting offset to 0
        NSS.SS3_VERSIONS_CR_OFFSET = 0;
        var nss_version = NSS.get_NSS_version();
        //console.log("nss_version:"+nss_version);
        if (nss_version >= 3107) {
            devlog("setting offsets for NSS version " + nss_version);
            NSS.SS3_VERSIONS_OFFSET = 96; // offset currentSecret
            NSS.SS3_VERSIONS_CR_OFFSET = 8; // offset for CLIENT_RANDOM
        }
        // version 3.108 beta
        // https://github.com/nss-dev/nss/blob/c277877bd8c01e107b097bbd57df094b34e37aab/lib/ssl/sslimpl.h#L615
        //console.log("[!] inspecing SSL3HandshakeStateStr at: "+ssl3_struct.add(pointerSize * 10 + 24));
        //dumpMemory(ssl3_struct.add(pointerSize * 10 + 24+NSS.SS3_VERSIONS_CR_OFFSET),820);
        //                                           80+ 24 + 8 = 112
        //                         pointerSize * 33 + 440 + 0
        //                                         264+ 440 = 704
        // 432 first ptr
        /*
        struct ssl3StateStr {
    
        ssl3CipherSpec *crSpec; // current read spec.
        ssl3CipherSpec *prSpec; // pending read spec.
        ssl3CipherSpec *cwSpec; // current write spec.
        ssl3CipherSpec *pwSpec; // pending write spec.
        
        PRBool peerRequestedKeyUpdate;                     --> enum type
        
        PRBool keyUpdateDeferred;                          --> enum type
        tls13KeyUpdateRequest deferredKeyUpdateRequest;    --> enum type
       
        PRBool clientCertRequested;                        --> enum type
    
        CERTCertificate *clientCertificate;
        SECKEYPrivateKey *clientPrivateKey;
        CERTCertificateList *clientCertChain;
        PRBool sendEmptyCert;
    
        PRUint8 policy;
        PLArenaPool *peerCertArena;
        
        void *peerCertChain;
        
        CERTDistNames *ca_list;
        
        SSL3HandshakeState hs;
        ...
        }
        */
        return {
            "crSpec": ssl3_struct.readPointer(),
            "prSpec": ssl3_struct.add(pointerSize).readPointer(),
            "cwSpec": ssl3_struct.add(pointerSize * 2).readPointer(),
            "pwSpec": ssl3_struct.add(pointerSize * 3).readPointer(),
            "peerRequestedKeyUpdate": ssl3_struct.add(pointerSize * 4).readU32(),
            "keyUpdateDeferred": ssl3_struct.add(pointerSize * 4 + 4).readU32(),
            "deferredKeyUpdateRequest": ssl3_struct.add(pointerSize * 4 + 8).readU32(),
            "clientCertRequested": ssl3_struct.add(pointerSize * 4 + 12).readU32(),
            "clientCertificate": ssl3_struct.add(pointerSize * 4 + 16).readPointer(),
            "clientPrivateKey": ssl3_struct.add(pointerSize * 5 + 16).readPointer(),
            "clientCertChain": ssl3_struct.add(pointerSize * 6 + 16).readPointer(),
            "sendEmptyCert": ssl3_struct.add(pointerSize * 7 + 16).readU32(),
            "policy": ssl3_struct.add(pointerSize * 7 + 20).readU32(),
            "peerCertArena": ssl3_struct.add(pointerSize * 7 + 24).readPointer(),
            "peerCertChain": ssl3_struct.add(pointerSize * 8 + 24).readPointer(),
            "ca_list": ssl3_struct.add(pointerSize * 9 + 24).readPointer(),
            "hs": {
                "server_random": ssl3_struct.add(pointerSize * 10 + 24 + NSS.SS3_VERSIONS_CR_OFFSET),
                "client_random": ssl3_struct.add(pointerSize * 10 + 56 + NSS.SS3_VERSIONS_CR_OFFSET),
                "client_inner_random": ssl3_struct.add(pointerSize * 10 + 88 + NSS.SS3_VERSIONS_CR_OFFSET),
                "ws": ssl3_struct.add(pointerSize * 10 + 120 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "hashType": ssl3_struct.add(pointerSize * 10 + 124 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "messages": {
                    "data": ssl3_struct.add(pointerSize * 10 + 128 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                    "len": ssl3_struct.add(pointerSize * 11 + 128 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                    "space": ssl3_struct.add(pointerSize * 11 + 132 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                    "fixed": ssl3_struct.add(pointerSize * 11 + 136 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                },
                "echInnerMessages": {
                    "data": ssl3_struct.add(pointerSize * 11 + 140 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                    "len": ssl3_struct.add(pointerSize * 12 + 140 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                    "space": ssl3_struct.add(pointerSize * 12 + 144 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                    "fixed": ssl3_struct.add(pointerSize * 12 + 148 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                },
                "md5": ssl3_struct.add(pointerSize * 12 + 152 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "sha": ssl3_struct.add(pointerSize * 13 + 152 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "shaEchInner": ssl3_struct.add(pointerSize * 14 + 152 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "shaPostHandshake": ssl3_struct.add(pointerSize * 15 + 152 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "signatureScheme": ssl3_struct.add(pointerSize * 16 + 152 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "kea_def": ssl3_struct.add(pointerSize * 16 + 156 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "cipher_suite": ssl3_struct.add(pointerSize * 17 + 156 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "suite_def": ssl3_struct.add(pointerSize * 17 + 160 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "msg_body": {
                    "data": ssl3_struct.add(pointerSize * 18 + 160 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                    "len": ssl3_struct.add(pointerSize * 19 + 160 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                    "space": ssl3_struct.add(pointerSize * 19 + 164 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                    "fixed": ssl3_struct.add(pointerSize * 19 + 168 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                },
                "header_bytes": ssl3_struct.add(pointerSize * 19 + 172 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "msg_type": ssl3_struct.add(pointerSize * 19 + 176 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "msg_len": ssl3_struct.add(pointerSize * 19 + 180 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "isResuming": ssl3_struct.add(pointerSize * 19 + 184 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "sendingSCSV": ssl3_struct.add(pointerSize * 19 + 188 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "receivedNewSessionTicket": ssl3_struct.add(pointerSize * 19 + 192 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "newSessionTicket": ssl3_struct.add(pointerSize * 19 + 196 + NSS.SS3_VERSIONS_OFFSET),
                "finishedBytes": ssl3_struct.add(pointerSize * 19 + 240 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "finishedMsgs": ssl3_struct.add(pointerSize * 19 + 244 + NSS.SS3_VERSIONS_OFFSET),
                "authCertificatePending": ssl3_struct.add(pointerSize * 18 + 316 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "restartTarget": ssl3_struct.add(pointerSize * 19 + 320 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "canFalseStart": ssl3_struct.add(pointerSize * 19 + 324 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "preliminaryInfo": ssl3_struct.add(pointerSize * 19 + 328 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "remoteExtensions": {
                    "next": ssl3_struct.add(pointerSize * 19 + 332 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                    "prev": ssl3_struct.add(pointerSize * 20 + 332 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                },
                "echOuterExtensions": {
                    "next": ssl3_struct.add(pointerSize * 21 + 332 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                    "prev": ssl3_struct.add(pointerSize * 22 + 332 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                },
                "sendMessageSeq": ssl3_struct.add(pointerSize * 23 + 332 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "lastMessageFlight": {
                    "next": ssl3_struct.add(pointerSize * 23 + 336 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                    "prev": ssl3_struct.add(pointerSize * 24 + 336 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                },
                "maxMessageSent": ssl3_struct.add(pointerSize * 25 + 336 + NSS.SS3_VERSIONS_OFFSET).readU16(),
                "recvMessageSeq": ssl3_struct.add(pointerSize * 25 + 338 + NSS.SS3_VERSIONS_OFFSET).readU16(),
                "recvdFragments": {
                    "data": ssl3_struct.add(pointerSize * 25 + 340 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                    "len": ssl3_struct.add(pointerSize * 26 + 340 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                    "space": ssl3_struct.add(pointerSize * 26 + 344 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                    "fixed": ssl3_struct.add(pointerSize * 26 + 348 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                },
                "recvdHighWater": ssl3_struct.add(pointerSize * 26 + 352 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "cookie": {
                    "type": ssl3_struct.add(pointerSize * 26 + 356 + NSS.SS3_VERSIONS_OFFSET).readU64(),
                    "data": ssl3_struct.add(pointerSize * 27 + 356 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                    "len": ssl3_struct.add(pointerSize * 28 + 356 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                },
                "times_array": ssl3_struct.add(pointerSize * 28 + 360 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "rtTimer": ssl3_struct.add(pointerSize * 28 + 432 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "ackTimer": ssl3_struct.add(pointerSize * 29 + 432 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "hdTimer": ssl3_struct.add(pointerSize * 30 + 432 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "rtRetries": ssl3_struct.add(pointerSize * 31 + 432 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                "srvVirtName": {
                    "type": ssl3_struct.add(pointerSize * 31 + 436 + NSS.SS3_VERSIONS_OFFSET).readU64(),
                    "data": ssl3_struct.add(pointerSize * 32 + 436 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                    "len": ssl3_struct.add(pointerSize * 33 + 436 + NSS.SS3_VERSIONS_OFFSET).readU32(),
                },
                "currentSecret": ssl3_struct.add(pointerSize * 33 + 440 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "resumptionMasterSecret": ssl3_struct.add(pointerSize * 34 + 440 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "dheSecret": ssl3_struct.add(pointerSize * 35 + 440 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "clientEarlyTrafficSecret": ssl3_struct.add(pointerSize * 36 + 440 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "clientHsTrafficSecret": ssl3_struct.add(pointerSize * 37 + 440 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "serverHsTrafficSecret": ssl3_struct.add(pointerSize * 38 + 440 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "clientTrafficSecret": ssl3_struct.add(pointerSize * 39 + 440 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "serverTrafficSecret": ssl3_struct.add(pointerSize * 40 + 440 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "earlyExporterSecret": ssl3_struct.add(pointerSize * 41 + 440 + NSS.SS3_VERSIONS_OFFSET).readPointer(),
                "exporterSecret": ssl3_struct.add(pointerSize * 42 + 440 + NSS.SS3_VERSIONS_OFFSET).readPointer()
            } // end of hs struct
            /*
            typedef struct SSL3HandshakeStateStr {
        SSL3Random server_random;
        SSL3Random client_random;
        SSL3Random client_inner_random;
        SSL3WaitState ws;                       --> enum type
    
        
        SSL3HandshakeHashType hashType;         --> enum type
        sslBuffer messages;                     --> struct of 20 bytes (1 ptr + 12 bytes;see lib/ssl/sslencode.h)
        sslBuffer echInnerMessages;
        
        PK11Context *md5;
        PK11Context *sha;
        PK11Context *shaEchInner;
        PK11Context *shaPostHandshake;
        SSLSignatureScheme signatureScheme;     --> enum type( see lib/ssl/sslt.h)
        const ssl3KEADef *kea_def;
        ssl3CipherSuite cipher_suite;           --> typedef PRUint16 ssl3CipherSuite (see lib/ssl/ssl3prot.h)
        const ssl3CipherSuiteDef *suite_def;
        sslBuffer msg_body;
                            
        unsigned int header_bytes;
        
        SSLHandshakeType msg_type;
        unsigned long msg_len;
        PRBool isResuming;
        PRBool sendingSCSV;
    
        
        PRBool receivedNewSessionTicket;
        NewSessionTicket newSessionTicket;      --> (see lib/ssl/ssl3prot.h)
    
        PRUint16 finishedBytes;
        union {
            TLSFinished tFinished[2];           --> 12 bytes
            SSL3Finished sFinished[2];          --> 36 bytes
            PRUint8 data[72];
        } finishedMsgs;                         --> 72
    
        PRBool authCertificatePending;
        
        sslRestartTarget restartTarget;
    
        PRBool canFalseStart;
        
        PRUint32 preliminaryInfo;
    
        
        PRCList remoteExtensions;
        PRCList echOuterExtensions;
    
        
        PRUint16 sendMessageSeq;
        PRCList lastMessageFlight;
        PRUint16 maxMessageSent;
        PRUint16 recvMessageSeq;
        sslBuffer recvdFragments;
        PRInt32 recvdHighWater;
        SECItem cookie;
        dtlsTimer timers[3];       24 * 3
        dtlsTimer *rtTimer;
        dtlsTimer *ackTimer;
        dtlsTimer *hdTimer;
        PRUint32 rtRetries;
        SECItem srvVirtName;
                                        
    
        // This group of values is used for TLS 1.3 and above
        PK11SymKey *currentSecret;            // The secret down the "left hand side"   --> ssl3_struct.add(704)
                                                //of the TLS 1.3 key schedule.
        PK11SymKey *resumptionMasterSecret;   // The resumption_master_secret.          --> ssl3_struct.add(712)
        PK11SymKey *dheSecret;                // The (EC)DHE shared secret.             --> ssl3_struct.add(720)
        PK11SymKey *clientEarlyTrafficSecret; // The secret we use for 0-RTT.           --> ssl3_struct.add(728)
        PK11SymKey *clientHsTrafficSecret;    // The source keys for handshake          --> ssl3_struct.add(736)
        PK11SymKey *serverHsTrafficSecret;    // traffic keys.                          --> ssl3_struct.add(744)
        PK11SymKey *clientTrafficSecret;      // The source keys for application        --> ssl3_struct.add(752)
        PK11SymKey *serverTrafficSecret;      // traffic keys                           --> ssl3_struct.add(760)
        PK11SymKey *earlyExporterSecret;      // for 0-RTT exporters                    --> ssl3_struct.add(768)
        PK11SymKey *exporterSecret;           // for exporters                          --> ssl3_struct.add(776)
        ...
    
    
        typedef struct {
        const char *label; 8
        DTLSTimerCb cb; 8
        PRIntervalTime started; 4
        PRUint32 timeout; 4
    } dtlsTimer;
    
            */
        };
    }
    // https://github.com/nss-dev/nss/blob/master/lib/ssl/sslspec.h#L140 
    static parse_struct_sl3CipherSpecStr(cwSpec) {
        /*
        truct ssl3CipherSpecStr {
            PRCList link;
            PRUint8 refCt;
    
            SSLSecretDirection direction;
            SSL3ProtocolVersion version;
            SSL3ProtocolVersion recordVersion;
    
            const ssl3BulkCipherDef *cipherDef;
            const ssl3MACDef *macDef;
    
            SSLCipher cipher;
            void *cipherContext;
    
            PK11SymKey *masterSecret;
            ...
        */
        return {
            "link": cwSpec.add,
            "refCt": cwSpec.add(pointerSize * 2),
            "direction": cwSpec.add(pointerSize * 2 + 4),
            "version": cwSpec.add(pointerSize * 2 + 8),
            "recordVersion": cwSpec.add(pointerSize * 2 + 12),
            "cipherDef": cwSpec.add(pointerSize * 2 + 16).readPointer(),
            "macDef": cwSpec.add(pointerSize * 3 + 16).readPointer(),
            "cipher": cwSpec.add(pointerSize * 4 + 16),
            "cipherContext": cwSpec.add(pointerSize * 4 + 24).readPointer(),
            "master_secret": cwSpec.add(pointerSize * 5 + 24).readPointer()
        };
    }
    /********* NSS helper functions  ********/
    /**
* Returns a dictionary of a sockfd's "src_addr", "src_port", "dst_addr", and
* "dst_port".
* @param {pointer} sockfd The file descriptor of the socket to inspect as PRFileDesc.
* @param {boolean} isRead If true, the context is an SSL_read call. If
*     false, the context is an SSL_write call.
* @param {{ [key: string]: NativePointer}} methodAddresses Dictionary containing (at least) addresses for getpeername, getsockname, ntohs and ntohl
* @return {{ [key: string]: string | number }} Dictionary of sockfd's "src_addr", "src_port", "dst_addr",
*     and "dst_port".

  PRStatus PR_GetPeerName(
PRFileDesc *fd,
PRNetAddr *addr);

PRStatus PR_GetSockName(
PRFileDesc *fd,
PRNetAddr *addr);

PRStatus PR_NetAddrToString(
const PRNetAddr *addr,
char *string,
PRUint32 size);


union PRNetAddr {
struct {
   PRUint16 family;
   char data[14];
} raw;
struct {
   PRUint16 family;
   PRUint16 port;
   PRUint32 ip;
   char pad[8];
} inet;
#if defined(_PR_INET6)
struct {
   PRUint16 family;
   PRUint16 port;
   PRUint32 flowinfo;
   PRIPv6Addr ip;
} ipv6;
#endif // defined(_PR_INET6)
};

typedef union PRNetAddr PRNetAddr;

*/
    static getPortsAndAddressesFromNSS(sockfd, isRead, methodAddresses, enable_default_fd) {
        var message = {};
        if (enable_default_fd && sockfd === null) {
            message["src" + "_port"] = 1234;
            message["src" + "_addr"] = "127.0.0.1";
            message["dst" + "_port"] = 2345;
            message["dst" + "_addr"] = "127.0.0.1";
            message["ss_family"] = "AF_INET";
            return message;
        }
        var getpeername = new NativeFunction(methodAddresses["PR_GetPeerName"], "int", ["pointer", "pointer"]);
        var getsockname = new NativeFunction(methodAddresses["PR_GetSockName"], "int", ["pointer", "pointer"]);
        var ntohs = new NativeFunction(methodAddresses["ntohs"], "uint16", ["uint16"]);
        var ntohl = new NativeFunction(methodAddresses["ntohl"], "uint32", ["uint32"]);
        var addrType = Memory.alloc(2); // PRUint16 is a 2 byte (16 bit) value on all plattforms
        //var prNetAddr = Memory.alloc(Process.pointerSize)
        var addrlen = Memory.alloc(4);
        var addr = Memory.alloc(128);
        var src_dst = ["src", "dst"];
        for (var i = 0; i < src_dst.length; i++) {
            addrlen.writeU32(128);
            if ((src_dst[i] == "src") !== isRead) {
                getsockname(sockfd, addr);
            }
            else {
                getpeername(sockfd, addr);
            }
            if (addr.readU16() == AF_INET) {
                message[src_dst[i] + "_port"] = ntohs(addr.add(2).readU16());
                message[src_dst[i] + "_addr"] = ntohl(addr.add(4).readU32());
                message["ss_family"] = "AF_INET";
            }
            else if (addr.readU16() == AF_INET6) {
                message[src_dst[i] + "_port"] = ntohs(addr.add(2).readU16());
                message[src_dst[i] + "_addr"] = "";
                var ipv6_addr = addr.add(8);
                for (var offset = 0; offset < 16; offset += 1) {
                    message[src_dst[i] + "_addr"] += ("0" + ipv6_addr.add(offset).readU8().toString(16).toUpperCase()).substr(-2);
                }
                if (message[src_dst[i] + "_addr"].toString().indexOf("00000000000000000000FFFF") === 0) {
                    message[src_dst[i] + "_addr"] = ntohl(ipv6_addr.add(12).readU32());
                    message["ss_family"] = "AF_INET";
                }
                else {
                    message["ss_family"] = "AF_INET6";
                }
            }
            else {
                devlog("[-] PIPE descriptor error: Only supporting IPv4/6: " + addr.readU16());
                //FIXME: Sometimes addr.readU16() will be 0 when a PIPE Read oder Write gets interpcepted, thus this error will be thrown.
                throw "Only supporting IPv4/6";
            }
        }
        return message;
    }
    /**
    * This functions tests if a given address is a readable pointer
    *
    * @param {*} ptr_addr is a pointer to the memory location where we want to check if there is already an address
    * @returns 1 to indicate that there is a ptr at
    */
    static is_ptr_at_mem_location(ptr_addr) {
        try {
            // an exception is thrown if there isn't a readable address
            ptr_addr.readPointer();
            return 1;
        }
        catch (error) {
            return -1;
        }
    }
    /**
    *
    * typedef struct PRFileDesc {
    *       const struct PRIOMethods *methods;
    *       PRFilePrivate *secret;
    *       PRFileDesc *lower;
    *       PRFileDesc *higher;
    *       void (*dtor) (PRFileDesc *);
    *       PRDescIdentity identity;
    *  } PRFileDesc;
    *
    * @param {*} pRFileDesc
    * @param {*} layer_name
    * @returns
    */
    static NSS_FindIdentityForName(pRFileDesc, layer_name) {
        var lower_ptr = pRFileDesc.add(pointerSize * 2).readPointer();
        var higher_ptr = pRFileDesc.add(pointerSize * 3).readPointer();
        var identity = pRFileDesc.add(pointerSize * 5).readPointer();
        if (!identity.isNull()) {
            var nameptr = NSS.PR_GetNameForIdentity(identity).readCString();
            if (nameptr == layer_name) {
                return pRFileDesc;
            }
        }
        if (!lower_ptr.isNull()) {
            return this.NSS_FindIdentityForName(lower_ptr, layer_name);
        }
        if (!higher_ptr.isNull()) {
            devlog('Have upper');
        }
        // when we reach this we have some sort of error 
        devlog("[-] error while getting SSL layer");
        return NULL;
    }
    static getSessionIdString(session_id_ptr, len) {
        var session_id = "";
        for (var i = 0; i < len; i++) {
            // Read a byte, convert it to a hex string (0xAB ==> "AB"), and append
            // it to session_id.
            session_id +=
                ("0" + session_id_ptr.add(i).readU8().toString(16).toUpperCase()).substr(-2);
        }
        return session_id;
    }
    static getSSL_Layer(pRFileDesc) {
        var ssl_layer_id = 3; // SSL has the Layer ID 3 normally.
        var getIdentitiesLayer = new NativeFunction(Module.getExportByName('libnspr4.so', 'PR_GetIdentitiesLayer'), "pointer", ["pointer", "int"]);
        var ssl_layer = getIdentitiesLayer(pRFileDesc, ssl_layer_id);
        if (ptr(ssl_layer.toString()).isNull()) {
            devlog("PR_BAD_DESCRIPTOR_ERROR: " + ssl_layer);
            return -1;
        }
        return ssl_layer;
    }
    /**
    *
    * @param {*} readAddr is the address where we start reading the bytes
    * @param {*} len is the length of bytes we want to convert to a hex string
    * @returns a hex string with the length of len
    */
    static getHexString(readAddr, len) {
        var secret_str = "";
        for (var i = 0; i < len; i++) {
            // Read a byte, convert it to a hex string (0xab ==> "ab"), and append
            // it to secret_str.
            secret_str +=
                ("0" + readAddr.add(i).readU8().toString(16).toLowerCase()).substr(-2);
        }
        return secret_str;
    }
    /**
 * Get the session_id of SSL object and return it as a hex string.
 * @param {!NativePointer} ssl A pointer to an SSL object.
 * @return {dict} A string representing the session_id of the SSL object's
 *     SSL_SESSION. For example,
 *     "59FD71B7B90202F359D89E66AE4E61247954E28431F6C6AC46625D472FF76336".
 *
 * On NSS the return type of SSL_GetSessionID is a SECItem:
      typedef enum {
 * siBuffer = 0,
 * siClearDataBuffer = 1,
 * siCipherDataBuffer = 2,
 * siDERCertBuffer = 3,
 * siEncodedCertBuffer = 4,
 * siDERNameBuffer = 5,
 * siEncodedNameBuffer = 6,
 * siAsciiNameString = 7,
 * siAsciiString = 8,
 * siDEROID = 9,
 * siUnsignedInteger = 10,
 * siUTCTime = 11,
 * siGeneralizedTime = 12,
 * siVisibleString = 13,
 * siUTF8String = 14,
 * siBMPString = 15
 * } SECItemType;
 *
 * typedef struct SECItemStr SECItem;
 *
 * struct SECItemStr {
 * SECItemType type;
 * unsigned char *data;
 * unsigned int len;
 * }; --> size = 20
 *
 *
 */
    static getSslSessionIdFromFD(pRFileDesc) {
        var dummySSL_SessionID = "3E8ABF58649A1A1C58824D704173BA9AAFA2DA33B45FFEA341D218B29BBACF8F";
        var fdType = NSS.getDescType(pRFileDesc);
        //log("pRFileDescType: "+ fdType)
        /*if(fdType == 4){ // LAYERED
            pRFileDesc = ptr(getSSL_Layer(pRFileDesc).toString())
            if(pRFileDesc.toString() == "-1"){
                log("error")
        
            }
        }*/
        var layer = NSS.NSS_FindIdentityForName(pRFileDesc, 'SSL');
        if (!layer || Java.available) { // on Android is no SSL_SESSION_get_id available
            return dummySSL_SessionID;
        }
        var sslSessionIdSECItem = ptr(NSS.SSL_SESSION_get_id(layer).toString());
        if (sslSessionIdSECItem == null || sslSessionIdSECItem.isNull()) {
            try {
                devlog("---- getSslSessionIdFromFD -----");
                devlog("ERROR");
                devlog("pRFileDescType: " + NSS.getDescType(pRFileDesc));
                if (fdType == 2) {
                    var c = Memory.dup(pRFileDesc, 32);
                    //log(hexdump(c))
                    var getLayersIdentity = null;
                    var getNameOfIdentityLayer;
                    try {
                        getLayersIdentity = new NativeFunction(Module.getExportByName('libnspr4.so', 'PR_GetLayersIdentity'), "uint32", ["pointer"]);
                        getNameOfIdentityLayer = new NativeFunction(Module.getExportByName('libnspr4.so', 'PR_GetNameForIdentity'), "pointer", ["uint32"]);
                    }
                    catch (e) {
                        getLayersIdentity = new NativeFunction(Module.getExportByName('libnss3.so', 'PR_GetLayersIdentity'), "uint32", ["pointer"]);
                        getNameOfIdentityLayer = new NativeFunction(Module.getExportByName('libnss3.so', 'PR_GetNameForIdentity'), "pointer", ["uint32"]);
                    }
                    var layerID = getLayersIdentity(pRFileDesc);
                    devlog("LayerID: " + layerID);
                    var nameIDentity = getNameOfIdentityLayer(layerID);
                    devlog("name address: " + nameIDentity);
                    devlog("name: " + ptr(nameIDentity.toString()).readCString());
                    var sslSessionIdSECItem2 = ptr(NSS.getSSL_Layer(pRFileDesc).toString());
                    devlog("sslSessionIdSECItem2 =" + sslSessionIdSECItem2);
                    if (sslSessionIdSECItem2.toString().startsWith("0x7f")) {
                        var aa = Memory.dup(sslSessionIdSECItem2, 32);
                        //log(hexdump(aa))
                        var sslSessionIdSECItem3 = ptr(NSS.SSL_SESSION_get_id(sslSessionIdSECItem2).toString());
                        devlog("sslSessionIdSECItem3 =" + sslSessionIdSECItem3);
                    }
                    var sslSessionIdSECItem4 = ptr(NSS.SSL_SESSION_get_id(pRFileDesc).toString());
                    devlog("sslSessionIdSECItem4 =" + sslSessionIdSECItem4);
                    devlog("Using Dummy Session ID");
                    devlog("");
                }
                else if (fdType == 4) {
                    pRFileDesc = ptr(NSS.getSSL_Layer(pRFileDesc).toString());
                    var sslSessionIdSECItem = ptr(NSS.SSL_SESSION_get_id(pRFileDesc).toString());
                    devlog("new sessionid_ITEM: " + sslSessionIdSECItem);
                }
                else {
                    devlog("---- SSL Session Analysis ------------");
                    var c = Memory.dup(sslSessionIdSECItem, 32);
                    devlog(hexdump(c));
                }
                devlog("---- getSslSessionIdFromFD finished -----");
                devlog("");
            }
            catch (error) {
                devlog("Error:" + error);
            }
            return dummySSL_SessionID;
        }
        var len = sslSessionIdSECItem.add(pointerSize * 2).readU32();
        var session_id_ptr = sslSessionIdSECItem.add(pointerSize).readPointer();
        var session_id = NSS.getSessionIdString(session_id_ptr, len);
        return session_id;
    }
    static get_SSL_FD(pRFileDesc) {
        var ssl_layer = NSS.NSS_FindIdentityForName(pRFileDesc, 'SSL');
        if (!ssl_layer) {
            devlog("error: couldn't get SSL Layer from pRFileDesc");
            return NULL;
        }
        var sslSocketFD = NSS.get_SSL_Socket(ssl_layer);
        if (!sslSocketFD) {
            devlog("error: couldn't get sslSocketFD");
            return NULL;
        }
        return sslSocketFD;
    }
    /**
    *
    *
    *
    *
    *
    *
    * /* This function tries to find the SSL layer in the stack.
    * It searches for the first SSL layer at or below the argument fd,
    * and failing that, it searches for the nearest SSL layer above the
    * argument fd.  It returns the private sslSocket from the found layer.
    *
    sslSocket *
    ssl_FindSocket(PRFileDesc *fd)
    {
    PRFileDesc *layer;
    sslSocket *ss;
    
    PORT_Assert(fd != NULL);
    PORT_Assert(ssl_layer_id != 0);
    
    layer = PR_GetIdentitiesLayer(fd, ssl_layer_id);
    if (layer == NULL) {
    PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
    return NULL;
    }
    
    ss = (sslSocket *)layer->secret;
    /* Set ss->fd lazily. We can't rely on the value of ss->fd set by
    * ssl_PushIOLayer because another PR_PushIOLayer call will switch the
    * contents of the PRFileDesc pointed by ss->fd and the new layer.
    * See bug 807250.
    *
    ss->fd = layer;
    return ss;
    }
    
    *
    *
    */
    static get_SSL_Socket(ssl_layer) {
        var sslSocket = ssl_layer.add(pointerSize * 1).readPointer();
        return sslSocket;
    }
    /******** NSS Encryption Keys *******/
    /**
     *
     * ss->ssl3.cwSpec->masterSecret
     *
     * @param {*} ssl3  the parsed ssl3 struct
     * @returns the client_random as hex string (lower case)
     */
    static getMasterSecret(ssl3) {
        var cwSpec = ssl3.cwSpec;
        var masterSecret_Ptr = NSS.parse_struct_sl3CipherSpecStr(cwSpec).master_secret;
        var master_secret = NSS.get_Secret_As_HexString(masterSecret_Ptr);
        return master_secret;
    }
    /**
     * ss->ssl3.hs.client_random
     *
     * @param {*} ssl3 is a ptr to current parsed ssl3 struct
     * @returns the client_random as hex string (lower case)
     */
    static getClientRandom(ssl3) {
        var client_random = NSS.getHexString(ssl3.hs.client_random, NSS.SSL3_RANDOM_LENGTH);
        return client_random;
    }
    /**
    
     
    typedef struct sslSocketStr sslSocket;
     *
    
        SSL Socket struct (https://github.com/nss-dev/nss/blob/master/lib/ssl/sslimpl.h#L971)
    struct sslSocketStr {
    PRFileDesc *fd;                                                                     +8
    
    /* Pointer to operations vector for this socket *
    const sslSocketOps *ops;                                                            +8
    
    /* SSL socket options *
    sslOptions opt;                                                                     sizeOf(sslOptions) --> 40
    /* Enabled version range *
    SSLVersionRange vrange;                                                             + 4
    
    /* A function that returns the current time. *
    SSLTimeFunc now;                                                                    +8
    void *nowArg;                                                                       +8
    
    /* State flags *
    unsigned long clientAuthRequested;                                                  +8
    unsigned long delayDisabled;     /* Nagle delay disabled *                          +8
    unsigned long firstHsDone;       /* first handshake is complete. *                  +8
    unsigned long enoughFirstHsDone; /* enough of the first handshake is                +8
                                      * done for callbacks to be able to
                                      * retrieve channel security
                                      * parameters from the SSL socket. *
    unsigned long handshakeBegun;                                                       +8
    unsigned long lastWriteBlocked;                                                     +8
    unsigned long recvdCloseNotify; /* received SSL EOF. *                              +8
    unsigned long TCPconnected;                                                         +8
    unsigned long appDataBuffered;                                                      +8
    unsigned long peerRequestedProtection; /* from old renegotiation *                  +8
    
    /* version of the protocol to use *
    SSL3ProtocolVersion version;                                                        +4
    SSL3ProtocolVersion clientHelloVersion; /* version sent in client hello. *          --> at offset 160
     */
    static get_SSL_Version(pRFileDesc) {
        var ssl_version_internal_Code = -1;
        var sslSocket = NSS.get_SSL_FD(pRFileDesc);
        if (sslSocket.isNull()) {
            return -1;
        }
        var sslVersion_pointerSize = 160;
        ssl_version_internal_Code = sslSocket.add((sslVersion_pointerSize)).readU16();
        return ssl_version_internal_Code;
    }
    static get_Secret_As_HexString(secret_key_Ptr) {
        var secret_as_hexString = "";
        var rv = NSS.PK11_ExtractKeyValue(secret_key_Ptr);
        if (rv != SECStatus.SECSuccess) {
            devlog("ERROR access the secret key: " + secret_key_Ptr + " return value: " + rv);
            /*
            // debug output
            try{
                
                console.log("\n[!] dumping secret key: ")
                dumpMemory(secret_key_Ptr, 0x80);

                if(!secret_key_Ptr.isNull()){
                    var keyData1 = NSS.PK11_GetKeyData(secret_key_Ptr);
                    console.log("[!] dumping key data at: "+keyData1);
                    dumpMemory(keyData1, 0x80);
                    var keyData_SECITem1 = NSS.parse_struct_SECItem(keyData1 as NativePointer);

                    console.log("Looking at the value of keyData_SECITem1 (len: "+keyData_SECITem1.len+"): ")
                    dumpMemory(keyData_SECITem1.data, 0x80);
                    console.log("--------------------------------------------------\n");
                }

                


            }catch(e){

            }*/
            return "";
        }
        var keyData = NSS.PK11_GetKeyData(secret_key_Ptr); // return value is a SECItem
        var keyData_SECITem = NSS.parse_struct_SECItem(keyData);
        try {
            if (keyData_SECITem.len > 64) {
                devlog("[!] error in identifiying the real key_len: " + keyData_SECITem.len);
                secret_as_hexString = NSS.getHexString(keyData_SECITem.data, 32);
            }
            else {
                secret_as_hexString = NSS.getHexString(keyData_SECITem.data, keyData_SECITem.len);
            }
        }
        catch (e) {
            devlog("[-] Error in extracting key from: " + keyData_SECITem.data + " with length: " + keyData_SECITem.len + " derived from secret_key_Ptr: " + secret_key_Ptr);
            dumpMemory(keyData_SECITem.data, 0x80);
        }
        return secret_as_hexString;
    }
    /**
     *
     * @param {*} ssl_version_internal_Code
     * @returns
     *
     *      https://github.com/nss-dev/nss/blob/c989bde00fe64c1b37df13c773adf3e91cc258c7/lib/ssl/sslproto.h#L16
     *      #define SSL_LIBRARY_VERSION_TLS_1_2             0x0303
     *      #define SSL_LIBRARY_VERSION_TLS_1_3             0x0304
     *
     *      0x0303 -->  771
     *      0x0304 -->  772
     *
     */
    static is_TLS_1_3(ssl_version_internal_Code) {
        if (ssl_version_internal_Code > 771) {
            return true;
        }
        else {
            return false;
        }
    }
    //see nss/lib/ssl/sslinfo.c for details */
    static get_Keylog_Dump(type, client_random, key) {
        // Debug output
        /*
        console.log("[!] CLIENT_RANDOM: "+client_random);
        console.log("[!] KEY: "+key);
        */
        return type + " " + client_random + " " + key;
    }
    /**
     *
     * @param {*} pRFileDesc
     * @param {*} dumping_handshake_secrets  a zero indicates an false and that the handshake just completed. A 1 indicates a true so that we are during the handshake itself
     * @returns
     */
    static getTLS_Keys(pRFileDesc, dumping_handshake_secrets) {
        var message = {};
        message["contentType"] = "keylog";
        devlog("trying to log some keying materials ...");
        var sslSocketFD = NSS.get_SSL_FD(pRFileDesc);
        if (sslSocketFD.isNull()) {
            return;
        }
        var sslSocketStr = NSS.parse_struct_sslSocketStr(sslSocketFD);
        var ssl3_struct = sslSocketStr.ssl3;
        var ssl3 = NSS.parse_struct_ssl3Str(ssl3_struct);
        //console.log("[!] inspecting ssl3: ");
        //dumpMemory(ssl3.hs.currentSecret,0x200);
        // the client_random is used to identify the diffrent SSL streams with their corresponding secrets
        var client_random = NSS.getClientRandom(ssl3);
        if (NSS.doTLS13_RTT0 == 1) {
            //var early_exporter_secret = get_Secret_As_HexString(ssl3_struct.add(768).readPointer()); //EARLY_EXPORTER_SECRET
            var early_exporter_secret = NSS.get_Secret_As_HexString(ssl3.hs.earlyExporterSecret); //EARLY_EXPORTER_SECRET
            devlog(NSS.get_Keylog_Dump("EARLY_EXPORTER_SECRET", client_random, early_exporter_secret));
            message["keylog"] = NSS.get_Keylog_Dump("EARLY_EXPORTER_SECRET", client_random, early_exporter_secret);
            send(message);
            NSS.doTLS13_RTT0 = -1;
        }
        if (dumping_handshake_secrets == 1) {
            devlog("exporting TLS 1.3 handshake keying material");
            /*
             * Those keys are computed in the beginning of a handshake
             */
            //var client_handshake_traffic_secret = get_Secret_As_HexString(ssl3_struct.add(736).readPointer()); //CLIENT_HANDSHAKE_TRAFFIC_SECRET
            var client_handshake_traffic_secret = NSS.get_Secret_As_HexString(ssl3.hs.clientHsTrafficSecret); //CLIENT_HANDSHAKE_TRAFFIC_SECRET
            //parse_struct_ssl3Str(ssl3_struct)
            devlog(NSS.get_Keylog_Dump("CLIENT_HANDSHAKE_TRAFFIC_SECRET", client_random, client_handshake_traffic_secret));
            message["keylog"] = NSS.get_Keylog_Dump("CLIENT_HANDSHAKE_TRAFFIC_SECRET", client_random, client_handshake_traffic_secret);
            send(message);
            //var server_handshake_traffic_secret = get_Secret_As_HexString(ssl3_struct.add(744).readPointer()); //SERVER_HANDSHAKE_TRAFFIC_SECRET
            var server_handshake_traffic_secret = NSS.get_Secret_As_HexString(ssl3.hs.serverHsTrafficSecret); //SERVER_HANDSHAKE_TRAFFIC_SECRET
            devlog(NSS.get_Keylog_Dump("SERVER_HANDSHAKE_TRAFFIC_SECRET", client_random, server_handshake_traffic_secret));
            message["keylog"] = NSS.get_Keylog_Dump("SERVER_HANDSHAKE_TRAFFIC_SECRET", client_random, server_handshake_traffic_secret);
            send(message);
            return;
        }
        else if (dumping_handshake_secrets == 2) {
            devlog("exporting TLS 1.3 RTT0 handshake keying material");
            var client_early_traffic_secret = NSS.get_Secret_As_HexString(ssl3.hs.clientEarlyTrafficSecret); //CLIENT_EARLY_TRAFFIC_SECRET
            devlog(NSS.get_Keylog_Dump("CLIENT_EARLY_TRAFFIC_SECRET", client_random, client_early_traffic_secret));
            message["keylog"] = NSS.get_Keylog_Dump("CLIENT_EARLY_TRAFFIC_SECRET", client_random, client_early_traffic_secret);
            send(message);
            NSS.doTLS13_RTT0 = 1; // there is no callback for the EARLY_EXPORTER_SECRET
            return;
        }
        var ssl_version_internal_Code = NSS.get_SSL_Version(pRFileDesc);
        if (NSS.is_TLS_1_3(ssl_version_internal_Code)) {
            devlog("exporting TLS 1.3 keying material");
            /*
            Testing offsets via brute force...

            var i = 432;
            try{
                for (; i <= 850; i += 8) {
                    try{
                        var dst_ptr = ssl3_struct.add(i).readPointer();
                        if(!dst_ptr.isNull()){
                            console.log(i);
                            var server_handshake_traffic_secret = NSS.get_Secret_As_HexString(dst_ptr);
                            console.log("[!] server_handshake_traffic_secret (offset: "+i+"): "+server_handshake_traffic_secret);
                        }
                    }catch(innere){}
                    
                }

            }catch(e){

            }*/
            var client_traffic_secret = NSS.get_Secret_As_HexString(ssl3.hs.clientTrafficSecret); //CLIENT_TRAFFIC_SECRET_0
            devlog(NSS.get_Keylog_Dump("CLIENT_TRAFFIC_SECRET_0", client_random, client_traffic_secret));
            message["keylog"] = NSS.get_Keylog_Dump("CLIENT_TRAFFIC_SECRET_0", client_random, client_traffic_secret);
            send(message);
            var server_traffic_secret = NSS.get_Secret_As_HexString(ssl3.hs.serverTrafficSecret); //SERVER_TRAFFIC_SECRET_0
            devlog(NSS.get_Keylog_Dump("SERVER_TRAFFIC_SECRET_0", client_random, server_traffic_secret));
            message["keylog"] = NSS.get_Keylog_Dump("SERVER_TRAFFIC_SECRET_0", client_random, server_traffic_secret);
            send(message);
            var exporter_secret = NSS.get_Secret_As_HexString(ssl3.hs.exporterSecret); //EXPORTER_SECRET 
            devlog(NSS.get_Keylog_Dump("EXPORTER_SECRET", client_random, exporter_secret));
            message["keylog"] = NSS.get_Keylog_Dump("EXPORTER_SECRET", client_random, exporter_secret);
            send(message);
        }
        else {
            devlog("exporting TLS 1.2 keying material");
            var master_secret = NSS.getMasterSecret(ssl3);
            devlog(NSS.get_Keylog_Dump("CLIENT_RANDOM", client_random, master_secret));
            message["keylog"] = NSS.get_Keylog_Dump("CLIENT_RANDOM", client_random, master_secret);
            send(message);
        }
        NSS.doTLS13_RTT0 = -1;
        return;
    }
    static ssl_RecordKeyLog(sslSocketFD) {
        NSS.getTLS_Keys(sslSocketFD, 0);
    }
    /***** Installing the hooks *****/
    install_plaintext_read_hook() {
        var current_module_name = this.module_name;
        var lib_addesses = this.addresses;
        Interceptor.attach(this.addresses[this.moduleName]["PR_Read"], {
            onEnter: function (args) {
                // ab hier nicht mehr
                this.fd = ptr(args[0]);
                this.buf = ptr(args[1]);
            },
            onLeave: function (retval) {
                if (retval.toInt32() <= 0 || NSS.getDescType(this.fd) == PRDescType.PR_DESC_FILE) {
                    return;
                }
                //devlog("The results of NSS and its PR_Read is likely not the information transmitted over the wire. Better do a full capture and just log the TLS keys")
                var addr = Memory.alloc(8);
                var res = NSS.getpeername(this.fd, addr);
                // peername return -1 this is due to the fact that a PIPE descriptor is used to read from the SSL socket
                if (addr.readU16() == 2 || addr.readU16() == 10 || addr.readU16() == 100) {
                    var message = NSS.getPortsAndAddressesFromNSS(this.fd, true, lib_addesses[current_module_name], enable_default_fd);
                    //devlog("Session ID: " + NSS.getSslSessionIdFromFD(this.fd))
                    message["ssl_session_id"] = NSS.getSslSessionIdFromFD(this.fd);
                    message["function"] = "NSS_read";
                    this.message = message;
                    this.message["contentType"] = "datalog";
                    var data = this.buf.readByteArray((new Uint32Array([retval]))[0]);
                    send(message, data);
                }
                else {
                    /*
                    var message = NSS.getPortsAndAddressesFromNSS( this.fd as NativePointer, true, lib_addesses[current_module_name], enable_default_fd)
                    message["ssl_session_id"] = NSS.getSslSessionIdFromFD(this.fd)
                    message["function"] = "NSS_read"
                    this.message = message

                    this.message["contentType"] = "datalog"
                    var temp = this.buf.readByteArray((new Uint32Array([retval]))[0])
                    devlog(JSON.stringify(temp))
                    send(message, temp)*/
                }
            }
        });
    }
    install_plaintext_write_hook() {
        var current_module_name = this.module_name;
        var lib_addesses = this.addresses;
        Interceptor.attach(this.addresses[this.moduleName]["PR_Write"], {
            onEnter: function (args) {
                this.fd = ptr(args[0]);
                this.buf = args[1];
                this.len = args[2];
            },
            onLeave: function (retval) {
                if (retval.toInt32() <= 0) { //|| NSS.getDescType(this.fd) == PRDescType.PR_DESC_FILE) {
                    return;
                }
                var addr = Memory.alloc(8);
                NSS.getsockname(this.fd, addr);
                if (addr.readU16() == 2 || addr.readU16() == 10 || addr.readU16() == 100) {
                    var message = NSS.getPortsAndAddressesFromNSS(this.fd, false, lib_addesses[current_module_name], enable_default_fd);
                    message["ssl_session_id"] = NSS.getSslSessionIdFromFD(this.fd);
                    message["function"] = "NSS_write";
                    message["contentType"] = "datalog";
                    send(message, this.buf.readByteArray((parseInt(this.len))));
                }
                else {
                    /*
                    log("The results of NSS and its PR_Write is likely not the information transmitted over the wire. Better do a full capture and just log the TLS keys")
                    var message = NSS.getPortsAndAddressesFromNSS(this.fd as NativePointer, true, lib_addesses[current_module_name], enable_default_fd)
                    message["ssl_session_id"] = NSS.getSslSessionIdFromFD(this.fd)
                    message["function"] = "NSS_write"
                    this.message = message

                    this.message["contentType"] = "datalog"
                    var temp = this.buf.readByteArray((new Uint32Array([retval]))[0])
                    devlog(JSON.stringify(temp))
                    send(message, temp)*/
                }
            }
        });
    }
    /***** install callbacks for key logging ******/
    /**
 *
 * This callback gets only called in TLS 1.3 and newer versions
 *
 * @param {*} pRFileDesc
 * @param {*} secret_label
 * @param {*} secret
 * @returns
 *
function tls13_RecordKeyLog(pRFileDesc, secret_label, secret){

    var sslSocketFD = get_SSL_FD(pRFileDesc);
    if(sslSocketFD == -1){
        return;
    }

    var sslSocketStr = parse_struct_sslSocketStr(sslSocketFD);

    var ssl3_struct = sslSocketStr.ssl3;
    var ssl3 = parse_struct_ssl3Str(ssl3_struct);
    

    var secret_as_hexString = get_Secret_As_HexString(secret);
    

    log(get_Keylog_Dump(secret_label,getClientRandom(ssl3),secret_as_hexString));


    return 0;
}

// our old way to get the diffrent secrets from TLS 1.3 and above
*/
    static parse_epoch_value_from_SSL_SetSecretCallback(sslSocketFD, epoch) {
        if (epoch == 1) { // client_early_traffic_secret
            NSS.getTLS_Keys(sslSocketFD, 2);
        }
        else if (epoch == 2) { // client|server}_handshake_traffic_secret
            NSS.getTLS_Keys(sslSocketFD, 1);
            /* our old way to get the diffrent secrets from TLS 1.3 and above
    
            per default we assume we are intercepting a TLS client therefore
            dir == 1 --> SERVER_HANDSHAKE_TRAFFIC_SECRET
            dir == 2 --> CLIENT_HANDSHAKE_TRAFFIC_SECRET
            typedef enum {
                ssl_secret_read = 1,
                ssl_secret_write = 2,
            } SSLSecretDirection;
            
            if(dir == 1){
                tls13_RecordKeyLog(sslSocketFD,"SERVER_HANDSHAKE_TRAFFIC_SECRET",secret);
            }else{
                tls13_RecordKeyLog(sslSocketFD,"CLIENT_HANDSHAKE_TRAFFIC_SECRET",secret);
            }*/
        }
        else if (epoch >= 3) { // {client|server}_application_traffic_secret_{N}
            return;
            // we intercept this through the handshake_callback
        }
        else {
            devlog("[-] secret_callback invocation: UNKNOWN");
        }
    }
    static insert_hook_into_secretCallback(addr_of_installed_secretCallback) {
        Interceptor.attach(addr_of_installed_secretCallback, {
            onEnter(args) {
                this.sslSocketFD = args[0];
                this.epoch = args[1];
                NSS.parse_epoch_value_from_SSL_SetSecretCallback(this.sslSocketFD, this.epoch);
            },
            onLeave(retval) {
            }
        });
    }
    /**
         * Registers a secret_callback through inserting the address to our TLS 1.3 callback function at the apprioate offset of the  SSL Socket struct
         * This is neccassy because the computed handshake secrets are already freed after the handshake is completed.
         *
         *
         * @param {*} pRFileDesc a file descriptor (NSS PRFileDesc) to a SSL socket
         * @returns
         */
    static register_secret_callback(pRFileDesc) {
        var sslSocketFD = NSS.get_SSL_FD(pRFileDesc);
        if (sslSocketFD.isNull()) {
            devlog("[-] error while installing secret callback: unable get SSL socket descriptor");
            return;
        }
        var sslSocketStr = NSS.parse_struct_sslSocketStr(sslSocketFD);
        if (NSS.is_ptr_at_mem_location(sslSocketStr.secretCallback.readPointer()) == 1) {
            NSS.insert_hook_into_secretCallback(sslSocketStr.secretCallback.readPointer());
        }
        else {
            sslSocketStr.secretCallback.writePointer(NSS.secret_callback);
        }
        devlog("secret callback (" + NSS.secret_callback + ") installed to address: " + sslSocketStr.secretCallback);
    }
    install_tls_keys_callback_hook() {
    }
}
// global definitions
NSS.doTLS13_RTT0 = -1;
NSS.SSL3_RANDOM_LENGTH = 32;
/********* NSS Callbacks ************/
/*
This callback gets called whenever a SSL Handshake completed

typedef void (*SSLHandshakeCallback)(
        PRFileDesc *fd,
        void *client_data);
*/
NSS.keylog_callback = new NativeCallback(function (sslSocketFD, client_data) {
    if (typeof this !== "undefined") {
        NSS.ssl_RecordKeyLog(sslSocketFD);
    }
    else {
        console.log("[-] Error while installing ssl_RecordKeyLog() callback");
    }
    return 0;
}, "void", ["pointer", "pointer"]);
/**
 * SSL_SetSecretCallback installs a callback that TLS calls when it installs new
 * traffic secrets.
 *
 *
 *
 * SSLSecretCallback is called with the current epoch and the corresponding
 * secret; this matches the epoch used in DTLS 1.3, even if the socket is
 * operating in stream mode:
 *
 * - client_early_traffic_secret corresponds to epoch 1
 * - {client|server}_handshake_traffic_secret is epoch 2
 * - {client|server}_application_traffic_secret_{N} is epoch 3+N
 *
 * The callback is invoked separately for read secrets (client secrets on the
 * server; server secrets on the client), and write secrets.
 *
 * This callback is only called if (D)TLS 1.3 is negotiated.
 *
 * typedef void(PR_CALLBACK *SSLSecretCallback)(
 *   PRFileDesc *fd, PRUint16 epoch, SSLSecretDirection dir, PK11SymKey *secret,
 *   void *arg);
 *
 *  More: https://github.com/nss-dev/nss/blob/master/lib/ssl/sslexp.h#L614
 *
 */
NSS.secret_callback = new NativeCallback(function (sslSocketFD, epoch, dir, secret, arg_ptr) {
    if (typeof this !== "undefined") {
        NSS.parse_epoch_value_from_SSL_SetSecretCallback(sslSocketFD, epoch);
    }
    else {
        console.log("[-] Error while installing parse_epoch_value_from_SSL_SetSecretCallback()");
    }
    return;
}, "void", ["pointer", "uint16", "uint16", "pointer", "pointer"]);
✄
{"version":3,"file":"openssl_boringssl.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ssl_lib/openssl_boringssl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAE,cAAc,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAC7I,OAAO,EAAc,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AAG7C,MAAM,cAAc;IAGhB;QAFO,qBAAgB,GAAuB,IAAI,CAAC;QAC5C,sBAAiB,GAAuB,IAAI,CAAC;QAEhD,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACxB,IAAI,CAAC,iBAAiB,EAAE,CAAC;IAC7B,CAAC;IAEO,gBAAgB;QACpB,IAAI,CAAC,SAAS,EAAE,CAAC,MAAM,EAAC,EAAE;YACtB,YA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GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;SACtE;QACD,OAAO,UAAU,CAAA;IACrB,CAAC;;AAhWM,iCAAe,GAAG,IAAI,cAAc,CAAC,UAAU,MAAqB,EAAE,OAAsB;IAC/F,MAAM,CAAC,iDAAiD,CAAC,CAAC;IAC1D,IAAI,OAAO,GAA8C,EAAE,CAAA;IAC3D,OAAO,CAAC,aAAa,CAAC,GAAG,QAAQ,CAAA;IACjC,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,WAAW,EAAE,CAAA;IACzC,IAAI,CAAC,OAAO,CAAC,CAAA;AACjB,CAAC,EAAE,MAAM,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC,AANZ,CAMY"}
✄
import { readAddresses, getPortsAndAddresses, getBaseAddress, isSymbolAvailable, checkNumberOfExports } from "../shared/shared_functions.js";
import { offsets, enable_default_fd } from "../ssl_log.js";
import { devlog, log } from "../util/log.js";
class ModifyReceiver {
    constructor() {
        this.readModification = null;
        this.writeModification = null;
        this.listenForReadMod();
        this.listenForWriteMod();
    }
    listenForReadMod() {
        recv("readmod", (newBuf) => {
            //@ts-ignore
            this.readModification = newBuf.payload != null ? new Uint8Array(newBuf.payload.match(/[\da-f]{2}/gi).map(function (h) {
                return parseInt(h, 16);
            })).buffer : null;
            this.listenForReadMod();
        });
    }
    listenForWriteMod() {
        recv("writemod", (newBuf) => {
            //@ts-ignore
            this.writeModification = newBuf.payload != null ? new Uint8Array(newBuf.payload.match(/[\da-f]{2}/gi).map(function (h) {
                return parseInt(h, 16);
            })).buffer : null;
            this.listenForWriteMod();
        });
    }
    get readmod() {
        return this.readModification;
    }
    get writemod() {
        return this.writeModification;
    }
    set readmod(val) {
        this.readModification = val;
    }
    set writemod(val) {
        this.writeModification = val;
    }
}
/**
 *
 * ToDO
 *  We need to find a way to calculate the offsets in a automated manner.
 *  Darwin: SSL_read/write need improvments
 *  Windows: how to extract the key material?
 *  Android: We need to find a way, when on some Android Apps the fd is below 0
 */
export class OpenSSL_BoringSSL {
    constructor(moduleName, socket_library, is_base_hook, passed_library_method_mapping) {
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.passed_library_method_mapping = passed_library_method_mapping;
        // global variables
        this.library_method_mapping = {};
        OpenSSL_BoringSSL.modReceiver = new ModifyReceiver();
        if (typeof passed_library_method_mapping !== 'undefined') {
            this.library_method_mapping = passed_library_method_mapping;
        }
        else {
            if (checkNumberOfExports(moduleName) > 2) {
                this.library_method_mapping[`*${moduleName}*`] = ["SSL_read", "SSL_write", "SSL_get_fd", "SSL_get_session", "SSL_SESSION_get_id", "SSL_new", "SSL_CTX_set_keylog_callback"];
            }
            this.library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        }
        if (isSymbolAvailable(moduleName, "SSL_CTX_new")) {
            this.library_method_mapping[`*${moduleName}*`].push("SSL_CTX_new");
        }
        // Check and add SSL_read_ex if available
        if (isSymbolAvailable(moduleName, "SSL_read_ex")) {
            this.library_method_mapping[`*${moduleName}*`].push("SSL_read_ex");
            this.is_openssl = true;
        }
        else {
            this.is_openssl = false;
        }
        // Check and add SSL_write_ex if available
        if (isSymbolAvailable(moduleName, "SSL_write_ex")) {
            this.library_method_mapping[`*${moduleName}*`].push("SSL_write_ex");
        }
        this.is_base_hook = is_base_hook;
        this.addresses = readAddresses(moduleName, this.library_method_mapping);
        this.module_name = moduleName;
        // @ts-ignore
        if (offsets != "{OFFSETS}" && offsets.openssl != null) {
            if (offsets.sockets != null) {
                const socketBaseAddress = getBaseAddress(socket_library);
                for (const method of Object.keys(offsets.sockets)) {
                    //@ts-ignore
                    this.addresses[this.moduleName][`${method}`] = offsets.sockets[`${method}`].absolute || socketBaseAddress == null ? ptr(offsets.sockets[`${method}`].address) : socketBaseAddress.add(ptr(offsets.sockets[`${method}`].address));
                }
            }
            const libraryBaseAddress = getBaseAddress(moduleName);
            if (libraryBaseAddress == null)
                log("Unable to find library base address! Given address values will be interpreted as absolute ones!");
            for (const method of Object.keys(offsets.openssl)) {
                //@ts-ignore
                this.addresses[this.moduleName][`${method}`] = offsets.openssl[`${method}`].absolute || libraryBaseAddress == null ? ptr(offsets.openssl[`${method}`].address) : libraryBaseAddress.add(ptr(offsets.openssl[`${method}`].address));
            }
        }
        if (!ObjC.available && checkNumberOfExports(moduleName) > 2) {
            this.SSL_SESSION_get_id = new NativeFunction(this.addresses[this.moduleName]["SSL_SESSION_get_id"], "pointer", ["pointer", "pointer"]);
            this.SSL_get_fd = ObjC.available ? new NativeFunction(this.addresses[this.moduleName]["BIO_get_fd"], "int", ["pointer"]) : new NativeFunction(this.addresses[this.moduleName]["SSL_get_fd"], "int", ["pointer"]);
            this.SSL_get_session = new NativeFunction(this.addresses[this.moduleName]["SSL_get_session"], "pointer", ["pointer"]);
        }
    }
    install_plaintext_read_hook() {
        if (!ObjC.available) {
            function ab2str(buf) {
                //@ts-ignore
                return String.fromCharCode.apply(null, new Uint16Array(buf));
            }
            function str2ab(str) {
                var buf = new ArrayBuffer(str.length + 1); // 2 bytes for each char
                var bufView = new Uint8Array(buf);
                for (var i = 0, strLen = str.length; i < strLen; i++) {
                    bufView[i] = str.charCodeAt(i);
                }
                bufView[str.length] = 0;
                return buf;
            }
            var lib_addesses = this.addresses;
            var instance = this;
            var current_module_name = this.module_name;
            Interceptor.attach(this.addresses[this.moduleName]["SSL_read"], {
                onEnter: function (args) {
                    this.bufLen = args[2].toInt32();
                    this.fd = instance.SSL_get_fd(args[0]);
                    if (this.fd < 0 && enable_default_fd == false) {
                        return;
                    }
                    var message = getPortsAndAddresses(this.fd, true, lib_addesses[current_module_name], enable_default_fd);
                    message["ssl_session_id"] = instance.getSslSessionId(args[0]);
                    message["function"] = "SSL_read";
                    this.message = message;
                    this.buf = args[1];
                },
                onLeave: function (retval) {
                    retval |= 0; // Cast retval to 32-bit integer.
                    if (retval <= 0 || this.fd < 0) {
                        return;
                    }
                    if (OpenSSL_BoringSSL.modReceiver.readmod !== null) {
                        //NULL out buffer
                        //@ts-ignore
                        Memory.writeByteArray(this.buf, new Uint8Array(this.bufLen));
                        //@ts-ignore
                        Memory.writeByteArray(this.buf, OpenSSL_BoringSSL.modReceiver.readmod);
                        retval = OpenSSL_BoringSSL.modReceiver.readmod.byteLength;
                    }
                    this.message["contentType"] = "datalog";
                    send(this.message, this.buf.readByteArray(retval));
                }
            });
        }
    }
    install_plaintext_write_hook() {
        if (!ObjC.available) {
            function str2ab(str) {
                var buf = new ArrayBuffer(str.length + 1); // 2 bytes for each char
                var bufView = new Uint8Array(buf);
                for (var i = 0, strLen = str.length; i < strLen; i++) {
                    bufView[i] = str.charCodeAt(i);
                }
                bufView[str.length] = 0;
                return buf;
            }
            var current_module_name = this.module_name;
            var lib_addesses = this.addresses;
            var instance = this;
            Interceptor.attach(this.addresses[this.moduleName]["SSL_write"], {
                onEnter: function (args) {
                    if (!ObjC.available) {
                        try {
                            this.fd = instance.SSL_get_fd(args[0]);
                        }
                        catch (error) {
                            if (!this.is_base_hook) {
                                const fallback_addresses = global.init_addresses;
                                //console.log("Current ModuleName: "+current_module_name);
                                let keys = Object.keys(fallback_addresses);
                                let firstKey = keys[0];
                                instance.SSL_SESSION_get_id = new NativeFunction(fallback_addresses[firstKey]["SSL_SESSION_get_id"], "pointer", ["pointer", "pointer"]);
                                instance.SSL_get_fd = ObjC.available ? new NativeFunction(fallback_addresses[firstKey]["BIO_get_fd"], "int", ["pointer"]) : new NativeFunction(fallback_addresses["SSL_get_fd"], "int", ["pointer"]);
                                instance.SSL_get_session = new NativeFunction(fallback_addresses[firstKey]["SSL_get_session"], "pointer", ["pointer"]);
                            }
                            else {
                                if (error instanceof Error) {
                                    console.log("Error: " + error.message);
                                    console.log("Stack: " + error.stack);
                                }
                                else {
                                    console.log("Unexpected error:", error);
                                }
                            }
                        }
                        if (this.fd < 0 && enable_default_fd == false) {
                            return;
                        }
                        var message = getPortsAndAddresses(this.fd, false, lib_addesses[current_module_name], enable_default_fd);
                        message["ssl_session_id"] = instance.getSslSessionId(args[0]);
                        message["function"] = "SSL_write";
                        message["contentType"] = "datalog";
                        if (OpenSSL_BoringSSL.modReceiver.writemod !== null) {
                            const newPointer = Memory.alloc(OpenSSL_BoringSSL.modReceiver.writemod.byteLength);
                            //@ts-ignore
                            Memory.writeByteArray(newPointer, OpenSSL_BoringSSL.modReceiver.writemod);
                            args[1] = newPointer;
                            args[2] = new NativePointer(OpenSSL_BoringSSL.modReceiver.writemod.byteLength);
                        }
                        send(message, args[1].readByteArray(args[2].toInt32()));
                    } // this is a temporary workaround for the fd problem on iOS
                },
                onLeave: function (retval) {
                }
            });
        }
    }
    install_tls_keys_callback_hook() {
        log("Error: TLS key extraction not implemented yet.");
    }
    install_extended_hooks() {
        // these functions (and its symbols) only available on OpenSSL
        if (this.is_openssl) {
            var current_module_name = this.module_name;
            var lib_addesses = this.addresses;
            var instance = this;
            Interceptor.attach(this.addresses[this.moduleName]["SSL_read_ex"], {
                onEnter: function (args) {
                    this.bufLen = args[2].toInt32();
                    this.fd = instance.SSL_get_fd(args[0]);
                    if (this.fd < 0 && enable_default_fd == false) {
                        return;
                    }
                    var message = getPortsAndAddresses(this.fd, true, lib_addesses[current_module_name], enable_default_fd);
                    message["ssl_session_id"] = instance.getSslSessionId(args[0]);
                    message["function"] = "SSL_read_ex";
                    this.message = message;
                    this.buf = args[1];
                },
                onLeave: function (retval) {
                    retval |= 0; // Cast retval to 32-bit integer.
                    if (retval <= 0 || this.fd < 0) {
                        return;
                    }
                    this.message["contentType"] = "datalog";
                    send(this.message, this.buf.readByteArray(retval));
                }
            });
            Interceptor.attach(this.addresses[this.moduleName]["SSL_write_ex"], {
                onEnter: function (args) {
                    if (!ObjC.available) {
                        try {
                            this.fd = instance.SSL_get_fd(args[0]);
                        }
                        catch (error) {
                            if (!this.is_base_hook) {
                                const fallback_addresses = global.init_addresses;
                                let keys = Object.keys(fallback_addresses);
                                let firstKey = keys[0];
                                instance.SSL_SESSION_get_id = new NativeFunction(fallback_addresses[firstKey]["SSL_SESSION_get_id"], "pointer", ["pointer", "pointer"]);
                                instance.SSL_get_fd = ObjC.available ? new NativeFunction(fallback_addresses[firstKey]["BIO_get_fd"], "int", ["pointer"]) : new NativeFunction(fallback_addresses["SSL_get_fd"], "int", ["pointer"]);
                                instance.SSL_get_session = new NativeFunction(fallback_addresses[firstKey]["SSL_get_session"], "pointer", ["pointer"]);
                            }
                            else {
                                if (error instanceof Error) {
                                    console.log("Error: " + error.message);
                                    console.log("Stack: " + error.stack);
                                }
                                else {
                                    console.log("Unexpected error:", error);
                                }
                            }
                        }
                        if (this.fd < 0 && enable_default_fd == false) {
                            return;
                        }
                        var message = getPortsAndAddresses(this.fd, false, lib_addesses[current_module_name], enable_default_fd);
                        message["ssl_session_id"] = instance.getSslSessionId(args[0]);
                        message["function"] = "SSL_write_ex";
                        message["contentType"] = "datalog";
                        send(message, args[1].readByteArray(args[2].toInt32()));
                    } // this is a temporary workaround for the fd problem on iOS
                },
                onLeave: function (retval) {
                }
            });
        }
    }
    /**
      * Get the session_id of SSL object and return it as a hex string.
      * @param {!NativePointer} ssl A pointer to an SSL object.
      * @return {dict} A string representing the session_id of the SSL object's
      *     SSL_SESSION. For example,
      *     "59FD71B7B90202F359D89E66AE4E61247954E28431F6C6AC46625D472FF76336".
      */
    getSslSessionId(ssl) {
        var session = this.SSL_get_session(ssl);
        if (session.isNull()) {
            if (enable_default_fd) {
                log("using dummy SessionID: 59FD71B7B90202F359D89E66AE4E61247954E28431F6C6AC46625D472FF76336");
                return "59FD71B7B90202F359D89E66AE4E61247954E28431F6C6AC46625D472FF76336";
            }
            log("Session is null");
            return 0;
        }
        var len_pointer = Memory.alloc(4);
        var p = this.SSL_SESSION_get_id(session, len_pointer);
        var len = len_pointer.readU32();
        var session_id = "";
        for (var i = 0; i < len; i++) {
            // Read a byte, convert it to a hex string (0xAB ==> "AB"), and append
            // it to session_id.
            session_id +=
                ("0" + p.add(i).readU8().toString(16).toUpperCase()).substr(-2);
        }
        return session_id;
    }
}
OpenSSL_BoringSSL.keylog_callback = new NativeCallback(function (ctxPtr, linePtr) {
    devlog("invoking keylog_callback from OpenSSL_BoringSSL");
    var message = {};
    message["contentType"] = "keylog";
    message["keylog"] = linePtr.readCString();
    send(message);
}, "void", ["pointer", "pointer"]);
✄
{"version":3,"file":"rustls.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ssl_lib/rustls.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkC,aAAa,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACpI,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAc,OAAO,EAAqB,MAAM,eAAe,CAAC;AAIvE,MAAM,OAAO,MAAM;IA4Cf,YAAmB,UAAiB,EAAS,cAAqB,EAAC,YAAqB,EAAS,6BAAgE;QAA9I,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;QAA+B,kCAA6B,GAA7B,6BAA6B,CAAmC;QAzCjK,mBAAmB;QACnB,2BAAsB,GAAqC,EAAE,CAAC;QA8G9D;;;UAGE;QACM,gBAAW,GAA8B;YAC7C,CAAC,EAAE,2BAA2B;YAC9B,CAAC,EAAE,6BAA6B;YAChC,CAAC,EAAE,iCAAiC;YACpC,CAAC,EAAE,iCAAiC;YACpC,CAAC,EAAE,yBAAyB;YAC5B,CAAC,EAAE,yBAAyB;YAC5B,CAAC,EAAE,iBAAiB;YACpB,CAAC,EAAE,0BAA0B;YAC7B,CAAC,EAAE,SAAS,CAA2B,UAAU;SACpD,CAAC;QAnFE,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;QAC9B,IAAI,CAAC,YAAY,GAAG,YAAY,CA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AC,aAAa,CAAC,iBAAiB,CAAC,QAAQ,EAAE,CAAC,CAAC;IAChF,IAAI,SAAS,GAAG,MAAM,CAAC,aAAa,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC;IAG7D,wDAAwD;IACxD,IAAI,eAAe,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,eAAe,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACrH,IAAI,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAEzG,+BAA+B;IAC/B,OAAO,CAAC,QAAQ,CAAC,GAAG,GAAG,QAAQ,IAAI,eAAe,IAAI,SAAS,EAAE,CAAC;IAClE,IAAI,CAAC,OAAO,CAAC,CAAC;IAEd,OAAO,CAAC,CAAC;AACb,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,SAAS,EAAE,QAAQ,CAAC,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC,AA3B9D,CA2B+D"}
✄
import { readAddresses, checkNumberOfExports, getBaseAddress } from "../shared/shared_functions.js";
import { devlog, log } from "../util/log.js";
import { offsets } from "../ssl_log.js";
export class RusTLS {
    constructor(moduleName, socket_library, is_base_hook, passed_library_method_mapping) {
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.passed_library_method_mapping = passed_library_method_mapping;
        // global variables
        this.library_method_mapping = {};
        /*
        In Rustls the labels are mapped as enums
        cf. https://github.com/rustls/rustls/blob/5860d10317528e4f162db6e26c74f81575c51403/rustls/src/tls13/key_schedule.rs#L31
        */
        this.enumMapping = {
            0: "RESUMPTION_PSK_BINDER_KEY",
            1: "CLIENT_EARLY_TRAFFIC_SECRET",
            2: "CLIENT_HANDSHAKE_TRAFFIC_SECRET",
            3: "SERVER_HANDSHAKE_TRAFFIC_SECRET",
            4: "CLIENT_TRAFFIC_SECRET_0",
            5: "SERVER_TRAFFIC_SECRET_0",
            6: "EXPORTER_SECRET",
            7: "RESUMPTION_MASTER_SECRET",
            8: "DERIVED" // Derived
        };
        this.module_name = moduleName;
        this.is_base_hook = is_base_hook;
        if (typeof passed_library_method_mapping !== 'undefined') {
            this.library_method_mapping = passed_library_method_mapping;
        }
        else {
            if (checkNumberOfExports(moduleName) > 2) {
                try {
                    this.library_method_mapping[`*${moduleName}*`] = ["*derive_logged_secret*", "*for_secret*"];
                }
                catch (e) {
                    // right now do nothing
                }
                try {
                    this.library_method_mapping[`*${moduleName}*`] = ["*rustls_connection_write_tls*", "*rustls_connection_read_tls*", "*rustls_client_config_builder_new*",
                        "*rustls_client_config_builder_new_custom*", "*rustls_client_config_builder_set_key_log*"];
                }
                catch (e) {
                    // right now do nothing
                }
            }
            this.library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        }
        this.addresses = readAddresses(moduleName, this.library_method_mapping);
        this.module_name = moduleName;
        //@ts-ignore
        if (offsets != "{OFFSETS}" && offsets.rustls != null) {
            if (offsets.sockets != null) {
                const socketBaseAddress = getBaseAddress(socket_library);
                for (const method of Object.keys(offsets.sockets)) {
                    const methodOffset = offsets.sockets[`${method}`];
                    const isAbsolute = methodOffset.absolute;
                    //@ts-ignore
                    const methodAddress = ptr(methodOffset.address);
                    if (isAbsolute || socketBaseAddress == null) {
                        this.addresses[this.moduleName][`${method}`] = methodAddress;
                    }
                    else {
                        this.addresses[this.moduleName][`${method}`] = socketBaseAddress.add(methodAddress);
                    }
                }
            }
            const libraryBaseAddress = getBaseAddress(moduleName);
            if (libraryBaseAddress == null) {
                log("Unable to find library base addresss! Given address values will be interpreted as absolute ones!");
            }
            for (const method of Object.keys(offsets.rustls)) {
                const methodOffset = offsets.rustls[`${method}`];
                const isAbsolute = methodOffset.absolute;
                //@ts-ignore
                const methodAddress = ptr(methodOffset.address);
                if (isAbsolute || libraryBaseAddress == null) {
                    this.addresses[this.moduleName][`${method}`] = methodAddress;
                }
                else {
                    this.addresses[this.moduleName][`${method}`] = libraryBaseAddress.add(methodAddress);
                }
            }
        }
    }
    getEnumString(enumValue) {
        return this.enumMapping[enumValue] || null;
    }
    // Checks if the pointer's C-string starts with "key expansion" - only used for TLS 1.2 traffic
    isArgKeyExp(ptr) {
        let labelStr = "";
        try {
            if (!ptr.isNull()) {
                const label = ptr.readCString();
                labelStr = label;
                if (labelStr === null) {
                    return false;
                }
                else {
                    return labelStr.startsWith("key expansion");
                }
            }
        }
        catch (error) {
            devlog("[!] Error reading pointer in isArgKeyExp (RusTLS):" + error.message);
            return false;
        }
        return false;
    }
    /**
     * Hooking hkdf_expand_label() to get secrets from TLS 1.3 traffic.
     * This is used for the Android Hooks only
     */
    /*
     Hooking hkdf_expand_label to get secrets from TLS 1.3 traffic.
     This is used for the Android Hooks.
    */
    dumpKeysFromDeriveSecrets(client_random_ptr, key, key_len, label_enum) {
        let KEY_LENGTH = 32; // Default to 32 bytes.
        if (key_len > 16) {
            KEY_LENGTH = key_len;
        }
        let labelStr = "";
        let client_random = "";
        let secret_key = "";
        const RANDOM_KEY_LENGTH = 32;
        // Retrieve the descriptive label from the enum mapping.
        labelStr = this.getEnumString(label_enum) || "";
        if (client_random_ptr != null) {
            //@ts-ignore
            const randomData = Memory.readByteArray(client_random_ptr, RANDOM_KEY_LENGTH);
            if (randomData) {
                client_random = Array
                    .from(new Uint8Array(randomData))
                    .map(byte => byte.toString(16).padStart(2, '0').toUpperCase())
                    .join('');
            }
        }
        else {
            //devlog("[Error] Argument 'client_random_ptr' is NULL");
            client_random = "<identify using PCAP> ";
        }
        if (!key.isNull()) {
            //@ts-ignore
            const keyData = Memory.readByteArray(key, KEY_LENGTH);
            if (keyData) {
                secret_key = Array
                    .from(new Uint8Array(keyData))
                    .map(byte => byte.toString(16).padStart(2, '0').toUpperCase())
                    .join('');
            }
        }
        else {
            devlog("[Error] Argument 'key' is NULL");
        }
        var message = {};
        message["contentType"] = "keylog";
        message["keylog"] = labelStr + " " + client_random + " " + secret_key;
        send(message);
        return true;
    }
    /**
     *  Hooking from_key_exchange() to get secrets from TLS 1.2 traffic
     *  https://github.com/rustls/rustls/blob/293f05e9d1011132a749b8b6e0435f701421fd01/rustls/src/tls12/mod.rs#L102
     *  This hook is used for both, Linux and Android.
     */
    dumpKeysFromPRF(client_random_ptr, key) {
        const KEY_LENGTH = 32;
        const MASTER_SECRET_LEN = 48;
        const labelStr = "CLIENT_RANDOM";
        let client_random = "";
        let secret_key = "";
        if (!key.isNull()) {
            //@ts-ignore
            const keyData = Memory.readByteArray(key, MASTER_SECRET_LEN);
            if (keyData) {
                secret_key = Array
                    .from(new Uint8Array(keyData))
                    .map(byte => byte.toString(16).padStart(2, '0').toUpperCase())
                    .join('');
            }
        }
        else {
            devlog("[!] Argument 'key' is NULL");
        }
        if (!client_random_ptr.isNull()) {
            //@ts-ignore
            const keyData = Memory.readByteArray(client_random_ptr, KEY_LENGTH);
            if (keyData) {
                client_random = Array
                    .from(new Uint8Array(keyData))
                    .map(byte => byte.toString(16).padStart(2, '0').toUpperCase())
                    .join('');
            }
        }
        else {
            devlog("[!] Argument 'client_random_ptr' is NULL");
        }
        var message = {};
        message["contentType"] = "keylog";
        message["keylog"] = labelStr + " " + client_random + " " + secret_key;
        send(message);
        return true;
    }
    /**
     * On Linux the BoringSecretHunter Identifies a different function (derive_logged_secrets()).
     * https://github.com/rustls/rustls/blob/bdb303696dea02ecc6b5de3907880e181899d717/rustls/src/tls13/key_schedule.rs#L676
     * The following extracts the secrets for TLS 1.3.
     */
    dumpKeysFromDeriveLogged(client_random_ptr, key, label_enum) {
        /*
        key_len needs to be parsed from key
        key has the following structure: | key (length: key_size) | padding (length: 64 bytes - key_size) | key_size
        */
        let KEY_LENGTH = (key.add(64)).readU32();
        let labelStr = "";
        let client_random = "";
        let secret_key = "";
        const RANDOM_KEY_LENGTH = 32;
        devlog("Called dumpKeysFromDeriveLogged()");
        // Retrieve the descriptive label from the enum mapping.
        labelStr = this.getEnumString(label_enum) || "";
        if (client_random_ptr != null) {
            //@ts-ignore
            const randomData = Memory.readByteArray(client_random_ptr, RANDOM_KEY_LENGTH);
            if (randomData) {
                client_random = Array
                    .from(new Uint8Array(randomData))
                    .map(byte => byte.toString(16).padStart(2, '0').toUpperCase())
                    .join('');
            }
        }
        else {
            client_random = "<identify using PCAP> ";
        }
        if (!key.isNull()) {
            //@ts-ignore
            const keyData = Memory.readByteArray(key, KEY_LENGTH);
            if (keyData) {
                secret_key = Array
                    .from(new Uint8Array(keyData))
                    .map(byte => byte.toString(16).padStart(2, '0').toUpperCase())
                    .join('');
            }
        }
        else {
            devlog("[Error] Argument 'key' is NULL");
        }
        var message = {};
        message["contentType"] = "keylog";
        message["keylog"] = labelStr + " " + client_random + " " + secret_key;
        send(message);
        return true;
    }
    hook_tls_12_key_generation_function() {
    }
    install_plaintext_read_hook() {
        // TBD
    }
    install_plaintext_write_hook() {
        // TBD
    }
    install_key_extraction_hook() {
        // needs to be setup for the specific plattform
    }
}
// Callbackfuntion for logging keying material
RusTLS.keyLogCB = new NativeCallback(function (label, client_random, client_random_len, secret, secret_size) {
    devlog("invoking keyLogCB from rustls");
    var message = {};
    message["contentType"] = "keylog";
    var labelStr;
    // If no label is provided the keyLog should begin with "CLIENT_RANDOM "
    if (label[1].toNumber() == 0) {
        labelStr = "CLIENT_RANDOM ";
    }
    else {
        labelStr = label[0].readUtf8String(label[1].toNumber());
    }
    // Read the client random and secrets as strings
    var clientRandomStr = client_random.readByteArray(client_random_len.toNumber());
    var secretStr = secret.readByteArray(secret_size.toNumber());
    // Convert byte arrays to hex strings for better logging
    var clientRandomHex = Array.from(new Uint8Array(clientRandomStr)).map(b => b.toString(16).padStart(2, '0')).join('');
    var secretHex = Array.from(new Uint8Array(secretStr)).map(b => b.toString(16).padStart(2, '0')).join('');
    // Construct the keylog message
    message["keylog"] = `${labelStr} ${clientRandomHex} ${secretHex}`;
    send(message);
    return 1;
}, 'void', [['pointer', 'size_t'], 'pointer', 'size_t', 'pointer', 'size_t']);
✄
{"version":3,"file":"s2ntls.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ssl_lib/s2ntls.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,oBAAoB,EAAC,MAAM,+BAA+B,CAAA;AAClG,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AAC1D,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAG5C,MAAM,OAAO,MAAM;IAoBf,YAAmB,UAAkB,EAAS,cAAsB,EAAS,6BAA+D;QAAzH,eAAU,GAAV,UAAU,CAAQ;QAAS,mBAAc,GAAd,cAAc,CAAQ;QAAS,kCAA6B,GAA7B,6BAA6B,CAAkC;QAlB5I,2BAAsB,GAAqC,EAAE,CAAC;QAoB1D,IAAG,OAAO,6BAA6B,KAAK,WAAW,EAAC;YACpD,IAAI,CAAC,sBAAsB,GAAG,6BAA6B,CAAC;SAC/D;aAAI;YACD,IAAI,CAAC,sBAAsB,CAAC,IAAI,UAAU,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,UAAU,EAAE,4BAA4B,EAAE,6BAA6B,EAAE,oBAAoB,EAAE,2BAA2B,EAAE,2BAA2B,EAAE,gBAAgB,CAAC,CAAC;YACzO,IAAI,CAAC,sBAAsB,CAAC,IAAI,cAAc,GAAG,CAAC,GAAG,CAAC,aAAa,EAAE,aAAa,EAAE,OAAO,EAAE,O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C,CAAC,CAAC;IAC/C,IAAI,OAAO,GAA8C,EAAE,CAAC;IAC5D,OAAO,CAAC,aAAa,CAAC,GAAG,QAAQ,CAAC;IAClC,OAAO,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC;IACvD,IAAI,CAAC,OAAO,CAAC,CAAC;IACd,OAAO,CAAC,CAAC;AACb,CAAC,EAAE,KAAK,EAAE,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC,AAPjC,CAOkC"}
✄
import { readAddresses, getBaseAddress, getPortsAndAddresses } from "../shared/shared_functions.js";
import { offsets, enable_default_fd } from "../ssl_log.js";
import { log, devlog } from "../util/log.js";
export class S2nTLS {
    constructor(moduleName, socket_library, passed_library_method_mapping) {
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.passed_library_method_mapping = passed_library_method_mapping;
        this.library_method_mapping = {};
        if (typeof passed_library_method_mapping !== 'undefined') {
            this.library_method_mapping = passed_library_method_mapping;
        }
        else {
            this.library_method_mapping[`*${moduleName}*`] = ["s2n_send", "s2n_recv", "s2n_connection_get_read_fd", "s2n_connection_get_write_fd", "s2n_connection_new", "s2n_config_set_key_log_cb", "s2n_connection_set_config", "s2n_config_new"];
            this.library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        }
        this.addresses = readAddresses(moduleName, this.library_method_mapping);
        this.module_name = moduleName;
        //@ts-ignore
        if (offsets != "{OFFSETS}" && offsets.s2n != null) {
            if (offsets.sockets != null) {
                const socketBaseAddress = getBaseAddress(socket_library);
                for (const method of Object.keys(offsets.sockets)) {
                    const methodOffset = offsets.sockets[`${method}`];
                    const isAbsolute = methodOffset.absolute;
                    //@ts-ignore
                    const methodAddress = ptr(methodOffset.address);
                    if (isAbsolute || socketBaseAddress == null) {
                        this.addresses[this.moduleName][`${method}`] = methodAddress;
                    }
                    else {
                        this.addresses[this.moduleName][`${method}`] = socketBaseAddress.add(methodAddress);
                    }
                }
            }
            const libraryBaseAddress = getBaseAddress(moduleName);
            if (libraryBaseAddress == null) {
                log("Unable to find library base address! Given address values will be interpreted as absolute ones!");
            }
            for (const method of Object.keys(offsets.s2n)) {
                const methodOffset = offsets.s2n[`${method}`];
                const isAbsolute = methodOffset.absolute;
                //@ts-ignore
                const methodAddress = ptr(methodOffset.address);
                if (isAbsolute || libraryBaseAddress == null) {
                    this.addresses[this.moduleName][`${method}`] = methodAddress;
                }
                else {
                    this.addresses[this.moduleName][`${method}`] = libraryBaseAddress.add(methodAddress);
                }
            }
        }
        //s2n_connection-get_read_fd and s2n_connection_get_write_fd return the corresponding file descriptors
        S2nTLS.s2n_get_read_fd = new NativeFunction(this.addresses[this.moduleName]["s2n_connection_get_read_fd"], "int", ["pointer", "pointer"]);
        S2nTLS.s2n_get_write_fd = new NativeFunction(this.addresses[this.moduleName]["s2n_connection_get_write_fd"], "int", ["pointer", "pointer"]);
    }
    install_tls_keys_callback_hook() { }
    //Hooks the s2n_send function
    //Get the buffer on enter and read the data from it
    install_plaintext_read_hook() {
        var current_module_name = this.module_name;
        var lib_addresses = this.addresses;
        Interceptor.attach(lib_addresses[this.moduleName]["s2n_recv"], {
            onEnter: function (args) {
                var readfdPtr = Memory.alloc(Process.pointerSize);
                S2nTLS.s2n_get_read_fd(args[0], readfdPtr);
                var readfd = readfdPtr.readInt();
                var message = getPortsAndAddresses(readfd, false, lib_addresses[current_module_name], enable_default_fd);
                message["function"] = "s2n_recv";
                message["ssl_session_id"] = "0";
                this.message = message;
                this.buf = args[1];
            },
            onLeave: function (retval) {
                try {
                    retval = parseInt(retval);
                    if (retval <= 0 || retval > 184332) {
                        return;
                    }
                    // Ensure this.buf is valid before accessing it
                    if (this.buf && this.buf.readByteArray) {
                        this.message["contentType"] = "datalog";
                        send(this.message, this.buf.readByteArray(retval));
                    }
                    else {
                        console.error("Buffer is not valid or readByteArray method is missing.");
                    }
                }
                catch (error) {
                    console.error("Error in onLeave (retval: " + retval + "):", error);
                }
            }
        });
    }
    //Hooks the s2n_recv function
    //Get the buffer on enter and read the retval bytes from it on leave
    install_plaintext_write_hook() {
        var current_module_name = this.module_name;
        var lib_addresses = this.addresses;
        Interceptor.attach(lib_addresses[this.moduleName]["s2n_send"], {
            onEnter: function (args) {
                var writefdPtr = Memory.alloc(Process.pointerSize);
                S2nTLS.s2n_get_write_fd(args[0], writefdPtr);
                var writefd = writefdPtr.readInt();
                var message = getPortsAndAddresses(writefd, true, lib_addresses[current_module_name], enable_default_fd);
                message["function"] = "s2n_send";
                message["ssl_session_id"] = "0";
                this.message = message;
                this.buf = args[1];
            },
            onLeave: function (retval) {
                retval = parseInt(retval);
                if (retval < 0) {
                    return;
                }
                this.message["contentType"] = "datalog";
                send(this.message, this.buf.readByteArray(retval));
            }
        });
    }
}
//this function logs the given keylog line
S2nTLS.keylog_callback = new NativeCallback(function (ctxPtr, conn, logline, len) {
    devlog("invoking keylog_callback from s2ntls");
    var message = {};
    message["contentType"] = "keylog";
    message["keylog"] = logline.readCString(len.toInt32());
    send(message);
    return 1;
}, "int", ["pointer", "pointer", "pointer", "pointer"]);
✄
{"version":3,"file":"wolfssl.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/ssl_lib/wolfssl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAe,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACjH,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAE3D,MAAM,OAAO,OAAO;IAahB,YAAmB,UAAiB,EAAS,cAAqB,EAAQ,6BAAgE;QAAvH,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;QAAQ,kCAA6B,GAA7B,6BAA6B,CAAmC;QAX1I,mBAAmB;QAC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AAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;YAC3D,CAAC;YACD,OAAO,EAAE,UAAU,MAAW;YAC9B,CAAC;SACJ,CAAC,CAAA;IACN,CAAC;CAIJ"}
✄
import { readAddresses, getPortsAndAddresses, getBaseAddress } from "../shared/shared_functions.js";
import { log } from "../util/log.js";
import { offsets, enable_default_fd } from "../ssl_log.js";
export class WolfSSL {
    constructor(moduleName, socket_library, passed_library_method_mapping) {
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        this.passed_library_method_mapping = passed_library_method_mapping;
        // global variables
        this.library_method_mapping = {};
        if (typeof passed_library_method_mapping !== 'undefined') {
            this.library_method_mapping = passed_library_method_mapping;
        }
        else {
            this.library_method_mapping[`*${moduleName}*`] = ["wolfSSL_read", "wolfSSL_write", "wolfSSL_get_fd", "wolfSSL_get_session", "wolfSSL_connect", "wolfSSL_KeepArrays", "wolfSSL_SESSION_get_master_key", "wolfSSL_get_client_random", "wolfSSL_get_server_random"];
            this.library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        }
        this.addresses = readAddresses(moduleName, this.library_method_mapping);
        this.module_name = moduleName;
        // @ts-ignore
        if (offsets != "{OFFSETS}" && offsets.wolfssl != null) {
            if (offsets.sockets != null) {
                const socketBaseAddress = getBaseAddress(socket_library);
                for (const method of Object.keys(offsets.sockets)) {
                    //@ts-ignore
                    this.addresses[this.moduleName][`${method}`] = offsets.sockets[`${method}`].absolute || socketBaseAddress == null ? ptr(offsets.sockets[`${method}`].address) : socketBaseAddress.add(ptr(offsets.sockets[`${method}`].address));
                }
            }
            const libraryBaseAddress = getBaseAddress(moduleName);
            if (libraryBaseAddress == null) {
                log("Unable to find library base address! Given address values will be interpreted as absolute ones!");
            }
            for (const method of Object.keys(offsets.wolfssl)) {
                //@ts-ignore
                this.addresses[this.moduleName][`${method}`] = offsets.wolfssl[`${method}`].absolute || libraryBaseAddress == null ? ptr(offsets.wolfssl[`${method}`].address) : libraryBaseAddress.add(ptr(offsets.wolfssl[`${method}`].address));
            }
        }
        WolfSSL.wolfSSL_get_fd = new NativeFunction(this.addresses[this.moduleName]["wolfSSL_get_fd"], "int", ["pointer"]);
        WolfSSL.wolfSSL_get_session = new NativeFunction(this.addresses[this.moduleName]["wolfSSL_get_session"], "pointer", ["pointer"]);
    }
    install_tls_keys_callback_hook() {
        log("Error: TLS key extraction not implemented yet.");
    }
    /**
       * Get the session_id of SSL object and return it as a hex string.
       * @param {!NativePointer} ssl A pointer to an SSL object.
       * @return {dict} A string representing the session_id of the SSL object's
       *     SSL_SESSION. For example,
       *     "59FD71B7B90202F359D89E66AE4E61247954E28431F6C6AC46625D472FF76336".
       */
    static getSslSessionId(ssl) {
        var session = WolfSSL.wolfSSL_get_session(ssl);
        if (session.isNull()) {
            if (enable_default_fd) {
                log("using dummy SessionID: 59FD71B7B90202F359D89E66AE4E61247954E28431F6C6AC46625D472FF76338");
                return "59FD71B7B90202F359D89E66AE4E61247954E28431F6C6AC46625D472FF76338";
            }
            log("Session is null");
            return 0;
        }
        var p = session.add(8);
        var len = 32; // This comes from internals.h. It is untested!
        var session_id = "";
        for (var i = 0; i < len; i++) {
            // Read a byte, convert it to a hex string (0xAB ==> "AB"), and append
            // it to session_id.
            session_id +=
                ("0" + p.add(i).readU8().toString(16).toUpperCase()).substr(-2);
        }
        return session_id;
    }
    install_plaintext_read_hook() {
        var current_module_name = this.module_name;
        var lib_addesses = this.addresses;
        Interceptor.attach(this.addresses[this.moduleName]["wolfSSL_read"], {
            onEnter: function (args) {
                var message = getPortsAndAddresses(WolfSSL.wolfSSL_get_fd(args[0]), true, lib_addesses[current_module_name], enable_default_fd);
                message["function"] = "wolfSSL_read";
                message["ssl_session_id"] = WolfSSL.getSslSessionId(args[0]);
                this.message = message;
                this.buf = args[1];
            },
            onLeave: function (retval) {
                retval |= 0; // Cast retval to 32-bit integer.
                if (retval <= 0) {
                    return;
                }
                this.message["contentType"] = "datalog";
                send(this.message, this.buf.readByteArray(retval));
            }
        });
    }
    install_plaintext_write_hook() {
        var current_module_name = this.module_name;
        var lib_addesses = this.addresses;
        Interceptor.attach(this.addresses[this.moduleName]["wolfSSL_write"], {
            onEnter: function (args) {
                var message = getPortsAndAddresses(WolfSSL.wolfSSL_get_fd(args[0]), false, lib_addesses[current_module_name], enable_default_fd);
                message["ssl_session_id"] = WolfSSL.getSslSessionId(args[0]);
                message["function"] = "wolfSSL_write";
                message["contentType"] = "datalog";
                send(message, args[1].readByteArray(parseInt(args[2])));
            },
            onLeave: function (retval) {
            }
        });
    }
}
✄
{"version":3,"file":"anti_root.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/util/anti_root.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,aAAa,EAAkB,MAAM,+BAA+B,CAAC;AAE9E;;GAEG;AAGH,MAAM,OAAO,QAAQ;IA2BjB;QAzBA,iBAAY,GAAG,CAAC,yBAAyB,EAAE,+BAA+B,EAAE,sBAAsB;YAC9F,4BAA4B,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,6BAA6B;YAC1G,qCAAqC,EAAE,6BAA6B,EAAE,wBAAwB;YAC9F,4BAA4B,EAAE,+BAA+B,EAAE,0BAA0B,EAAE,8BAA8B;YACzH,kCAAkC,EAAE,sBAAsB,EAAE,gCAAgC,EAAE,yBAAyB;YACvH,+BAA+B,EAAE,6BAA6B,EAAE,sBAAsB,EAAE,kBAAkB;YAC1G,0BAA0B,EAAE,mBAAmB,EAAE,sBAAsB;SAC1E,CAAC;QAEF,iBAAY,GAAG,CAAC,IAAI,EAAE,SAAS,EAAE,SAAS,EAAE,eAAe,EAAE,eAAe,EAAE,aAAa,EAAE,QAAQ,CAAC,CAAC;QAEvG,mBAAc,GAAG;YACb,kBAAkB,EAAE,GAAG;YACvB,eAAe,EAAE,GAAG;YACpB,kBAAk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D,OAAO,EAAE,UAAS,MAAM;YAExB,CAAC;SACJ,CAAC,CAAC;QAEH,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,QAAQ,CAAC,EAAE;YAC3D,OAAO,EAAE,UAAS,IAAI;gBAClB,IAAI,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;gBACjC,GAAG,CAAC,cAAc,GAAG,GAAG,CAAC,CAAC;gBACzB,YAAY;gBACZ,IAAI,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,GAAG,IAAI,OAAO,IAAI,GAAG,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,IAAI,GAAG,IAAI,IAAI,EAAE;oBACnG,GAAG,CAAC,wBAAwB,GAAG,GAAG,CAAC,CAAC;oBACnC,IAAI,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;iBACnC;gBACD,IAAI,GAAG,IAAI,IAAI,EAAE;oBACd,GAAG,CAAC,wBAAwB,GAAG,GAAG,CAAC,CAAC;oBACnC,IAAI,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,cAAc,CAAC,CAAC;iBAC3C;YACL,CAAC;YACD,OAAO,EAAE,UAAS,MAAM;YAExB,CAAC;SACJ,CAAC,CAAC;QAEH;;;;;;;;;;;;;;;UAeE;IAGE,CAAC;IAED,aAAa;QACT,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC3B,IAAI,CAAC,qBAAqB,EAAE,CAAC;IACjC,CAAC;CAEJ;AAED,MAAM,UAAU,iBAAiB;IAC7B,IAAI,SAAS,GAAG,IAAI,QAAQ,EAAE,CAAC;IAC/B,SAAS,CAAC,aAAa,EAAE,CAAC;AAG9B,CAAC"}
✄
import { log, devlog } from "./log.js";
import { readAddresses } from "../shared/shared_functions.js";
/*
 * mostly taken from here: https://codeshare.frida.re/@dzonerzy/fridantiroot/
 */
export class AntiRoot {
    constructor() {
        this.RootPackages = ["com.noshufou.android.su", "com.noshufou.android.su.elite", "eu.chainfire.supersu",
            "com.koushikdutta.superuser", "com.thirdparty.superuser", "com.yellowes.su", "com.koushikdutta.rommanager",
            "com.koushikdutta.rommanager.license", "com.dimonvideo.luckypatcher", "com.chelpus.lackypatch",
            "com.ramdroid.appquarantine", "com.ramdroid.appquarantinepro", "com.devadvance.rootcloak", "com.devadvance.rootcloakplus",
            "de.robv.android.xposed.installer", "com.saurik.substrate", "com.zachspong.temprootremovejb", "com.amphoras.hidemyroot",
            "com.amphoras.hidemyrootadfree", "com.formyhm.hiderootPremium", "com.formyhm.hideroot", "me.phh.superuser",
            "eu.chainfire.supersu.pro", "com.kingouser.com", "com.topjohnwu.magisk"
        ];
        this.RootBinaries = ["su", "busybox", "supersu", "Superuser.apk", "KingoUser.apk", "SuperSu.apk", "magisk"];
        this.RootProperties = {
            "ro.build.selinux": "1",
            "ro.debuggable": "0",
            "service.adb.root": "0",
            "ro.secure": "1"
        };
        this.RootPropertiesKeys = [];
        this.library_method_mapping = {};
        this.library_method_mapping["libc.so"] = ["strstr", "fopen", "system"];
        this.module_name = "libc.so";
        this.addresses = readAddresses(this.module_name, this.library_method_mapping);
        for (var k in this.RootProperties)
            this.RootPropertiesKeys.push(k);
    }
    java_based_bypasses() {
        Java.perform(function () {
            var PackageManager = Java.use("android.app.ApplicationPackageManager");
            var Runtime = Java.use('java.lang.Runtime');
            var NativeFile = Java.use('java.io.File');
            var String = Java.use('java.lang.String');
            var SystemProperties = Java.use('android.os.SystemProperties');
            var BufferedReader = Java.use('java.io.BufferedReader');
            var ProcessBuilder = Java.use('java.lang.ProcessBuilder');
            var StringBuffer = Java.use('java.lang.StringBuffer');
            var useKeyInfo = false;
            var useProcessManager = false;
            //@ts-ignore
            var ProcessManager = NULL;
            var loaded_classes = Java.enumerateLoadedClassesSync();
            devlog("Loaded " + loaded_classes.length + " classes!");
            devlog("loaded: " + loaded_classes.indexOf('java.lang.ProcessManager'));
            if (loaded_classes.indexOf('java.lang.ProcessManager') != -1) {
                try {
                    useProcessManager = true;
                    ProcessManager = Java.use('java.lang.ProcessManager');
                }
                catch (err) {
                    devlog("ProcessManager Hook failed: " + err);
                }
            }
            else {
                //ProcessManager = null;
                devlog("ProcessManager hook not loaded");
            }
            var KeyInfo = NULL;
            if (loaded_classes.indexOf('android.security.keystore.KeyInfo') != -1) {
                try {
                    useKeyInfo = true;
                    KeyInfo = Java.use('android.security.keystore.KeyInfo');
                }
                catch (err) {
                    log("KeyInfo Hook failed: " + err);
                }
            }
            else {
                log("KeyInfo hook not loaded");
            }
            PackageManager.getPackageInfo.overload('java.lang.String', 'int').implementation = function (pname, flags) {
                var shouldFakePackage = (this.RootPackages.indexOf(pname) > -1);
                if (shouldFakePackage) {
                    log("Bypass root check for package: " + pname);
                    pname = "set.package.name.to.a.fake.one.so.we.can.bypass.it";
                }
                return this.getPackageInfo.overload('java.lang.String', 'int').call(this, pname, flags);
            };
            /*
            This check results into the following error:
            {'description': 'Error: expected an unsigned integer', 'type': 'error'}


            NativeFile.exists.implementation = function() {
                var name = NativeFile.getName.call(this);
                var shouldFakeReturn = (this.RootBinaries.indexOf(name) > -1);
                console.log(shouldFakeReturn);
                if (shouldFakeReturn) {
                   log("Bypass return value for binary: " + name);
                    return false;
                } else {
                    return this.exists.call(this);
                }
            };  */
            var exec = Runtime.exec.overload('[Ljava.lang.String;');
            var exec1 = Runtime.exec.overload('java.lang.String');
            var exec2 = Runtime.exec.overload('java.lang.String', '[Ljava.lang.String;');
            var exec3 = Runtime.exec.overload('[Ljava.lang.String;', '[Ljava.lang.String;');
            var exec4 = Runtime.exec.overload('[Ljava.lang.String;', '[Ljava.lang.String;', 'java.io.File');
            var exec5 = Runtime.exec.overload('java.lang.String', '[Ljava.lang.String;', 'java.io.File');
            exec5.implementation = function (cmd, env, dir) {
                if (cmd.indexOf("getprop") != -1 || cmd == "mount" || cmd.indexOf("build.prop") != -1 || cmd == "id" || cmd == "sh") {
                    var fakeCmd = "grep";
                    log("Bypass " + cmd + " command");
                    return exec1.call(this, fakeCmd);
                }
                if (cmd == "su") {
                    var fakeCmd = "awesome_tool";
                    log("Bypass " + cmd + " command");
                    return exec1.call(this, fakeCmd);
                }
                return exec5.call(this, cmd, env, dir);
            };
            exec4.implementation = function (cmdarr, env, file) {
                for (var i = 0; i < cmdarr.length; i = i + 1) {
                    var tmp_cmd = cmdarr[i];
                    if (tmp_cmd.indexOf("getprop") != -1 || tmp_cmd == "mount" || tmp_cmd.indexOf("build.prop") != -1 || tmp_cmd == "id" || tmp_cmd == "sh") {
                        var fakeCmd = "grep";
                        log("Bypass " + cmdarr + " command");
                        return exec1.call(this, fakeCmd);
                    }
                    if (tmp_cmd == "su") {
                        var fakeCmd = "awesome_tool";
                        log("Bypass " + cmdarr + " command");
                        return exec1.call(this, fakeCmd);
                    }
                }
                return exec4.call(this, cmdarr, env, file);
            };
            exec3.implementation = function (cmdarr, envp) {
                for (var i = 0; i < cmdarr.length; i = i + 1) {
                    var tmp_cmd = cmdarr[i];
                    if (tmp_cmd.indexOf("getprop") != -1 || tmp_cmd == "mount" || tmp_cmd.indexOf("build.prop") != -1 || tmp_cmd == "id" || tmp_cmd == "sh") {
                        var fakeCmd = "grep";
                        log("Bypass " + cmdarr + " command");
                        return exec1.call(this, fakeCmd);
                    }
                    if (tmp_cmd == "su") {
                        var fakeCmd = "awesome_tool";
                        log("Bypass " + cmdarr + " command");
                        return exec1.call(this, fakeCmd);
                    }
                }
                return exec3.call(this, cmdarr, envp);
            };
            exec2.implementation = function (cmd, env) {
                if (cmd.indexOf("getprop") != -1 || cmd == "mount" || cmd.indexOf("build.prop") != -1 || cmd == "id" || cmd == "sh") {
                    var fakeCmd = "grep";
                    log("Bypass " + cmd + " command");
                    return exec1.call(this, fakeCmd);
                }
                if (cmd == "su") {
                    var fakeCmd = "awesome_tool";
                    log("Bypass " + cmd + " command");
                    return exec1.call(this, fakeCmd);
                }
                return exec2.call(this, cmd, env);
            };
            exec.implementation = function (cmd) {
                for (var i = 0; i < cmd.length; i = i + 1) {
                    var tmp_cmd = cmd[i];
                    if (tmp_cmd.indexOf("getprop") != -1 || tmp_cmd == "mount" || tmp_cmd.indexOf("build.prop") != -1 || tmp_cmd == "id" || tmp_cmd == "sh") {
                        var fakeCmd = "grep";
                        log("Bypass " + cmd + " command");
                        return exec1.call(this, fakeCmd);
                    }
                    if (tmp_cmd == "su") {
                        var fakeCmd = "awesome_tool";
                        log("Bypass " + cmd + " command");
                        return exec1.call(this, fakeCmd);
                    }
                }
                return exec.call(this, cmd);
            };
            exec1.implementation = function (cmd) {
                if (cmd.indexOf("getprop") != -1 || cmd == "mount" || cmd.indexOf("build.prop") != -1 || cmd == "id" || cmd == "sh") {
                    var fakeCmd = "grep";
                    log("Bypass " + cmd + " command");
                    return exec1.call(this, fakeCmd);
                }
                if (cmd == "su") {
                    var fakeCmd = "awesome_tool";
                    log("Bypass " + cmd + " command");
                    return exec1.call(this, fakeCmd);
                }
                return exec1.call(this, cmd);
            };
            String.contains.implementation = function (name) {
                if (name == "test-keys") {
                    log("Bypass test-keys check");
                    return false;
                }
                return this.contains.call(this, name);
            };
            var get = SystemProperties.get.overload('java.lang.String');
            get.implementation = function (name) {
                if (this.RootPropertiesKeys.indexOf(name) != -1) {
                    log("Bypass " + name);
                    return this.RootProperties[name];
                }
                return this.get.call(this, name);
            };
            BufferedReader.readLine.overload('boolean').implementation = function () {
                var text = this.readLine.overload('boolean').call(this);
                if (text === null) {
                    // just pass , i know it's ugly as hell but test != null won't work :(
                }
                else {
                    var shouldFakeRead = (text.indexOf("ro.build.tags=test-keys") > -1);
                    if (shouldFakeRead) {
                        log("Bypass build.prop file read");
                        text = text.replace("ro.build.tags=test-keys", "ro.build.tags=release-keys");
                    }
                }
                return text;
            };
            var executeCommand = ProcessBuilder.command.overload('java.util.List');
            ProcessBuilder.start.implementation = function () {
                var cmd = this.command.call(this);
                var shouldModifyCommand = false;
                for (var i = 0; i < cmd.size(); i = i + 1) {
                    var tmp_cmd = cmd.get(i).toString();
                    if (tmp_cmd.indexOf("getprop") != -1 || tmp_cmd.indexOf("mount") != -1 || tmp_cmd.indexOf("build.prop") != -1 || tmp_cmd.indexOf("id") != -1) {
                        shouldModifyCommand = true;
                    }
                }
                if (shouldModifyCommand) {
                    log("Bypass ProcessBuilder " + cmd);
                    this.command.call(this, ["grep"]);
                    return this.start.call(this);
                }
                if (cmd.indexOf("su") != -1) {
                    log("Bypass ProcessBuilder " + cmd);
                    this.command.call(this, ["awesome_tool"]);
                    return this.start.call(this);
                }
                return this.start.call(this);
            };
            if (useProcessManager) {
                //@ts-ignore
                var ProcManExec = ProcessManager.exec.overload('[Ljava.lang.String;', '[Ljava.lang.String;', 'java.io.File', 'boolean');
                //@ts-ignore
                var ProcManExecVariant = ProcessManager.exec.overload('[Ljava.lang.String;', '[Ljava.lang.String;', 'java.lang.String', 'java.io.FileDescriptor', 'java.io.FileDescriptor', 'java.io.FileDescriptor', 'boolean');
                ProcManExec.implementation = function (cmd, env, workdir, redirectstderr) {
                    var fake_cmd = cmd;
                    for (var i = 0; i < cmd.length; i = i + 1) {
                        var tmp_cmd = cmd[i];
                        if (tmp_cmd.indexOf("getprop") != -1 || tmp_cmd == "mount" || tmp_cmd.indexOf("build.prop") != -1 || tmp_cmd == "id") {
                            var fake_cmd = ["grep"];
                            log("Bypass " + cmd + " command");
                        }
                        if (tmp_cmd == "su") {
                            var fake_cmd = ["awesome_tool"];
                            log("Bypass " + cmd + " command");
                        }
                    }
                    return ProcManExec.call(this, fake_cmd, env, workdir, redirectstderr);
                };
                ProcManExecVariant.implementation = function (cmd, env, directory, stdin, stdout, stderr, redirect) {
                    var fake_cmd = cmd;
                    for (var i = 0; i < cmd.length; i = i + 1) {
                        var tmp_cmd = cmd[i];
                        if (tmp_cmd.indexOf("getprop") != -1 || tmp_cmd == "mount" || tmp_cmd.indexOf("build.prop") != -1 || tmp_cmd == "id") {
                            var fake_cmd = ["grep"];
                            log("Bypass " + cmd + " command");
                        }
                        if (tmp_cmd == "su") {
                            var fake_cmd = ["awesome_tool"];
                            log("Bypass " + cmd + " command");
                        }
                    }
                    return ProcManExecVariant.call(this, fake_cmd, env, directory, stdin, stdout, stderr, redirect);
                };
            }
            if (useKeyInfo) {
                //@ts-ignore
                KeyInfo.isInsideSecureHardware.implementation = function () {
                    log("Bypass isInsideSecureHardware");
                    return true;
                };
            }
        });
    }
    native_based_bypasses() {
        // char *strstr(const char *str1, const char *str2);
        Interceptor.attach(this.addresses[this.module_name]["strstr"], {
            onEnter: function (args) {
                this.str_source = args[0];
                this.str_to_look_for = args[1];
                this.frida = Boolean(0);
                var haystack = this.str_source.readUtf8String();
                var needle = this.str_to_look_for.readUtf8String();
                if (haystack.indexOf("frida") != -1 || haystack.indexOf("xposed") != -1) {
                    this.frida = Boolean(1);
                }
            },
            onLeave: function (retval) {
                if (this.frida) {
                    //send("strstr(frida) was patched!! :) " + haystack);
                    retval.replace(ptr(0));
                }
                return retval;
            }
        });
        Interceptor.attach(this.addresses[this.module_name]["fopen"], {
            onEnter: function (args) {
                var path = args[0].readCString();
                //@ts-ignore
                var path_array = path.split("/");
                var executable = path_array[path_array.length - 1];
                var shouldFakeReturn = (this.RootBinaries.indexOf(executable) > -1);
                if (shouldFakeReturn) {
                    args[0].writeUtf8String("/notexists");
                    log("Bypass native fopen");
                }
            },
            onLeave: function (retval) {
            }
        });
        Interceptor.attach(this.addresses[this.module_name]["system"], {
            onEnter: function (args) {
                var cmd = args[0].readCString();
                log("SYSTEM CMD: " + cmd);
                //@ts-ignore
                if (cmd.indexOf("getprop") != -1 || cmd == "mount" || cmd.indexOf("build.prop") != -1 || cmd == "id") {
                    log("Bypass native system: " + cmd);
                    args[0].writeUtf8String("grep");
                }
                if (cmd == "su") {
                    log("Bypass native system: " + cmd);
                    args[0].writeUtf8String("awesome_tool");
                }
            },
            onLeave: function (retval) {
            }
        });
        /*
        
        TO IMPLEMENT:
        
        Exec Family
        
        int execl(const char *path, const char *arg0, ..., const char *argn, (char *)0);
        int execle(const char *path, const char *arg0, ..., const char *argn, (char *)0, char *const envp[]);
        int execlp(const char *file, const char *arg0, ..., const char *argn, (char *)0);
        int execlpe(const char *file, const char *arg0, ..., const char *argn, (char *)0, char *const envp[]);
        int execv(const char *path, char *const argv[]);
        int execve(const char *path, char *const argv[], char *const envp[]);
        int execvp(const char *file, char *const argv[]);
        int execvpe(const char *file, char *const argv[], char *const envp[]);
        
        */
    }
    execute_hooks() {
        this.java_based_bypasses();
        this.native_based_bypasses();
    }
}
export function anti_root_execute() {
    var anti_root = new AntiRoot();
    anti_root.execute_hooks();
}
✄
{"version":3,"file":"log.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/util/log.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,GAAG,CAAC,GAAW;IAC3B,IAAI,OAAO,GAA8B,EAAE,CAAA;IAC3C,OAAO,CAAC,aAAa,CAAC,GAAG,SAAS,CAAA;IAClC,OAAO,CAAC,SAAS,CAAC,GAAG,GAAG,CAAA;IACxB,IAAI,CAAC,OAAO,CAAC,CAAA;AACjB,CAAC;AAGD,MAAM,UAAU,MAAM,CAAC,GAAW;IAC9B,IAAI,OAAO,GAA8B,EAAE,CAAA;IAC3C,OAAO,CAAC,aAAa,CAAC,GAAG,aAAa,CAAA;IACtC,OAAO,CAAC,aAAa,CAAC,GAAG,GAAG,CAAA;IAC5B,IAAI,CAAC,OAAO,CAAC,CAAA;AACjB,CAAC;AAGD,MAAM,UAAU,YAAY,CAAC,GAAW;IACpC,IAAI,OAAO,GAA8B,EAAE,CAAA;IAC3C,OAAO,CAAC,aAAa,CAAC,GAAG,eAAe,CAAA;IACxC,OAAO,CAAC,eAAe,CAAC,GAAG,GAAG,CAAA;IAC9B,IAAI,CAAC,OAAO,CAAC,CAAA;AACjB,CAAC"}
✄
export function log(str) {
    var message = {};
    message["contentType"] = "console";
    message["console"] = str;
    send(message);
}
export function devlog(str) {
    var message = {};
    message["contentType"] = "console_dev";
    message["console_dev"] = str;
    send(message);
}
export function devlog_error(str) {
    var message = {};
    message["contentType"] = "console_error";
    message["console_error"] = str;
    send(message);
}
✄
{"version":3,"file":"process_infos.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/util/process_infos.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAElC,MAAM,UAAU,wBAAwB;IAChC,OAAO,OAAO,CAAC,IAAI,CAAC;AAC5B,CAAC;AAGD,MAAM,UAAU,SAAS;IACrB,IAAG,IAAI,CAAC,SAAS,IAAI,OAAO,CAAC,QAAQ,IAAI,OAAO,EAAC;QAC7C,IAAG;YACC,IAAI,CAAC,cAAc,CAAA,CAAC,yDAAyD;YAC7E,OAAO,IAAI,CAAA;SACd;QAAA,OAAM,KAAK,EAAC;YACT,OAAO,KAAK,CAAA;SACf;KACJ;SAAI;QACD,OAAO,KAAK,CAAA;KACf;AACL,CAAC;AAED,SAAS,6BAA6B;IAClC,gEAAgE;IAChE,IAAI,IAAI,CAAC,OAAO,CAAC,aAAa,KAAK,SAAS,EAAE;QAC1C,IAAI;YACA,0CAA0C;YAC1C,MAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC;YAGjD,MAAM,OAAO,GAAG,aAAa,CAAC,WAAW,EAAE;iBACtC,4BAA4B,EAAE;iBAC9B,QAAQ,EAAE,CAAC,WAAW,EAAE,CAAC;YAG9B,iEAAiE;YACjE,iCAAiC;YACjC,MAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,KAAK,SAAS,CAAC;YAE9D,IAAI,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;gBACzB,OAAO,KAAK,CAAC;aAChB;iBAAM,IAAI,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,QA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AC,+BAA+B,CAAC,CAAC,CAAC;aAC3D;YAAC,OAAO,GAAG,EAAE;gBACZ,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;aACpB;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC"}
✄
import { devlog } from "./log.js";
export function get_process_architecture() {
    return Process.arch;
}
export function isAndroid() {
    if (Java.available && Process.platform == "linux") {
        try {
            Java.androidVersion; // this will raise an error when we are not under Android
            return true;
        }
        catch (error) {
            return false;
        }
    }
    else {
        return false;
    }
}
function is_macos_based_version_string() {
    // Check if NSProcessInfo is available (indicating macOS or iOS)
    if (ObjC.classes.NSProcessInfo !== undefined) {
        try {
            // Get the operating system version string
            const NSProcessInfo = ObjC.classes.NSProcessInfo;
            const version = NSProcessInfo.processInfo()
                .operatingSystemVersionString()
                .toString().toLowerCase();
            // https://developer.apple.com/documentation/appkit/nsapplication
            // should only available on MacOS
            const isMacOSCheck = ObjC.classes.NSApplication !== undefined;
            if (version.includes("ios")) {
                return false;
            }
            else if (version.includes("macos") || version.includes("os x") || isMacOSCheck) {
                return true;
            }
        }
        catch (error) {
            devlog("[!] error:" + error);
            return false;
        }
    }
    return false;
}
export function isiOS() {
    if (get_process_architecture() === "arm64" && Process.platform == "darwin") {
        try {
            if (is_macos_based_version_string()) {
                return false;
            }
            else {
                return true;
            }
        }
        catch (error) {
            return false;
        }
    }
    else {
        return false;
    }
}
export function isMacOS() {
    if (get_process_architecture() === "x64" && Process.platform == "darwin") {
        return true;
    }
    else {
        if (Process.platform == "darwin") {
            if (is_macos_based_version_string()) {
                return true;
            }
        }
        return false;
    }
}
export function isLinux() {
    if (Process.platform == "linux") {
        if (Java.available == false && Process.platform == "linux") {
            return true;
        }
        else {
            try {
                Java.androidVersion; // this will raise an error when we are not under Android
                return false;
            }
            catch (error) {
                return true;
            }
        }
    }
    else {
        return false;
    }
}
export function isWindows() {
    if (Process.platform == "windows") {
        return true;
    }
    else {
        return false;
    }
}
export function getAndroidVersion() {
    var version = "-1";
    Java.perform(function () {
        version = Java.androidVersion; // this will return a value like 12 for Android version 12
    });
    var casted_version = +version;
    return casted_version;
}
/**
 * Returns the current Android package name that the script is running inside.
 *
 * Works on all modern Android versions (API 21 +).  Uses ActivityThread first;
 * falls back to any available Context if necessary.
 */
export function getPackageName() {
    return new Promise((resolve, reject) => {
        Java.perform(() => {
            try {
                // Preferred: ActivityThread.currentPackageName() (SDK ≈ 23 +)
                const ActivityThread = Java.use('android.app.ActivityThread');
                const currentPkg = ActivityThread.currentPackageName();
                if (currentPkg && currentPkg.length > 0) {
                    return resolve(currentPkg);
                }
                // Fallback: grab a Context and call getPackageName()
                const Context = Java.use('android.content.Context');
                const ActivityThread$ = Java.use('android.app.ActivityThread');
                const app = ActivityThread$.currentApplication();
                if (app && Context.isInstance(app)) {
                    // @ts-ignore
                    return resolve(app.getPackageName());
                }
                return reject(new Error('Unable to obtain package name'));
            }
            catch (err) {
                return reject(err);
            }
        });
    });
}
✄
{"version":3,"file":"cronet_windows.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/windows/cronet_windows.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAC,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACxE,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAExC,MAAM,OAAO,cAAe,SAAQ,MAAM;IAEtC,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,KAAK,CAAC,UAAU,EAAC,cAAc,EAAC,YAAY,CAAC,CAAC;QAD/B,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAElE,CAAC;IAED,2BAA2B;QACvB,MAAM,YAAY,GAAG,OAAO,CAAC,gBAAgB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAChE,MAAM,MAAM,GAAG,IAAI,mBAAmB,CAAC,YAAY,CAAC,CAAC;QAErD,IAAI,iBAAiB,EAAE,EAAC;YACpB,MAAM,CAAC,wCAAwC,CAAC,CAAC;YACjD,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,WAAW,EAAC,eAAe,EAAC,QAAQ,EAAC,CAAC,IAAW,EAAE,EAAE;gBAC3E,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAE,4BAA4B;YAC3E,CAAC,CAAC,CAAC;SACN;IAOL,CAAC;IAED,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;IACvC,CAAC;CAEJ;AAGD,MAAM,UAAU,cAAc,CAAC,UAAiB,EAAE,YAAqB;IACnE,IAAI,MAAM,GAAG,IAAI,cAAc,CAAC,UAAU,EAAC,cAAc,EAAC,YAAY,CAAC,CAAC;IACxE,MAAM,CAAC,aAAa,EAAE,CAAC;IAEvB,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACpD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AAEL,CAAC"}
✄
import { Cronet } from "../ssl_lib/cronet.js";
import { socket_library } from "./windows_agent.js";
import { PatternBasedHooking } from "../shared/pattern_based_hooking.js";
import { patterns, isPatternReplaced } from "../ssl_log.js";
import { devlog } from "../util/log.js";
export class Cronet_Windows extends Cronet {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library, is_base_hook);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    install_key_extraction_hook() {
        const cronetModule = Process.findModuleByName(this.module_name);
        const hooker = new PatternBasedHooking(cronetModule);
        if (isPatternReplaced()) {
            devlog("Hooking libcronet functions by pattern");
            hooker.hook_DumpKeys(this.module_name, "libcronet.dll", patterns, (args) => {
                this.dumpKeys(args[1], args[0], args[2]); // Unpack args into dumpKeys
            });
        }
    }
    execute_hooks() {
        this.install_key_extraction_hook();
    }
}
export function cronet_execute(moduleName, is_base_hook) {
    var cronet = new Cronet_Windows(moduleName, socket_library, is_base_hook);
    cronet.execute_hooks();
    if (is_base_hook) {
        const init_addresses = cronet.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"gnutls_windows.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/windows/gnutls_windows.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,MAAM,OAAO,cAAe,SAAQ,MAAM;IAEtC,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,KAAK,CAAC,UAAU,EAAC,cAAc,CAAC,CAAC;QADlB,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAElE,CAAC;IAGD,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;QACnC,IAAI,CAAC,4BAA4B,EAAE,CAAC;QAEpC,wCAAwC;IAC5C,CAAC;IAED,8BAA8B;QAC1B,qBAAqB;IACzB,CAAC;CAEJ;AAGD,MAAM,UAAU,cAAc,CAAC,UAAiB,EAAE,YAAqB;IACnE,IAAI,OAAO,GAAG,IAAI,cAAc,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IAC1E,OAAO,CAAC,aAAa,EAAE,CAAC;IAExB,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACrD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { GnuTLS } from "../ssl_lib/gnutls.js";
import { socket_library } from "./windows_agent.js";
export class GnuTLS_Windows extends GnuTLS {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        //this.install_tls_keys_callback_hook();
    }
    install_tls_keys_callback_hook() {
        //Not implemented yet
    }
}
export function gnutls_execute(moduleName, is_base_hook) {
    var gnu_ssl = new GnuTLS_Windows(moduleName, socket_library, is_base_hook);
    gnu_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = gnu_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"matrixssl_windows.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/windows/matrixssl_windows.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,UAAU,EAAE,MAAM,yBAAyB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,MAAM,OAAO,kBAAmB,SAAQ,UAAU;IAE9C,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,KAAK,CAAC,UAAU,EAAC,cAAc,CAAC,CAAC;QADlB,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAElE,CAAC;IAGD,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;QACnC,IAAI,CAAC,4BAA4B,EAAE,CAAC;QACpC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAE3B,wCAAwC;IAC5C,CAAC;IAED,8BAA8B;QAC1B,qBAAqB;IACzB,CAAC;CAEJ;AAGD,MAAM,UAAU,iBAAiB,CAAC,UAAiB,EAAE,YAAqB;IACtE,IAAI,UAAU,GAAG,IAAI,kBAAkB,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IACjF,UAAU,CAAC,aAAa,EAAE,CAAC;IAE3B,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,UAAU,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACxD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { matrix_SSL } from "../ssl_lib/matrixssl.js";
import { socket_library } from "./windows_agent.js";
export class matrix_SSL_Windows extends matrix_SSL {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        this.install_helper_hook();
        //this.install_tls_keys_callback_hook();
    }
    install_tls_keys_callback_hook() {
        //Not implemented yet
    }
}
export function matrixSSL_execute(moduleName, is_base_hook) {
    var matrix_ssl = new matrix_SSL_Windows(moduleName, socket_library, is_base_hook);
    matrix_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = matrix_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"mbedTLS_windows.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/windows/mbedTLS_windows.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,MAAM,OAAO,gBAAiB,SAAQ,QAAQ;IAE1C,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,KAAK,CAAC,UAAU,EAAC,cAAc,CAAC,CAAC;QADlB,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAElE,CAAC;IAED;;;;;;MAME;IACF,8BAA8B;QAC1B,8BAA8B;IAClC,CAAC;IAED,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;QACnC,IAAI,CAAC,4BAA4B,EAAE,CAAC;IACxC,CAAC;CAEJ;AAGD,MAAM,UAAU,eAAe,CAAC,UAAiB,EAAE,YAAqB;IACpE,IAAI,WAAW,GAAG,IAAI,gBAAgB,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IAChF,WAAW,CAAC,aAAa,EAAE,CAAC;IAE5B,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,WAAW,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACzD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { mbed_TLS } from "../ssl_lib/mbedTLS.js";
import { socket_library } from "./windows_agent.js";
export class mbed_TLS_Windows extends mbed_TLS {
    constructor(moduleName, socket_library, is_base_hook) {
        super(moduleName, socket_library);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    /*
    SSL_CTX_set_keylog_callback not exported by default on windows.

    We need to find a way to install the callback function for doing that

    Alternatives?:SSL_export_keying_material, SSL_SESSION_get_master_key
    */
    install_tls_keys_callback_hook() {
        // install hooking for windows
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
    }
}
export function mbedTLS_execute(moduleName, is_base_hook) {
    var mbedTLS_ssl = new mbed_TLS_Windows(moduleName, socket_library, is_base_hook);
    mbedTLS_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = mbedTLS_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"nss_windows.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/windows/nss_windows.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,MAAM,OAAO,WAAY,SAAQ,GAAG;IAEhC,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,IAAI,sBAAsB,GAAqC,EAAE,CAAC;QAClE,sBAAsB,CAAC,IAAI,UAAU,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,SAAS,EAAE,0BAA0B,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,uBAAuB,CAAC,CAAA;QAC5J,mFAAmF;QACnF,sBAAsB,CAAC,WAAW,CAAC,GAAG,CAAC,cAAc,EAAE,kBAAkB,EAAE,uBAAuB,CAAC,CAAA;QAEnG,KAAK,CAAC,UAAU,EAAC,cAAc,EAAC,sBAAsB,CAAC,CAAC;QANzC,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAOlE,CAAC;IAED,8BAA8B;QAC1B,MAAM;IACV,CAAC;IAGD,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;QACnC,IAAI,CAAC,4BAA4B,EAAE,CAAC;QACpC,iEAAiE;IACrE,CAAC;CAEJ;AAGD,MAAM,UAAU,WAAW,CAAC,UAAiB,EAAE,YAAqB;IAChE,IAAI,OAAO,GAAG,IAAI,WAAW,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IACvE,OAAO,CAAC,aAAa,EAAE,CAAC;IAExB,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACrD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AAEL,CAAC"}
✄
import { NSS } from "../ssl_lib/nss.js";
import { socket_library } from "./windows_agent.js";
export class NSS_Windows extends NSS {
    constructor(moduleName, socket_library, is_base_hook) {
        var library_method_mapping = {};
        library_method_mapping[`*${moduleName}*`] = ["PR_Write", "PR_Read", "PR_FileDesc2NativeHandle", "PR_GetPeerName", "PR_GetSockName", "PR_GetNameForIdentity"];
        // library_method_mapping[`*libnss*`] = ["PK11_ExtractKeyValue", "PK11_GetKeyData"]
        library_method_mapping["*ssl*.dll"] = ["SSL_ImportFD", "SSL_GetSessionID", "SSL_HandshakeCallback"];
        super(moduleName, socket_library, library_method_mapping);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    install_tls_keys_callback_hook() {
        // TBD
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        // this.install_tls_keys_callback_hook(); needs to be implemented
    }
}
export function nss_execute(moduleName, is_base_hook) {
    var nss_ssl = new NSS_Windows(moduleName, socket_library, is_base_hook);
    nss_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = nss_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"openssl_boringssl_windows.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/windows/openssl_boringssl_windows.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACnE,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,MAAM,OAAO,yBAA0B,SAAQ,iBAAiB;IAE5D,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,IAAI,OAAO,GAAoC,EAAE,CAAC;QAClD,OAAO,CAAC,GAAG,UAAU,EAAE,CAAC,GAAG,CAAC,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,SAAS,CAAC,CAAA;QACtH,OAAO,CAAC,IAAI,cAAc,GAAG,CAAC,GAAG,CAAC,aAAa,EAAE,aAAa,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;QACjF,KAAK,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;QAJzC,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAKlE,CAAC;IAED;;;;;;MAME;IACF,8BAA8B;QAC1B,8BAA8B;IAClC,CAAC;IAED,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;QACnC,IAAI,CAAC,4BAA4B,EAAE,CAAC;IACxC,CAAC;CAEJ;AAGD,MAAM,UAAU,cAAc,CAAC,UAAiB,EAAE,YAAqB;IACnE,IAAI,UAAU,GAAG,IAAI,yBAAyB,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IACxF,UAAU,CAAC,aAAa,EAAE,CAAC;IAE3B,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,UAAU,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACxD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { OpenSSL_BoringSSL } from "../ssl_lib/openssl_boringssl.js";
import { socket_library } from "./windows_agent.js";
export class OpenSSL_BoringSSL_Windows extends OpenSSL_BoringSSL {
    constructor(moduleName, socket_library, is_base_hook) {
        let mapping = {};
        mapping[`${moduleName}`] = ["SSL_read", "SSL_write", "SSL_get_fd", "SSL_get_session", "SSL_SESSION_get_id", "SSL_new"];
        mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        super(moduleName, socket_library, is_base_hook, mapping);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    /*
    SSL_CTX_set_keylog_callback not exported by default on windows.

    We need to find a way to install the callback function for doing that

    Alternatives?:SSL_export_keying_material, SSL_SESSION_get_master_key
    */
    install_tls_keys_callback_hook() {
        // install hooking for windows
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
    }
}
export function boring_execute(moduleName, is_base_hook) {
    var boring_ssl = new OpenSSL_BoringSSL_Windows(moduleName, socket_library, is_base_hook);
    boring_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = boring_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"sspi.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/windows/sspi.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,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YACZ,IAAI,CAAC,qBAAqB,EAAE,CAAC;SAChC;IACL,CAAC;CAEJ;AAGD,MAAM,UAAU,YAAY,CAAC,UAAiB,EAAE,YAAqB;IACjE,IAAI,QAAQ,GAAG,IAAI,YAAY,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IACzE,QAAQ,CAAC,aAAa,EAAE,CAAC;IAEzB,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,QAAQ,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACtD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { readAddresses, getBaseAddress } from "../shared/shared_functions.js";
import { socket_library } from "./windows_agent.js";
import { devlog, log } from "../util/log.js";
import { experimental, offsets } from "../ssl_log.js";
/*
ToDo:
- Write Test Client for ground truth and test everything
- Obtain information from the running process to get the socket information instead of using default values
*/
var keylog = (key, tlsVersion) => {
    devlog(`Exporting TLS 1.${tlsVersion} handshake keying material`);
    var message = {};
    message["contentType"] = "keylog";
    message["keylog"] = key;
    send(message);
};
// This library is only existend under Windows therefore there is no Superclass
export class SSPI_Windows {
    constructor(moduleName, socket_library, is_base_hook) {
        this.moduleName = moduleName;
        this.socket_library = socket_library;
        // global variables
        this.library_method_mapping = {};
        this.library_method_mapping[`*${moduleName}*`] = ["DecryptMessage", "EncryptMessage"];
        if (experimental) {
            // ncrypt is used for the TLS keys
            log(`ncrypt.dll was loaded & will be hooked on Windows!`);
            this.library_method_mapping["*ncrypt*.dll"] = ["SslHashHandshake", "SslGenerateMasterKey", "SslImportMasterKey", "SslGenerateSessionKeys", "SslExpandExporterMasterKey", "SslExpandTrafficKeys"];
        }
        this.library_method_mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        this.addresses = readAddresses(moduleName, this.library_method_mapping);
        this.module_name = moduleName;
        // @ts-ignore
        if (offsets != "{OFFSETS}" && offsets.sspi != null) {
            if (offsets.sockets != null) {
                const socketBaseAddress = getBaseAddress(socket_library);
                for (const method of Object.keys(offsets.sockets)) {
                    //@ts-ignore
                    this.addresses[this.module_name][`${method}`] = offsets.sockets[`${method}`].absolute || socketBaseAddress == null ? ptr(offsets.sockets[`${method}`].address) : socketBaseAddress.add(ptr(offsets.sockets[`${method}`].address));
                }
            }
            const libraryBaseAddress = getBaseAddress(moduleName);
            if (libraryBaseAddress == null) {
                log("Unable to find library base address! Given address values will be interpreted as absolute ones!");
            }
            for (const method of Object.keys(offsets.sspi)) {
                //@ts-ignore
                this.addresses[this.module_name][`${method}`] = offsets.sspi[`${method}`].absolute || libraryBaseAddress == null ? ptr(offsets.sspi[`${method}`].address) : libraryBaseAddress.add(ptr(offsets.sspi[`${method}`].address));
            }
        }
    }
    install_plaintext_read_hook() {
        Interceptor.attach(this.addresses[this.module_name]["DecryptMessage"], {
            onEnter: function (args) {
                this.pMessage = args[1];
            },
            onLeave: function () {
                this.cBuffers = this.pMessage.add(4).readULong(); //unsigned long cBuffers (Count of buffers)
                this.pBuffers = this.pMessage.add(8).readPointer(); //PSecBuffer  pBuffers (Pointer to array of secBuffers)
                //https://docs.microsoft.com/en-us/windows/win32/api/sspi/ns-sspi-secbuffer
                //One SecBuffer got 16 Bytes (unsigned long + unsigned long + pointer (64 Bit))
                //--> Bytes to read: cBuffers + 16 Bytes
                this.secBuffers = []; //Addresses of all secBuffers
                for (let i = 0; i < this.cBuffers; i++) {
                    var secBuffer = this.pBuffers.add(i * 16);
                    this.secBuffers.push(secBuffer);
                }
                for (let i = 0; i < this.secBuffers.length; i++) {
                    var size = this.secBuffers[i].add(0).readULong();
                    var type = this.secBuffers[i].add(4).readULong();
                    var bufferPointer = this.secBuffers[i].add(8).readPointer();
                    if (type == 1) {
                        //TODO: Obtain information from the running process to get the socket information
                        var bytes = bufferPointer.readByteArray(size);
                        var message = {};
                        message["ss_family"] = "AF_INET";
                        message["src_port"] = 444;
                        message["src_addr"] = 222;
                        message["dst_port"] = 443;
                        message["dst_addr"] = 222;
                        message["function"] = "DecryptMessage";
                        message["contentType"] = "datalog";
                        message["ssl_session_id"] = 10;
                        send(message, bytes);
                    }
                }
            }
        });
    }
    install_plaintext_write_hook() {
        Interceptor.attach(this.addresses[this.module_name]["EncryptMessage"], {
            onEnter: function (args) {
                this.pMessage = args[2]; //PSecBufferDesc pMessage (https://docs.microsoft.com/en-us/windows/win32/api/sspi/ns-sspi-secbufferdesc)
                this.cBuffers = this.pMessage.add(4).readULong(); //unsigned long cBuffers (Count of buffers)
                this.pBuffers = this.pMessage.add(8).readPointer(); //PSecBuffer  pBuffers (Pointer to array of secBuffers)
                //https://docs.microsoft.com/en-us/windows/win32/api/sspi/ns-sspi-secbuffer
                //One SecBuffer got 16 Bytes (unsigned long + unsigned long + pointer (64 Bit))
                //--> Bytes to read: cBuffers + 16 Bytes
                this.secBuffers = []; //Addresses of all secBuffers
                for (let i = 0; i < this.cBuffers; i++) {
                    var secBuffer = this.pBuffers.add(i * 16);
                    this.secBuffers.push(secBuffer);
                }
                for (let i = 0; i < this.secBuffers.length; i++) {
                    var size = this.secBuffers[i].add(0).readULong();
                    var type = this.secBuffers[i].add(4).readULong();
                    var bufferPointer = this.secBuffers[i].add(8).readPointer();
                    if (type == 1) {
                        //TODO: Obtain information from the running process
                        var bytes = bufferPointer.readByteArray(size);
                        var message = {};
                        message["ss_family"] = "AF_INET";
                        message["src_port"] = 443;
                        message["src_addr"] = 222;
                        message["dst_port"] = 444;
                        message["dst_addr"] = 222;
                        message["function"] = "EncryptMessage";
                        message["contentType"] = "datalog";
                        message["ssl_session_id"] = 10;
                        send(message, bytes);
                    }
                }
            }
        });
    }
    install_tls_keys_hook() {
        /* Most of the following code fragments were copied from
         * https://github.com/ngo/win-frida-scripts/tree/master/lsasslkeylog-easy
        */
        var client_randoms = {};
        var buf2hex = function (buffer) {
            return Array.prototype.map.call(new Uint8Array(buffer), function (x) { return ('00' + x.toString(16)).slice(-2); }).join('');
        };
        /* ----- TLS1.2-specific ----- */
        var parse_h_master_key = function (pMasterKey) {
            var NcryptSslKey_ptr = pMasterKey; // NcryptSslKey
            var ssl5_ptr = NcryptSslKey_ptr.add(0x10).readPointer();
            var master_key = ssl5_ptr.add(28).readByteArray(48);
            return buf2hex(master_key);
        };
        var parse_parameter_list = function (pParameterList, calling_func) {
            /*
                typedef struct _NCryptBufferDesc {
                    ULONG         ulVersion;
                    ULONG         cBuffers;
                    PNCryptBuffer pBuffers;
                } NCryptBufferDesc, *PNCryptBufferDesc;
                typedef struct _NCryptBuffer {
                    ULONG cbBuffer;
                    ULONG BufferType;
                    PVOID pvBuffer;
                } NCryptBuffer, *PNCryptBuffer;
             */
            var buffer_count = pParameterList.add(4).readU32();
            var buffers = pParameterList.add(8).readPointer();
            for (var i = 0; i < buffer_count; i++) {
                var buf = buffers.add(16 * i);
                var buf_size = buf.readU32();
                var buf_type = buf.add(4).readU32();
                var buf_buf = buf.add(8).readPointer().readByteArray(buf_size);
                // For buf_type values see NCRYPTBUFFER_SSL_* constans in ncrypt.h
                if (buf_type == 20) { // NCRYPTBUFFER_SSL_CLIENT_RANDOM
                    devlog("Got client random from " + calling_func + "'s pParameterList: " + buf2hex(buf_buf));
                    return buf2hex(buf_buf);
                }
            }
            return null;
        };
        if (this.addresses[this.module_name]["SslHashHandshake"] != null)
            Interceptor.attach(this.addresses[this.module_name]["SslHashHandshake"], {
                onEnter: function (args) {
                    // https://docs.microsoft.com/en-us/windows/win32/seccng/sslhashhandshake
                    var buf = ptr(args[2]);
                    var len = args[3].toInt32();
                    var mem = buf.readByteArray(len);
                    var msg_type = buf.readU8();
                    var version = buf.add(4).readU16();
                    if (msg_type == 1 && version == 0x0303) {
                        // If we have client random, save it tied to current thread
                        var crandom = buf2hex(buf.add(6).readByteArray(32));
                        devlog("Got client random from SslHashHandshake: " + crandom);
                        client_randoms[this.threadId] = crandom;
                    }
                },
                onLeave: function (retval) {
                }
            });
        if (this.addresses[this.module_name]["SslGenerateMasterKey"] != null)
            Interceptor.attach(this.addresses[this.module_name]["SslGenerateMasterKey"], {
                onEnter: function (args) {
                    // https://docs.microsoft.com/en-us/windows/win32/seccng/sslgeneratemasterkey
                    this.phMasterKey = ptr(args[3]);
                    this.hSslProvider = ptr(args[0]);
                    this.pParameterList = ptr(args[6]);
                    this.client_random = parse_parameter_list(this.pParameterList, 'SslGenerateMasterKey') || client_randoms[this.threadId] || "???";
                },
                onLeave: function (retval) {
                    var master_key = parse_h_master_key(this.phMasterKey.readPointer());
                    devlog("Got masterkey from SslGenerateMasterKey");
                    keylog("CLIENT_RANDOM " + this.client_random + " " + master_key, 2 /* TLSVersion.ONE_TWO */);
                }
            });
        if (this.addresses[this.module_name]["SslImportMasterKey"] != null)
            Interceptor.attach(this.addresses[this.module_name]["SslImportMasterKey"], {
                onEnter: function (args) {
                    // https://docs.microsoft.com/en-us/windows/win32/seccng/sslimportmasterkey
                    this.phMasterKey = ptr(args[2]);
                    this.pParameterList = ptr(args[5]);
                    // Get client random from the pParameterList, and if that fails - from the value saved by SslHashHandshake handler
                    this.client_random = parse_parameter_list(this.pParameterList, 'SslImportMasterKey') || client_randoms[this.threadId] || "???";
                },
                onLeave: function (retval) {
                    var master_key = parse_h_master_key(this.phMasterKey.readPointer());
                    devlog("[*] Got masterkey from SslImportMasterKey");
                    keylog("CLIENT_RANDOM " + this.client_random + " " + master_key, 2 /* TLSVersion.ONE_TWO */);
                }
            });
        if (this.addresses[this.module_name]["SslGenerateSessionKeys"] != null)
            Interceptor.attach(this.addresses[this.module_name]["SslGenerateSessionKeys"], {
                onEnter: function (args) {
                    // https://docs.microsoft.com/en-us/windows/win32/seccng/sslgeneratesessionkeys
                    this.hMasterKey = ptr(args[1]);
                    this.hSslProvider = ptr(args[0]);
                    this.pParameterList = ptr(args[4]);
                    this.client_random = parse_parameter_list(this.pParameterList, 'SslGenerateSessionKeys') || client_randoms[this.threadId] || "???";
                    var master_key = parse_h_master_key(this.hMasterKey);
                    devlog("Got masterkey from SslGenerateSessionKeys");
                    keylog("CLIENT_RANDOM " + this.client_random + " " + master_key, 2 /* TLSVersion.ONE_TWO */);
                },
                onLeave: function (retval) {
                }
            });
        /* ----- TLS1.3-specific ----- */
        var stages = {};
        var get_secret_from_BDDD = function (struct_BDDD) {
            var struct_3lss = struct_BDDD.add(0x10).readPointer();
            var struct_RUUU = struct_3lss.add(0x20).readPointer();
            var struct_YKSM = struct_RUUU.add(0x10).readPointer();
            var secret_ptr = struct_YKSM.add(0x18).readPointer();
            var size = struct_YKSM.add(0x10).readU32();
            return secret_ptr.readByteArray(size);
        };
        if (this.addresses[this.module_name]["SslExpandTrafficKeys"] != null)
            Interceptor.attach(this.addresses[this.module_name]["SslExpandTrafficKeys"], {
                onEnter: function (args) {
                    this.retkey1 = ptr(args[3]);
                    this.retkey2 = ptr(args[4]);
                    this.client_random = client_randoms[this.threadId] || "???";
                    if (stages[this.threadId]) {
                        stages[this.threadId] = null;
                        this.suffix = "TRAFFIC_SECRET_0";
                    }
                    else {
                        stages[this.threadId] = "handshake";
                        this.suffix = "HANDSHAKE_TRAFFIC_SECRET";
                    }
                },
                onLeave: function (retval) {
                    var key1 = get_secret_from_BDDD(this.retkey1.readPointer());
                    var key2 = get_secret_from_BDDD(this.retkey2.readPointer());
                    keylog("CLIENT_" + this.suffix + " " + this.client_random + " " + buf2hex(key1), 3 /* TLSVersion.ONE_THREE */);
                    keylog("SERVER_" + this.suffix + " " + this.client_random + " " + buf2hex(key2), 3 /* TLSVersion.ONE_THREE */);
                }
            });
        if (this.addresses[this.module_name]["SslExpandExporterMasterKey"] != null)
            Interceptor.attach(this.addresses[this.module_name]["SslExpandExporterMasterKey"], {
                onEnter: function (args) {
                    this.retkey = ptr(args[3]);
                    this.client_random = client_randoms[this.threadId] || "???";
                },
                onLeave: function (retval) {
                    var key = this.retkey.readPointer().add(0x10).readPointer().add(0x20).readPointer().add(0x10).readPointer().add(0x18).readPointer().readByteArray(48);
                    keylog("EXPORTER_SECRET " + this.client_random + " " + buf2hex(key), 3 /* TLSVersion.ONE_THREE */);
                }
            });
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        if (experimental) {
            this.install_tls_keys_hook();
        }
    }
}
export function sspi_execute(moduleName, is_base_hook) {
    var sspi_ssl = new SSPI_Windows(moduleName, socket_library, is_base_hook);
    sspi_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = sspi_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}
✄
{"version":3,"file":"windows_agent.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/windows/windows_agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAqB,MAAM,gCAAgC,CAAC;AAC3F,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAC1G,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAGrD,IAAI,cAAc,GAAG,SAAS,CAAC;AAC/B,IAAI,WA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AAC,OAAO,KAAK,EAAE;QACZ,MAAM,CAAC,gBAAgB,GAAG,KAAK,CAAC,CAAA;QAChC,GAAG,CAAC,wCAAwC,CAAC,CAAA;KAChD;AACL,CAAC;AAED,SAAS,qBAAqB,CAAC,sBAA0E,EAAE,YAAqB;IAC5H,kBAAkB,CAAC,cAAc,EAAE,sBAAsB,EAAC,WAAW,EAAC,SAAS,EAAE,YAAY,CAAC,CAAA;AAClG,CAAC;AAED,MAAM,UAAU,0BAA0B;IACtC,sBAAsB,CAAC,cAAc,CAAC,GAAG;QACrC,CAAC,yCAAyC,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;QAClF,CAAC,8BAA8B,EAAE,qBAAqB,CAAC,eAAe,CAAC,CAAC;QACxE,CAAC,uCAAuC,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;QAChF,CAAC,yBAAyB,EAAE,qBAAqB,CAAC,WAAW,CAAC,CAAC;QAC/D,CAAC,iCAAiC,EAAE,qBAAqB,CAAC,YAAY,CAAC,CAAC;QACxE,CAAC,cAAc,EAAE,qBAAqB,CAAC,eAAe,CAAC,CAAC;QACxD,CAAC,2BAA2B,EAAE,qBAAqB,CAAC,cAAc,CAAC,CAAC;QACpE,CAAC,iBAAiB,EAAE,qBAAqB,CAAC,iBAAiB,CAAC,CAAC;KAAC,CAAA;IAElE,qBAAqB,CAAC,sBAAsB,EAAE,IAAI,CAAC,CAAC;IACpD,2BAA2B,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAAC;AAC/D,CAAC"}
✄
import { module_library_mapping } from "../shared/shared_structures.js";
import { log, devlog } from "../util/log.js";
import { getModuleNames, ssl_library_loader, invokeHookingFunction } from "../shared/shared_functions.js";
import { sspi_execute } from "./sspi.js";
import { boring_execute } from "./openssl_boringssl_windows.js";
import { gnutls_execute } from "./gnutls_windows.js";
import { mbedTLS_execute } from "./mbedTLS_windows.js";
import { nss_execute } from "./nss_windows.js";
import { wolfssl_execute } from "./wolfssl_windows.js";
import { matrixSSL_execute } from "./matrixssl_windows.js";
import { cronet_execute } from "./cronet_windows.js";
var plattform_name = "windows";
var moduleNames = getModuleNames();
export const socket_library = "WS2_32.dll";
function hook_Windows_Dynamic_Loader(module_library_mapping, is_base_hook) {
    try {
        const resolver = new ApiResolver('module');
        var loadLibraryExW = resolver.enumerateMatches("exports:KERNELBASE.dll!*LoadLibraryExW");
        if (loadLibraryExW.length == 0)
            return console.log("[-] Missing windows dynamic loader!");
        Interceptor.attach(loadLibraryExW[0].address, {
            onLeave(retval) {
                let map = new ModuleMap();
                let moduleName = map.findName(retval);
                if (moduleName === null)
                    return;
                for (let map of module_library_mapping[plattform_name]) {
                    let regex = new RegExp(map[0]);
                    let func = map[1];
                    if (regex.test(moduleName)) {
                        log(`${moduleName} was loaded & will be hooked on Windows!`);
                        try {
                            func(moduleName, is_base_hook);
                        }
                        catch (error_msg) {
                            devlog(`Windows dynamic loader error: ${error_msg}`);
                        }
                        log("\n[*] Remember to hook the default SSL provider for the Windows API you have to hook lsass.exe\n");
                    }
                }
            }
        });
        log("[*] Windows dynamic loader hooked.");
    }
    catch (error) {
        devlog("Loader error: " + error);
        log("No dynamic loader present for hooking.");
    }
}
function hook_Windows_SSL_Libs(module_library_mapping, is_base_hook) {
    ssl_library_loader(plattform_name, module_library_mapping, moduleNames, "Windows", is_base_hook);
}
export function load_windows_hooking_agent() {
    module_library_mapping[plattform_name] = [
        [/^(libssl|LIBSSL)-[0-9]+(_[0-9]+)?\.dll$/, invokeHookingFunction(boring_execute)],
        [/^.*(wolfssl|WOLFSSL).*\.dll$/, invokeHookingFunction(wolfssl_execute)],
        [/^.*(libgnutls|LIBGNUTLS)-[0-9]+\.dll$/, invokeHookingFunction(gnutls_execute)],
        [/^(nspr|NSPR)[0-9]*\.dll/, invokeHookingFunction(nss_execute)],
        [/(sspicli|SSPICLI|SspiCli)\.dll$/, invokeHookingFunction(sspi_execute)],
        [/mbedTLS\.dll/, invokeHookingFunction(mbedTLS_execute)],
        [/^.*(cronet|CRONET).*\.dll/, invokeHookingFunction(cronet_execute)],
        ["/matrixSSL\.dll", invokeHookingFunction(matrixSSL_execute)]
    ];
    hook_Windows_SSL_Libs(module_library_mapping, true);
    hook_Windows_Dynamic_Loader(module_library_mapping, false);
}
✄
{"version":3,"file":"wolfssl_windows.js","sourceRoot":"/Users/danielbaier/research/projects/github/issues/2024 fritap issues/2025_steil/friTap/","sources":["agent/windows/wolfssl_windows.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AAErC,MAAM,OAAO,eAAgB,SAAQ,OAAO;IAExC,YAAmB,UAAiB,EAAS,cAAqB,EAAE,YAAqB;QACrF,IAAI,OAAO,GAAoC,EAAE,CAAC;QAClD,OAAO,CAAC,GAAG,UAAU,EAAE,CAAC,GAAG,CAAC,cAAc,EAAE,eAAe,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,oBAAoB,CAAC,CAAA;QAC9I,OAAO,CAAC,IAAI,cAAc,GAAG,CAAC,GAAG,CAAC,aAAa,EAAE,aAAa,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;QACjF,KAAK,CAAC,UAAU,EAAC,cAAc,EAAE,OAAO,CAAC,CAAC;QAJ3B,eAAU,GAAV,UAAU,CAAO;QAAS,mBAAc,GAAd,cAAc,CAAO;IAKlE,CAAC;IAGD,8BAA8B;QAC1B,GAAG,CAAC,uDAAuD,CAAC,CAAC;IACjE,CAAC;IAKD,aAAa;QACT,IAAI,CAAC,2BAA2B,EAAE,CAAC;QACnC,IAAI,CAAC,4BAA4B,EAAE,CAAC;QACpC,kEAAkE;IACtE,CAAC;CAEJ;AAGD,MAAM,UAAU,eAAe,CAAC,UAAiB,EAAE,YAAqB;IACpE,IAAI,QAAQ,GAAG,IAAI,eAAe,CAAC,UAAU,EAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IAC5E,QAAQ,CAAC,aAAa,EAAE,CAAC;IAEzB,IAAI,YAAY,EAAE;QACd,MAAM,cAAc,GAAG,QAAQ,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACtD,wDAAwD;QACxD,IAAI,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAc,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,cAAc,CAAC;SAC/D;KACJ;AACL,CAAC"}
✄
import { WolfSSL } from "../ssl_lib/wolfssl.js";
import { socket_library } from "./windows_agent.js";
import { log } from "../util/log.js";
export class WolfSSL_Windows extends WolfSSL {
    constructor(moduleName, socket_library, is_base_hook) {
        let mapping = {};
        mapping[`${moduleName}`] = ["wolfSSL_read", "wolfSSL_write", "wolfSSL_get_fd", "wolfSSL_get_session", "wolfSSL_connect", "wolfSSL_KeepArrays"];
        mapping[`*${socket_library}*`] = ["getpeername", "getsockname", "ntohs", "ntohl"];
        super(moduleName, socket_library, mapping);
        this.moduleName = moduleName;
        this.socket_library = socket_library;
    }
    install_tls_keys_callback_hook() {
        log("Key extraction currently not implemented for windows!");
    }
    execute_hooks() {
        this.install_plaintext_read_hook();
        this.install_plaintext_write_hook();
        //this.install_tls_keys_callback_hook(); currently not implemented
    }
}
export function wolfssl_execute(moduleName, is_base_hook) {
    var wolf_ssl = new WolfSSL_Windows(moduleName, socket_library, is_base_hook);
    wolf_ssl.execute_hooks();
    if (is_base_hook) {
        const init_addresses = wolf_ssl.addresses[moduleName];
        // ensure that we only add it to global when we are not 
        if (Object.keys(init_addresses).length > 0) {
            global.init_addresses[moduleName] = init_addresses;
        }
    }
}

