frida修改安卓设备信息,imsi、imei、mac、utdid等设备信息生成算法

啥也不说了,直接上代码,好多文章莫名其妙就被删除了,不得不说资本的力量真是强大,以下代码仅供交流学习,都是chatgpt生成的,如有侵权请找gpt!

function main() {
    Java.perform(function()
    {
        
        function modifyUtdid(){
            var SettingsSystem = Java.use('android.provider.Settings$System');
        
            // 获取 android.content.Context 类的引用
            var Context = Java.use('android.content.Context');
            
            // 获取当前应用的 Context 实例
            var appContext = Java.use('android.app.ActivityThread').currentApplication().getApplicationContext();
            
            // 删除
            SettingsSystem.putString.call(SettingsSystem, appContext.getContentResolver(), 'mqBRboGZkQPcAkyk', null);
            SettingsSystem.putString.call(SettingsSystem, appContext.getContentResolver(), 'dxCRMxhQkdGePGnp', null);
        };

        
        var newModel = "Pixel 4 XL";
        var newManufacturer = "Google";
        var newBrand = "google";
        var newDevice = "Pixel_4_XL";
        var newProduct = "Pixel_4_XL";
        var newID = "RQ3A.210905.001";
        var newSerialNumber = "3LJ9VCBI8J0M7DYL"


        // 获取android.os.Build类的引用
        var Build = Java.use('android.os.Build');

        // 修改属性值
        Build.MODEL.value = newModel;
        Build.MANUFACTURER.value = newManufacturer;
        Build.BRAND.value = newBrand;
        Build.DEVICE.value = newDevice;
        Build.PRODUCT.value = newProduct;
        Build.ID.value = newID;
        Build.SERIAL.value = newSerialNumber;
        

        console.log("Device properties changed successfully.");

        var Signature = Java.use('com.yunos.tvtaobao.uuid.security.Signature');
        Signature.sign.implementation = function(priKey,str){
            // console.log("priKey:"+priKey)
            // console.log("str:"+str)
            var result = this.sign(priKey,str);
            // console.log("sign:"+result)
            return result
        }
        Signature.bytesToHexStr.implementation = function(bcd){
            var result = this.bytesToHexStr(bcd);
            console.log("bytesToHexStr:"+result)
            return result
        }
        var SGMWrapper = Java.use("com.yunos.tvtaobao.uuid.utils.SGMWrapper");
        SGMWrapper.encryptUUID.implementation = function(uuid){
            var result = this.encryptUUID(uuid);
            console.log("uuid:"+result)
            console.log("encryptUUID:"+result)
            return result
        }
        var NetworkSdkSetting = Java.use("anetwork.channel.http.NetworkSdkSetting")
        NetworkSdkSetting.init.overload("android.app.Application","java.util.HashMap").implementation = function(application,params){
            var tb_name = this.init(application,params);
            console.log("params:"+params.tostring()) 
        }

        var TelephonyManager = Java.use('android.telephony.TelephonyManager');
        var getSubscriberIdMethod = TelephonyManager.getSubscriberId.overload();
        getSubscriberIdMethod.implementation = function() {
            return Java.use('java.lang.String').valueOf("460001683194238");
        };

        
        var TelephonyManager = Java.use('android.telephony.TelephonyManager');
        var getDeviceIdMethod = TelephonyManager.getDeviceId.overload();
        getDeviceIdMethod.implementation = function() {
            return Java.use('java.lang.String').valueOf("223424882910925");
        };

        var WifiInfo = Java.use('android.net.wifi.WifiInfo');
        var getMacAddressMethod = WifiInfo.getMacAddress.overload();
        getMacAddressMethod.implementation = function() {
            return Java.use('java.lang.String').valueOf("E4:CF:41:75:0F:A1");
        };
        var ZPDeviceImpl = Java.use('com.tvtao.user.dclib.impl.ZPDeviceImpl');
        ZPDeviceImpl.getWifiMac.implementation = function(ct){
            var result = this.getWifiMac(ct);
            console.log("getWifiMac:"+result);
            return "E4:9E:E2:2B:DB:75"
        }

        var Secure = Java.use('android.provider.Settings$Secure');
        Secure.getString.overload('android.content.ContentResolver', 'java.lang.String').implementation = function(contentResolver, name) {
            if (name === 'android_id') {
                return "7efa777a98538df8db12ea1e2866ea8351d83d8a";
            }
            return this.getString(contentResolver, name);
        };
        
        console.log("WifiInfo changed successfully.");

       
       
        var newCpuInfo = 'processor\t: 0\n' +
            'model name\t: Custom CPU\n' +
            'BogoMIPS\t: 200.00\n' +
            'Features\t: fp asimd evtstrm aes pmull sha1 sha2 crc32\n' +
            'CPU implementer\t: 0x41\n' +
            'CPU architecture: 8\n' +
            'CPU variant\t: 0x0\n' +
            'CPU part\t: 0xd03\n' +
            'CPU revision\t: 4\n';
    
        var openFunc = Module.findExportByName(null, "open");
        var readFunc = Module.findExportByName(null, "read");
    
        var openPtr = Interceptor.attach(openFunc, {
            onEnter: function (args) {
                var path = Memory.readUtf8String(args[0]);
                if (path === "/proc/cpuinfo") {
                    this.cpuInfoReplace = true;
                }
            },
            onLeave: function (retval) {
                if (this.cpuInfoReplace) {
                    this.fd = retval.toInt32();
                }
            }
        });
    
        var readPtr = Interceptor.attach(readFunc, {
            onEnter: function (args) {
                if (this.cpuInfoReplace && args[0].toInt32() === this.fd) {
                    var buf = args[1];
                    var cpuInfoBuf = Memory.allocUtf8String(newCpuInfo);
                    Memory.copy(buf, cpuInfoBuf, newCpuInfo.length);
                    this.cpuInfoRead = true;
                }
            },
            onLeave: function (retval) {
                if (this.cpuInfoRead) {
                    retval.replace(newCpuInfo.length);
                }
            }
        });
    
        console.log("CPU information changed successfully.");    

}
setImmediate(main)
# -*- coding: utf-8 -*-
import os
import sys
import string
import json
import hashlib
import random
import subprocess
import time


def genDescription(line, release, name):
    value = line.split("=")[1]
    list_value = value.split(" ")
    list_value[0] = name.replace(' ', '') + "-user"
    list_value[1] = release
    description = ' '.join(list_value)
    return description


def genFinger(line, release, model, brand, name):
    value = line.split("=")[1]
    list_value = value.split("/")
    list_value[0] = brand
    list_value[1] = name.replace(' ', '')
    list_value[2] = name.replace(' ', '') + ":" + release
    finger = '/'.join(list_value)
    return finger


def modify(release, model, brand, name, manufacturer):
    for line in open("./o/build.prop"):
        rline = line
        if "ro.build.version.release=" in line:
            rline = "ro.build.version.release=" + str(release) + "\n"
        elif "ro.product.model=" in line:
            rline = "ro.product.model=" + str(model) + "\n"
        elif "ro.product.brand=" in line:
            rline = "ro.product.brand=" + str(brand) + "\n"
        elif "ro.product.name=" in line:
            rline = "ro.product.name=" + str(name) + "\n"
        elif "ro.product.manufacturer=" in line:
            rline = "ro.product.manufacturer=" + str(manufacturer) + "\n"
        elif "ro.build.description=" in line:
            rline = "ro.build.description=" + str(genDescription(line, release, name)) + "\n"
        elif "ro.build.finger=" in line:
            rline = "ro.build.finger=" + str(genFinger(line, release, model, brand, name)) + "\n"

        with open("./n/build.prop", "a") as f:
            f.write(rline)


def main_modify():
    json_data = open("phone.json",encoding='utf-8').read()
    json_data = json.loads(json_data)
    array_phone = json_data['phone']
    pid = random.randint(0, len(array_phone))
    item_phone = array_phone[pid]
    name = item_phone['name']
    manufacturer = item_phone['manufacturer']
    model = item_phone['model']

    array_release = json_data['release']
    rid = random.randint(0, len(array_release))
    release = array_release[rid]

    brand = manufacturer
    if os.path.exists("./n/build.prop"):
        os.remove("./n/build.prop")
    modify(release, model, brand, name, manufacturer)





def run_adb_command(command):
    try:
        subprocess.check_output(["adb"] + command.split(" "))
    except Exception as e:
        print("Error: ", e)
        return None


def change_device_properties():
    # 修改设备型号
    new_model = "Pixel 4 XL"
    run_adb_command(f"shell setprop ro.product.model {new_model}")

    # 修改设备制造商
    new_manufacturer = "Google"
    run_adb_command(f"shell setprop ro.product.manufacturer {new_manufacturer}")

    # 修改设备品牌
    new_brand = "google"
    run_adb_command(f"shell setprop ro.product.brand {new_brand}")

    # 修改设备版本号
    new_version = "12.0"
    run_adb_command(f"shell setprop ro.build.version.release {new_version}")

    print("Device properties changed successfully.")



def generate_custom_mac():
    """
    Wi-Fi MAC(Media Access Control)地址是一个设备在局域网中进行通信时所使用的唯一硬件标识符。
    它由12个十六进制字符组成,通常以6组2位字符的形式表示,例如:A1:B2:C3:D4:E5:F6。
    在现实生活中,Wi-Fi MAC地址是由网络接口控制器(NIC)的制造商分配的,确保世界范围内的唯一性。
    然而,你也可以生成一个伪造的Wi-Fi MAC地址,以用于某些特定场景,如测试、隐私保护等。以下是生成随机Wi-Fi MAC地址的方法.
    Wi-Fi BSSID 通常与AP的MAC地址相同
    :return:
    """
    return "E4:%02X:%02X:%02X:%02X:%02X" % (
        random.randint(0, 255),
        random.randint(0, 255),
        random.randint(0, 255),
        random.randint(0, 255),
        random.randint(0, 255),
    )


def generate_random_imei():
    """
    IMEI(International Mobile Equipment Identity,国际移动设备识别码)是一个15位数的唯一标识符,
    用于识别GSM、UMTS、LTE和其他无线通信设备。IMEI码通常由四个部分组成:
    TAC(Type Allocation Code,型号分配代码):前8位,由制造商申请获得。
    SNR(Serial Number,序列号):接下来的6位,由制造商分配给每个设备的唯一序列号。
    Luhn校验码:最后1位,用于确保IMEI码的有效性。
    要生成一个随机的IMEI码,你可以遵循以下步骤:
    1、生成一个14位的随机数字字符串。
    2、计算Luhn校验码并将其添加到随机数字字符串的末尾。
    :return:
    """
    imei_base = [random.randint(0, 9) for _ in range(14)]

    def calculate_luhn_checksum(digits):
        checksum = 0
        for i, digit in enumerate(digits):
            if i % 2 == 0:
                doubled_digit = digit * 2
                if doubled_digit > 9:
                    doubled_digit -= 9
                checksum += doubled_digit
            else:
                checksum += digit
        return (10 - (checksum % 10)) % 10

    imei_base.append(calculate_luhn_checksum(imei_base))
    return ''.join(map(str, imei_base))


def generate_random_imsi(mcc, mnc):
    """
    # 中国移动(MCC:460,MNC:00或02或07或08)
    :param mcc:MCC(Mobile Country Code,移动国家码):3位数字,表示国家/地区。
    :param mnc:MNC(Mobile Network Code,移动网络码):2或3位数字,表示特定的移动运营商。
    :return:
    """
    msin = ''.join(str(int(time.time())))
    return mcc + mnc + msin


import base64
import struct


def decode_unique_id(encoded_unique_id):
    # Base64解码
    decoded_bytes = base64.b64decode(encoded_unique_id)

    # 将字节转换为四个整数
    t1, t2, t3, t4 = struct.unpack('>IIII', decoded_bytes)

    return t1, t2, t3, t4

def generate_serial_number(length=16):
    """
    安卓设备序列号
    :param length:
    :return:
    """
    characters = string.ascii_uppercase + string.digits
    serial_number = ''.join(random.choice(characters) for _ in range(length))
    return serial_number

def generate_device_info():
    android_version = "Android " + str(random.randint(2, 12)) + "." + str(random.randint(0, 4))
    device_type = random.choice(["Phone", "Tablet", "Smart TV"])
    manufacturer = random.choice(["Samsung", "Google", "Xiaomi", "OnePlus", "Huawei", "LG", "Sony"])
    model = ""
    if manufacturer == "Samsung":
        model = random.choice(["Galaxy S21", "Galaxy S20", "Galaxy Note 20", "Galaxy A52"])
    elif manufacturer == "Google":
        model = random.choice(["Pixel 6", "Pixel 5", "Pixel 4a", "Pixel 3"])
    elif manufacturer == "Xiaomi":
        model = random.choice(["Redmi Note 10", "Mi 11", "Mi 10T", "Poco X3"])
    elif manufacturer == "OnePlus":
        model = random.choice(["OnePlus 9 Pro", "OnePlus 8T", "OnePlus Nord 2", "OnePlus 7T"])
    elif manufacturer == "Huawei":
        model = random.choice(["Mate 40 Pro", "P40 Pro", "Nova 8", "Honor V40"])
    elif manufacturer == "LG":
        model = random.choice(["LG V60 ThinQ", "LG Velvet", "LG G8 ThinQ", "LG K92 5G"])
    elif manufacturer == "Sony":
        model = random.choice(["Xperia 1 III", "Xperia 5 II", "Xperia 10 II", "Xperia L4"])
    return [manufacturer,model,device_type,android_version]

def generate_android_id(hardware_info, system_info):
    input_str = hardware_info + system_info
    sha1 = hashlib.sha1(input_str.encode())
    android_id = sha1.hexdigest()
    return android_id

if __name__ == "__main__":
    random_mac = generate_custom_mac()
    print(random_mac)
    mcc = "460"
    mnc = "00"
    random_imsi = generate_random_imsi(mcc, mnc)
    print(random_imsi)
    print(generate_random_imei())
    print(generate_serial_number())
    change_device_properties()


你可能感兴趣的:(app逆向,android,算法)