mirror of
https://github.com/frida/frida-python.git
synced 2026-11-07 09:35:57 -10:00
Automatically format code with Black and Isort
This commit is contained in:
1 parent
32df9f05b2
commit
fc00ac2b75
30 files changed
+522
-465
No files matched your search
@@ -1,14 +1,16 @@
|
||||
import frida
|
||||
|
||||
|
||||
system_session = frida.attach(0)
|
||||
bytecode = system_session.compile_script(name="bytecode-example", source="""\
|
||||
bytecode = system_session.compile_script(
|
||||
name="bytecode-example",
|
||||
source="""\
|
||||
rpc.exports = {
|
||||
listThreads: function () {
|
||||
return Process.enumerateThreadsSync();
|
||||
}
|
||||
};
|
||||
""")
|
||||
""",
|
||||
)
|
||||
|
||||
session = frida.attach("Twitter")
|
||||
script = session.create_script_from_bytes(bytecode)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import frida
|
||||
|
||||
|
||||
device = frida.get_usb_device()
|
||||
|
||||
channel = device.open_channel("tcp:21")
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import threading
|
||||
|
||||
import frida
|
||||
from frida_tools.application import Reactor
|
||||
|
||||
import frida
|
||||
|
||||
|
||||
class Application:
|
||||
def __init__(self):
|
||||
@@ -27,7 +28,7 @@ class Application:
|
||||
"SNAKE": "mushroom-mushroom",
|
||||
}
|
||||
print(f"✔ spawn(argv={argv})")
|
||||
pid = self._device.spawn(argv, env=env, stdio='pipe')
|
||||
pid = self._device.spawn(argv, env=env, stdio="pipe")
|
||||
self._instrument(pid)
|
||||
|
||||
def _stop_if_idle(self):
|
||||
@@ -41,7 +42,8 @@ class Application:
|
||||
print("✔ enable_child_gating()")
|
||||
session.enable_child_gating()
|
||||
print("✔ create_script()")
|
||||
script = session.create_script("""\
|
||||
script = session.create_script(
|
||||
"""\
|
||||
Interceptor.attach(Module.getExportByName(null, 'open'), {
|
||||
onEnter: function (args) {
|
||||
send({
|
||||
@@ -50,7 +52,8 @@ Interceptor.attach(Module.getExportByName(null, 'open'), {
|
||||
});
|
||||
}
|
||||
});
|
||||
""")
|
||||
"""
|
||||
)
|
||||
script.on("message", lambda message, data: self._reactor.schedule(lambda: self._on_message(pid, message)))
|
||||
print("✔ load()")
|
||||
script.load()
|
||||
|
||||
@@ -2,6 +2,7 @@ from Cocoa import NSApp
|
||||
from Foundation import NSObject
|
||||
from MainWindowController import MainWindowController
|
||||
|
||||
|
||||
class AppDelegate(NSObject):
|
||||
def applicationDidFinishLaunching_(self, notification):
|
||||
window = MainWindowController()
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import bisect
|
||||
from Foundation import NSAutoreleasePool, NSObject, NSThread
|
||||
from PyObjCTools import AppHelper
|
||||
import re
|
||||
import struct
|
||||
|
||||
from Foundation import NSAutoreleasePool, NSObject, NSThread
|
||||
from PyObjCTools import AppHelper
|
||||
|
||||
PROBE_CALLS = re.compile(r"^\/stalker\/probes\/(.*?)\/calls$")
|
||||
|
||||
|
||||
class Capture(NSObject):
|
||||
def __new__(cls, device):
|
||||
return cls.alloc().initWithDevice_(device)
|
||||
@@ -31,7 +33,7 @@ class Capture(NSObject):
|
||||
def attachToProcess_triggerPort_(self, process, triggerPort):
|
||||
assert self.state == CaptureState.DETACHED
|
||||
self._updateState_(CaptureState.ATTACHING)
|
||||
NSThread.detachNewThreadSelector_toTarget_withObject_('_doAttachWithParams:', self, (process.pid, triggerPort))
|
||||
NSThread.detachNewThreadSelector_toTarget_withObject_("_doAttachWithParams:", self, (process.pid, triggerPort))
|
||||
|
||||
def detach(self):
|
||||
assert self.state == CaptureState.ATTACHED
|
||||
@@ -40,10 +42,10 @@ class Capture(NSObject):
|
||||
self.session = None
|
||||
self.script = None
|
||||
self._updateState_(CaptureState.DETACHED)
|
||||
NSThread.detachNewThreadSelector_toTarget_withObject_('_doDetachWithParams:', self, (session, script))
|
||||
NSThread.detachNewThreadSelector_toTarget_withObject_("_doDetachWithParams:", self, (session, script))
|
||||
|
||||
def _post(self, message):
|
||||
NSThread.detachNewThreadSelector_toTarget_withObject_('_doPostWithParams:', self, (self.script, message))
|
||||
NSThread.detachNewThreadSelector_toTarget_withObject_("_doPostWithParams:", self, (self.script, message))
|
||||
|
||||
def _updateState_(self, newState):
|
||||
self.state = newState
|
||||
@@ -57,11 +59,9 @@ class Capture(NSObject):
|
||||
error = None
|
||||
try:
|
||||
session = self.device.attach(pid)
|
||||
session.on('detached', self._onSessionDetached)
|
||||
script = session.create_script(name="cpushark", source=SCRIPT_TEMPLATE % {
|
||||
'trigger_port': triggerPort
|
||||
})
|
||||
script.on('message', self._onScriptMessage)
|
||||
session.on("detached", self._onSessionDetached)
|
||||
script = session.create_script(name="cpushark", source=SCRIPT_TEMPLATE % {"trigger_port": triggerPort})
|
||||
script.on("message", self._onScriptMessage)
|
||||
script.load()
|
||||
except Exception as e:
|
||||
if session is not None:
|
||||
@@ -113,15 +113,15 @@ class Capture(NSObject):
|
||||
self._updateState_(CaptureState.DETACHED)
|
||||
|
||||
def _sessionDidReceiveMessage_data_(self, message, data):
|
||||
if message['type'] == 'send':
|
||||
stanza = message['payload']
|
||||
fromAddress = stanza['from']
|
||||
name = stanza['name']
|
||||
if fromAddress == "/process/modules" and name == '+sync':
|
||||
self.modules._sync(stanza['payload'])
|
||||
elif fromAddress == "/stalker/calls" and name == '+add':
|
||||
self.calls._add_(stanza['payload'])
|
||||
elif fromAddress == "/interceptor/functions" and name == '+add':
|
||||
if message["type"] == "send":
|
||||
stanza = message["payload"]
|
||||
fromAddress = stanza["from"]
|
||||
name = stanza["name"]
|
||||
if fromAddress == "/process/modules" and name == "+sync":
|
||||
self.modules._sync(stanza["payload"])
|
||||
elif fromAddress == "/stalker/calls" and name == "+add":
|
||||
self.calls._add_(stanza["payload"])
|
||||
elif fromAddress == "/interceptor/functions" and name == "+add":
|
||||
self.recvTotal += 1
|
||||
self._delegate.captureRecvTotalDidChange()
|
||||
else:
|
||||
@@ -136,11 +136,13 @@ class Capture(NSObject):
|
||||
def _onScriptMessage(self, message, data):
|
||||
AppHelper.callAfter(self._sessionDidReceiveMessage_data_, message, data)
|
||||
|
||||
|
||||
class CaptureState:
|
||||
DETACHED = 1
|
||||
ATTACHING = 2
|
||||
ATTACHED = 3
|
||||
|
||||
|
||||
class Modules:
|
||||
def __init__(self):
|
||||
self._modules = []
|
||||
@@ -148,11 +150,11 @@ class Modules:
|
||||
|
||||
def _sync(self, payload):
|
||||
modules = []
|
||||
for item in payload['items']:
|
||||
modules.append(Module(item['name'], int(item['base'], 16), item['size']))
|
||||
for item in payload["items"]:
|
||||
modules.append(Module(item["name"], int(item["base"], 16), item["size"]))
|
||||
modules.sort(lambda x, y: x.address - y.address)
|
||||
self._modules = modules
|
||||
self._indices = [ m.address for m in modules ]
|
||||
self._indices = [m.address for m in modules]
|
||||
|
||||
def lookup(self, addr):
|
||||
idx = bisect.bisect(self._indices, addr)
|
||||
@@ -163,6 +165,7 @@ class Modules:
|
||||
return None
|
||||
return m
|
||||
|
||||
|
||||
class Module:
|
||||
def __init__(self, name, address, size):
|
||||
self.name = name
|
||||
@@ -172,6 +175,7 @@ class Module:
|
||||
def __repr__(self):
|
||||
return "(%d, %d, %s)" % (self.address, self.size, self.name)
|
||||
|
||||
|
||||
class Calls(NSObject):
|
||||
def __new__(cls, capture):
|
||||
return cls.alloc().initWithCapture_(capture)
|
||||
@@ -192,28 +196,16 @@ class Calls(NSObject):
|
||||
self._delegate = delegate
|
||||
|
||||
def addProbe_(self, func):
|
||||
self.capture._post({
|
||||
'to': "/stalker/probes",
|
||||
'name': '+add',
|
||||
'payload': {
|
||||
'address': "0x%x" % func.address
|
||||
}
|
||||
})
|
||||
self.capture._post({"to": "/stalker/probes", "name": "+add", "payload": {"address": "0x%x" % func.address}})
|
||||
self._probes[func.address] = func
|
||||
|
||||
def removeProbe_(self, func):
|
||||
self.capture._post({
|
||||
'to': "/stalker/probes",
|
||||
'name': '+remove',
|
||||
'payload': {
|
||||
'address': "0x%x" % func.address
|
||||
}
|
||||
})
|
||||
self.capture._post({"to": "/stalker/probes", "name": "+remove", "payload": {"address": "0x%x" % func.address}})
|
||||
self._probes.pop(func.address, None)
|
||||
|
||||
def _add_(self, data):
|
||||
modules = self.capture.modules
|
||||
for rawTarget, count in data['summary'].items():
|
||||
for rawTarget, count in data["summary"].items():
|
||||
target = int(rawTarget, 16)
|
||||
tm = self.getTargetModuleByModule_(modules.lookup(target))
|
||||
if tm is not None:
|
||||
@@ -237,13 +229,13 @@ class Calls(NSObject):
|
||||
return x.total - y.total
|
||||
|
||||
def _handleStanza_(self, stanza):
|
||||
m = PROBE_CALLS.match(stanza['from'])
|
||||
m = PROBE_CALLS.match(stanza["from"])
|
||||
if m is not None:
|
||||
func = self._probes.get(int(m.groups()[0], 16), None)
|
||||
if func is not None:
|
||||
if len(func.calls) == 3:
|
||||
func.calls.pop(0)
|
||||
func.calls.append(FunctionCall(func, stanza['payload']['args']))
|
||||
func.calls.append(FunctionCall(func, stanza["payload"]["args"]))
|
||||
self._delegate.callItemDidChange_(func)
|
||||
return True
|
||||
return False
|
||||
@@ -291,27 +283,28 @@ class Calls(NSObject):
|
||||
def outlineView_objectValueForTableColumn_byItem_(self, outlineView, tableColumn, item):
|
||||
identifier = tableColumn.identifier()
|
||||
if isinstance(item, TargetModule):
|
||||
if identifier == 'name':
|
||||
if identifier == "name":
|
||||
return item.module.name
|
||||
elif identifier == 'total':
|
||||
elif identifier == "total":
|
||||
return item.total
|
||||
else:
|
||||
return False
|
||||
elif isinstance(item, TargetFunction):
|
||||
if identifier == 'name':
|
||||
if identifier == "name":
|
||||
return item.name
|
||||
elif identifier == 'total':
|
||||
elif identifier == "total":
|
||||
return item.total
|
||||
else:
|
||||
return item.hasProbe
|
||||
else:
|
||||
if identifier == 'name':
|
||||
if identifier == "name":
|
||||
return item.summary
|
||||
elif identifier == 'total':
|
||||
elif identifier == "total":
|
||||
return ""
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
class TargetModule(NSObject):
|
||||
def __new__(cls, module):
|
||||
return cls.alloc().initWithModule_(module)
|
||||
@@ -332,6 +325,7 @@ class TargetModule(NSObject):
|
||||
self._functionByAddress[address] = f
|
||||
return f
|
||||
|
||||
|
||||
class TargetFunction(NSObject):
|
||||
def __new__(cls, module, offset):
|
||||
return cls.alloc().initWithModule_offset_(module, offset)
|
||||
@@ -347,6 +341,7 @@ class TargetFunction(NSObject):
|
||||
self.calls = []
|
||||
return self
|
||||
|
||||
|
||||
class FunctionCall(NSObject):
|
||||
def __new__(cls, func, args):
|
||||
return cls.alloc().initWithFunction_args_(func, args)
|
||||
@@ -358,6 +353,7 @@ class FunctionCall(NSObject):
|
||||
self.summary = f"{func.name}({', '.join(args)})"
|
||||
return self
|
||||
|
||||
|
||||
SCRIPT_TEMPLATE = """
|
||||
var probes = Object.create(null);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, "/Users/oleavr/src/frida/build/frida-macos-universal/lib/python2.7/site-packages")
|
||||
import AppDelegate
|
||||
import Capture
|
||||
@@ -7,4 +8,5 @@ import ProcessList
|
||||
|
||||
if __name__ == "__main__":
|
||||
from PyObjCTools import AppHelper
|
||||
|
||||
AppHelper.runEventLoop()
|
||||
@@ -1,8 +1,10 @@
|
||||
import frida
|
||||
from Capture import Capture, CaptureState, TargetFunction
|
||||
from Cocoa import NSRunCriticalAlertPanel, NSUserDefaults, NSWindowController, objc
|
||||
from ProcessList import ProcessList
|
||||
|
||||
import frida
|
||||
|
||||
|
||||
class MainWindowController(NSWindowController):
|
||||
processCombo = objc.IBOutlet()
|
||||
triggerField = objc.IBOutlet()
|
||||
@@ -26,7 +28,7 @@ class MainWindowController(NSWindowController):
|
||||
def windowDidLoad(self):
|
||||
NSWindowController.windowDidLoad(self)
|
||||
|
||||
device = [device for device in frida.get_device_manager().enumerate_devices() if device.type == 'local'][0]
|
||||
device = [device for device in frida.get_device_manager().enumerate_devices() if device.type == "local"][0]
|
||||
self.processList = ProcessList(device)
|
||||
self.capture = Capture(device)
|
||||
self.processCombo.setUsesDataSource_(True)
|
||||
@@ -127,4 +129,3 @@ class MainWindowController(NSWindowController):
|
||||
|
||||
def callItemDidChange_(self, item):
|
||||
self.callTableView.reloadItem_reloadChildren_(item, True)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from Foundation import NSObject, NSNotFound
|
||||
from Foundation import NSNotFound, NSObject
|
||||
|
||||
|
||||
class ProcessList(NSObject):
|
||||
def __new__(cls, device):
|
||||
@@ -30,4 +31,3 @@ class ProcessList(NSObject):
|
||||
|
||||
def comboBox_indexOfItemWithStringValue_(self, comboBox, value):
|
||||
return self._processIndexByName.get(value.lower(), NSNotFound)
|
||||
|
||||
@@ -5,21 +5,21 @@ Usage:
|
||||
python setup.py py2app
|
||||
"""
|
||||
|
||||
from setuptools import setup
|
||||
import py2app
|
||||
from setuptools import setup
|
||||
|
||||
plist = dict(
|
||||
CFBundleShortVersionString='CpuShark v1',
|
||||
CFBundleIconFile='CpuShark.icns',
|
||||
CFBundleGetInfoString='CpuShark v1',
|
||||
CFBundleIdentifier='com.tillitech.CpuShark',
|
||||
CFBundleShortVersionString="CpuShark v1",
|
||||
CFBundleIconFile="CpuShark.icns",
|
||||
CFBundleGetInfoString="CpuShark v1",
|
||||
CFBundleIdentifier="com.tillitech.CpuShark",
|
||||
CFBundleDocumentTypes=[],
|
||||
CFBundleName='CpuShark'
|
||||
CFBundleName="CpuShark",
|
||||
)
|
||||
|
||||
setup(
|
||||
app=["CpuShark.py"],
|
||||
data_files=["MainMenu.xib", "MainWindow.xib"],
|
||||
options={'py2app': {'plist': plist}},
|
||||
setup_requires=['py2app'],
|
||||
options={"py2app": {"plist": plist}},
|
||||
setup_requires=["py2app"],
|
||||
)
|
||||
@@ -7,14 +7,16 @@ def on_process_crashed(crash):
|
||||
print("on_process_crashed")
|
||||
print("\tcrash:", crash)
|
||||
|
||||
|
||||
def on_detached(reason, crash):
|
||||
print("on_detached()")
|
||||
print("\treason:", reason)
|
||||
print("\tcrash:", crash)
|
||||
|
||||
|
||||
device = frida.get_usb_device()
|
||||
device.on('process-crashed', on_process_crashed)
|
||||
device.on("process-crashed", on_process_crashed)
|
||||
session = device.attach("Hello")
|
||||
session.on('detached', on_detached)
|
||||
session.on("detached", on_detached)
|
||||
print("[*] Ready")
|
||||
sys.stdin.read()
|
||||
@@ -6,15 +6,18 @@ import frida
|
||||
def on_detached():
|
||||
print("on_detached")
|
||||
|
||||
|
||||
def on_detached_with_reason(reason):
|
||||
print("on_detached_with_reason:", reason)
|
||||
|
||||
|
||||
def on_detached_with_varargs(*args):
|
||||
print("on_detached_with_varargs:", args)
|
||||
|
||||
|
||||
session = frida.attach("Twitter")
|
||||
print("attached")
|
||||
session.on('detached', on_detached)
|
||||
session.on('detached', on_detached_with_reason)
|
||||
session.on('detached', on_detached_with_varargs)
|
||||
session.on("detached", on_detached)
|
||||
session.on("detached", on_detached_with_reason)
|
||||
session.on("detached", on_detached_with_varargs)
|
||||
sys.stdin.read()
|
||||
@@ -1,21 +1,24 @@
|
||||
import frida
|
||||
from pprint import pformat
|
||||
|
||||
from pygments import highlight
|
||||
from pygments.formatters import Terminal256Formatter
|
||||
from pygments.lexers import PythonLexer
|
||||
|
||||
import frida
|
||||
|
||||
device = frida.get_usb_device()
|
||||
|
||||
|
||||
def trim_icon(icon):
|
||||
result = dict(icon)
|
||||
result['image'] = result['image'][0:16] + b"..."
|
||||
result["image"] = result["image"][0:16] + b"..."
|
||||
return result
|
||||
|
||||
apps = device.enumerate_applications(scope='full')
|
||||
|
||||
apps = device.enumerate_applications(scope="full")
|
||||
for app in apps:
|
||||
params = dict(app.parameters)
|
||||
if 'icons' in params:
|
||||
params['icons'] = [trim_icon(icon) for icon in params['icons']]
|
||||
if "icons" in params:
|
||||
params["icons"] = [trim_icon(icon) for icon in params["icons"]]
|
||||
parameters = highlight(pformat(params), PythonLexer(), Terminal256Formatter()).rstrip()
|
||||
print(f"Application(identifier=\"{app.identifier}\", name=\"{app.name}\", pid={app.pid}, parameters={parameters})")
|
||||
print(f'Application(identifier="{app.identifier}", name="{app.name}", pid={app.pid}, parameters={parameters})')
|
||||
@@ -1,20 +1,25 @@
|
||||
import frida
|
||||
from pprint import pformat
|
||||
|
||||
from pygments import highlight
|
||||
from pygments.formatters import Terminal256Formatter
|
||||
from pygments.lexers import PythonLexer
|
||||
|
||||
import frida
|
||||
|
||||
device = frida.get_usb_device()
|
||||
|
||||
|
||||
def trim_icon(icon):
|
||||
result = dict(icon)
|
||||
result['image'] = result['image'][0:16] + b"..."
|
||||
result["image"] = result["image"][0:16] + b"..."
|
||||
return result
|
||||
|
||||
processes = device.enumerate_processes(scope='full')
|
||||
|
||||
processes = device.enumerate_processes(scope="full")
|
||||
for proc in processes:
|
||||
params = dict(proc.parameters)
|
||||
if 'icons' in params:
|
||||
params['icons'] = [trim_icon(icon) for icon in params['icons']]
|
||||
print(f"Process(pid={proc.pid}, name=\"{proc.name}\", parameters={highlight(pformat(params), PythonLexer(), Terminal256Formatter()).rstrip()})")
|
||||
if "icons" in params:
|
||||
params["icons"] = [trim_icon(icon) for icon in params["icons"]]
|
||||
print(
|
||||
f'Process(pid={proc.pid}, name="{proc.name}", parameters={highlight(pformat(params), PythonLexer(), Terminal256Formatter()).rstrip()})'
|
||||
)
|
||||
@@ -1,22 +1,25 @@
|
||||
import frida
|
||||
from pprint import pformat
|
||||
|
||||
from pygments import highlight
|
||||
from pygments.formatters import Terminal256Formatter
|
||||
from pygments.lexers import PythonLexer
|
||||
|
||||
import frida
|
||||
|
||||
device = frida.get_usb_device()
|
||||
|
||||
|
||||
def trim_icon(icon):
|
||||
result = dict(icon)
|
||||
result['image'] = result['image'][0:16] + b"..."
|
||||
result["image"] = result["image"][0:16] + b"..."
|
||||
return result
|
||||
|
||||
app = device.get_frontmost_application(scope='full')
|
||||
|
||||
app = device.get_frontmost_application(scope="full")
|
||||
if app is not None:
|
||||
params = dict(app.parameters)
|
||||
if 'icons' in params:
|
||||
params['icons'] = [trim_icon(icon) for icon in params['icons']]
|
||||
if "icons" in params:
|
||||
params["icons"] = [trim_icon(icon) for icon in params["icons"]]
|
||||
print(f"{app.identifier}:", highlight(pformat(params), PythonLexer(), Terminal256Formatter()))
|
||||
else:
|
||||
print("No frontmost application")
|
||||
@@ -14,6 +14,7 @@ import frida
|
||||
def on_uninjected(id):
|
||||
print("on_uninjected id=%u" % id)
|
||||
|
||||
|
||||
(target, library_path) = sys.argv[1:]
|
||||
|
||||
device = frida.get_local_device()
|
||||
|
||||
@@ -14,6 +14,7 @@ import frida
|
||||
def on_uninjected(id):
|
||||
print("on_uninjected id=%u" % id)
|
||||
|
||||
|
||||
(target, library_path) = sys.argv[1:]
|
||||
|
||||
device = frida.get_local_device()
|
||||
|
||||
+28
-40
@@ -1,22 +1,20 @@
|
||||
import frida
|
||||
from frida_tools.application import Reactor
|
||||
import json
|
||||
import sys
|
||||
|
||||
from frida_tools.application import Reactor
|
||||
|
||||
import frida
|
||||
|
||||
|
||||
class Application:
|
||||
def __init__(self, nick):
|
||||
self._reactor = Reactor(run_until_return=self._process_input)
|
||||
|
||||
token = {
|
||||
'nick': nick,
|
||||
'secret': "knock-knock"
|
||||
}
|
||||
self._device = frida.get_device_manager().add_remote_device("::1",
|
||||
token=json.dumps(token))
|
||||
token = {"nick": nick, "secret": "knock-knock"}
|
||||
self._device = frida.get_device_manager().add_remote_device("::1", token=json.dumps(token))
|
||||
|
||||
self._bus = self._device.bus
|
||||
self._bus.on('message', lambda *args: self._reactor.schedule(lambda: self._on_bus_message(*args)))
|
||||
self._bus.on("message", lambda *args: self._reactor.schedule(lambda: self._on_bus_message(*args)))
|
||||
|
||||
self._channel = None
|
||||
self._prompt = "> "
|
||||
@@ -45,53 +43,43 @@ class Application:
|
||||
|
||||
if text.startswith("/join "):
|
||||
if self._channel is not None:
|
||||
self._bus.post({
|
||||
'type': 'part',
|
||||
'channel': self._channel
|
||||
})
|
||||
self._bus.post({"type": "part", "channel": self._channel})
|
||||
channel = text[6:]
|
||||
self._channel = channel
|
||||
self._prompt = f"{channel} > "
|
||||
self._bus.post({
|
||||
'type': 'join',
|
||||
'channel': channel
|
||||
})
|
||||
self._bus.post({"type": "join", "channel": channel})
|
||||
continue
|
||||
|
||||
if text.startswith("/announce "):
|
||||
self._bus.post({
|
||||
'type': 'announce',
|
||||
'text': text[10:]
|
||||
})
|
||||
self._bus.post({"type": "announce", "text": text[10:]})
|
||||
continue
|
||||
|
||||
if self._channel is not None:
|
||||
self._bus.post({
|
||||
'channel': self._channel,
|
||||
'type': 'say',
|
||||
'text': text
|
||||
})
|
||||
self._bus.post({"channel": self._channel, "type": "say", "text": text})
|
||||
else:
|
||||
self._print("*** Need to /join a channel first")
|
||||
|
||||
def _on_bus_message(self, message, data):
|
||||
mtype = message['type']
|
||||
if mtype == 'welcome':
|
||||
self._print("*** Welcome! Available channels:", repr(message['channels']))
|
||||
elif mtype == 'membership':
|
||||
self._print("*** Joined", message['channel'])
|
||||
self._print("- Members:\n\t" + "\n\t".join([f"{m['nick']} (connected from {m['address']})" for m in message['members']]))
|
||||
for item in message['history']:
|
||||
mtype = message["type"]
|
||||
if mtype == "welcome":
|
||||
self._print("*** Welcome! Available channels:", repr(message["channels"]))
|
||||
elif mtype == "membership":
|
||||
self._print("*** Joined", message["channel"])
|
||||
self._print(
|
||||
"- Members:\n\t"
|
||||
+ "\n\t".join([f"{m['nick']} (connected from {m['address']})" for m in message["members"]])
|
||||
)
|
||||
for item in message["history"]:
|
||||
self._print(f"<{item['sender']}> {item['text']}")
|
||||
elif mtype == 'join':
|
||||
user = message['user']
|
||||
elif mtype == "join":
|
||||
user = message["user"]
|
||||
self._print(f"👋 {user['nick']} ({user['address']}) joined {message['channel']}")
|
||||
elif mtype == 'part':
|
||||
user = message['user']
|
||||
elif mtype == "part":
|
||||
user = message["user"]
|
||||
self._print(f"🚪 {user['nick']} ({user['address']}) left {message['channel']}")
|
||||
elif mtype == 'chat':
|
||||
elif mtype == "chat":
|
||||
self._print(f"<{message['sender']}> {message['text']}")
|
||||
elif mtype == 'announce':
|
||||
elif mtype == "announce":
|
||||
self._print(f"📣 <{message['sender']}> {message['text']}")
|
||||
else:
|
||||
self._print("Unhandled message:", message)
|
||||
@@ -102,7 +90,7 @@ class Application:
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
nick = sys.argv[1]
|
||||
app = Application(nick)
|
||||
app.run()
|
||||
+54
-66
@@ -1,10 +1,11 @@
|
||||
import frida
|
||||
from frida_tools.application import Reactor
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from frida_tools.application import Reactor
|
||||
|
||||
import frida
|
||||
|
||||
ENABLE_CONTROL_INTERFACE = True
|
||||
|
||||
@@ -13,16 +14,17 @@ class Application:
|
||||
def __init__(self):
|
||||
self._reactor = Reactor(run_until_return=self._process_input)
|
||||
|
||||
cluster_params = frida.EndpointParameters(address="unix:/Users/oleavr/src/cluster",
|
||||
certificate="/Users/oleavr/src/identity2.pem",
|
||||
authentication=('token', "wow-such-secret"))
|
||||
cluster_params = frida.EndpointParameters(
|
||||
address="unix:/Users/oleavr/src/cluster",
|
||||
certificate="/Users/oleavr/src/identity2.pem",
|
||||
authentication=("token", "wow-such-secret"),
|
||||
)
|
||||
|
||||
if ENABLE_CONTROL_INTERFACE:
|
||||
www = Path(__file__).parent.resolve() / "web_client" / "dist"
|
||||
control_params = frida.EndpointParameters(address="::1",
|
||||
port=27042,
|
||||
authentication=('callback', self._authenticate),
|
||||
asset_root=www)
|
||||
control_params = frida.EndpointParameters(
|
||||
address="::1", port=27042, authentication=("callback", self._authenticate), asset_root=www
|
||||
)
|
||||
else:
|
||||
control_params = None
|
||||
|
||||
@@ -33,15 +35,20 @@ class Application:
|
||||
self._nicks = set()
|
||||
self._channels = {}
|
||||
|
||||
service.on('node-connected', lambda *args: self._reactor.schedule(lambda: self._on_node_connected(*args)))
|
||||
service.on('node-joined', lambda *args: self._reactor.schedule(lambda: self._on_node_joined(*args)))
|
||||
service.on('node-left', lambda *args: self._reactor.schedule(lambda: self._on_node_left(*args)))
|
||||
service.on('node-disconnected', lambda *args: self._reactor.schedule(lambda: self._on_node_disconnected(*args)))
|
||||
service.on('controller-connected', lambda *args: self._reactor.schedule(lambda: self._on_controller_connected(*args)))
|
||||
service.on('controller-disconnected', lambda *args: self._reactor.schedule(lambda: self._on_controller_disconnected(*args)))
|
||||
service.on('authenticated', lambda *args: self._reactor.schedule(lambda: self._on_authenticated(*args)))
|
||||
service.on('subscribe', lambda *args: self._reactor.schedule(lambda: self._on_subscribe(*args)))
|
||||
service.on('message', lambda *args: self._reactor.schedule(lambda: self._on_message(*args)))
|
||||
service.on("node-connected", lambda *args: self._reactor.schedule(lambda: self._on_node_connected(*args)))
|
||||
service.on("node-joined", lambda *args: self._reactor.schedule(lambda: self._on_node_joined(*args)))
|
||||
service.on("node-left", lambda *args: self._reactor.schedule(lambda: self._on_node_left(*args)))
|
||||
service.on("node-disconnected", lambda *args: self._reactor.schedule(lambda: self._on_node_disconnected(*args)))
|
||||
service.on(
|
||||
"controller-connected", lambda *args: self._reactor.schedule(lambda: self._on_controller_connected(*args))
|
||||
)
|
||||
service.on(
|
||||
"controller-disconnected",
|
||||
lambda *args: self._reactor.schedule(lambda: self._on_controller_disconnected(*args)),
|
||||
)
|
||||
service.on("authenticated", lambda *args: self._reactor.schedule(lambda: self._on_authenticated(*args)))
|
||||
service.on("subscribe", lambda *args: self._reactor.schedule(lambda: self._on_subscribe(*args)))
|
||||
service.on("message", lambda *args: self._reactor.schedule(lambda: self._on_message(*args)))
|
||||
|
||||
def run(self):
|
||||
self._reactor.schedule(self._start)
|
||||
@@ -74,8 +81,8 @@ class Application:
|
||||
def _authenticate(self, raw_token):
|
||||
try:
|
||||
token = json.loads(raw_token)
|
||||
nick = str(token['nick'])
|
||||
secret = token['secret'].encode('utf-8')
|
||||
nick = str(token["nick"])
|
||||
secret = token["secret"].encode("utf-8")
|
||||
except:
|
||||
raise ValueError("invalid request")
|
||||
|
||||
@@ -85,7 +92,7 @@ class Application:
|
||||
raise ValueError("get outta here")
|
||||
|
||||
return {
|
||||
'nick': nick,
|
||||
"nick": nick,
|
||||
}
|
||||
|
||||
def _on_node_connected(self, connection_id, remote_address):
|
||||
@@ -118,37 +125,30 @@ class Application:
|
||||
peer = self._peers.get(connection_id, None)
|
||||
if peer is None:
|
||||
return
|
||||
peer.nick = self._acquire_nick(session_info['nick'])
|
||||
peer.nick = self._acquire_nick(session_info["nick"])
|
||||
|
||||
def _on_subscribe(self, connection_id):
|
||||
print("on_subscribe()", connection_id)
|
||||
self._service.post(connection_id, {
|
||||
'type': 'welcome',
|
||||
'channels': list(self._channels.keys())
|
||||
})
|
||||
self._service.post(connection_id, {"type": "welcome", "channels": list(self._channels.keys())})
|
||||
|
||||
def _on_message(self, connection_id, message, data):
|
||||
peer = self._peers[connection_id]
|
||||
|
||||
mtype = message['type']
|
||||
if mtype == 'join':
|
||||
self._get_channel(message['channel']).add_member(peer)
|
||||
elif mtype == 'part':
|
||||
channel = self._channels.get(message['channel'], None)
|
||||
mtype = message["type"]
|
||||
if mtype == "join":
|
||||
self._get_channel(message["channel"]).add_member(peer)
|
||||
elif mtype == "part":
|
||||
channel = self._channels.get(message["channel"], None)
|
||||
if channel is None:
|
||||
return
|
||||
channel.remove_member(peer)
|
||||
elif mtype == 'say':
|
||||
channel = self._channels.get(message['channel'], None)
|
||||
elif mtype == "say":
|
||||
channel = self._channels.get(message["channel"], None)
|
||||
if channel is None:
|
||||
return
|
||||
channel.post(message['text'], peer)
|
||||
elif mtype == 'announce':
|
||||
self._service.broadcast({
|
||||
'type': 'announce',
|
||||
'sender': peer.nick,
|
||||
'text': message['text']
|
||||
})
|
||||
channel.post(message["text"], peer)
|
||||
elif mtype == "announce":
|
||||
self._service.broadcast({"type": "announce", "sender": peer.nick, "text": message["text"]})
|
||||
else:
|
||||
print("Unhandled message:", message)
|
||||
|
||||
@@ -183,10 +183,7 @@ class Peer:
|
||||
self.memberships = set()
|
||||
|
||||
def to_json(self):
|
||||
return {
|
||||
'nick': self.nick,
|
||||
'address': self.remote_address[0]
|
||||
}
|
||||
return {"nick": self.nick, "address": self.remote_address[0]}
|
||||
|
||||
|
||||
class Channel:
|
||||
@@ -204,19 +201,18 @@ class Channel:
|
||||
peer.memberships.add(self)
|
||||
self.members.add(peer)
|
||||
|
||||
self._service.narrowcast(self.name, {
|
||||
'type': 'join',
|
||||
'channel': self.name,
|
||||
'user': peer.to_json()
|
||||
})
|
||||
self._service.narrowcast(self.name, {"type": "join", "channel": self.name, "user": peer.to_json()})
|
||||
self._service.tag(peer.connection_id, self.name)
|
||||
|
||||
self._service.post(peer.connection_id, {
|
||||
'type': 'membership',
|
||||
'channel': self.name,
|
||||
'members': [peer.to_json() for peer in self.members],
|
||||
'history': self.history
|
||||
})
|
||||
self._service.post(
|
||||
peer.connection_id,
|
||||
{
|
||||
"type": "membership",
|
||||
"channel": self.name,
|
||||
"members": [peer.to_json() for peer in self.members],
|
||||
"history": self.history,
|
||||
},
|
||||
)
|
||||
|
||||
def remove_member(self, peer):
|
||||
if self not in peer.memberships:
|
||||
@@ -226,21 +222,13 @@ class Channel:
|
||||
self.members.remove(peer)
|
||||
|
||||
self._service.untag(peer.connection_id, self.name)
|
||||
self._service.narrowcast(self.name, {
|
||||
'type': 'part',
|
||||
'channel': self.name,
|
||||
'user': peer.to_json()
|
||||
})
|
||||
self._service.narrowcast(self.name, {"type": "part", "channel": self.name, "user": peer.to_json()})
|
||||
|
||||
def post(self, text, peer):
|
||||
if self not in peer.memberships:
|
||||
return
|
||||
|
||||
item = {
|
||||
'type': 'chat',
|
||||
'sender': peer.nick,
|
||||
'text': text
|
||||
}
|
||||
item = {"type": "chat", "sender": peer.nick, "text": text}
|
||||
|
||||
self._service.narrowcast(self.name, item)
|
||||
|
||||
@@ -250,6 +238,6 @@ class Channel:
|
||||
history.pop(0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
app = Application()
|
||||
app.run()
|
||||
@@ -1,9 +1,13 @@
|
||||
import frida
|
||||
from pprint import pformat
|
||||
|
||||
from pygments import highlight
|
||||
from pygments.formatters import Terminal256Formatter
|
||||
from pygments.lexers import PythonLexer
|
||||
|
||||
import frida
|
||||
|
||||
print("Local parameters:", highlight(pformat(frida.query_system_parameters()), PythonLexer(), Terminal256Formatter()))
|
||||
print("USB device parameters:", highlight(pformat(frida.get_usb_device().query_system_parameters()), PythonLexer(), Terminal256Formatter()))
|
||||
print(
|
||||
"USB device parameters:",
|
||||
highlight(pformat(frida.get_usb_device().query_system_parameters()), PythonLexer(), Terminal256Formatter()),
|
||||
)
|
||||
+4
-3
@@ -1,8 +1,8 @@
|
||||
import frida
|
||||
|
||||
|
||||
session = frida.attach("Twitter")
|
||||
script = session.create_script("""\
|
||||
script = session.create_script(
|
||||
"""\
|
||||
rpc.exports = {
|
||||
hello: function () {
|
||||
return 'Hello';
|
||||
@@ -11,7 +11,8 @@ rpc.exports = {
|
||||
oops;
|
||||
}
|
||||
};
|
||||
""")
|
||||
"""
|
||||
)
|
||||
script.load()
|
||||
api = script.exports
|
||||
print("api.hello() =>", api.hello())
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import frida
|
||||
from frida_tools.application import Reactor
|
||||
|
||||
import frida
|
||||
|
||||
|
||||
class Application:
|
||||
def __init__(self):
|
||||
@@ -19,9 +20,10 @@ class Application:
|
||||
|
||||
session = self._device.attach("hello2", persist_timeout=30)
|
||||
self._session = session
|
||||
session.on('detached', lambda *args: self._reactor.schedule(lambda: self._on_detached(*args)))
|
||||
session.on("detached", lambda *args: self._reactor.schedule(lambda: self._on_detached(*args)))
|
||||
|
||||
script = session.create_script("""
|
||||
script = session.create_script(
|
||||
"""
|
||||
let _puts = null;
|
||||
|
||||
Interceptor.attach(DebugSymbol.getFunctionByName('f'), {
|
||||
@@ -46,9 +48,10 @@ function puts(s) {
|
||||
}
|
||||
_puts(Memory.allocUtf8String(s));
|
||||
}
|
||||
""")
|
||||
"""
|
||||
)
|
||||
self._script = script
|
||||
script.on('message', lambda *args: self._reactor.schedule(lambda: self._on_message(*args)))
|
||||
script.on("message", lambda *args: self._reactor.schedule(lambda: self._on_message(*args)))
|
||||
script.load()
|
||||
|
||||
def _process_input(self, reactor):
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import frida
|
||||
|
||||
|
||||
embed_script = """
|
||||
const button = {
|
||||
color: 'blue',
|
||||
@@ -28,9 +27,11 @@ session = frida.attach(0)
|
||||
|
||||
snapshot = session.snapshot_script(embed_script, warmup_script=warmup_script, runtime=runtime)
|
||||
|
||||
|
||||
def on_message(message, data):
|
||||
print("on_message:", message)
|
||||
|
||||
|
||||
script = session.create_script(test_script, snapshot=snapshot, runtime=runtime)
|
||||
script.on("message", on_message)
|
||||
script.load()
|
||||
Reference in new issue
Block a user