示例#1
0
def frida_runner(app_name, script_name, verbose, host):
    """
    Attach Frida script to an app running on a device
    """
    try:
        content = open(script_name, 'r').read()

        device_id = DEVICE_ID_PLACEHOLDER
        script_text = SCRIPT_WRAPPER % locals()
        script_text = script_text % 1

        if verbose:
            _print_with_line_no(script_text)

        print('Starting session...')
        if host:
            remote_device = frida.get_device_manager().add_remote_device(host)
            session = remote_device.attach(app_name)
        else:
            session = frida.get_usb_device().attach(app_name)
        script = session.create_script(script_text)

        script.on('message', on_message)
        script.load()

        print('Connected')
        sys.stdin.read()

    except Exception as e:
        print(e)
示例#2
0
def init_session():
    try:
        session = None
        if platform == 'ios' or platform == 'android':
            try:
                device = frida.get_usb_device()
            except Exception as e:
                print colored(str(e), "red")
                traceback.print_exc()
                if platform == 'android':
                    print colored("Troubleshooting Help", "blue")
                    print colored("HINT: Is USB Debugging enabled?", "blue")
                    print colored("HINT: Is `frida-server` running on mobile device (with +x permissions)?", "blue")
                    print colored("HINT: Is `adb` daemon running?", "blue")
                    sys.exit(1)
                elif platform == "ios":
                    print colored("Troubleshooting Help", "blue")
                    print colored("HINT: Have you installed `frida` module from Cydia?", "blue")
                    print colored("HINT: Have used `ipa_installer` to inject the `FridaGadget` shared lbrary?", "blue")
                    sys.exit(1)
        elif platform == 'macos':
            device = frida.get_local_device()
        else:
            print colored('[ERROR] Unsupported Platform', 'red')
            sys.exit(1)
        pid = None
        if app_name:
            try:
                if platform == 'android' and spawn == 1:
                    print colored("Now Spawning %s" % app_name, "green")
                    pid = device.spawn([app_name])
                    time.sleep(5)
                    session = device.attach(pid)
                    time.sleep(5)
                elif (platform == 'ios' or platform == 'macos') and spawn == 1:
                    bundleID = getBundleID(device, app_name, platform)
                    if bundleID:
                        print colored("Now Spawning %s" % bundleID, "green")
                        pid = device.spawn([bundleID])
                        time.sleep(5)
                        session = device.attach(pid)
                    else:
                        print colored("[ERROR] Can't spawn %s" % app_name, "red")
                        traceback.print_exc()
                        sys.exit(1)
                else:
                    session = device.attach(app_name)
            except Exception as e:
                print colored('[ERROR] ' + str(e), 'red')
                traceback.print_exc()
        if session:
            print colored('[INFO] Attached to %s' % (app_name), 'yellow')
            session.on('detached', on_detached)
    except Exception as e:
        print colored('[ERROR] ' + str(e), 'red')
        traceback.print_exc()
        sys.exit(1)
    return device, session, pid
示例#3
0
def main():
	if args.show_devices:
		for i,device in enumerate(frida.get_device_manager().enumerate_devices()):
			print "Index: {} | {}".format(i,device)
		return

	#Get device
	if args.device is None: #no args supplied, use USB
		device = frida.get_usb_device()
	else: #use device_id if supplied
		device = get_device(args.device)


	printlog("Device Connected: {}".format(device.name), 'ok')

	try:
		pid = device.spawn([package_name]) #spawned process with pid at suspended state
	except (frida.TransportError, frida.NotSupportedError, frida.ExecutableNotFoundError) as e:
		printlog(e.message, 'error')
		return
	except Exception:
		raise
	printlog("Spawned target with PID: {}".format(pid), 'debug')

	process = device.attach(pid) #get a debug session from pid
	printlog("Process attached!", 'ok')
	device.resume(pid) #resume process from suspended state

	#Create dumps directory, if it does not exist
	if not os.path.exists(dump_directory_location):
	    os.makedirs(dump_directory_location)
	    printlog( "Created Dumps Directory: {}".format(dump_directory_location), 'debug')
	else:
		printlog( "Dumps Directory: {}".format(dump_directory_location), 'debug')

	script = process.create_script(instrument_debugger_checks())
	script.on('message',get_messages_from_js)
	printlog("Hook script start!", 'debug')

	script.load()
	try:
		sys.stdin.read()
	except KeyboardInterrupt:
		printlog("\r", 'raw')
		printlog("Abort script acknowledged, cleaning up...".format(pid))
		device.kill(pid)
		printlog("Killed target with PID: {}".format(pid), 'debug')
		printlog("Script Exit.")
		return
	except Exception:
		raise
示例#4
0
def begin_instrumentation(appName, script_source):
    device = frida.get_usb_device()
    try:
        session = device.attach(appName)
    except Exception as e:
        print colored('[ERROR]: ' + str(e), "red")
        sys.exit()
    try:
        script = session.create_script(script_source)
        script.on('message', on_message)
        script.load()
    except Exception as e:
        print colored('[ERROR]: ' + str(e), "red")
        sys.exit()
示例#5
0
    def __init__(self, handlers, device=None):
        """
        Initialize the Injector with a mapping apps to handlers.

        :param handlers: A mapping between a process we want to hook and a handler.
        Each handler provides the script we want to inject and an optional on_message function.
        :type handlers: dict
        :param device: An attached device or None if you want to attach to the USB device.
        :type device: frida.core.Device
        """
        self.device = device or frida.get_usb_device()
        self.handlers = handlers
        self._pending = []
        self.active_sessions = []
        self._do_spawn_gating = False
        self._event = threading.Event()
示例#6
0
    def __spawn_and_inject__(self, package_name, script_path):
        """
        :param package_name:
        :param script_path:
        :return:
        """
        print(f"[*] Staring at {datetime.now().strftime('%H:%M:%S')}")

        if os.path.isabs(script_path) is False:
            script_path = os.path.abspath(script_path)

        output_script = os.path.join(self.temp_script_path,
                                     os.path.basename(script_path))
        self.__compile_javascript__(script_path, output_script)

        script_content = open(output_script, encoding="utf-8").read()
        script_content = script_content.replace("__PACKAGE_NAME__", package_name)

        device = frida.get_usb_device()

        pid = self.__get_process_pid__(device, package_name)
        if pid != -1:
            device.kill(package_name)
            time.sleep(0.1)

        self.exec_command("adb", "shell", "monkey", "-p",
                          package_name, "-c", "android.intent.category.LAUNCHER", "1")

        pid = -1
        for i in range(15):
            pid = self.__get_process_pid__(device, package_name)
            if pid != -1:
                break
            time.sleep(0.05)

        if pid == -1:
            logger.error(f"Run package {package_name} failed.")
            return

        logger.info(f"Injecting {os.path.basename(script_path)} to {package_name}({pid})")

        self.__start_session__(device, pid, script_content)
示例#7
0
文件: module.py 项目: mwrlabs/needle
    def module_pre(self):
        def launch_spawn():
            # Launching the app
            self.printer.info("Spawning the app...")
            pid = device.spawn([self.APP_METADATA['bundle_id']])
            # Attaching to the process
            self.printer.info("Attaching to process: %s" % pid)
            self.session = device.attach(pid)
            if self.options['resume']:
                self.printer.verbose("Resuming the app's process...")
                device.resume(pid)
        def launch_attach():
            # Launching the app
            self.printer.info("Launching the app...")
            self.device.app.open(self.APP_METADATA['bundle_id'])
            pid = int(self.device.app.search_pid(self.APP_METADATA['binary_name']))
            # Attaching to the process
            self.printer.info("Attaching to process: %s" % pid)
            self.session = device.attach(pid)

        # Run FridaModule setup function
        FridaModule.module_pre(self)
        # Get an handle to the device
        import frida
        if self.device.is_usb():
            self.printer.debug("Connected over USB")
            device = frida.get_usb_device()
        else:
            self.printer.debug("Connected over Wi-Fi")
            device = frida.get_device_manager().enumerate_devices()[1]
        # Spawn/attach to the process
        if self.options['spawn']:
            launch_spawn()
        else:
           launch_attach()
        # Prepare results
        self.results = []
        return 1
示例#8
0
def init_session():
	try:
		session = None
		if platform == 'ios' or platform == 'android':
			device = frida.get_usb_device()
		elif platform == 'mac':
			device = frida.get_local_device()
		else:
			print colored('[ERROR] Unsupported platform', 'red')
			sys.exit()
		if app_name:
			try:
				session = device.attach(app_name)
			except Exception as e:
				print colored('[ERROR] ' + str(e), 'red')
				traceback.print_exc()
		if session:
			print colored('[INFO] Attached to %s' % (app_name), 'yellow')
			session.on('detached', on_detached)
	except Exception as e:
		print colored('[ERROR] ' + str(e), 'red')
		traceback.print_exc()
		sys.exit(1)
	return device, session
示例#9
0
def show_packages():
    global device
    try:
        remote = request.args.get('remote')
        if device == None:
            if len(remote) != 0:
                # check remote ip address
                try:
                    socket.inet_aton(remote)
                    print "adding remote device to device manager : ",remote
                    device=frida.get_device_manager().add_remote_device(remote)
                    print "remote device : ", device
                except socket.error:
                    return render_template('intro.html')
            else:
                device = frida.get_usb_device()

        # get list of apps
        packages=device.enumerate_processes()
        print packages
    except frida.ServerNotRunningError :
        return render_template('error.html',error="cannot connect to remote :(")
    return render_template('packages_list.html',
                           packages=packages)
                send("Hooked the target method : " + sel);

                var obj = ObjC.Object(args[2]);
                send("[+] File : " + obj.toString());
                
		var obj = ObjC.Object(args[3]);
                send("[+] Content : " + obj.toString());
                
		var obj = ObjC.Object(args[4]);
                send("[+] Attributes : " + obj.toString());
            }
        });
    } else {
        console.log("Objective-C Runtime is not available!");
    }


    """

    return hook

if __name__ == '__main__':
    try:
        session = frida.get_usb_device().attach(str(sys.argv[1]))
        script = session.create_script(do_hook())
        script.on('message', on_message)
        script.load()
        sys.stdin.read()
    except KeyboardInterrupt:
        sys.exit(0)
示例#11
0
import frida, sys


def on_message(message, data):
    if message['type'] == 'send':
        print("[*] {0}".format(message['payload']))
    else:
        print(message)


jscode = """
Java.perform(function () {
    var MainActivity = Java.use('com.example.seccon2015.rock_paper_scissors.MainActivity');
    MainActivity.onClick.implementation = function (v) {
        send("Hook Start...");
        this.onClick(v);
        this.n.value = 0;
        this.m.value = 2;
        this.cnt.value = 999;
        send("Success!")
    }
});
"""

process = frida.get_usb_device().attach(
    'com.example.seccon2015.rock_paper_scissors')
script = process.create_script(jscode)
script.on('message', on_message)
script.load()
sys.stdin.read()
示例#12
0
import frida, sys


def on_message(message, data):
    if message['type'] == 'send':
        print("[*] {0}".format(message['payload']))
    else:
        print(message)


jscode = """
Java.perform(function () {
    var MainActivity = Java.use('com.android.insecurebankv2.PostLogin');
    MainActivity.doesSUexist.implementation = function () {
        console.log('Done: doesSUexist');
		return false;
    };
	
	MainActivity.doesSuperuserApkExist.implementation = function (b) {
        console.log('Done: doesSuperuserApkExist');
		return false;
    };
});
"""

process = frida.get_usb_device().attach('com.android.insecurebankv2')
script = process.create_script(jscode)
script.on('message', on_message)
script.load()
sys.stdin.read()
示例#13
0
        util.getMsg.implementation = function(){
            console.log("Hook Start...");
            console.log("return : " + this.getMsg());
            return this.getMsg();
        }
    });
}
"""


def on_message(message, data):
    if message['type'] == 'send':
        print(" {0}".format(message['payload']))
    else:
        print(message)


# 查找USB设备并附加到目标进程
session = frida.get_usb_device().attach('com.qzdsp.tiktok')

# 在目标进程里创建脚本
script = session.create_script(jscode)

# 注册消息回调
script.on('message', on_message)

# 加载创建好的javascript脚本
script.load()

# 读取系统输入
sys.stdin.read()
			var extra = extraByteMap[(ch >> 3) & 0x07];
			if (!(ch & 0x40) || !extra || ((index + extra) > count))
			  return null;
			
			ch = ch & (0x3F >> extra);
			for (;extra > 0;extra -= 1)
			{
			  var chx = bArray[index++];
			  if ((chx & 0xC0) != 0x80)
				return null;
			  
			  ch = (ch << 6) | (chx & 0x3F);
			}
		  }
		  
		  str += String.fromCharCode(ch);
		}
	
		console.log("HMAC-Key: "+str);
		
		return this.init(v);
    };
});
"""

process = frida.get_usb_device(1).attach('com.tellm.android.app')
script = process.create_script(jscode)
script.on('message', on_message)
print('Running...')
script.load()
sys.stdin.read()
示例#15
0
		},
		onLeave: function(retval) {
					console.log("INPUT AFTER END OF FUNCTION:");
					var buf = Memory.readByteArray(this.bufPtr, this.bufLen);
					console.log(hexdump(buf, {
					  offset: 0,
					  length: this.bufLen,
					  header: true,
					  ansi: true
					}));
		}
	});
        """

        return hook_code

device = frida.get_usb_device()
print u"Device Found: {}".format(device.name)

pid = device.spawn([package_name]) #spawned process with pid at suspended state
print "Spawned with PID: {}".format(pid)

process = device.attach(pid) #get a debug session from pid
print "Process attached!"
device.resume(pid) #resume process from suspended state

script = process.create_script(instrument_debugger_checks())
script.on('message',get_messages_from_js)
script.load()
sys.stdin.read()
示例#16
0
import frida
import sys

if __name__ == '__main__':
    jscode = open('script.js', 'r').read()
    process = frida.get_usb_device().attach('com.ss.android.ugc.aweme')
    script = process.create_script(jscode)
    print('[*] Running CTF')
    script.load()
    sys.stdin.read()
    rSAPublicKeySpec.$init.overload('java.math.BigInteger','java.math.BigInteger').implementation = function (a,b) {
        showStacks();
        var result = this.$init(a,b);
        send("======================================");
        //send("RSA密钥:" + bytesToBase64(a));
        send("RSA密钥N:" + a.toString(16));
        send("RSA密钥E:" + b.toString(16));
        return result;
    }
});
"""

print(sys.argv[1])
fw = open(sys.argv[1], 'w+', encoding='utf-8')


def message(message, data):
    if message["type"] == 'send':
        # print(u"[*] {0}".format(message['payload']))
        fw.write(u"[*] {0}\n".format(message['payload']))
        fw.flush()
    else:
        # print(message)
        pass


process = frida.get_usb_device().attach(sys.argv[1])
script = process.create_script(jsCode)
script.on("message", message)
script.load()
sys.stdin.read()
示例#18
0
            }
            var ret = this.getProperty(param1);
            return ret;
        }
    });
}
"""


def on_message(message, data):
    if message['type'] == 'send':
        print(" {0}".format(message['payload']))
    else:
        print(message)


# 查找USB设备并附加到目标进程
session = frida.get_usb_device().attach('com.fenzotech.jimu')

# 在目标进程里创建脚本
script = session.create_script(jscode)

# 注册消息回调
script.on('message', on_message)

# 加载创建好的javascript脚本
script.load()

# 读取系统输入
sys.stdin.read()
示例#19
0
def attchProcess(processname):
    process = frida.get_usb_device().attch(processname)
示例#20
0
        return

    if (message['payload']['function'] == 'SharedPrefernece'):
        sharedPreference_hook(message)

    else:
        pass


if __name__ == "__main__":
    # pcap logging
    print("[+] START")
    print("[I] Press Ctrl+C to stop logging.")

    if (1 == 1):
        session = frida.get_usb_device().attach(application)
    else:
        device = frida.get_usb_device()
        pid = device.spawn(application)
        device.attach(pid)
        device.resume(pid)

    script = session.create_script(_FRIDA_SCRIPT)
    script.on('message', on_message)
    script.load()

    try:
        sys.stdin.read()
    except KeyboardInterrupt:
        pass
    session.detach()
示例#21
0
            console.log(param3);
            console.log(param4);
            console.log(param5);
            this.$init("Leo","man",18,99.5,true);
        }
    });
}
"""


def on_message(message, data):
    if message['type'] == 'send':
        print(" {0}".format(message['payload']))
    else:
        print(message)


# 查找USB设备并附加到目标进程
session = frida.get_usb_device().attach('com.my.fridademo')

# 在目标进程里创建脚本
script = session.create_script(jscode)

# 注册消息回调
script.on('message', on_message)

# 加载创建好的javascript脚本
script.load()

# 读取系统输入
sys.stdin.read()
示例#22
0
        var Classz = Java.use("java.net.URL");
        Classz.$init.overload("java.lang.String").implementation=function(param1){
            console.log(param1);
            this.$init(param1);
        }
    });
}
"""


def on_message(message, data):
    if message['type'] == 'send':
        print(" {0}".format(message['payload']))
    else:
        print(message)


# 查找USB设备并附加到目标进程
session = frida.get_usb_device().attach('com.wuba')

# 在目标进程里创建脚本
script = session.create_script(jscode)

# 注册消息回调
script.on('message', on_message)

# 加载创建好的javascript脚本
script.load()

# 读取系统输入
sys.stdin.read()
        Java.perform(function () {

            var TM = Java.use("android.os.Debug");

            TM.isDebuggerConnected.implementation = function () {

                send("Called - isDebuggerConnected()");

            return false;
            };

            var TMS = Java.use("android.telephony.TelephonyManager");
            TMS.getDeviceId.implementation = function () {
                send("Called - deviceID()");
                return "pwn3d";
            };

        });

    },0);
        """

        return hook_code


process = frida.get_usb_device().attach(package_name)
script = process.create_script(instrument_debugger_checks())
script.on('message',get_messages_from_js)
script.load()
sys.stdin.read()
示例#24
0
import codecs
import frida
from time import sleep

#session = frida.get_usb_device().attach('Grand Summoners')

session = frida.get_usb_device().spawn("jp.goodsmile.grandsummonersglobal")
# frida -U --no-pause -f "jp.goodsmile.grandsummonersglobal" -l ./hooks.js

with codecs.open('./hooks.js', 'r', 'utf-8') as f:
    source = f.read()

script = session.create_script(source)
script.load()

#rpc = script.exports

#session.detach()
示例#25
0
import os


def on_message(message, data):
    if message["type"] == "error":
        print("[*]Message: ")
        for key, value in message.items():
            print(key, ":", value)
    elif message["type"] == "send":
        print("[*]", message["payload"])
    else:
        print("[*]Message: ", message)
        print("[*]Payload: ", data)


device = frida.get_usb_device()  # 获取usb设备

processId = device.spawn("com.tencent.mm")  # 重启应用,返回进程ID
device.resume(processId)  # 防止附着后进程失效,重启一下
time.sleep(10)
attachSession = device.attach(processId)  # 附着微信的进程,并返回进程的会话
# attachSession = device.attach("com.tencent.mm")  # 附着微信的进程,并返回进程的会话

with open(os.listdir("./")[0], "r", encoding="utf-8") as f:
    jscode = f.read()
script = attachSession.create_script(jscode)  # 创建一个新的js脚本
script.on("message", on_message)  # 设置 message 回调函数

print('[*] Running CTF')

script.load()  # 加载js脚本运行结果
示例#26
0
STRINGS = arguments.strings
MAX_SIZE = 20971520
PERMS = 'rw-'

if arguments.read_only:
    PERMS = 'r--'

if arguments.verbose:
    DEBUG_LEVEL = logging.DEBUG
logging.basicConfig(format='%(levelname)s:%(message)s', level=DEBUG_LEVEL)

# Start a new Session
session = None
try:
    if USB:
        session = frida.get_usb_device().attach(APP_NAME)
    else:
        session = frida.attach(APP_NAME)
except:
    print "Can't connect to App. Have you connected the device?"
    sys.exit(0)


# Selecting Output directory
if arguments.out is not None:
    DIRECTORY = arguments.out
    if os.path.isdir(DIRECTORY):
        print "Output directory is set to: " + DIRECTORY
    else:
        print "The selected output directory does not exist!"
        sys.exit(1)
示例#27
0
''')

print("\033[1;34m[*]___author___: @noobpk\033[1;37m")
print("\033[1;34m[*]___version___: 1.1\033[1;37m")
print("")


def parse_hook(filename):
    print('[*] Script: ' + filename)
    hook = open(filename, 'r')
    script = session.create_script(hook.read())
    script.load()


if __name__ == '__main__':
    try:
        parser = argparse.ArgumentParser()
        parser.add_argument('package', help='Spawn a new process and attach')
        parser.add_argument('script', help='Print stack trace for each hook')
        args = parser.parse_args()

        print('[*] Spawning: ' + args.package)
        pid = frida.get_usb_device().spawn(args.package)
        session = frida.get_usb_device().attach(pid)
        parse_hook(args.script)
        frida.get_usb_device().resume(pid)
        print('---------------Done-----------------')
        sys.stdin.read()

    except KeyboardInterrupt:
        sys.exit(0)
        self.wfile.write(self.rfile.read(content_length))

    do_RESPONSE = do_REQUEST


def echo_server_thread():
    print('start echo server at port {}'.format(ECHO_PORT))
    server = HTTPServer(('', ECHO_PORT), RequestHandler)
    server.serve_forever()


t = Thread(target=echo_server_thread)
t.daemon = True
t.start()

session = frida.get_usb_device().attach('支付宝')

script = session.create_script('''


try{
    var className = "DTURLRequestOperation";
    var funcName = "- addHTTPBodyParameter:forKey:";

    var hook = eval('ObjC.classes.' + className + '["' + funcName + '"]');
    console.log("[*] Class Name: " + className);
    console.log("[*] Method Name: " + funcName);
    Interceptor.attach(hook.implementation, {
      onEnter: function(args) {
      var v = new ObjC.Object(args[2]);
      send({type: 'REQ', data: v.toString()})
示例#29
0
import frida,sys


jscode="""
 
"""



process = frida.get_usb_device().attach('com.fingersoft.hillclimb')
print('[*] process')
script = process.create_script(jscode)
def on_message(message,data):
	print (message)
script.on("message",on_message)
script.load()
sys.stdin.read()




示例#30
0
        var Activity = Java.use("org.apache.http.client.methods.HttpPost");
        Activity.$init.overload('java.lang.String').implementation = function(a){
            console.log("HttpPost is called")
            console.log(Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()))
            this.$init.overload('java.lang.String').call(this, a)
        }

        var Activity3 = Java.use("java.net.URL");
        Activity3.$init.overload('java.lang.String').implementation = function(a){
            console.log("URL is called")
            this.$init.overload('java.lang.String').call(this, a)
        }


        console.log("=== hooking finish ====")

    });
    console.log("[*] Finish ");
"""

device = frida.get_usb_device(timeout=10)
pid = device.spawn("com.ibk.smsmanager")
process = device.attach(pid)
script = process.create_script(j_code)

script.on('message', on_message)
print('[*] on Going')
script.load()
sys.stdin.read()
示例#31
0
def ssl_log(process, pcap=None, verbose=False, remote=False):
    """Decrypts and logs a process's SSL traffic.

  Hooks the functions SSL_read() and SSL_write() in a given process and logs
  the decrypted data to the console and/or to a pcap file.

  Args:
    process: The target process's name (as a string) or process ID (as an int).
    pcap: The file path to which the pcap file should be written.
    verbose: If True, log the decrypted traffic to the console.

  Raises:
    NotImplementedError: Not running on a Linux or macOS system.
  """

    if platform.system() not in ("Darwin", "Linux"):
        raise NotImplementedError(
            "This function is only implemented for Linux and "
            "macOS systems.")

    def log_pcap(pcap_file, ssl_session_id, function, src_addr, src_port,
                 dst_addr, dst_port, data):
        """Writes the captured data to a pcap file.

    Args:
      pcap_file: The opened pcap file.
      ssl_session_id: The SSL session ID for the communication.
      function: The function that was intercepted ("SSL_read" or "SSL_write").
      src_addr: The source address of the logged packet.
      src_port: The source port of the logged packet.
      dst_addr: The destination address of the logged packet.
      dst_port: The destination port of the logged packet.
      data: The decrypted packet data.
    """
        t = time.time()

        if ssl_session_id not in ssl_sessions:
            ssl_sessions[ssl_session_id] = (random.randint(0, 0xFFFFFFFF),
                                            random.randint(0, 0xFFFFFFFF))
        client_sent, server_sent = ssl_sessions[ssl_session_id]

        if function == "SSL_read":
            seq, ack = (server_sent, client_sent)
        else:
            seq, ack = (client_sent, server_sent)

        for writes in (
                # PCAP record (packet) header
            ("=I", int(t)),  # Timestamp seconds
            ("=I", int((t * 1000000) % 1000000)),  # Timestamp microseconds
            ("=I", int(40 + len(data))),  # Number of octets saved
            ("=i", int(40 + len(data))),  # Actual length of packet
                # IPv4 header
            (">B", 0x45),  # Version and Header Length
            (">B", 0),  # Type of Service
            (">H", 40 + len(data)),  # Total Length
            (">H", 0),  # Identification
            (">H", 0x4000),  # Flags and Fragment Offset
            (">B", 0xFF),  # Time to Live
            (">B", 6),  # Protocol
            (">H", 0),  # Header Checksum
            (">I", src_addr),  # Source Address
            (">I", dst_addr),  # Destination Address
                # TCP header
            (">H", src_port),  # Source Port
            (">H", dst_port),  # Destination Port
            (">I", seq),  # Sequence Number
            (">I", ack),  # Acknowledgment Number
            (">H", 0x5018),  # Header Length and Flags
            (">H", 0xFFFF),  # Window Size
            (">H", 0),  # Checksum
            (">H", 0)):  # Urgent Pointer
            pcap_file.write(struct.pack(writes[0], writes[1]))
        pcap_file.write(data)

        if function == "SSL_read":
            server_sent += len(data)
        else:
            client_sent += len(data)
        ssl_sessions[ssl_session_id] = (client_sent, server_sent)

    def on_message(message, data):
        """Callback for errors and messages sent from Frida-injected JavaScript.

    Logs captured packet data received from JavaScript to the console and/or a
    pcap file. See https://www.frida.re/docs/messages/ for more detail on
    Frida's messages.

    Args:
      message: A dictionary containing the message "type" and other fields
          dependent on message type.
      data: The string of captured decrypted data.
    """
        if message["type"] == "error":
            pprint.pprint(message)
            os.kill(os.getpid(), signal.SIGTERM)
            return
        if len(data) == 0:
            return
        p = message["payload"]

        p["src_port"] = socket.ntohs(p["src_port"])
        p["dst_port"] = socket.ntohs(p["dst_port"])
        p["src_addr"] = socket.ntohl(p["src_addr"])
        p["dst_addr"] = socket.ntohl(p["dst_addr"])
        if verbose:
            src_addr = socket.inet_ntop(socket.AF_INET,
                                        struct.pack(">I", p["src_addr"]))
            dst_addr = socket.inet_ntop(socket.AF_INET,
                                        struct.pack(">I", p["dst_addr"]))
            print("SSL Session: " + p["ssl_session_id"])
            print("[%s] %s:%d --> %s:%d" %
                  (p["function"], src_addr, p["src_port"], dst_addr,
                   p["dst_port"]))
            hexdump.hexdump(data)
            print()
        if pcap:
            log_pcap(pcap_file, p["ssl_session_id"], p["function"],
                     p["src_addr"], p["src_port"], p["dst_addr"],
                     p["dst_port"], data)

    device = frida.get_usb_device()
    if remote:
        pid = device.spawn([process])
        session = device.attach(pid)
        # session=frida.get_remote_device().attach(process)
    else:
        session = frida.attach(process)

    if pcap:
        pcap_file = open(pcap, "wb", 0)
        for writes in (
            ("=I", 0xa1b2c3d4),  # Magic number
            ("=H", 2),  # Major version number
            ("=H", 4),  # Minor version number
            ("=i", time.timezone),  # GMT to local correction
            ("=I", 0),  # Accuracy of timestamps
            ("=I", 65535),  # Max length of captured packets
            ("=I", 228)):  # Data link type (LINKTYPE_IPV4)
            pcap_file.write(struct.pack(writes[0], writes[1]))

    scriptname = "ssl_logger_script.js"
    fd = open(scriptname, "r")
    script = session.create_script(fd.read())
    fd.close()
    script.on("message", on_message)
    script.load()
    if remote:
        device.resume(pid)

    print("Press Ctrl+C to stop logging.")
    try:
        signal.pause()
    except KeyboardInterrupt:
        pass

    session.detach()
    if pcap:
        pcap_file.close()
示例#32
0
            payload = str(message['payload']) + '\n'
            sc.sendto(payload.encode(), ('127.0.0.1', 5585))
            print(str(message['payload']) + '\n')
        except:
            print('error')
    elif message['type'] == 'error':
        try:
            print(str(message['stack']) + '\n')
        except:
            print('error')
    else:
        print("something...")


jscode = '''
'''

if __name__ == "__main__":
    print("[*] Start Process ...")
    PACKAGE_NAME = sys.argv[1]

    try:
        process = frida.get_usb_device().attach(PACKAGE_NAME)
        script = process.create_script(jscode)
        script.on('message', on_message)
        script.load()
        sys.stdin.read()

    except Exception as error:
        print(error)
示例#33
0
#         console.log('----------------');
#     },
#     onLeave: function(retval) {
#     }
# })
# """

# jscode = """
# var pointer = Module.findBaseAddress("libjdpdj.so").add(0x35E7E + 1);
# console.log("hmac_sha256 pointer: ", pointer);
#
# Interceptor.attach(pointer, {
#     onEnter: function(args) {
#         console.log("参数1:", Memory.readUtf8String(args[0]));
#         console.log("参数2:", parseInt(args[1]));
#         console.log("参数3:", Memory.readCString(args[2]));
#         console.log("参数4:", parseInt(args[3]));
#         console.log('---------------');
#     },
#     onLeave:function(retval){
#     }
# });
# """

process = frida.get_usb_device().attach('com.jingdong.pdj')
script = process.create_script(jscode)
script.on('message', on_message)
print('[*] Running CTF')
script.load()
sys.stdin.read()
示例#34
0

def on_message(message, data):
    if message['type'] == 'send':
        print("[*] {0}".format(message['payload']))
    else:
        print(message)


jscode = """
Java.perform(function () {
    var class_u = Java.use("com.sensetime.senseid.sdk.liveness.interactive.common.util.StringUtil");
    class_u.sha256 = function (str) {
        console.log("Success");
        console.log("str:", str);
        var result = this.sha256(str);
        console.log(result);
        return result;
    };
});
"""

process = frida.get_usb_device().attach('cn.roleft.mobile.liaoliaoapp')
script = process.create_script(jscode)
script.on('message', on_message)
print('[*] Running CTF')
script.load()
sys.stdin.read()


示例#35
0
 def frida_device(self):
     return frida.get_usb_device()
示例#36
0
import frida
import sys

session = frida.get_usb_device(1000000).attach("com.instagram.android")
script = session.create_script("""
fscrambler = Module.findExportByName(null,"_ZN9Scrambler9getStringESs");
Interceptor.attach(ptr(fscrambler), {
   onLeave: function (retval) {
		send("key: " + Memory.readCString(retval));
   }
});
""")


def on_message(message, data):
    print(message)


script.on('message', on_message)
script.load()
sys.stdin.read()
示例#37
0
import codecs
import frida
from time import sleep

session = frida.get_usb_device().attach('Telegram')

with codecs.open('./audiobox_rpc.js', 'r', 'utf-8') as f:
    source = f.read()

script = session.create_script(source)
script.load()

rpc = script.exports

rpc.sms()
sleep(1)
rpc.email()
sleep(1)
rpc.lock()
sleep(1)
rpc.photo()

session.detach()
示例#38
0
def start_frida(x,bleeh):
    process = frida.get_usb_device().attach(bleeh)
    script = process.create_script(x)
    script.on('message',get_messages_from_js)
    script.load()
示例#39
0
Java.perform(function ()
{
    // Function to hook is defined here
    var MainActivity = Java.use('com.example.seccon2015.rock_paper_scissors.MainActivity');

    // Whenever button is clicked
    MainActivity.onClick.implementation = function (v) {
        // Show a message to know that the function got called
        send('onClick');

        // Call the original onClick handler
        this.onClick(v);

        // Set our values after running the original onClick handler
        this.m.value = 0;
        this.n.value = 1;
        this.cnt.value = 999;

        // Log to the console that it's done, and we should have the flag!
        console.log('Done:' + JSON.stringify(this.cnt));
    };
});
"""

process = frida.get_usb_device().attach('com.example.seccon2015.rock_paper_scissors')
script = process.create_script(jscode)
script.on('message', on_message)
print('[*] Running CTF')
script.load()
sys.stdin.read()
示例#40
0
import frida
import sys

session = frida.get_usb_device().attach(88906)
script_string = """
if (ObjC.available)
{
    try
    {
        var className = "WCDeviceStepObject";
        var funcName = "- m7StepCount";
        var hook = eval('ObjC.classes.' + className + '["' + funcName + '"]');
        console.log("[*] Class Name: " + className);
        console.log("[*] Method Name: " + funcName);
        Interceptor.attach(hook.implementation, {
          onEnter: function(args) {
            var arg0 = new ObjC.Object(args[0]);
            console.log("arg0:"+ arg0.toString());

          },
          onLeave: function(retval) {
            var retvalue = new ObjC.Object(retval);  
            console.log("retval:"+ retvalue.toString());
            newretval=ptr("0x5000");
            retval.replace(newretval);
            console.log("newretval:"+ retval);
          }
        });

    }
    catch(err)
示例#41
0
        util.a.overload("int").implementation = function(p1){
            console.log("p1 : " + p1);
            this.a(p1);
        }
    });
}
"""


def on_message(message, data):
    if message['type'] == 'send':
        print(" {0}".format(message['payload']))
    else:
        print(message)


# 查找USB设备并附加到目标进程
session = frida.get_usb_device().attach('com.uustock.dayi')

# 在目标进程里创建脚本
script = session.create_script(jscode)

# 注册消息回调
script.on('message', on_message)

# 加载创建好的javascript脚本
script.load()

# 读取系统输入
sys.stdin.read()
示例#42
0
文件: dump.py 项目: TSKGhost/project
        instance.onReceive(context,ins2);
    },
  
  onComplete:function(){
  
  }


});
});


"""


def get_message(message,data):

	if 'payload' in message:
	    print message['payload']
	else:
	    print message


s = frida.get_usb_device(1).attach("com.tamu.ctf.hidden")
script = s.create_script(jsnative)
script.on('message',get_message)
script.load()
pause() 


示例#43
0
def init():
    global session
    if session == None:
        session = frida.get_usb_device()
示例#44
0
    else:
        if message['type'] == 'error':
            print (message['stack'])
        else:
            print_result(message)


def kill_process():
    cmd = "adb shell pm clear {} 1> /dev/null".format(APP_NAME)
    os.system(cmd)

kill_process()

try:
    with codecs.open("hooks.js", 'r', encoding='utf8') as f:
        jscode  = f.read()
        device  = frida.get_usb_device(timeout=5)
        pid     = device.spawn([APP_NAME])
        session = device.attach(pid)
        script  = session.create_script(jscode)
        device.resume(APP_NAME)
        script.on('message', on_message)
        print ("[*] Intercepting on {} (pid:{})...".format(APP_NAME,pid))
        script.load()
        sys.stdin.read()
except KeyboardInterrupt:
        print ("[!] Killing app...")
        kill_process()
        time.sleep(1)
        kill_process()
示例#45
0
STRINGS = arguments.strings
MAX_SIZE = 20971520
PERMS = 'rw-'

if arguments.read_only:
    PERMS = 'r--'

if arguments.verbose:
    DEBUG_LEVEL = logging.DEBUG
logging.basicConfig(format='%(levelname)s:%(message)s', level=DEBUG_LEVEL)

# Start a new Session
session = None
try:
    if USB:
        session = frida.get_usb_device().attach(APP_NAME)
    else:
        session = frida.attach(APP_NAME)
except Exception as e:
    print("Can't connect to App. Have you connected the device?")
    logging.debug(str(e))
    sys.exit()

# Selecting Output directory
if arguments.out is not None:
    DIRECTORY = arguments.out
    if os.path.isdir(DIRECTORY):
        print("Output directory is set to: " + DIRECTORY)
    else:
        print("The selected output directory does not exist!")
        sys.exit(1)
示例#46
0
if __name__ == '__main__':


    try:
        parser = OptionParser(usage="usage: %prog [options] <process_to_hook>",version="%prog 1.0")
        parser.add_option("-A", "--attach", action="store_true", default=False,help="Attach to a running process")
        parser.add_option("-S", "--spawn", action="store_true", default=False,help="Spawn a new process and attach")
        parser.add_option("-P", "--pid", action="store_true", default=False,help="Attach to a pid process")
        parser.add_option("-R", "--resume", action="store_true", default=False,help="Resume Process")
        parser.add_option("-f", "--function", action="store", dest="function", help="Name of the Function")
        parser.add_option("-a", "--address", action="store", dest="address", help="Address to attach")

        (options, args) = parser.parse_args()
        if (options.spawn):
            print ("[*] Spawning "+ str(args[0]))
            pid = frida.get_usb_device().spawn([args[0]])
            session = frida.get_usb_device().attach(pid)
        elif (options.attach):
            print ("[*] Attaching to process "+str(args[0]))
            session = frida.get_usb_device().attach(str(args[0]))
        elif (options.pid):
            print ("[*] Attaching to PID "+str(args[0]))
            session = frida.get_usb_device().attach(str(args[0]))
        elif (options.resume):
            session = frida.get_usb_device().resume()
            sys.exit(0)
        else:
            print ("Error")
            print ("[X] Option not selected. View --help option.")
            sys.exit(0)
示例#47
0
import os

import frida
import json
import sys


def on_message(message, payload):
    if 'payload' in message:
        message = message['payload']
        print(message)
    else:
        print(message)


if not os.path.exists('compiled_agent.js'):
    print('use `npm install` to build the agent')
    exit(0)

d = frida.get_usb_device()
pid = d.spawn('com.my.target')
session = d.attach(pid)
script = session.create_script(open('compiled_agent.js', 'r').read())
script.on('message', on_message)
script.load()
d.resume(pid)
sys.stdin.read()
示例#48
0
def init_session():
    try:
        session = None
        if platform == 'ios' or platform == 'android':
            try:
                device = frida.get_usb_device(3) # added timeout to wait for 3 seconds
            except Exception as e:
                print colored(str(e), "red")
                traceback.print_exc()
                if platform == 'android':
                    print colored("Troubleshooting Help", "blue")
                    print colored("HINT: Is USB Debugging enabled?", "blue")
                    print colored("HINT: Is `frida-server` running on mobile device (with +x permissions)?", "blue")
                    print colored("HINT: Is `adb` daemon running?", "blue")
                    sys.exit(1)
                elif platform == "ios":
                    print colored("Troubleshooting Help", "blue")
                    print colored("HINT: Have you installed `frida` module from Cydia?", "blue")
                    print colored("HINT: Have used `ipa_installer` to inject the `FridaGadget` shared lbrary?", "blue")
                    sys.exit(1)
        elif platform == 'iossim':
            try:
                device = frida.get_remote_device()
            except Exception as e:
                # print traceback.print_exc()
                print colored("Troubleshooting Help", "blue")
                print colored("HINT: Have you successfully integrated the FridaGadget dylib with the XCode Project?", "blue")
                print colored("HINT: Do you see a message similar to \"[Frida INFO] Listening on 127.0.0.1 TCP port 27042\" on XCode console logs?", "blue")
                sys.exit(1)
        elif platform == 'macos':
            device = frida.get_local_device()
        else:
            print colored('[ERROR] Unsupported Platform', 'red')
            sys.exit(1)
        pid = None
        if app_name:
            try:
                if platform == 'android' and spawn == 1:
                    print colored("Now Spawning %s" % app_name, "green")
                    pid = device.spawn([app_name])
                    #time.sleep(5)
                    session = device.attach(pid)
                    #time.sleep(5)
                elif (platform == 'ios' or platform == 'macos') and spawn == 1:
                    bundleID = getBundleID(device, app_name, platform)
                    if bundleID:
                        print colored("Now Spawning %s" % bundleID, "green")
                        pid = device.spawn([bundleID])
                        #time.sleep(5)
                        session = device.attach(pid)
                    else:
                        print colored("[ERROR] Can't spawn %s" % app_name, "red")
                        traceback.print_exc()
                        sys.exit(1)
                else:
                    arg_to_attach = app_name
                    if app_name.isdigit():
                        arg_to_attach = int(app_name)

                    session = device.attach(arg_to_attach)
            except Exception as e:
                print colored('[ERROR] ' + str(e), 'red')
                traceback.print_exc()
        if session:
            print colored('[INFO] Attached to %s' % (app_name), 'yellow')
            session.on('detached', on_detached)
    except Exception as e:
        print colored('[ERROR] ' + str(e), 'red')
        traceback.print_exc()
        sys.exit(1)
    return device, session, pid
示例#49
0
    # this.cnt.value = 999;

    // Log to the console that it's done, and we should have the flag!
    console.log('Done:' + JSON.stringify(this.cnt));
  };
});
"""

jscode2 = """
    Java.perform(function () {
        console.log("枚举所有类...");
        Java.enumerateLoadedClasses({
            onMatch: function (_className) {
                if (_className.split(".")[1] === "example") {
                    console.log("[->]t" + _className);
                }
            },
            onComplete: function () {
                console.log("枚举所有类 complete");
            }
        });
    });
"""

process = frida.get_usb_device().attach('com.example.myfridatest')
script = process.create_script(jscode1)
script.on('message', on_message)
print('[*] Running CTF')
script.load()
sys.stdin.read()